test.cc 969 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833
  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. // ".//x.sock", which is not taken for a URL
  153. client_GET("./" + pathname_.substr(1));
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_TRUE(s0.is_peer_alive());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.is_peer_alive());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. // PORT + 1 is shared with the SSL redirect tests and with
  263. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  264. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  265. // because that happens on a worker thread the ASSERT does not stop the
  266. // test: it runs on and fails at the disconnected_svr_sock check instead.
  267. default_socket_options(s);
  268. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  269. ASSERT_EQ(0, listen(s, 1));
  270. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  274. std::thread cli{[&] {
  275. const int s = socket(AF_INET, SOCK_STREAM, 0);
  276. ASSERT_LE(0, s);
  277. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. cli.join();
  281. svr.join();
  282. ASSERT_NE(disconnected_svr_sock, -1);
  283. const auto asSocketStream = [&](socket_t fd,
  284. std::function<bool(Stream &)> func) {
  285. return detail::process_client_socket(
  286. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  287. };
  288. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  289. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  290. // wait_writable() returns true because select_write() only checks if the
  291. // send buffer has space. Peer disconnection is detected later by send().
  292. EXPECT_TRUE(ss.wait_writable());
  293. return true;
  294. });
  295. ASSERT_EQ(0, close(disconnected_svr_sock));
  296. }
  297. #endif // #ifndef _WIN32
  298. TEST(SetSocketOptTest, TcpNoDelay) {
  299. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  300. ASSERT_NE(sock, INVALID_SOCKET);
  301. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  302. int val = 0;
  303. socklen_t len = sizeof(val);
  304. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  305. reinterpret_cast<char *>(&val), &len));
  306. EXPECT_NE(val, 0);
  307. detail::close_socket(sock);
  308. }
  309. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  310. // accept() reports failures through WSAGetLastError() on Windows and through
  311. // errno everywhere else. Asking the wrong one is what made the accept loop
  312. // treat every recoverable failure as fatal on Windows.
  313. struct Classification {
  314. bool resource;
  315. bool transient;
  316. };
  317. auto classify = [](int err) {
  318. #ifdef _WIN32
  319. WSASetLastError(err);
  320. #else
  321. errno = err;
  322. #endif
  323. // Read both before asserting: an assertion may clobber the error slot.
  324. Classification c;
  325. c.resource = detail::is_accept_resource_error();
  326. c.transient = detail::is_accept_transient_error();
  327. return c;
  328. };
  329. #ifdef _WIN32
  330. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  331. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  332. WSAECONNRESET, WSAECONNABORTED};
  333. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  334. #else
  335. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  336. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  337. ECONNABORTED};
  338. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  339. #endif
  340. for (auto err : resource_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.resource) << "error " << err;
  343. EXPECT_FALSE(c.transient) << "error " << err;
  344. }
  345. for (auto err : transient_errors) {
  346. const auto c = classify(err);
  347. EXPECT_TRUE(c.transient) << "error " << err;
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. }
  350. for (auto err : fatal_errors) {
  351. const auto c = classify(err);
  352. EXPECT_FALSE(c.resource) << "error " << err;
  353. EXPECT_FALSE(c.transient) << "error " << err;
  354. }
  355. #ifdef _WIN32
  356. WSASetLastError(0);
  357. #else
  358. errno = 0;
  359. #endif
  360. }
  361. TEST(ClientTest, MoveConstructible) {
  362. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  364. }
  365. TEST(ClientTest, MoveAssignable) {
  366. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  367. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  368. }
  369. #ifdef _WIN32
  370. TEST(StartupTest, WSAStartup) {
  371. WSADATA wsaData;
  372. int ret = WSAStartup(0x0002, &wsaData);
  373. ASSERT_EQ(0, ret);
  374. }
  375. #endif
  376. TEST(DecodePathTest, PercentCharacter) {
  377. EXPECT_EQ(
  378. decode_path_component(
  379. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  380. U8("descrip=Gastos áéíóúñÑ 6"));
  381. }
  382. TEST(DecodePathTest, PercentCharacterNUL) {
  383. string expected;
  384. expected.push_back('x');
  385. expected.push_back('\0');
  386. expected.push_back('x');
  387. EXPECT_EQ(decode_path_component("x%00x"), expected);
  388. }
  389. TEST(DecodePathTest, UnicodeEncoding) {
  390. // %u0041 = 'A' (1-byte UTF-8)
  391. EXPECT_EQ("A", decode_path_component("%u0041"));
  392. // %u00E9 = 'é' (2-byte UTF-8)
  393. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  394. // %u3042 = 'あ' (3-byte UTF-8)
  395. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  396. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  397. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  398. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  399. // neighbours)
  400. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  401. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  402. }
  403. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  404. // A sign or whitespace inside the two-character escape window must not be
  405. // accepted as a valid percent-encoding; the sequence is passed through
  406. // literally, matching decode_uri_component / decode_path_component.
  407. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  408. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  409. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  410. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  411. // Well-formed escapes still decode.
  412. EXPECT_EQ("-", decode_query_component("%2D", false));
  413. EXPECT_EQ("A", decode_query_component("%41", false));
  414. }
  415. TEST(SanitizeFilenameTest, VariousPatterns) {
  416. // Path traversal
  417. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  419. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  420. // Normal and edge cases
  421. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  422. EXPECT_EQ("filename.txt",
  423. httplib::sanitize_filename("/path/to/filename.txt"));
  424. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  425. EXPECT_EQ("", httplib::sanitize_filename(".."));
  426. EXPECT_EQ("", httplib::sanitize_filename(""));
  427. // Null bytes stripped
  428. EXPECT_EQ("safe.txt",
  429. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  430. // Whitespace-only rejected
  431. EXPECT_EQ("", httplib::sanitize_filename(" "));
  432. }
  433. // Forward declaration (see the base64_encode note below): split builds move the
  434. // definition into httplib.cc, so re-declaring it here lets the test link.
  435. namespace httplib {
  436. namespace detail {
  437. bool is_chunked_transfer_encoding(const Headers &headers);
  438. } // namespace detail
  439. } // namespace httplib
  440. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  441. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  442. auto make = [](std::initializer_list<const char *> lines) {
  443. Headers h;
  444. for (auto te : lines) {
  445. if (te) { h.emplace("Transfer-Encoding", te); }
  446. }
  447. return h;
  448. };
  449. // Sole coding, matched case-insensitively.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  453. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  457. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  462. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  463. // were received, into one list. Headers preserves that order, so the answer
  464. // is decided by the last coding of the last line and the order the lines
  465. // arrived in is significant.
  466. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  469. // The split can fall anywhere in the list.
  470. EXPECT_TRUE(
  471. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  472. EXPECT_FALSE(
  473. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  474. // A trailing line naming no coding leaves the list ending in nothing, so it
  475. // must not inherit the chunked from the line before it.
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  477. }
  478. // Forward declarations (see the base64_encode note below).
  479. namespace httplib {
  480. namespace detail {
  481. bool parse_status_line(const char *line, std::string &version, int &status,
  482. std::string &reason);
  483. std::string file_extension(const std::string &path);
  484. std::string
  485. find_content_type(const std::string &path,
  486. const std::map<std::string, std::string> &user_data,
  487. const std::string &default_content_type);
  488. bool can_compress_content_type(const std::string &content_type);
  489. bool is_prohibited_header_name(const std::string &name);
  490. #ifdef CPPHTTPLIB_SSL_ENABLED
  491. bool match_hostname(const std::string &pattern, const std::string &hostname);
  492. #endif
  493. } // namespace detail
  494. } // namespace httplib
  495. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  496. struct {
  497. const char *line;
  498. const char *version;
  499. int status;
  500. const char *reason;
  501. } cases[] = {
  502. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  503. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  504. // The reason phrase may be empty, or left out along with its space.
  505. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  506. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  507. };
  508. for (const auto &c : cases) {
  509. std::string version;
  510. int status = 0;
  511. std::string reason = "unset";
  512. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  513. << c.line;
  514. EXPECT_EQ(c.version, version);
  515. EXPECT_EQ(c.status, status);
  516. EXPECT_EQ(c.reason, reason);
  517. }
  518. }
  519. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  520. const char *lines[] = {
  521. "HTTP/2 200 OK\r\n",
  522. "HTTP/1.2 200 OK\r\n",
  523. "HTTP/1.1 20 OK\r\n",
  524. "HTTP/1.1 2000 OK\r\n",
  525. "HTTP/1.1 2x0 OK\r\n",
  526. "HTTP/1.1 200 OK\r\n",
  527. "HTTP/1.1 200OK\r\n",
  528. "HTTP/1.1 200 O\rK\r\n",
  529. "HTTP/1.1 200 OK",
  530. "HTTP/1.1 200 OK\r\nX",
  531. "",
  532. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  533. "HTTP/1.1 200 OK\n",
  534. #endif
  535. };
  536. for (auto line : lines) {
  537. std::string version;
  538. int status = 0;
  539. std::string reason;
  540. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  541. << line;
  542. }
  543. }
  544. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  545. // Long enough to overflow the stack when matched with std::regex.
  546. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  547. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  548. std::string version;
  549. int status = 0;
  550. std::string reason;
  551. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  552. EXPECT_EQ(200, status);
  553. EXPECT_EQ(long_reason, reason);
  554. }
  555. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  556. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  557. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  558. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  559. EXPECT_EQ("", detail::file_extension("noext"));
  560. EXPECT_EQ("", detail::file_extension("a."));
  561. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  562. EXPECT_EQ("", detail::file_extension("a.b-c"));
  563. // Long enough to overflow the stack when matched with std::regex.
  564. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  565. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  566. }
  567. #ifdef CPPHTTPLIB_SSL_ENABLED
  568. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  569. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  570. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  572. // A wildcard needs two labels after it, in the leftmost label only
  573. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  574. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  575. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  576. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  577. EXPECT_FALSE(
  578. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  579. // No name may have an empty label
  580. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  581. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  582. }
  583. #endif
  584. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  585. detail::case_ignore::hash hash;
  586. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  587. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  588. // Long enough to overflow the stack if hashed one call per character.
  589. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  590. }
  591. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  592. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  593. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  594. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  595. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  596. // Same 26-bit hash as html, svg and js.
  597. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  598. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  600. }
  601. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  602. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  603. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  604. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  605. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  606. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  607. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  608. // Same 26-bit hash as application/json.
  609. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  610. }
  611. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  612. Request req;
  613. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  614. EXPECT_TRUE(req.is_multipart_form_data());
  615. std::string boundary;
  616. EXPECT_TRUE(detail::parse_multipart_boundary(
  617. req.get_header_value("Content-Type"), boundary));
  618. EXPECT_EQ("x", boundary);
  619. }
  620. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  621. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  623. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  624. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  625. // Same 26-bit hash as REMOTE_ADDR.
  626. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  627. }
  628. // Forward declaration: in split builds split.py strips `inline` and moves the
  629. // definition into httplib.cc, so detail::base64_encode is not visible from the
  630. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  631. // in both header-only and split builds.
  632. namespace httplib {
  633. namespace detail {
  634. std::string base64_encode(const std::string &in);
  635. } // namespace detail
  636. } // namespace httplib
  637. TEST(Base64EncodeTest, KnownAnswers) {
  638. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  639. // where the accumulator's top bit is already set before the next shift.
  640. EXPECT_EQ("", detail::base64_encode(""));
  641. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  642. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  643. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  644. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  645. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  646. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  647. // High bytes keep the top bit set across several rounds.
  648. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  649. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  650. }
  651. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  652. string unescapedCharacters = "-_.!~*'()";
  653. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  654. }
  655. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  656. string reservedCharacters = ";,/?:@&=+$";
  657. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  658. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  659. }
  660. TEST(ClientQueryOrder, PreserveOrder) {
  661. // This test reproduces Issue #2259: client may reorder query parameters
  662. // when sending a GET request. The expected behavior is that the client
  663. // preserves the original query string order when the caller supplied it
  664. // as part of the path.
  665. Server svr;
  666. svr.Get("/", [&](const Request &req, Response &res) {
  667. // Echo back the raw target so the test can assert ordering
  668. res.set_content(req.target, "text/plain");
  669. });
  670. std::thread t{[&] { svr.listen(HOST, PORT); }};
  671. auto se = detail::scope_exit([&] {
  672. svr.stop();
  673. t.join();
  674. ASSERT_FALSE(svr.is_running());
  675. });
  676. svr.wait_until_ready();
  677. Client cli(HOST, PORT);
  678. ASSERT_TRUE(cli.is_valid());
  679. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  680. auto res = cli.Get(original);
  681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  682. // Expect the echoed target to exactly match the original path (order
  683. // preserved)
  684. EXPECT_EQ(res->body, original);
  685. }
  686. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  687. string chineseCharacters = U8("中国語");
  688. string russianCharacters = U8("дом");
  689. string brazilianCharacters = U8("óculos");
  690. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  691. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  692. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  693. "%D0%B4%D0%BE%D0%BC");
  694. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  695. }
  696. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  697. string unescapedCharacters = "-_.!~*'()";
  698. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  699. }
  700. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  701. string reservedCharacters = ";,/?:@&=+$";
  702. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  703. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  704. }
  705. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  706. string chineseCharacters = U8("中国語");
  707. string russianCharacters = U8("дом");
  708. string brazilianCharacters = U8("óculos");
  709. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  710. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  711. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  712. "%D0%B4%D0%BE%D0%BC");
  713. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  714. }
  715. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  716. // Issue #2082 use case: encoding path component with ampersand
  717. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  718. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  719. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  720. }
  721. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  722. string unescapedCharacters = "-_.!~*'()";
  723. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  724. }
  725. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  726. string reservedCharacters = ";,/?:@&=+$#";
  727. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  728. }
  729. TEST(EncodeUriTest, TestUTF8Characters) {
  730. string chineseCharacters = U8("中国語");
  731. string russianCharacters = U8("дом");
  732. string brazilianCharacters = U8("óculos");
  733. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  734. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  735. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  736. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  737. }
  738. TEST(EncodeUriTest, TestCompleteUri) {
  739. string uri =
  740. "https://example.com/path/to/resource?query=value&param=test#fragment";
  741. EXPECT_EQ(
  742. httplib::encode_uri(uri),
  743. "https://example.com/path/to/resource?query=value&param=test#fragment");
  744. }
  745. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  746. string uri =
  747. "https://example.com/path with spaces/file name.html?q=hello world";
  748. EXPECT_EQ(httplib::encode_uri(uri),
  749. "https://example.com/path%20with%20spaces/"
  750. "file%20name.html?q=hello%20world");
  751. }
  752. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  753. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  755. }
  756. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  757. string unescapedCharacters = "-_.!~*'()";
  758. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  759. }
  760. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  761. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  762. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  763. string encodedBrazilian = "%C3%B3culos";
  764. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  765. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  767. }
  768. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  769. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  770. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  771. "Piri Tommy Villiers - on & on");
  772. }
  773. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  774. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  775. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  776. }
  777. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  778. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  779. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  780. }
  781. TEST(DecodeUriTest, TestUTF8Characters) {
  782. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  783. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  784. string encodedBrazilian = "%C3%B3culos";
  785. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  786. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  787. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  788. }
  789. TEST(DecodeUriTest, TestCompleteUri) {
  790. string encodedUri = "https://example.com/path%20with%20spaces/"
  791. "file%20name.html?q=hello%20world";
  792. EXPECT_EQ(
  793. httplib::decode_uri(encodedUri),
  794. "https://example.com/path with spaces/file name.html?q=hello world");
  795. }
  796. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  797. string original =
  798. "https://example.com/path with spaces/file name.html?q=hello world";
  799. string encoded = httplib::encode_uri(original);
  800. string decoded = httplib::decode_uri(encoded);
  801. EXPECT_EQ(decoded, original);
  802. }
  803. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  804. // decode_uri is the inverse of encode_uri: an escaped reserved character
  805. // stays encoded so it is not promoted into a real delimiter, while
  806. // non-reserved escapes still decode (like JS decodeURI).
  807. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  808. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  809. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  810. "%3F%3A%40%26%3D%2B%24%2C%3B");
  811. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  812. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  813. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  814. "http://example.com/a%2Fb");
  815. // decode_uri_component still decodes the reserved character.
  816. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  817. }
  818. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  819. string original = "Piri Tommy Villiers - on & on";
  820. string encoded = httplib::encode_uri_component(original);
  821. string decoded = httplib::decode_uri_component(encoded);
  822. EXPECT_EQ(decoded, original);
  823. }
  824. TEST(TrimTests, TrimStringTests) {
  825. EXPECT_EQ("abc", detail::trim_copy("abc"));
  826. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  827. EXPECT_TRUE(detail::trim_copy("").empty());
  828. }
  829. TEST(AsciiTest, LocaleIndependentClassification) {
  830. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  831. // which consult the global C locale: std::isalnum(0xC5) can return true
  832. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  833. // helpers must classify every byte by the ASCII grammar alone.
  834. for (int i = 0; i < 256; i++) {
  835. auto c = static_cast<char>(i);
  836. auto is_digit = i >= '0' && i <= '9';
  837. auto is_upper = i >= 'A' && i <= 'Z';
  838. auto is_lower = i >= 'a' && i <= 'z';
  839. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  840. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  841. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  842. << "byte " << i;
  843. }
  844. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  845. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  846. // Non-ASCII bytes must be percent-encoded, never passed through as
  847. // alphanumeric.
  848. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  849. }
  850. TEST(FromCharsTest, Double) {
  851. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  852. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  853. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  854. auto parse = [](const std::string &s, double &v) {
  855. return detail::from_chars(s.data(), s.data() + s.size(), v);
  856. };
  857. double v = -1.0;
  858. // Representative quality values.
  859. EXPECT_EQ(parse("0", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 0.0);
  861. EXPECT_EQ(parse("1", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 1.0);
  863. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.8);
  865. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.001);
  867. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 1.0);
  869. // A missing integer or fractional part is tolerated.
  870. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.5);
  872. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 5.0);
  874. // Values outside [0, 1] still parse; the caller range-checks them.
  875. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 123.456);
  877. // Stops at the first byte that is not part of the number and reports where.
  878. std::string trailing = "0.9, text/html";
  879. auto r = parse(trailing, v);
  880. EXPECT_EQ(r.ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 0.9);
  882. EXPECT_EQ(*r.ptr, ',');
  883. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  884. // outright, and an 'e'/'E' simply ends the number.
  885. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  886. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  887. std::string exp_input = "1.5e3";
  888. r = parse(exp_input, v);
  889. EXPECT_EQ(r.ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 1.5);
  891. EXPECT_EQ(*r.ptr, 'e');
  892. // Invalid inputs.
  893. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  898. // Pathological but well-formed inputs must stay bounded (no overflow, no
  899. // out-of-bounds table access) and stay within [0, 1] for the caller.
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  901. std::errc{});
  902. EXPECT_DOUBLE_EQ(v, 0.0);
  903. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  904. std::errc{});
  905. EXPECT_GE(v, 0.0);
  906. EXPECT_LE(v, 1.0);
  907. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  908. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  909. }
  910. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  911. // Simple case without quality values
  912. std::vector<std::string> result1;
  913. EXPECT_TRUE(detail::parse_accept_header(
  914. "text/html,application/json,text/plain", result1));
  915. EXPECT_EQ(result1.size(), 3U);
  916. EXPECT_EQ(result1[0], "text/html");
  917. EXPECT_EQ(result1[1], "application/json");
  918. EXPECT_EQ(result1[2], "text/plain");
  919. // With quality values
  920. std::vector<std::string> result2;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  923. EXPECT_EQ(result2.size(), 3U);
  924. EXPECT_EQ(result2[0], "application/json"); // highest q value
  925. EXPECT_EQ(result2[1], "text/html");
  926. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  927. }
  928. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  929. // Mixed with and without quality values
  930. std::vector<std::string> result;
  931. EXPECT_TRUE(detail::parse_accept_header(
  932. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  933. EXPECT_EQ(result.size(), 3U);
  934. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  935. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  936. EXPECT_EQ(result[2], "application/json"); // q=0.5
  937. }
  938. TEST(ParseAcceptHeaderTest, EdgeCases) {
  939. // Empty header
  940. std::vector<std::string> empty_result;
  941. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  942. EXPECT_TRUE(empty_result.empty());
  943. // Single type
  944. std::vector<std::string> single_result;
  945. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  946. EXPECT_EQ(single_result.size(), 1U);
  947. EXPECT_EQ(single_result[0], "application/json");
  948. // Wildcard types
  949. std::vector<std::string> wildcard_result;
  950. EXPECT_TRUE(detail::parse_accept_header(
  951. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  952. EXPECT_EQ(wildcard_result.size(), 3U);
  953. EXPECT_EQ(wildcard_result[0], "application/json");
  954. EXPECT_EQ(wildcard_result[1], "text/*");
  955. EXPECT_EQ(wildcard_result[2], "*/*");
  956. }
  957. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  958. // Common browser Accept header
  959. std::vector<std::string> browser_result;
  960. EXPECT_TRUE(
  961. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  962. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  963. browser_result));
  964. EXPECT_EQ(browser_result.size(), 6U);
  965. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  970. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  971. // API client header
  972. std::vector<std::string> api_result;
  973. EXPECT_TRUE(detail::parse_accept_header(
  974. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  975. api_result));
  976. EXPECT_EQ(api_result.size(), 3U);
  977. EXPECT_EQ(api_result[0], "application/json");
  978. EXPECT_EQ(api_result[1], "application/xml");
  979. EXPECT_EQ(api_result[2], "text/plain");
  980. }
  981. TEST(ParseAcceptHeaderTest, SpecialCases) {
  982. // Quality value with 3 decimal places
  983. std::vector<std::string> decimal_result;
  984. EXPECT_TRUE(detail::parse_accept_header(
  985. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  986. EXPECT_EQ(decimal_result.size(), 2U);
  987. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  988. EXPECT_EQ(decimal_result[1], "text/html");
  989. // Zero quality (should still be included but with lowest priority)
  990. std::vector<std::string> zero_q_result;
  991. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  992. zero_q_result));
  993. EXPECT_EQ(zero_q_result.size(), 2U);
  994. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  995. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  996. // No spaces around commas
  997. std::vector<std::string> no_space_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1000. no_space_result));
  1001. EXPECT_EQ(no_space_result.size(), 3U);
  1002. EXPECT_EQ(no_space_result[0], "text/html");
  1003. EXPECT_EQ(no_space_result[1], "application/json");
  1004. EXPECT_EQ(no_space_result[2], "text/plain");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1007. // Quality values always use '.' as the decimal separator, so parsing must
  1008. // not depend on the process locale. An embedding application may have
  1009. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1010. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1011. std::string saved = cur ? cur : "C";
  1012. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1013. "fr_FR.UTF-8"};
  1014. bool switched = false;
  1015. for (const auto loc : comma_locales) {
  1016. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1017. std::localeconv()->decimal_point[0] == ',') {
  1018. switched = true;
  1019. break;
  1020. }
  1021. }
  1022. if (!switched) {
  1023. std::setlocale(LC_NUMERIC, saved.c_str());
  1024. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1025. }
  1026. // The higher-weighted type appears later in the list, so a correct parse
  1027. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1028. // sensitive parse reads both weights as 0 and leaves the original order.
  1029. std::vector<std::string> result;
  1030. EXPECT_TRUE(detail::parse_accept_header(
  1031. "application/json;q=0.1,text/html;q=0.9", result));
  1032. ASSERT_EQ(result.size(), 2U);
  1033. EXPECT_EQ(result[0], "text/html");
  1034. EXPECT_EQ(result[1], "application/json");
  1035. std::setlocale(LC_NUMERIC, saved.c_str());
  1036. }
  1037. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1038. std::vector<std::string> result;
  1039. // Invalid quality value (> 1.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1042. // Invalid quality value (< 0.0)
  1043. EXPECT_FALSE(
  1044. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1045. // Invalid quality value (not a number)
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=invalid,application/json", result));
  1048. // A valid numeric prefix does not make the entire quality value valid.
  1049. EXPECT_FALSE(detail::parse_accept_header(
  1050. "text/html;q=0.5junk,application/json", result));
  1051. // Empty quality value
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("text/html;q=,application/json", result));
  1054. // Invalid media type format (no slash and not wildcard)
  1055. EXPECT_FALSE(
  1056. detail::parse_accept_header("invalidtype,application/json", result));
  1057. // Valid cases should still work
  1058. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*/*");
  1061. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "*");
  1064. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1065. EXPECT_EQ(result.size(), 1U);
  1066. EXPECT_EQ(result[0], "text/*");
  1067. }
  1068. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1069. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1070. // and must not be answered with 400 Bad Request.
  1071. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1072. struct {
  1073. const char *value;
  1074. std::vector<std::string> expected;
  1075. } cases[] = {
  1076. {",application/json", {"application/json"}},
  1077. {"text/html,", {"text/html"}},
  1078. {"text/html,,*/*", {"text/html", "*/*"}},
  1079. // An empty element may be spelled with whitespace in it
  1080. {"text/html, , application/json", {"text/html", "application/json"}},
  1081. // Nothing but empty elements is an empty list, which means the same
  1082. // thing as no Accept header at all
  1083. {",,,", {}},
  1084. // Quality values still apply across ignored empty elements
  1085. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1086. };
  1087. for (const auto &c : cases) {
  1088. std::vector<std::string> result;
  1089. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1090. << "value: " << c.value;
  1091. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1092. }
  1093. // An invalid entry is still rejected when empty elements surround it
  1094. std::vector<std::string> result;
  1095. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1096. }
  1097. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1098. // or ';' inside one does not end the list element or the parameter. Section
  1099. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1100. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1101. struct {
  1102. const char *value;
  1103. std::vector<std::string> expected;
  1104. } cases[] = {
  1105. {"text/html;profile=\"a,b\",application/json",
  1106. {"text/html", "application/json"}},
  1107. // A "q=" inside a quoted value is not the weight
  1108. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1109. {"text/html", "application/json"}},
  1110. // The weight after a quoted value still applies
  1111. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1114. {"application/json", "text/html"}},
  1115. {"text/html;profile=\"a\\\"b\",application/json",
  1116. {"text/html", "application/json"}},
  1117. // An escaped backslash does not escape the '"' after it
  1118. {"text/html;profile=\"a\\\\\",application/json",
  1119. {"text/html", "application/json"}},
  1120. };
  1121. for (const auto &c : cases) {
  1122. std::vector<std::string> result;
  1123. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1124. << "value: " << c.value;
  1125. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1126. }
  1127. }
  1128. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1129. Server svr;
  1130. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1131. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1132. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1133. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1134. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1135. res.set_content("ok", "text/plain");
  1136. });
  1137. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1138. EXPECT_TRUE(false);
  1139. res.set_content("bad request", "text/plain");
  1140. });
  1141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1142. auto se = detail::scope_exit([&] {
  1143. svr.stop();
  1144. listen_thread.join();
  1145. ASSERT_FALSE(svr.is_running());
  1146. });
  1147. svr.wait_until_ready();
  1148. Client cli("localhost", PORT);
  1149. {
  1150. auto res = cli.Get(
  1151. "/accept_ok",
  1152. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. auto res = cli.Get("/accept_bad_request",
  1158. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1161. }
  1162. }
  1163. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1164. Server svr;
  1165. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1166. res.set_content("ok", "text/plain");
  1167. });
  1168. std::atomic<int> start_count{0};
  1169. std::atomic<bool> running_when_called{false};
  1170. svr.set_start_handler([&]() {
  1171. running_when_called = svr.is_running();
  1172. start_count++;
  1173. });
  1174. auto port = svr.bind_to_any_port(HOST);
  1175. std::thread t([&]() { svr.listen_after_bind(); });
  1176. auto se = detail::scope_exit([&] {
  1177. svr.stop();
  1178. t.join();
  1179. ASSERT_FALSE(svr.is_running());
  1180. });
  1181. svr.wait_until_ready();
  1182. // A successful request proves the accept loop is running, which the start
  1183. // handler precedes; so by now the handler must have run exactly once.
  1184. Client cli(HOST, port);
  1185. cli.set_connection_timeout(std::chrono::seconds(5));
  1186. auto res = cli.Get("/");
  1187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1188. EXPECT_EQ(StatusCode::OK_200, res->status);
  1189. EXPECT_EQ(1, start_count.load());
  1190. EXPECT_TRUE(running_when_called.load());
  1191. }
  1192. TEST(DivideTest, DivideStringTests) {
  1193. auto divide = [](const std::string &str, char d) {
  1194. std::string lhs;
  1195. std::string rhs;
  1196. detail::divide(str, d,
  1197. [&](const char *lhs_data, std::size_t lhs_size,
  1198. const char *rhs_data, std::size_t rhs_size) {
  1199. lhs.assign(lhs_data, lhs_size);
  1200. rhs.assign(rhs_data, rhs_size);
  1201. });
  1202. return std::make_pair(std::move(lhs), std::move(rhs));
  1203. };
  1204. {
  1205. const auto res = divide("", '=');
  1206. EXPECT_EQ(res.first, "");
  1207. EXPECT_EQ(res.second, "");
  1208. }
  1209. {
  1210. const auto res = divide("=", '=');
  1211. EXPECT_EQ(res.first, "");
  1212. EXPECT_EQ(res.second, "");
  1213. }
  1214. {
  1215. const auto res = divide(" ", '=');
  1216. EXPECT_EQ(res.first, " ");
  1217. EXPECT_EQ(res.second, "");
  1218. }
  1219. {
  1220. const auto res = divide("a", '=');
  1221. EXPECT_EQ(res.first, "a");
  1222. EXPECT_EQ(res.second, "");
  1223. }
  1224. {
  1225. const auto res = divide("a=", '=');
  1226. EXPECT_EQ(res.first, "a");
  1227. EXPECT_EQ(res.second, "");
  1228. }
  1229. {
  1230. const auto res = divide("=b", '=');
  1231. EXPECT_EQ(res.first, "");
  1232. EXPECT_EQ(res.second, "b");
  1233. }
  1234. {
  1235. const auto res = divide("a=b", '=');
  1236. EXPECT_EQ(res.first, "a");
  1237. EXPECT_EQ(res.second, "b");
  1238. }
  1239. {
  1240. const auto res = divide("a=b=", '=');
  1241. EXPECT_EQ(res.first, "a");
  1242. EXPECT_EQ(res.second, "b=");
  1243. }
  1244. {
  1245. const auto res = divide("a=b=c", '=');
  1246. EXPECT_EQ(res.first, "a");
  1247. EXPECT_EQ(res.second, "b=c");
  1248. }
  1249. }
  1250. TEST(SplitTest, ParseQueryString) {
  1251. string s = "key1=val1&key2=val2&key3=val3";
  1252. Params dic;
  1253. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1254. [&](const char *b, const char *e) {
  1255. string key, val;
  1256. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1257. if (key.empty()) {
  1258. key.assign(b2, e2);
  1259. } else {
  1260. val.assign(b2, e2);
  1261. }
  1262. });
  1263. dic.emplace(key, val);
  1264. });
  1265. EXPECT_EQ("val1", dic.find("key1")->second);
  1266. EXPECT_EQ("val2", dic.find("key2")->second);
  1267. EXPECT_EQ("val3", dic.find("key3")->second);
  1268. }
  1269. TEST(SplitTest, ParseInvalidQueryTests) {
  1270. {
  1271. string s = " ";
  1272. Params dict;
  1273. detail::parse_query_text(s, dict);
  1274. EXPECT_TRUE(dict.empty());
  1275. }
  1276. {
  1277. string s = " = =";
  1278. Params dict;
  1279. detail::parse_query_text(s, dict);
  1280. EXPECT_TRUE(dict.empty());
  1281. }
  1282. }
  1283. TEST(ParseQueryTest, ParseQueryString) {
  1284. {
  1285. std::string s = "key1=val1&key2=val2&key3=val3";
  1286. Params dic;
  1287. detail::parse_query_text(s, dic);
  1288. EXPECT_EQ("val1", dic.find("key1")->second);
  1289. EXPECT_EQ("val2", dic.find("key2")->second);
  1290. EXPECT_EQ("val3", dic.find("key3")->second);
  1291. }
  1292. {
  1293. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("", dic.find("key1")->second);
  1297. EXPECT_EQ("val1", dic.find("key2")->second);
  1298. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1299. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1300. }
  1301. }
  1302. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1303. Params dic;
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1305. dic.emplace("key1", "val1");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1307. dic.emplace("key2", "val2");
  1308. dic.emplace("key3", "val3");
  1309. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1310. }
  1311. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1312. Params params;
  1313. params.emplace("a", "1");
  1314. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1315. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1316. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1317. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1318. // Long enough to overflow the stack when matched with std::regex.
  1319. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1320. EXPECT_EQ("/p?" + long_query + "&a=1",
  1321. append_query_params("/p?" + long_query, params));
  1322. }
  1323. // Joins every entry of a Headers or Params into "key=value " so a whole
  1324. // traversal can be compared in one assertion. Both are instantiations of the
  1325. // same insertion-ordered container, so one helper serves both.
  1326. template <typename Map> static std::string entries_to_string(const Map &m) {
  1327. std::string s;
  1328. for (const auto &entry : m) {
  1329. s += entry.first + "=" + entry.second + " ";
  1330. }
  1331. return s;
  1332. }
  1333. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1334. // Params used to be a std::multimap, which sorted by name and handed the
  1335. // caller's query back alphabetised. A client signing its query string could
  1336. // not reproduce the order it asked for.
  1337. Params dic;
  1338. dic.emplace("zulu", "1");
  1339. dic.emplace("alpha", "2");
  1340. dic.emplace("mike", "3");
  1341. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1342. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1343. }
  1344. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1345. Params dic;
  1346. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1347. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1348. }
  1349. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1350. Request req;
  1351. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1352. req.params);
  1353. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1354. EXPECT_EQ("first", req.get_param_value("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1356. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1357. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1358. EXPECT_EQ("", req.get_param_value("tag", 3));
  1359. }
  1360. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1361. // Params shares its container with Headers, which matches field names
  1362. // case-insensitively. Parameter names must not pick that up.
  1363. Params dic;
  1364. dic.emplace("Key", "upper");
  1365. dic.emplace("key", "lower");
  1366. EXPECT_EQ(2U, dic.size());
  1367. EXPECT_EQ(1U, dic.count("Key"));
  1368. EXPECT_EQ(1U, dic.count("key"));
  1369. EXPECT_EQ("upper", dic.find("Key")->second);
  1370. EXPECT_EQ("lower", dic.find("key")->second);
  1371. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1372. }
  1373. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1374. Server svr;
  1375. std::string order;
  1376. svr.Get("/order", [&](const Request &req, Response &res) {
  1377. order = entries_to_string(req.params);
  1378. res.set_content("ok", "text/plain");
  1379. });
  1380. auto port = svr.bind_to_any_port(HOST);
  1381. thread t = thread([&] { svr.listen_after_bind(); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. t.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, port);
  1389. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1390. ASSERT_TRUE(res);
  1391. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1392. }
  1393. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1394. Server svr;
  1395. std::string field_order, file_order;
  1396. svr.Post("/order", [&](const Request &req, Response &res) {
  1397. for (const auto &field : req.form.fields) {
  1398. field_order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. for (const auto &file : req.form.files) {
  1401. file_order += file.first + "=" + file.second.filename + " ";
  1402. }
  1403. res.set_content("ok", "text/plain");
  1404. });
  1405. auto port = svr.bind_to_any_port(HOST);
  1406. thread t = thread([&] { svr.listen_after_bind(); });
  1407. auto se = detail::scope_exit([&] {
  1408. svr.stop();
  1409. t.join();
  1410. ASSERT_FALSE(svr.is_running());
  1411. });
  1412. svr.wait_until_ready();
  1413. UploadFormDataItems items = {
  1414. {"zulu", "1", "", ""},
  1415. {"alpha", "2", "", ""},
  1416. {"mike", "3", "", ""},
  1417. {"zebra", "z", "z.txt", "text/plain"},
  1418. {"apple", "a", "a.txt", "text/plain"},
  1419. };
  1420. Client cli(HOST, port);
  1421. auto res = cli.Post("/order", items);
  1422. ASSERT_TRUE(res);
  1423. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1424. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1425. }
  1426. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1427. Server svr;
  1428. std::vector<std::string> values;
  1429. std::string first, second, out_of_range, order;
  1430. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1431. values = req.form.get_fields("tag");
  1432. first = req.form.get_field("tag", 0);
  1433. second = req.form.get_field("tag", 1);
  1434. out_of_range = req.form.get_field("tag", 2);
  1435. for (const auto &field : req.form.fields) {
  1436. order += field.first + "=" + field.second.content + " ";
  1437. }
  1438. res.set_content("ok", "text/plain");
  1439. });
  1440. auto port = svr.bind_to_any_port(HOST);
  1441. thread t = thread([&] { svr.listen_after_bind(); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. t.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1449. // not adjacent in the container.
  1450. UploadFormDataItems items = {
  1451. {"tag", "first", "", ""},
  1452. {"other", "x", "", ""},
  1453. {"tag", "second", "", ""},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/repeated", items);
  1457. ASSERT_TRUE(res);
  1458. ASSERT_EQ(2U, values.size());
  1459. EXPECT_EQ("first", values[0]);
  1460. EXPECT_EQ("second", values[1]);
  1461. EXPECT_EQ("first", first);
  1462. EXPECT_EQ("second", second);
  1463. // std::multimap already kept entries sharing a name in insertion order, so
  1464. // everything above passes without this change too. The whole traversal is
  1465. // what tells the two apart: sorting by name would hoist "other" to the front
  1466. // and the two "tag" parts would end up adjacent.
  1467. EXPECT_EQ("tag=first other=x tag=second ", order);
  1468. // Advancing past the last entry of a name used to run off the container;
  1469. // the container's saturating increment makes it return the default instead.
  1470. EXPECT_EQ("", out_of_range);
  1471. }
  1472. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1473. Server svr;
  1474. std::string file_names;
  1475. svr.Post("/upload", [&](const Request &req, Response &res) {
  1476. for (const auto &file : req.form.files) {
  1477. file_names += file.first + "|" + file.second.filename + " ";
  1478. }
  1479. res.set_content("ok", "text/plain");
  1480. });
  1481. auto port = svr.bind_to_any_port(HOST);
  1482. thread t = thread([&] { svr.listen_after_bind(); });
  1483. auto se = detail::scope_exit([&] {
  1484. svr.stop();
  1485. t.join();
  1486. ASSERT_FALSE(svr.is_running());
  1487. });
  1488. svr.wait_until_ready();
  1489. // A trailing backslash would otherwise escape the closing quote.
  1490. UploadFormDataItems items = {
  1491. {"dir\\", "x", "a.txt", "text/plain"},
  1492. {"b", "y", "a\\\\b.txt", "text/plain"},
  1493. };
  1494. Client cli(HOST, port);
  1495. auto res = cli.Post("/upload", items);
  1496. ASSERT_TRUE(res);
  1497. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1498. }
  1499. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1500. // Server::read_content() keeps a FormFields::iterator alive across the
  1501. // content callbacks that fill the part it points at. The container is
  1502. // vector-backed, so a later emplace can reallocate and invalidate an older
  1503. // iterator; 64 parts grow the vector through seven reallocations, which
  1504. // checks that every part's content still lands in its own entry.
  1505. const size_t part_count = 64;
  1506. // One formula for both the parts sent and the values expected back, so the
  1507. // two cannot drift apart.
  1508. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1509. auto content_of = [](size_t i) {
  1510. return std::string(64, static_cast<char>('a' + (i % 26)));
  1511. };
  1512. Server svr;
  1513. std::vector<std::pair<std::string, std::string>> received;
  1514. svr.Post("/many", [&](const Request &req, Response &res) {
  1515. for (const auto &field : req.form.fields) {
  1516. received.emplace_back(field.first, field.second.content);
  1517. }
  1518. res.set_content("ok", "text/plain");
  1519. });
  1520. auto port = svr.bind_to_any_port(HOST);
  1521. thread t = thread([&] { svr.listen_after_bind(); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. t.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. UploadFormDataItems items;
  1529. for (size_t i = 0; i < part_count; i++) {
  1530. items.push_back({name_of(i), content_of(i), "", ""});
  1531. }
  1532. Client cli(HOST, port);
  1533. auto res = cli.Post("/many", items);
  1534. ASSERT_TRUE(res);
  1535. ASSERT_EQ(part_count, received.size());
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1538. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1539. }
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1542. string content_type = "multipart/form-data; boundary=something";
  1543. string boundary;
  1544. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1545. EXPECT_TRUE(ret);
  1546. EXPECT_EQ(boundary, "something");
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1549. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1556. string content_type =
  1557. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1572. const string boundary(70, 'a');
  1573. string content_type = "multipart/form-data; boundary=" + boundary;
  1574. string parsed;
  1575. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(parsed, boundary);
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1580. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1581. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_FALSE(ret);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1587. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1588. // is 72 characters on the wire and still valid.
  1589. const string boundary(70, 'a');
  1590. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1591. string parsed;
  1592. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1593. EXPECT_EQ(parsed, boundary);
  1594. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1595. parsed.clear();
  1596. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1597. }
  1598. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1599. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1600. // The parameter parser must not treat that '=' as the key/value separator.
  1601. string content_type =
  1602. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1603. "charset=UTF-8";
  1604. string parsed;
  1605. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1606. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1607. }
  1608. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1609. // A ';' inside the quoted-string is part of the value, not a parameter
  1610. // separator, so it must not truncate the boundary.
  1611. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "a;b");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1617. string parsed;
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1620. EXPECT_EQ("a\\b", parsed);
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(
  1622. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1623. EXPECT_EQ("a\"b", parsed);
  1624. }
  1625. TEST(ParseDispositionParamsTest, QuotedValues) {
  1626. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1627. // ';' and '=' are ordinary characters inside one.
  1628. struct {
  1629. const char *value;
  1630. std::vector<std::pair<const char *, const char *>> expected;
  1631. } cases[] = {
  1632. {"name=\"file1\"; filename=\"a.txt\"",
  1633. {{"name", "file1"}, {"filename", "a.txt"}}},
  1634. // Whitespace around '=' and ';' is still trimmed
  1635. {"name=\"file2\" ;filename = \"a.html\"",
  1636. {{"name", "file2"}, {"filename", "a.html"}}},
  1637. // '=' inside the value used to leave only the text after the last one
  1638. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1639. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1640. {"name=\"x=y\"", {{"name", "x=y"}}},
  1641. // ';' inside the value used to truncate the pair and leave a bogus one
  1642. {"name=\"file3\"; filename=\"a;b.txt\"",
  1643. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1644. // An unquoted value keeps working, and so does filename*
  1645. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1646. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1647. // A parameter with no key is dropped rather than turned into one whose
  1648. // key is the value
  1649. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1650. // An escaped quote does not end the value
  1651. {"name=\"a\\\"; filename=evil.php\"",
  1652. {{"name", "a\"; filename=evil.php"}}},
  1653. // Other backslashes, as in a Windows path, are kept
  1654. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1655. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1656. };
  1657. for (const auto &c : cases) {
  1658. Params params;
  1659. detail::parse_disposition_params(c.value, params);
  1660. for (const auto &kv : c.expected) {
  1661. auto it = params.find(kv.first);
  1662. ASSERT_NE(it, params.end())
  1663. << "value: " << c.value << ", key: " << kv.first;
  1664. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1665. }
  1666. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1667. }
  1668. }
  1669. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1670. Server svr;
  1671. std::string filename;
  1672. std::string content;
  1673. svr.Post("/upload", [&](const Request &req, Response &) {
  1674. const auto &file = req.form.get_file("file");
  1675. filename = file.filename;
  1676. content = file.content;
  1677. });
  1678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1679. auto se = detail::scope_exit([&] {
  1680. svr.stop();
  1681. thread.join();
  1682. ASSERT_FALSE(svr.is_running());
  1683. });
  1684. svr.wait_until_ready();
  1685. std::string body = "--B\r\n"
  1686. "Content-Disposition: form-data; name=\"file\"; "
  1687. "filename=\"a.txt\"\r\n"
  1688. "Content-Type: text/plain\r\n"
  1689. "\r\n"
  1690. "hello\r\n"
  1691. "--B--\r\n";
  1692. Client cli(HOST, PORT);
  1693. auto res = cli.Post(
  1694. "/upload",
  1695. [&](size_t offset, DataSink &sink) {
  1696. if (offset < body.size()) {
  1697. sink.write(&body[offset], 1);
  1698. } else {
  1699. sink.done();
  1700. }
  1701. return true;
  1702. },
  1703. "multipart/form-data; boundary=B");
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. EXPECT_EQ(StatusCode::OK_200, res->status);
  1706. EXPECT_EQ("a.txt", filename);
  1707. EXPECT_EQ("hello", content);
  1708. }
  1709. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1710. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1711. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1712. Server svr;
  1713. std::string field_value, file_name, file_filename;
  1714. bool has_field = false, has_file = false;
  1715. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1716. has_field = req.form.has_field("x=y");
  1717. field_value = req.form.get_field("x=y");
  1718. has_file = req.form.has_file("file1");
  1719. const auto &file = req.form.get_file("file1");
  1720. file_name = file.name;
  1721. file_filename = file.filename;
  1722. res.set_content("ok", "text/plain");
  1723. });
  1724. auto port = svr.bind_to_any_port(HOST);
  1725. thread t = thread([&] { svr.listen_after_bind(); });
  1726. auto se = detail::scope_exit([&] {
  1727. svr.stop();
  1728. t.join();
  1729. ASSERT_FALSE(svr.is_running());
  1730. });
  1731. svr.wait_until_ready();
  1732. UploadFormDataItems items = {
  1733. {"x=y", "field-value", "", ""},
  1734. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1735. };
  1736. Client cli(HOST, port);
  1737. auto res = cli.Post("/quoted", items);
  1738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1739. ASSERT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_TRUE(has_field);
  1741. EXPECT_EQ("field-value", field_value);
  1742. EXPECT_TRUE(has_file);
  1743. EXPECT_EQ("file1", file_name);
  1744. EXPECT_EQ("a;b=report.pdf", file_filename);
  1745. }
  1746. TEST(GetHeaderValueTest, DefaultValue) {
  1747. Headers headers = {{"Dummy", "Dummy"}};
  1748. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1749. EXPECT_STREQ("text/plain", val);
  1750. }
  1751. TEST(GetHeaderValueTest, DefaultValueInt) {
  1752. Headers headers = {{"Dummy", "Dummy"}};
  1753. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1754. EXPECT_EQ(100ull, val);
  1755. }
  1756. TEST(GetHeaderValueTest, RegularValue) {
  1757. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1758. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1759. EXPECT_STREQ("text/html", val);
  1760. }
  1761. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1762. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1763. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1764. EXPECT_STREQ("text/html", val);
  1765. }
  1766. TEST(GetHeaderValueTest, SetContent) {
  1767. Response res;
  1768. res.set_content("html", "text/html");
  1769. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1770. res.set_content("text", "text/plain");
  1771. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1772. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1773. }
  1774. TEST(GetHeaderValueTest, RegularValueInt) {
  1775. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1776. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1777. EXPECT_EQ(100ull, val);
  1778. }
  1779. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1780. Headers headers = {{"Content-Length", "x"}};
  1781. auto is_invalid_value = false;
  1782. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1783. is_invalid_value);
  1784. EXPECT_EQ(0ull, val);
  1785. EXPECT_TRUE(is_invalid_value);
  1786. }
  1787. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1788. // An all-digit value that overflows size_t must be reported as invalid, not
  1789. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1790. // a large length to a small one on 32-bit builds, leaving the framing length
  1791. // wrong while is_invalid_value stayed false.
  1792. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1793. auto is_invalid_value = false;
  1794. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1795. is_invalid_value);
  1796. EXPECT_TRUE(is_invalid_value);
  1797. // A well-formed length is unaffected.
  1798. Headers ok = {{"Content-Length", "1234"}};
  1799. is_invalid_value = false;
  1800. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1801. is_invalid_value);
  1802. EXPECT_EQ(1234ull, val);
  1803. EXPECT_FALSE(is_invalid_value);
  1804. }
  1805. TEST(GetHeaderValueTest, Range) {
  1806. {
  1807. Headers headers = {make_range_header({{1, -1}})};
  1808. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1809. EXPECT_STREQ("bytes=1-", val);
  1810. }
  1811. {
  1812. Headers headers = {make_range_header({{-1, 1}})};
  1813. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1814. EXPECT_STREQ("bytes=-1", val);
  1815. }
  1816. {
  1817. Headers headers = {make_range_header({{1, 10}})};
  1818. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1819. EXPECT_STREQ("bytes=1-10", val);
  1820. }
  1821. {
  1822. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1823. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1824. EXPECT_STREQ("bytes=1-10, 100-", val);
  1825. }
  1826. {
  1827. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1828. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1829. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1830. }
  1831. {
  1832. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1834. EXPECT_STREQ("bytes=0-0, -1", val);
  1835. }
  1836. }
  1837. TEST(BearerTokenAuthTest, SchemeValidation) {
  1838. // A value shorter than "Bearer " must not throw from the fixed-length
  1839. // substr, and a non-Bearer scheme must not be reported as a token.
  1840. struct {
  1841. const char *value;
  1842. const char *expected;
  1843. } cases[] = {
  1844. {"x", ""},
  1845. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1846. {"Bearer abc123", "abc123"},
  1847. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1848. };
  1849. for (const auto &c : cases) {
  1850. Request req;
  1851. req.set_header("Authorization", c.value);
  1852. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1853. }
  1854. }
  1855. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1856. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1857. // to depend on the standard library (libstdc++ handed back duplicates in
  1858. // reverse insertion order, libc++ in insertion order).
  1859. Request req;
  1860. req.set_header("Accept-Encoding", "gzip");
  1861. req.set_header("Accept-Encoding", "deflate");
  1862. req.set_header("Accept-Encoding", "br");
  1863. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1864. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1866. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1867. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1868. }
  1869. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1870. Request req;
  1871. req.set_header("X-Test", "only");
  1872. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1873. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1875. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1876. }
  1877. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-First", "1");
  1880. req.set_header("X-Test", "2");
  1881. req.params.emplace("first", "1");
  1882. req.params.emplace("test", "2");
  1883. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1884. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1885. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1886. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1887. // The second one is negative when read as a signed value
  1888. const auto max_id = (std::numeric_limits<size_t>::max)();
  1889. for (auto id : {max_id / 2, max_id}) {
  1890. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1891. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1892. EXPECT_EQ("", req.get_param_value("test", id));
  1893. EXPECT_EQ("", req.form.get_field("test", id));
  1894. EXPECT_EQ("", req.form.get_file("test", id).content);
  1895. }
  1896. }
  1897. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1898. Headers headers;
  1899. headers.emplace("Host", "example.com");
  1900. headers.emplace("Accept-Encoding", "gzip");
  1901. headers.emplace("User-Agent", "test");
  1902. headers.emplace("Accept-Encoding", "deflate");
  1903. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1904. "Accept-Encoding=deflate ",
  1905. entries_to_string(headers));
  1906. }
  1907. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1908. Headers headers = {{"Content-Type", "text/html"},
  1909. {"CONTENT-TYPE", "text/xml"}};
  1910. EXPECT_EQ(2U, headers.count("content-type"));
  1911. auto it = headers.find("content-type");
  1912. ASSERT_TRUE(it != headers.end());
  1913. EXPECT_EQ("text/html", it->second);
  1914. }
  1915. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1916. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1917. // drop only those fields and leave everything positioned between them.
  1918. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1919. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1920. auto rng = headers.equal_range("a");
  1921. headers.erase(rng.first, rng.second);
  1922. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1923. }
  1924. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1925. Headers headers = {
  1926. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1927. EXPECT_EQ(3U, headers.erase("A"));
  1928. EXPECT_EQ(0U, headers.count("A"));
  1929. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1932. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1933. headers.emplace_front("Host", "example.com");
  1934. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1935. entries_to_string(headers));
  1936. }
  1937. TEST(ParseHeaderValueTest, Range) {
  1938. {
  1939. Ranges ranges;
  1940. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1941. EXPECT_TRUE(ret);
  1942. EXPECT_EQ(1u, ranges.size());
  1943. EXPECT_EQ(1u, ranges[0].first);
  1944. EXPECT_EQ(-1, ranges[0].second);
  1945. }
  1946. {
  1947. Ranges ranges;
  1948. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1949. EXPECT_TRUE(ret);
  1950. EXPECT_EQ(1u, ranges.size());
  1951. EXPECT_EQ(-1, ranges[0].first);
  1952. EXPECT_EQ(1u, ranges[0].second);
  1953. }
  1954. {
  1955. Ranges ranges;
  1956. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1957. EXPECT_TRUE(ret);
  1958. EXPECT_EQ(1u, ranges.size());
  1959. EXPECT_EQ(1u, ranges[0].first);
  1960. EXPECT_EQ(10u, ranges[0].second);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1965. EXPECT_FALSE(ret);
  1966. }
  1967. {
  1968. Ranges ranges;
  1969. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1970. EXPECT_TRUE(ret);
  1971. EXPECT_EQ(2u, ranges.size());
  1972. EXPECT_EQ(1u, ranges[0].first);
  1973. EXPECT_EQ(10u, ranges[0].second);
  1974. EXPECT_EQ(100u, ranges[1].first);
  1975. EXPECT_EQ(-1, ranges[1].second);
  1976. }
  1977. {
  1978. Ranges ranges;
  1979. auto ret =
  1980. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1981. EXPECT_TRUE(ret);
  1982. EXPECT_EQ(3u, ranges.size());
  1983. EXPECT_EQ(1u, ranges[0].first);
  1984. EXPECT_EQ(10u, ranges[0].second);
  1985. EXPECT_EQ(100u, ranges[1].first);
  1986. EXPECT_EQ(200u, ranges[1].second);
  1987. EXPECT_EQ(300u, ranges[2].first);
  1988. EXPECT_EQ(400u, ranges[2].second);
  1989. }
  1990. {
  1991. Ranges ranges;
  1992. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=0", 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=,,", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2003. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2004. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2005. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2006. EXPECT_FALSE(
  2007. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2008. EXPECT_TRUE(ranges.empty());
  2009. }
  2010. {
  2011. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2012. // remainder of the representation, so it stays accepted.
  2013. Ranges ranges;
  2014. auto ret =
  2015. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2016. EXPECT_TRUE(ret);
  2017. ASSERT_EQ(1u, ranges.size());
  2018. EXPECT_EQ(0, ranges[0].first);
  2019. EXPECT_EQ(-1, ranges[0].second);
  2020. }
  2021. // RFC 9110 14.1: range unit names are case-insensitive.
  2022. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2023. Ranges ranges;
  2024. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2025. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2026. }
  2027. }
  2028. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2029. Request req;
  2030. req.set_header("Accept-Encoding", "gzip");
  2031. Response res;
  2032. res.set_header("Content-Type", "text/plain");
  2033. auto ret = detail::encoding_type(req, res);
  2034. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2035. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2036. #else
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. #endif
  2039. }
  2040. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2041. Request req;
  2042. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2043. Response res;
  2044. res.set_header("Content-Type", "text/plain");
  2045. auto ret = detail::encoding_type(req, res);
  2046. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2048. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2050. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2052. #else
  2053. EXPECT_TRUE(ret == detail::EncodingType::None);
  2054. #endif
  2055. }
  2056. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2057. Request req;
  2058. req.set_header("Accept-Encoding",
  2059. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2060. Response res;
  2061. res.set_header("Content-Type", "text/plain");
  2062. auto ret = detail::encoding_type(req, res);
  2063. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2065. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2067. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2068. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2069. #else
  2070. EXPECT_TRUE(ret == detail::EncodingType::None);
  2071. #endif
  2072. }
  2073. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2074. // All supported encodings rejected with q=0 should return None
  2075. Request req;
  2076. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2077. Response res;
  2078. res.set_header("Content-Type", "text/plain");
  2079. auto ret = detail::encoding_type(req, res);
  2080. EXPECT_TRUE(ret == detail::EncodingType::None);
  2081. }
  2082. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2083. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. auto ret = detail::encoding_type(req, res);
  2089. EXPECT_TRUE(ret == detail::EncodingType::None);
  2090. }
  2091. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2092. Request req;
  2093. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2094. Response res;
  2095. res.set_header("Content-Type", "text/plain");
  2096. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2097. }
  2098. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2099. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2100. Request req;
  2101. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2102. Response res;
  2103. res.set_header("Content-Type", "text/plain");
  2104. auto ret = detail::encoding_type(req, res);
  2105. EXPECT_TRUE(ret == detail::EncodingType::None);
  2106. }
  2107. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2108. // RFC 7231: Accept-Encoding values are case-insensitive
  2109. Request req;
  2110. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2111. Response res;
  2112. res.set_header("Content-Type", "text/plain");
  2113. auto ret = detail::encoding_type(req, res);
  2114. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2116. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2118. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2120. #else
  2121. EXPECT_TRUE(ret == detail::EncodingType::None);
  2122. #endif
  2123. }
  2124. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2125. // q value should determine priority, not hardcoded order
  2126. Request req;
  2127. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2128. Response res;
  2129. res.set_header("Content-Type", "text/plain");
  2130. auto ret = detail::encoding_type(req, res);
  2131. // gzip has highest q=1.0, so it should be selected even though
  2132. // br and zstd are also supported
  2133. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2135. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2137. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2138. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2139. #else
  2140. EXPECT_TRUE(ret == detail::EncodingType::None);
  2141. #endif
  2142. }
  2143. TEST(BufferStreamTest, read) {
  2144. detail::BufferStream strm1;
  2145. Stream &strm = strm1;
  2146. EXPECT_EQ(5, strm.write("hello"));
  2147. char buf[512];
  2148. EXPECT_EQ(2, strm.read(buf, 2));
  2149. EXPECT_EQ('h', buf[0]);
  2150. EXPECT_EQ('e', buf[1]);
  2151. EXPECT_EQ(2, strm.read(buf, 2));
  2152. EXPECT_EQ('l', buf[0]);
  2153. EXPECT_EQ('l', buf[1]);
  2154. EXPECT_EQ(1, strm.read(buf, 1));
  2155. EXPECT_EQ('o', buf[0]);
  2156. EXPECT_EQ(0, strm.read(buf, 1));
  2157. }
  2158. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2159. auto host = "www.httpwatch.com";
  2160. auto ip = hosted_at(host);
  2161. EXPECT_EQ("23.96.13.243", ip);
  2162. std::vector<std::string> addrs;
  2163. hosted_at(host, addrs);
  2164. EXPECT_EQ(1u, addrs.size());
  2165. }
  2166. #if 0 // It depends on each test environment...
  2167. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2168. auto host = "www.youtube.com";
  2169. std::vector<std::string> addrs;
  2170. hosted_at(host, addrs);
  2171. EXPECT_EQ(20u, addrs.size());
  2172. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2173. EXPECT_TRUE(it != addrs.end());
  2174. }
  2175. #endif
  2176. class ChunkedEncodingTest : public ::testing::Test {
  2177. protected:
  2178. ChunkedEncodingTest()
  2179. : cli_(HOST, PORT)
  2180. #ifdef CPPHTTPLIB_SSL_ENABLED
  2181. ,
  2182. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2183. #endif
  2184. {
  2185. cli_.set_connection_timeout(2);
  2186. #ifdef CPPHTTPLIB_SSL_ENABLED
  2187. cli_.enable_server_certificate_verification(false);
  2188. #endif
  2189. }
  2190. virtual void SetUp() {
  2191. read_file("./image.jpg", image_data_);
  2192. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2193. res.set_content("Hello World!", "text/plain");
  2194. });
  2195. svr_.Get(
  2196. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2197. res.set_chunked_content_provider(
  2198. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2199. size_t remaining = image_data_.size() - offset;
  2200. if (remaining == 0) {
  2201. sink.done();
  2202. } else {
  2203. constexpr size_t CHUNK_SIZE = 1024;
  2204. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2205. sink.write(&image_data_[offset], send_size);
  2206. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2207. }
  2208. return true;
  2209. });
  2210. });
  2211. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2212. svr_.wait_until_ready();
  2213. }
  2214. virtual void TearDown() {
  2215. svr_.stop();
  2216. if (!request_threads_.empty()) {
  2217. std::this_thread::sleep_for(std::chrono::seconds(1));
  2218. for (auto &t : request_threads_) {
  2219. t.join();
  2220. }
  2221. }
  2222. t_.join();
  2223. }
  2224. #ifdef CPPHTTPLIB_SSL_ENABLED
  2225. SSLClient cli_;
  2226. SSLServer svr_;
  2227. #else
  2228. Client cli_;
  2229. Server svr_;
  2230. #endif
  2231. thread t_;
  2232. std::vector<thread> request_threads_;
  2233. std::string image_data_;
  2234. };
  2235. TEST_F(ChunkedEncodingTest, NormalGet) {
  2236. auto res = cli_.Get("/chunked");
  2237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2238. std::string out;
  2239. read_file("./image.jpg", out);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. EXPECT_EQ(out, res->body);
  2242. }
  2243. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2244. std::string body;
  2245. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2246. body.append(data, data_length);
  2247. return true;
  2248. });
  2249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2250. std::string out;
  2251. read_file("./image.jpg", out);
  2252. EXPECT_EQ(StatusCode::OK_200, res->status);
  2253. EXPECT_EQ(out, body);
  2254. }
  2255. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2256. std::string body;
  2257. auto res = cli_.Get(
  2258. "/chunked",
  2259. [&](const Response &response) {
  2260. EXPECT_EQ(StatusCode::OK_200, response.status);
  2261. return true;
  2262. },
  2263. [&](const char *data, size_t data_length) {
  2264. body.append(data, data_length);
  2265. return true;
  2266. });
  2267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2268. std::string out;
  2269. read_file("./image.jpg", out);
  2270. EXPECT_EQ(StatusCode::OK_200, res->status);
  2271. EXPECT_EQ(out, body);
  2272. }
  2273. TEST(RangeTest, FromHTTPBin_Online) {
  2274. auto host = "httpbingo.org";
  2275. auto path = std::string{"/range/32"};
  2276. #ifdef CPPHTTPLIB_SSL_ENABLED
  2277. auto port = 443;
  2278. SSLClient cli(host, port);
  2279. #else
  2280. auto port = 80;
  2281. Client cli(host, port);
  2282. #endif
  2283. cli.set_connection_timeout(5);
  2284. {
  2285. auto res = cli.Get(path);
  2286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2287. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2288. EXPECT_EQ(StatusCode::OK_200, res->status);
  2289. }
  2290. {
  2291. Headers headers = {make_range_header({{1, -1}})};
  2292. auto res = cli.Get(path, headers);
  2293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2294. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2296. }
  2297. {
  2298. Headers headers = {make_range_header({{1, 10}})};
  2299. auto res = cli.Get(path, headers);
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. EXPECT_EQ("bcdefghijk", res->body);
  2302. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2303. }
  2304. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2305. // entire resource, while the original httpbin returned 200. Both are
  2306. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2307. {
  2308. Headers headers = {make_range_header({{0, 31}})};
  2309. auto res = cli.Get(path, headers);
  2310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2311. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2312. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2313. res->status == StatusCode::PartialContent_206);
  2314. }
  2315. {
  2316. Headers headers = {make_range_header({{0, -1}})};
  2317. auto res = cli.Get(path, headers);
  2318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2319. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2320. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2321. res->status == StatusCode::PartialContent_206);
  2322. }
  2323. // go-httpbin returns 206 with clamped range for over-range requests,
  2324. // while the original httpbin returned 416. Both behaviors are observed
  2325. // in real servers, so we only verify the request succeeds.
  2326. {
  2327. Headers headers = {make_range_header({{0, 32}})};
  2328. auto res = cli.Get(path, headers);
  2329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2330. }
  2331. }
  2332. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2333. auto host = "unresolvableaddress.local";
  2334. auto path = std::string{"/"};
  2335. #ifdef CPPHTTPLIB_SSL_ENABLED
  2336. auto port = 443;
  2337. SSLClient cli(host, port);
  2338. #else
  2339. auto port = 80;
  2340. Client cli(host, port);
  2341. #endif
  2342. cli.set_connection_timeout(1);
  2343. {
  2344. auto res = cli.Get(path);
  2345. ASSERT_FALSE(res);
  2346. }
  2347. std::this_thread::sleep_for(std::chrono::seconds(8));
  2348. }
  2349. #if defined(__linux__) && defined(__GLIBC__) && \
  2350. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2351. // Forward declaration: in split builds split.py strips `inline` and moves the
  2352. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2353. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2354. // against the symbol in both header-only and split builds.
  2355. namespace httplib {
  2356. namespace detail {
  2357. int getaddrinfo_with_timeout(const char *node, const char *service,
  2358. const struct addrinfo *hints,
  2359. struct addrinfo **res, time_t timeout_sec);
  2360. } // namespace detail
  2361. } // namespace httplib
  2362. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2363. //
  2364. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2365. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2366. // gai_suspend() call hits the connection timeout the function calls
  2367. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2368. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2369. // still alive and still references the now-destroyed stack frame.
  2370. //
  2371. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2372. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2373. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2374. // and runs them in a container.
  2375. namespace {
  2376. bool should_run_issue_2431_tests() {
  2377. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2378. return v && *v && std::string(v) != "0";
  2379. }
  2380. std::string unique_unresolvable_host(int n) {
  2381. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2382. // glibc still asks the configured nameserver — which is exactly the path
  2383. // we want to exercise. A unique label per call avoids the resolver cache.
  2384. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2385. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2386. std::to_string(n) + ".invalid";
  2387. }
  2388. } // namespace
  2389. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2390. if (!should_run_issue_2431_tests()) {
  2391. GTEST_SKIP()
  2392. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2393. }
  2394. for (int i = 0; i < 8; ++i) {
  2395. struct addrinfo hints;
  2396. memset(&hints, 0, sizeof(hints));
  2397. hints.ai_family = AF_UNSPEC;
  2398. hints.ai_socktype = SOCK_STREAM;
  2399. auto host = unique_unresolvable_host(i);
  2400. struct addrinfo *result = nullptr;
  2401. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2402. &result, /*timeout_sec=*/1);
  2403. if (rc == 0 && result) { freeaddrinfo(result); }
  2404. }
  2405. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2406. // stack region they still believe holds their gaicb.
  2407. std::this_thread::sleep_for(std::chrono::seconds(3));
  2408. }
  2409. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2410. if (!should_run_issue_2431_tests()) {
  2411. GTEST_SKIP()
  2412. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2413. }
  2414. std::atomic<bool> stop{false};
  2415. std::vector<std::thread> threads;
  2416. for (int t = 0; t < 8; ++t) {
  2417. threads.emplace_back([t, &stop] {
  2418. int i = 0;
  2419. while (!stop.load(std::memory_order_relaxed)) {
  2420. struct addrinfo hints;
  2421. memset(&hints, 0, sizeof(hints));
  2422. hints.ai_family = AF_UNSPEC;
  2423. hints.ai_socktype = SOCK_STREAM;
  2424. auto host = unique_unresolvable_host(t * 100000 + i++);
  2425. struct addrinfo *result = nullptr;
  2426. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2427. &result, /*timeout_sec=*/1);
  2428. if (rc == 0 && result) { freeaddrinfo(result); }
  2429. }
  2430. });
  2431. }
  2432. std::this_thread::sleep_for(std::chrono::seconds(8));
  2433. stop.store(true, std::memory_order_relaxed);
  2434. for (auto &th : threads) {
  2435. th.join();
  2436. }
  2437. std::this_thread::sleep_for(std::chrono::seconds(3));
  2438. }
  2439. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2440. if (!should_run_issue_2431_tests()) {
  2441. GTEST_SKIP()
  2442. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2443. }
  2444. std::atomic<bool> stop{false};
  2445. std::vector<std::thread> threads;
  2446. for (int t = 0; t < 8; ++t) {
  2447. threads.emplace_back([t, &stop] {
  2448. int i = 0;
  2449. while (!stop.load(std::memory_order_relaxed)) {
  2450. auto host = unique_unresolvable_host(t * 100000 + i++);
  2451. Client cli(host, 80);
  2452. cli.set_connection_timeout(1, 0);
  2453. cli.set_read_timeout(1, 0);
  2454. cli.set_write_timeout(1, 0);
  2455. (void)cli.Get("/");
  2456. }
  2457. });
  2458. }
  2459. std::this_thread::sleep_for(std::chrono::seconds(8));
  2460. stop.store(true, std::memory_order_relaxed);
  2461. for (auto &th : threads) {
  2462. th.join();
  2463. }
  2464. std::this_thread::sleep_for(std::chrono::seconds(3));
  2465. }
  2466. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2467. TEST(ConnectionErrorTest, InvalidHost) {
  2468. auto host = "-abcde.com";
  2469. #ifdef CPPHTTPLIB_SSL_ENABLED
  2470. auto port = 443;
  2471. SSLClient cli(host, port);
  2472. #else
  2473. auto port = 80;
  2474. Client cli(host, port);
  2475. #endif
  2476. cli.set_connection_timeout(std::chrono::seconds(2));
  2477. auto res = cli.Get("/");
  2478. ASSERT_TRUE(!res);
  2479. EXPECT_EQ(Error::Connection, res.error());
  2480. }
  2481. TEST(ConnectionErrorTest, InvalidHost2) {
  2482. auto host = "httpcan.org/";
  2483. #ifdef CPPHTTPLIB_SSL_ENABLED
  2484. SSLClient cli(host);
  2485. #else
  2486. Client cli(host);
  2487. #endif
  2488. cli.set_connection_timeout(std::chrono::seconds(2));
  2489. auto res = cli.Get("/");
  2490. ASSERT_TRUE(!res);
  2491. EXPECT_EQ(Error::Connection, res.error());
  2492. }
  2493. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2494. auto host = "httpcan.org/";
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host);
  2497. #else
  2498. Client cli(host);
  2499. #endif
  2500. cli.set_connection_timeout(std::chrono::seconds(2));
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(!res);
  2503. stringstream s;
  2504. s << "error code: " << res.error();
  2505. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2506. }
  2507. TEST(ConnectionErrorTest, InvalidPort) {
  2508. auto host = "localhost";
  2509. auto port = 44380;
  2510. #ifdef CPPHTTPLIB_SSL_ENABLED
  2511. SSLClient cli(host, port);
  2512. #else
  2513. Client cli(host, port);
  2514. #endif
  2515. cli.set_connection_timeout(std::chrono::seconds(2));
  2516. auto res = cli.Get("/");
  2517. ASSERT_TRUE(!res);
  2518. EXPECT_TRUE(Error::Connection == res.error() ||
  2519. Error::ConnectionTimeout == res.error());
  2520. }
  2521. TEST(ConnectionErrorTest, Timeout_Online) {
  2522. auto host = "google.com";
  2523. #ifdef CPPHTTPLIB_SSL_ENABLED
  2524. auto port = 44380;
  2525. SSLClient cli(host, port);
  2526. #else
  2527. auto port = 8080;
  2528. Client cli(host, port);
  2529. #endif
  2530. cli.set_connection_timeout(std::chrono::seconds(2));
  2531. // only probe one address type so that the error reason
  2532. // correlates to the timed-out IPv4, not the unsupported
  2533. // IPv6 connection attempt
  2534. cli.set_address_family(AF_INET);
  2535. auto res = cli.Get("/");
  2536. ASSERT_TRUE(!res);
  2537. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2538. }
  2539. TEST(CancelTest, NoCancel_Online) {
  2540. auto host = "httpbingo.org";
  2541. auto path = std::string{"/range/32"};
  2542. #ifdef CPPHTTPLIB_SSL_ENABLED
  2543. auto port = 443;
  2544. SSLClient cli(host, port);
  2545. #else
  2546. auto port = 80;
  2547. Client cli(host, port);
  2548. #endif
  2549. cli.set_connection_timeout(std::chrono::seconds(5));
  2550. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2552. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2556. // Use /bytes with a large payload so that the DownloadProgress callback
  2557. // (which only fires for Content-Length responses) is invoked before the
  2558. // entire body is received, giving cancellation a chance to fire.
  2559. auto host = "httpbingo.org";
  2560. auto path = std::string{"/bytes/524288"};
  2561. #ifdef CPPHTTPLIB_SSL_ENABLED
  2562. auto port = 443;
  2563. SSLClient cli(host, port);
  2564. #else
  2565. auto port = 80;
  2566. Client cli(host, port);
  2567. #endif
  2568. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2569. cli.set_connection_timeout(std::chrono::seconds(5));
  2570. ASSERT_TRUE(!res);
  2571. EXPECT_EQ(Error::Canceled, res.error());
  2572. }
  2573. TEST(CancelTest, WithCancelLargePayload_Online) {
  2574. auto host = "httpbingo.org";
  2575. auto path = std::string{"/bytes/524288"};
  2576. #ifdef CPPHTTPLIB_SSL_ENABLED
  2577. auto port = 443;
  2578. SSLClient cli(host, port);
  2579. #else
  2580. auto port = 80;
  2581. Client cli(host, port);
  2582. #endif
  2583. cli.set_connection_timeout(std::chrono::seconds(5));
  2584. uint32_t count = 0;
  2585. auto res =
  2586. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2587. ASSERT_TRUE(!res);
  2588. EXPECT_EQ(Error::Canceled, res.error());
  2589. }
  2590. TEST(CancelTest, NoCancelPost) {
  2591. Server svr;
  2592. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2593. res.set_content("Hello World!", "text/plain");
  2594. });
  2595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2596. auto se = detail::scope_exit([&] {
  2597. svr.stop();
  2598. thread.join();
  2599. ASSERT_FALSE(svr.is_running());
  2600. });
  2601. svr.wait_until_ready();
  2602. Client cli(HOST, PORT);
  2603. cli.set_connection_timeout(std::chrono::seconds(5));
  2604. auto res =
  2605. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2606. "application/json", [](uint64_t, uint64_t) { return true; });
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. EXPECT_EQ("Hello World!", res->body);
  2609. EXPECT_EQ(StatusCode::OK_200, res->status);
  2610. }
  2611. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2612. Server svr;
  2613. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2614. res.set_content("Hello World!", "text/plain");
  2615. });
  2616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2617. auto se = detail::scope_exit([&] {
  2618. svr.stop();
  2619. thread.join();
  2620. ASSERT_FALSE(svr.is_running());
  2621. });
  2622. svr.wait_until_ready();
  2623. Client cli(HOST, PORT);
  2624. cli.set_connection_timeout(std::chrono::seconds(5));
  2625. auto res =
  2626. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2627. "application/json", [](uint64_t, uint64_t) { return false; });
  2628. ASSERT_TRUE(!res);
  2629. EXPECT_EQ(Error::Canceled, res.error());
  2630. }
  2631. TEST(CancelTest, WithCancelLargePayloadPost) {
  2632. Server svr;
  2633. svr.set_payload_max_length(200 * 1024 * 1024);
  2634. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2635. res.set_content(LARGE_DATA, "text/plain");
  2636. });
  2637. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2638. auto se = detail::scope_exit([&] {
  2639. svr.stop();
  2640. thread.join();
  2641. ASSERT_FALSE(svr.is_running());
  2642. });
  2643. svr.wait_until_ready();
  2644. Client cli(HOST, PORT);
  2645. cli.set_payload_max_length(200 * 1024 * 1024);
  2646. cli.set_connection_timeout(std::chrono::seconds(5));
  2647. auto res =
  2648. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2649. "application/json", [](uint64_t, uint64_t) { return false; });
  2650. ASSERT_TRUE(!res);
  2651. EXPECT_EQ(Error::Canceled, res.error());
  2652. }
  2653. TEST(CancelTest, NoCancelPut) {
  2654. Server svr;
  2655. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2656. res.set_content("Hello World!", "text/plain");
  2657. });
  2658. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2659. auto se = detail::scope_exit([&] {
  2660. svr.stop();
  2661. thread.join();
  2662. ASSERT_FALSE(svr.is_running());
  2663. });
  2664. svr.wait_until_ready();
  2665. Client cli(HOST, PORT);
  2666. cli.set_connection_timeout(std::chrono::seconds(5));
  2667. auto res =
  2668. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2669. "application/json", [](uint64_t, uint64_t) { return true; });
  2670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2671. EXPECT_EQ("Hello World!", res->body);
  2672. EXPECT_EQ(StatusCode::OK_200, res->status);
  2673. }
  2674. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2675. Server svr;
  2676. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2677. res.set_content("Hello World!", "text/plain");
  2678. });
  2679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2680. auto se = detail::scope_exit([&] {
  2681. svr.stop();
  2682. thread.join();
  2683. ASSERT_FALSE(svr.is_running());
  2684. });
  2685. svr.wait_until_ready();
  2686. Client cli(HOST, PORT);
  2687. cli.set_connection_timeout(std::chrono::seconds(5));
  2688. auto res =
  2689. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2690. "application/json", [](uint64_t, uint64_t) { return false; });
  2691. ASSERT_TRUE(!res);
  2692. EXPECT_EQ(Error::Canceled, res.error());
  2693. }
  2694. TEST(CancelTest, WithCancelLargePayloadPut) {
  2695. Server svr;
  2696. svr.set_payload_max_length(200 * 1024 * 1024);
  2697. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2698. res.set_content(LARGE_DATA, "text/plain");
  2699. });
  2700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2701. auto se = detail::scope_exit([&] {
  2702. svr.stop();
  2703. thread.join();
  2704. ASSERT_FALSE(svr.is_running());
  2705. });
  2706. svr.wait_until_ready();
  2707. Client cli(HOST, PORT);
  2708. cli.set_payload_max_length(200 * 1024 * 1024);
  2709. cli.set_connection_timeout(std::chrono::seconds(5));
  2710. auto res =
  2711. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2712. "application/json", [](uint64_t, uint64_t) { return false; });
  2713. ASSERT_TRUE(!res);
  2714. EXPECT_EQ(Error::Canceled, res.error());
  2715. }
  2716. TEST(CancelTest, NoCancelPatch) {
  2717. Server svr;
  2718. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2719. res.set_content("Hello World!", "text/plain");
  2720. });
  2721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2722. auto se = detail::scope_exit([&] {
  2723. svr.stop();
  2724. thread.join();
  2725. ASSERT_FALSE(svr.is_running());
  2726. });
  2727. svr.wait_until_ready();
  2728. Client cli(HOST, PORT);
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. auto res =
  2731. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2732. "application/json", [](uint64_t, uint64_t) { return true; });
  2733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2734. EXPECT_EQ("Hello World!", res->body);
  2735. EXPECT_EQ(StatusCode::OK_200, res->status);
  2736. }
  2737. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2738. Server svr;
  2739. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2740. res.set_content("Hello World!", "text/plain");
  2741. });
  2742. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2743. auto se = detail::scope_exit([&] {
  2744. svr.stop();
  2745. thread.join();
  2746. ASSERT_FALSE(svr.is_running());
  2747. });
  2748. svr.wait_until_ready();
  2749. Client cli(HOST, PORT);
  2750. cli.set_connection_timeout(std::chrono::seconds(5));
  2751. auto res =
  2752. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2753. "application/json", [](uint64_t, uint64_t) { return false; });
  2754. ASSERT_TRUE(!res);
  2755. EXPECT_EQ(Error::Canceled, res.error());
  2756. }
  2757. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2758. Server svr;
  2759. svr.set_payload_max_length(200 * 1024 * 1024);
  2760. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2761. res.set_content(LARGE_DATA, "text/plain");
  2762. });
  2763. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2764. auto se = detail::scope_exit([&] {
  2765. svr.stop();
  2766. thread.join();
  2767. ASSERT_FALSE(svr.is_running());
  2768. });
  2769. svr.wait_until_ready();
  2770. Client cli(HOST, PORT);
  2771. cli.set_payload_max_length(200 * 1024 * 1024);
  2772. cli.set_connection_timeout(std::chrono::seconds(5));
  2773. auto res =
  2774. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2775. "application/json", [](uint64_t, uint64_t) { return false; });
  2776. ASSERT_TRUE(!res);
  2777. EXPECT_EQ(Error::Canceled, res.error());
  2778. }
  2779. TEST(CancelTest, NoCancelDelete) {
  2780. Server svr;
  2781. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2782. res.set_content("Hello World!", "text/plain");
  2783. });
  2784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2785. auto se = detail::scope_exit([&] {
  2786. svr.stop();
  2787. thread.join();
  2788. ASSERT_FALSE(svr.is_running());
  2789. });
  2790. svr.wait_until_ready();
  2791. Client cli(HOST, PORT);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return true; });
  2796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2797. EXPECT_EQ("Hello World!", res->body);
  2798. EXPECT_EQ(StatusCode::OK_200, res->status);
  2799. }
  2800. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2801. Server svr;
  2802. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2803. res.set_content("Hello World!", "text/plain");
  2804. });
  2805. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2806. auto se = detail::scope_exit([&] {
  2807. svr.stop();
  2808. thread.join();
  2809. ASSERT_FALSE(svr.is_running());
  2810. });
  2811. svr.wait_until_ready();
  2812. Client cli(HOST, PORT);
  2813. cli.set_connection_timeout(std::chrono::seconds(5));
  2814. auto res =
  2815. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2816. "application/json", [](uint64_t, uint64_t) { return false; });
  2817. ASSERT_TRUE(!res);
  2818. EXPECT_EQ(Error::Canceled, res.error());
  2819. }
  2820. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2821. Server svr;
  2822. svr.set_payload_max_length(200 * 1024 * 1024);
  2823. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2824. res.set_content(LARGE_DATA, "text/plain");
  2825. });
  2826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2827. auto se = detail::scope_exit([&] {
  2828. svr.stop();
  2829. thread.join();
  2830. ASSERT_FALSE(svr.is_running());
  2831. });
  2832. svr.wait_until_ready();
  2833. Client cli(HOST, PORT);
  2834. cli.set_payload_max_length(200 * 1024 * 1024);
  2835. cli.set_connection_timeout(std::chrono::seconds(5));
  2836. auto res =
  2837. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2838. "application/json", [](uint64_t, uint64_t) { return false; });
  2839. ASSERT_TRUE(!res);
  2840. EXPECT_EQ(Error::Canceled, res.error());
  2841. }
  2842. static std::string remove_whitespace(const std::string &input) {
  2843. std::string output;
  2844. output.reserve(input.size());
  2845. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2846. [](unsigned char c) { return !std::isspace(c); });
  2847. return output;
  2848. }
  2849. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2850. auto host = "httpbingo.org";
  2851. auto path = std::string{"/basic-auth/hello/world"};
  2852. #ifdef CPPHTTPLIB_SSL_ENABLED
  2853. auto port = 443;
  2854. SSLClient cli(host, port);
  2855. #else
  2856. auto port = 80;
  2857. Client cli(host, port);
  2858. #endif
  2859. {
  2860. auto res = cli.Get(path);
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2863. }
  2864. {
  2865. auto res = cli.Get(
  2866. path, Headers{make_basic_authentication_header("hello", "world")});
  2867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2868. auto body = remove_whitespace(res->body);
  2869. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2870. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2871. EXPECT_EQ(StatusCode::OK_200, res->status);
  2872. }
  2873. {
  2874. cli.set_basic_auth("hello", "world");
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. auto body = remove_whitespace(res->body);
  2878. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2879. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2880. EXPECT_EQ(StatusCode::OK_200, res->status);
  2881. }
  2882. {
  2883. cli.set_basic_auth("hello", "bad");
  2884. auto res = cli.Get(path);
  2885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2886. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2887. }
  2888. {
  2889. cli.set_basic_auth("bad", "world");
  2890. auto res = cli.Get(path);
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2893. }
  2894. }
  2895. #ifdef CPPHTTPLIB_SSL_ENABLED
  2896. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2897. auto host = "httpbingo.org";
  2898. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2899. auto paths = std::vector<std::string>{
  2900. "/digest-auth/auth/hello/world/MD5",
  2901. "/digest-auth/auth/hello/world/SHA-256",
  2902. };
  2903. auto port = 443;
  2904. SSLClient cli(host, port);
  2905. {
  2906. auto res = cli.Get(unauth_path);
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2909. }
  2910. {
  2911. cli.set_digest_auth("hello", "world");
  2912. for (const auto &path : paths) {
  2913. auto res = cli.Get(path.c_str());
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. auto body = remove_whitespace(res->body);
  2916. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2917. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. }
  2920. cli.set_digest_auth("hello", "bad");
  2921. for (const auto &path : paths) {
  2922. auto res = cli.Get(path.c_str());
  2923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2924. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2925. }
  2926. }
  2927. }
  2928. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2929. // comma-separated list of challenges, and each challenge may itself carry a
  2930. // comma-separated auth-param list, so a server can legally offer Basic
  2931. // before Digest, either as two field lines or packed into one. Runs one 401
  2932. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2933. // value() joins them in receipt order) and checks that the retry carries a
  2934. // well-formed Digest Authorization header naming expected_realm.
  2935. static void
  2936. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2937. const std::string &expected_realm) {
  2938. std::atomic<int> hits{0};
  2939. Server svr;
  2940. svr.Get("/x", [&](const Request &req, Response &res) {
  2941. if (++hits == 1) {
  2942. res.status = StatusCode::Unauthorized_401;
  2943. for (const auto &challenge : challenges) {
  2944. res.set_header("WWW-Authenticate", challenge);
  2945. }
  2946. } else {
  2947. auto authorization = req.get_header_value("Authorization");
  2948. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2949. EXPECT_NE(std::string::npos,
  2950. authorization.find("realm=\"" + expected_realm + "\""));
  2951. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2952. res.set_content("ok", "text/plain");
  2953. }
  2954. });
  2955. auto port = svr.bind_to_any_port(HOST);
  2956. std::thread t([&]() { svr.listen_after_bind(); });
  2957. auto se = detail::scope_exit([&] {
  2958. svr.stop();
  2959. t.join();
  2960. });
  2961. svr.wait_until_ready();
  2962. Client cli(HOST, port);
  2963. cli.set_digest_auth("hello", "world");
  2964. auto res = cli.Get("/x");
  2965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2966. EXPECT_EQ(2, hits.load());
  2967. }
  2968. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2969. static const char *kDigestChallenge =
  2970. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2971. "algorithm=MD5";
  2972. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2973. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2974. "testrealm");
  2975. }
  2976. // Same challenge list with the schemes in the opposite order, to make sure
  2977. // the fix above didn't just special-case "Basic first".
  2978. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2979. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2980. "testrealm");
  2981. }
  2982. // A comma inside a quoted auth-param value must not be mistaken for the
  2983. // separator between two challenges (or two auth-params).
  2984. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2985. run_digest_challenge_list_test(
  2986. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2987. "algorithm=MD5"},
  2988. "test,realm");
  2989. }
  2990. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2991. // the params and leaves out the fragment.
  2992. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2993. Server svr;
  2994. std::string uri, target;
  2995. svr.Get("/a b", [&](const Request &req, Response &res) {
  2996. auto auth = req.get_header_value("Authorization");
  2997. if (auth.empty()) {
  2998. res.status = StatusCode::Unauthorized_401;
  2999. res.set_header("WWW-Authenticate",
  3000. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3001. return;
  3002. }
  3003. auto b = auth.find("uri=\"") + 5;
  3004. uri = auth.substr(b, auth.find('"', b) - b);
  3005. target = req.target;
  3006. });
  3007. auto port = svr.bind_to_any_port(HOST);
  3008. std::thread t([&]() { svr.listen_after_bind(); });
  3009. auto se = detail::scope_exit([&] {
  3010. svr.stop();
  3011. t.join();
  3012. });
  3013. svr.wait_until_ready();
  3014. Client cli(HOST, port);
  3015. cli.set_digest_auth("hello", "world");
  3016. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3018. EXPECT_EQ("/a%20b?x=1", target);
  3019. EXPECT_EQ(target, uri);
  3020. }
  3021. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3022. // make_digest_authentication_header() dereferences both unconditionally, so
  3023. // a server sending a challenge missing either one must not be treated as
  3024. // usable -- doing so used to crash the client with std::out_of_range.
  3025. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3026. Server svr;
  3027. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3028. res.status = StatusCode::Unauthorized_401;
  3029. res.set_header("WWW-Authenticate", challenge);
  3030. });
  3031. auto port = svr.bind_to_any_port(HOST);
  3032. std::thread t([&]() { svr.listen_after_bind(); });
  3033. auto se = detail::scope_exit([&] {
  3034. svr.stop();
  3035. t.join();
  3036. });
  3037. svr.wait_until_ready();
  3038. Client cli(HOST, port);
  3039. cli.set_digest_auth("hello", "world");
  3040. auto res = cli.Get("/x");
  3041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3042. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3043. }
  3044. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3045. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3046. }
  3047. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3048. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3049. }
  3050. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3051. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3052. }
  3053. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3054. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3055. // when storing the values, so the header builder has to re-escape them (and
  3056. // keep algorithm a bare token); otherwise the value breaks out of its
  3057. // quoted-string and injects extra auth-params into the client's Authorization.
  3058. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3059. std::atomic<int> hits{0};
  3060. std::string authorization;
  3061. Server svr;
  3062. svr.Get("/x", [&](const Request &req, Response &res) {
  3063. if (++hits == 1) {
  3064. res.status = StatusCode::Unauthorized_401;
  3065. // On the wire the quotes embedded in the values are backslash-escaped.
  3066. res.set_header("WWW-Authenticate",
  3067. "Digest realm=\"testrealm\", "
  3068. "nonce=\"n\\\"; injected=\\\"x\", "
  3069. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3070. } else {
  3071. authorization = req.get_header_value("Authorization");
  3072. res.set_content("ok", "text/plain");
  3073. }
  3074. });
  3075. auto port = svr.bind_to_any_port(HOST);
  3076. std::thread t([&]() { svr.listen_after_bind(); });
  3077. auto se = detail::scope_exit([&] {
  3078. svr.stop();
  3079. t.join();
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(HOST, port);
  3083. cli.set_digest_auth("hello", "world");
  3084. auto res = cli.Get("/x");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(2, hits.load());
  3087. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3088. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3089. // inside its quoted-string rather than starting an "injected" auth-param.
  3090. EXPECT_NE(std::string::npos,
  3091. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3092. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3093. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3094. }
  3095. #endif
  3096. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3097. auto host = "google.com";
  3098. auto another_host = "example.com";
  3099. auto wrong_ip = "0.0.0.0";
  3100. #ifdef CPPHTTPLIB_SSL_ENABLED
  3101. SSLClient cli(host);
  3102. #else
  3103. Client cli(host);
  3104. #endif
  3105. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3106. auto res = cli.Get("/");
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3109. }
  3110. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3111. auto host = "google.com";
  3112. auto wrong_ip = "0.0.0.0";
  3113. #ifdef CPPHTTPLIB_SSL_ENABLED
  3114. SSLClient cli(host);
  3115. #else
  3116. Client cli(host);
  3117. #endif
  3118. cli.set_hostname_addr_map({{host, wrong_ip}});
  3119. auto res = cli.Get("/");
  3120. ASSERT_TRUE(!res);
  3121. EXPECT_EQ(Error::Connection, res.error());
  3122. }
  3123. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3124. // A mapped value that is not an IP literal must be resolved. "localhost"
  3125. // resolves from the hosts file, so this test needs no external DNS.
  3126. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3127. auto host = "target.invalid";
  3128. Server svr;
  3129. std::string received_host;
  3130. svr.Get("/hi", [&](const Request &req, Response &res) {
  3131. received_host = req.get_header_value("Host");
  3132. res.set_content("Hello World!", "text/plain");
  3133. });
  3134. auto port = svr.bind_to_any_port(HOST);
  3135. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3136. auto se = detail::scope_exit([&] {
  3137. svr.stop();
  3138. thread.join();
  3139. ASSERT_FALSE(svr.is_running());
  3140. });
  3141. svr.wait_until_ready();
  3142. Client cli(host, port);
  3143. cli.set_hostname_addr_map({{host, HOST}});
  3144. auto res = cli.Get("/hi");
  3145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3146. EXPECT_EQ(StatusCode::OK_200, res->status);
  3147. // The mapping only redirects the connection; the identity stays host_.
  3148. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3149. }
  3150. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3151. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3152. auto host = "target.invalid";
  3153. Server svr;
  3154. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3155. res.set_content("Hello World!", "text/plain");
  3156. });
  3157. auto port = svr.bind_to_any_port("127.0.0.1");
  3158. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3159. auto se = detail::scope_exit([&] {
  3160. svr.stop();
  3161. thread.join();
  3162. ASSERT_FALSE(svr.is_running());
  3163. });
  3164. svr.wait_until_ready();
  3165. Client cli(host, port);
  3166. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3167. auto res = cli.Get("/hi");
  3168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3169. EXPECT_EQ(StatusCode::OK_200, res->status);
  3170. }
  3171. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3172. // An empty mapped value must leave host_ as the connection target. Without
  3173. // that guard the empty value would become the host argument, getaddrinfo
  3174. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3175. // loopback - silently connecting somewhere the caller never asked for.
  3176. // The server listens on loopback, so such a fallback would succeed and is
  3177. // therefore observable as a failure of this test.
  3178. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3179. Server svr;
  3180. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3181. res.set_content("Hello World!", "text/plain");
  3182. });
  3183. auto port = svr.bind_to_any_port(HOST);
  3184. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3185. auto se = detail::scope_exit([&] {
  3186. svr.stop();
  3187. thread.join();
  3188. ASSERT_FALSE(svr.is_running());
  3189. });
  3190. svr.wait_until_ready();
  3191. Client cli(blackhole, port);
  3192. cli.set_hostname_addr_map({{blackhole, ""}});
  3193. cli.set_connection_timeout(1);
  3194. auto res = cli.Get("/hi");
  3195. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3196. }
  3197. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3198. auto host = "httpbingo.org";
  3199. auto path = std::string{"/absolute-redirect/3"};
  3200. #ifdef CPPHTTPLIB_SSL_ENABLED
  3201. SSLClient cli(host);
  3202. #else
  3203. Client cli(host);
  3204. #endif
  3205. cli.set_follow_location(true);
  3206. auto res = cli.Get(path);
  3207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3208. EXPECT_EQ(StatusCode::OK_200, res->status);
  3209. }
  3210. TEST(RedirectTest, Redirect_Online) {
  3211. auto host = "httpbingo.org";
  3212. auto path = std::string{"/redirect/3"};
  3213. #ifdef CPPHTTPLIB_SSL_ENABLED
  3214. SSLClient cli(host);
  3215. #else
  3216. Client cli(host);
  3217. #endif
  3218. cli.set_follow_location(true);
  3219. auto res = cli.Get(path);
  3220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. }
  3223. TEST(RelativeRedirectTest, Redirect_Online) {
  3224. auto host = "httpbingo.org";
  3225. auto path = std::string{"/relative-redirect/3"};
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. SSLClient cli(host);
  3228. #else
  3229. Client cli(host);
  3230. #endif
  3231. cli.set_follow_location(true);
  3232. auto res = cli.Get(path);
  3233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. }
  3236. TEST(TooManyRedirectTest, Redirect_Online) {
  3237. auto host = "httpbingo.org";
  3238. auto path = std::string{"/redirect/21"};
  3239. #ifdef CPPHTTPLIB_SSL_ENABLED
  3240. SSLClient cli(host);
  3241. #else
  3242. Client cli(host);
  3243. #endif
  3244. cli.set_follow_location(true);
  3245. auto res = cli.Get(path);
  3246. ASSERT_TRUE(!res);
  3247. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3248. }
  3249. #ifdef CPPHTTPLIB_SSL_ENABLED
  3250. TEST(YahooRedirectTest, Redirect_Online) {
  3251. Client cli("yahoo.com");
  3252. auto res = cli.Get("/");
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3255. cli.set_follow_location(true);
  3256. res = cli.Get("/");
  3257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3258. EXPECT_EQ(StatusCode::OK_200, res->status);
  3259. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3260. }
  3261. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3262. #define REDIR_HOST "httpbingo.org"
  3263. #define REDIR_PATH "/redirect-to"
  3264. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3265. SSLClient cli(REDIR_HOST);
  3266. cli.set_follow_location(true);
  3267. auto res =
  3268. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. }
  3272. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3273. SSLClient cli(REDIR_HOST);
  3274. cli.set_follow_location(true);
  3275. Params params;
  3276. params.emplace("url", "http://example.com");
  3277. params.emplace("status_code", "302");
  3278. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3283. SSLClient cli(REDIR_HOST);
  3284. cli.set_follow_location(true);
  3285. Params params;
  3286. params.emplace("url", "http://example.com");
  3287. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::OK_200, res->status);
  3290. }
  3291. TEST(UrlWithSpace, Redirect_Online) {
  3292. SSLClient cli("edge.forgecdn.net");
  3293. cli.set_follow_location(true);
  3294. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3298. }
  3299. #endif
  3300. #if !defined(_WIN32) && !defined(_WIN64)
  3301. TEST(ReceiveSignals, Signal) {
  3302. auto setupSignalHandlers = []() {
  3303. struct sigaction act;
  3304. sigemptyset(&act.sa_mask);
  3305. act.sa_flags = SA_SIGINFO;
  3306. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3307. switch (sig) {
  3308. case SIGINT:
  3309. default: break;
  3310. }
  3311. };
  3312. ::sigaction(SIGINT, &act, nullptr);
  3313. };
  3314. Server svr;
  3315. int port = 0;
  3316. auto thread = std::thread([&]() {
  3317. setupSignalHandlers();
  3318. port = svr.bind_to_any_port(HOST);
  3319. svr.listen_after_bind();
  3320. });
  3321. auto se = detail::scope_exit([&] {
  3322. svr.stop();
  3323. thread.join();
  3324. ASSERT_FALSE(svr.is_running());
  3325. });
  3326. svr.wait_until_ready();
  3327. ASSERT_TRUE(svr.is_running());
  3328. pthread_kill(thread.native_handle(), SIGINT);
  3329. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3330. ASSERT_TRUE(svr.is_running());
  3331. }
  3332. #endif
  3333. TEST(RedirectToDifferentPort, Redirect) {
  3334. Server svr1;
  3335. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3336. res.set_content("Hello World!", "text/plain");
  3337. });
  3338. int svr1_port = 0;
  3339. auto thread1 = std::thread([&]() {
  3340. svr1_port = svr1.bind_to_any_port(HOST);
  3341. svr1.listen_after_bind();
  3342. });
  3343. Server svr2;
  3344. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3345. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3346. });
  3347. int svr2_port = 0;
  3348. auto thread2 = std::thread([&]() {
  3349. svr2_port = svr2.bind_to_any_port(HOST);
  3350. svr2.listen_after_bind();
  3351. });
  3352. auto se = detail::scope_exit([&] {
  3353. svr2.stop();
  3354. thread2.join();
  3355. svr1.stop();
  3356. thread1.join();
  3357. ASSERT_FALSE(svr2.is_running());
  3358. ASSERT_FALSE(svr1.is_running());
  3359. });
  3360. svr1.wait_until_ready();
  3361. svr2.wait_until_ready();
  3362. Client cli("localhost", svr2_port);
  3363. cli.set_follow_location(true);
  3364. auto res = cli.Get("/2");
  3365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3366. EXPECT_EQ(StatusCode::OK_200, res->status);
  3367. EXPECT_EQ("Hello World!", res->body);
  3368. }
  3369. // GET /redir on one server redirects to /target on another port, so the
  3370. // client follows it with a new client.
  3371. static Result
  3372. GetThroughRedirectToDifferentPort(Server::Handler target,
  3373. const std::function<void(Client &)> &setup,
  3374. const Headers &headers = Headers()) {
  3375. Server target_svr;
  3376. target_svr.Get("/target", target);
  3377. int target_port = 0;
  3378. auto target_thread = std::thread([&]() {
  3379. target_port = target_svr.bind_to_any_port(HOST);
  3380. target_svr.listen_after_bind();
  3381. });
  3382. Server origin_svr;
  3383. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3384. res.set_redirect(
  3385. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3386. });
  3387. int origin_port = 0;
  3388. auto origin_thread = std::thread([&]() {
  3389. origin_port = origin_svr.bind_to_any_port(HOST);
  3390. origin_svr.listen_after_bind();
  3391. });
  3392. auto se = detail::scope_exit([&] {
  3393. origin_svr.stop();
  3394. origin_thread.join();
  3395. target_svr.stop();
  3396. target_thread.join();
  3397. });
  3398. target_svr.wait_until_ready();
  3399. origin_svr.wait_until_ready();
  3400. Client cli("localhost", origin_port);
  3401. cli.set_follow_location(true);
  3402. setup(cli);
  3403. return cli.Get("/redir", headers);
  3404. }
  3405. static void
  3406. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3407. std::string captured_authorization;
  3408. auto result = GetThroughRedirectToDifferentPort(
  3409. [&](const Request &req, Response &res) {
  3410. captured_authorization = req.get_header_value("Authorization");
  3411. res.set_content("OK", "text/plain");
  3412. },
  3413. set_auth);
  3414. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3415. EXPECT_EQ(StatusCode::OK_200, result->status);
  3416. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3417. EXPECT_TRUE(captured_authorization.empty());
  3418. }
  3419. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3420. TestDoNotForwardCredentialsOnRedirect(
  3421. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3422. }
  3423. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3424. TestDoNotForwardCredentialsOnRedirect(
  3425. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3426. }
  3427. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3428. std::string captured_cookie;
  3429. auto result = GetThroughRedirectToDifferentPort(
  3430. [&](const Request &req, Response &res) {
  3431. captured_cookie = req.get_header_value("Cookie");
  3432. res.set_content("OK", "text/plain");
  3433. },
  3434. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3435. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3436. EXPECT_EQ(StatusCode::OK_200, result->status);
  3437. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3438. EXPECT_TRUE(captured_cookie.empty());
  3439. }
  3440. TEST(RedirectToSamePort, ForwardCookie) {
  3441. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3442. // header so that ordinary session flows keep working.
  3443. Server svr;
  3444. std::string captured_cookie;
  3445. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3446. res.set_redirect("/target", 302);
  3447. });
  3448. svr.Get("/target", [&](const Request &req, Response &res) {
  3449. captured_cookie = req.get_header_value("Cookie");
  3450. res.set_content("OK", "text/plain");
  3451. });
  3452. auto port = svr.bind_to_any_port(HOST);
  3453. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3454. auto se = detail::scope_exit([&] {
  3455. svr.stop();
  3456. thread.join();
  3457. ASSERT_FALSE(svr.is_running());
  3458. });
  3459. svr.wait_until_ready();
  3460. Client cli(HOST, port);
  3461. cli.set_follow_location(true);
  3462. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3463. auto res = cli.Get("/redir", headers);
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ(StatusCode::OK_200, res->status);
  3466. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3467. }
  3468. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3469. std::string authorization;
  3470. std::string trace_id;
  3471. auto result = GetThroughRedirectToDifferentPort(
  3472. [&](const Request &req, Response &res) {
  3473. authorization = req.get_header_value("Authorization");
  3474. trace_id = req.get_header_value("X-Trace-Id");
  3475. res.set_content("OK", "text/plain");
  3476. },
  3477. [](Client &cli) {
  3478. cli.set_default_headers(
  3479. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3480. });
  3481. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3482. EXPECT_EQ(StatusCode::OK_200, result->status);
  3483. // Like a header given with the request, a default one goes along unless it
  3484. // carries credentials (RFC 9110 15.4).
  3485. EXPECT_TRUE(authorization.empty());
  3486. EXPECT_EQ("42", trace_id);
  3487. }
  3488. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3489. auto result = GetThroughRedirectToDifferentPort(
  3490. [](const Request &, Response &res) {
  3491. res.set_content(std::string(2048, 'x'), "text/plain");
  3492. },
  3493. [](Client &cli) { cli.set_payload_max_length(1024); });
  3494. EXPECT_FALSE(result);
  3495. }
  3496. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3497. auto result = GetThroughRedirectToDifferentPort(
  3498. [](const Request &req, Response &res) {
  3499. // Answer after a second, or once the client gives up.
  3500. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3501. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3502. }
  3503. res.set_content("late", "text/plain");
  3504. },
  3505. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3506. ASSERT_FALSE(result);
  3507. EXPECT_EQ(Error::Read, result.error());
  3508. }
  3509. #ifdef CPPHTTPLIB_SSL_ENABLED
  3510. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3511. auto result = GetThroughRedirectToDifferentPort(
  3512. [](const Request &, Response &res) {
  3513. res.status = StatusCode::Unauthorized_401;
  3514. res.set_header("WWW-Authenticate",
  3515. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3516. },
  3517. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3518. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3519. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3520. }
  3521. #endif
  3522. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3523. Server svr;
  3524. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3525. // Port number that overflows int — should not crash
  3526. res.set_redirect("http://localhost:99999999999999999999/target");
  3527. });
  3528. auto port = svr.bind_to_any_port(HOST);
  3529. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3530. auto se = detail::scope_exit([&] {
  3531. svr.stop();
  3532. thread.join();
  3533. ASSERT_FALSE(svr.is_running());
  3534. });
  3535. svr.wait_until_ready();
  3536. Client cli(HOST, port);
  3537. cli.set_follow_location(true);
  3538. auto res = cli.Get("/redir");
  3539. // Should fail gracefully, not crash (no valid response due to bad port)
  3540. EXPECT_FALSE(res);
  3541. }
  3542. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3543. Server svr;
  3544. auto port = svr.bind_to_any_port(HOST);
  3545. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3546. // The server's own port followed by junk must not be followed
  3547. res.set_redirect("http://" + std::string(HOST) + ":" +
  3548. std::to_string(port) + "junk/target");
  3549. });
  3550. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3551. res.set_content("target", "text/plain");
  3552. });
  3553. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3554. auto se = detail::scope_exit([&] {
  3555. svr.stop();
  3556. thread.join();
  3557. ASSERT_FALSE(svr.is_running());
  3558. });
  3559. svr.wait_until_ready();
  3560. Client cli(HOST, port);
  3561. cli.set_follow_location(true);
  3562. auto res = cli.Get("/redir");
  3563. EXPECT_FALSE(res);
  3564. }
  3565. TEST(RedirectFromPageWithContent, Redirect) {
  3566. Server svr;
  3567. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3568. res.set_content("___", "text/plain");
  3569. res.set_redirect("/2");
  3570. });
  3571. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3572. res.set_content("Hello World!", "text/plain");
  3573. });
  3574. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3575. auto se = detail::scope_exit([&] {
  3576. svr.stop();
  3577. th.join();
  3578. ASSERT_FALSE(svr.is_running());
  3579. });
  3580. svr.wait_until_ready();
  3581. {
  3582. Client cli("localhost", PORT);
  3583. cli.set_follow_location(true);
  3584. std::string body;
  3585. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3586. body.append(data, data_length);
  3587. return true;
  3588. });
  3589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3590. EXPECT_EQ(StatusCode::OK_200, res->status);
  3591. EXPECT_EQ("Hello World!", body);
  3592. }
  3593. {
  3594. Client cli("localhost", PORT);
  3595. std::string body;
  3596. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3597. body.append(data, data_length);
  3598. return true;
  3599. });
  3600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3601. EXPECT_EQ(StatusCode::Found_302, res->status);
  3602. EXPECT_EQ("___", body);
  3603. }
  3604. }
  3605. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3606. Server svr;
  3607. auto port_str = std::to_string(PORT);
  3608. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3609. auto expected_host = "[::1]:" + port_str;
  3610. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3611. res.set_content("___", "text/plain");
  3612. // res.set_redirect("/2");
  3613. res.set_redirect(redirect_url);
  3614. });
  3615. svr.Get("/2", [&](const Request &req, Response &res) {
  3616. auto host_header = req.headers.find("Host");
  3617. ASSERT_TRUE(host_header != req.headers.end());
  3618. EXPECT_EQ(expected_host, host_header->second);
  3619. res.set_content("Hello World!", "text/plain");
  3620. });
  3621. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3622. auto se = detail::scope_exit([&] {
  3623. svr.stop();
  3624. th.join();
  3625. ASSERT_FALSE(svr.is_running());
  3626. });
  3627. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3628. // actually starts anything, so the condition !svr.is_running() will
  3629. // always remain true, and the loop never stops.
  3630. // This basically counts how many milliseconds have passed since the
  3631. // call to svr.listen(), and if after 5 seconds nothing started yet
  3632. // aborts the test.
  3633. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3634. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3635. ASSERT_LT(milliseconds, 5000U);
  3636. }
  3637. {
  3638. Client cli("::1", PORT);
  3639. cli.set_follow_location(true);
  3640. std::string body;
  3641. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3642. body.append(data, data_length);
  3643. return true;
  3644. });
  3645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3646. EXPECT_EQ(StatusCode::OK_200, res->status);
  3647. EXPECT_EQ("Hello World!", body);
  3648. }
  3649. {
  3650. Client cli("::1", PORT);
  3651. std::string body;
  3652. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3653. body.append(data, data_length);
  3654. return true;
  3655. });
  3656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3657. EXPECT_EQ(StatusCode::Found_302, res->status);
  3658. EXPECT_EQ("___", body);
  3659. }
  3660. }
  3661. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3662. Server svr;
  3663. svr.Get("/foo", [](const Request &req, Response &res) {
  3664. auto a = req.params.find("a");
  3665. if (a != req.params.end()) {
  3666. res.set_content((*a).second, "text/plain");
  3667. res.status = StatusCode::OK_200;
  3668. } else {
  3669. res.status = StatusCode::BadRequest_400;
  3670. }
  3671. });
  3672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3673. auto se = detail::scope_exit([&] {
  3674. svr.stop();
  3675. thread.join();
  3676. ASSERT_FALSE(svr.is_running());
  3677. });
  3678. svr.wait_until_ready();
  3679. {
  3680. Client cli(HOST, PORT);
  3681. cli.set_path_encode(false);
  3682. auto res = cli.Get("/foo?a=explicitly+encoded");
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ(StatusCode::OK_200, res->status);
  3685. // This expects it back with a space, as the `+` won't have been
  3686. // url-encoded, and server-side the params get decoded turning `+`
  3687. // into spaces.
  3688. EXPECT_EQ("explicitly encoded", res->body);
  3689. }
  3690. }
  3691. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3692. // When path encoding is disabled the client must transmit the supplied
  3693. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3694. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3695. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3696. // than a space (0x20). Assert on the raw wire target to catch this.
  3697. Server svr;
  3698. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3699. svr.Get("/foo", [&](const Request &req, Response &res) {
  3700. EXPECT_EQ(expected_target, req.target);
  3701. res.status = StatusCode::OK_200;
  3702. });
  3703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3704. auto se = detail::scope_exit([&] {
  3705. svr.stop();
  3706. thread.join();
  3707. ASSERT_FALSE(svr.is_running());
  3708. });
  3709. svr.wait_until_ready();
  3710. {
  3711. Client cli(HOST, PORT);
  3712. cli.set_path_encode(false);
  3713. auto res = cli.Get(expected_target.c_str());
  3714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. }
  3717. }
  3718. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3719. // `open_stream()` used to skip the path encoding that the buffered send
  3720. // path applies, so the same `path` produced different bytes in the request
  3721. // line depending on which API was used. Assert the two agree.
  3722. Server svr;
  3723. std::string target;
  3724. svr.Get(".*", [&](const Request &req, Response &res) {
  3725. target = req.target;
  3726. res.status = StatusCode::OK_200;
  3727. });
  3728. auto port = svr.bind_to_any_port(HOST);
  3729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. struct {
  3737. const char *path;
  3738. const char *expected;
  3739. } cases[] = {
  3740. {"/a b?x=1", "/a%20b?x=1"},
  3741. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3742. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3743. };
  3744. for (const auto &c : cases) {
  3745. Client cli(HOST, port);
  3746. target.clear();
  3747. auto res = cli.Get(c.path);
  3748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3749. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3750. auto buffered_target = target;
  3751. target.clear();
  3752. auto handle = cli.open_stream("GET", c.path);
  3753. EXPECT_TRUE(handle.is_valid())
  3754. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3755. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3756. }
  3757. }
  3758. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3759. // The `set_path_encode(false)` contract — transmit the supplied target
  3760. // verbatim — must hold for the streaming API too.
  3761. Server svr;
  3762. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3763. std::string target;
  3764. svr.Get("/foo", [&](const Request &req, Response &res) {
  3765. target = req.target;
  3766. res.status = StatusCode::OK_200;
  3767. });
  3768. auto port = svr.bind_to_any_port(HOST);
  3769. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3770. auto se = detail::scope_exit([&] {
  3771. svr.stop();
  3772. thread.join();
  3773. ASSERT_FALSE(svr.is_running());
  3774. });
  3775. svr.wait_until_ready();
  3776. {
  3777. Client cli(HOST, port);
  3778. cli.set_path_encode(false);
  3779. auto handle = cli.open_stream("GET", expected_target);
  3780. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3781. EXPECT_EQ(expected_target, target);
  3782. }
  3783. }
  3784. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3785. // With path encoding enabled a CR/LF in the target is percent-encoded
  3786. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3787. // write_request_line still backstops `set_path_encode(false)`, which is
  3788. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3789. Server svr;
  3790. // Captured before routing: the decoded path contains a newline, which a
  3791. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3792. std::string target;
  3793. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3794. target = req.target;
  3795. res.status = StatusCode::OK_200;
  3796. return Server::HandlerResponse::Handled;
  3797. });
  3798. auto port = svr.bind_to_any_port(HOST);
  3799. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3800. auto se = detail::scope_exit([&] {
  3801. svr.stop();
  3802. thread.join();
  3803. ASSERT_FALSE(svr.is_running());
  3804. });
  3805. svr.wait_until_ready();
  3806. {
  3807. Client cli(HOST, port);
  3808. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3809. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3810. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3811. }
  3812. }
  3813. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3814. // Every control character is percent-encoded, not just CR/LF, so the target
  3815. // passes the request-target check in write_request_line.
  3816. Server svr;
  3817. std::string target;
  3818. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3819. target = req.target;
  3820. res.status = StatusCode::OK_200;
  3821. return Server::HandlerResponse::Handled;
  3822. });
  3823. auto port = svr.bind_to_any_port(HOST);
  3824. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3825. auto se = detail::scope_exit([&] {
  3826. svr.stop();
  3827. thread.join();
  3828. ASSERT_FALSE(svr.is_running());
  3829. });
  3830. svr.wait_until_ready();
  3831. {
  3832. Client cli(HOST, port);
  3833. auto res = cli.Get("/a\tb\x1b\x7f");
  3834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3835. EXPECT_EQ("/a%09b%1B%7F", target);
  3836. }
  3837. }
  3838. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3839. // Nothing may reach the wire: a raw CR/LF target would split the request
  3840. // line and inject headers.
  3841. Server svr;
  3842. // Pre-routing so that "not called" means nothing reached the server at all,
  3843. // rather than merely failing to match a handler pattern.
  3844. auto handler_called = false;
  3845. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3846. handler_called = true;
  3847. res.status = StatusCode::OK_200;
  3848. return Server::HandlerResponse::Handled;
  3849. });
  3850. auto port = svr.bind_to_any_port(HOST);
  3851. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3852. auto se = detail::scope_exit([&] {
  3853. svr.stop();
  3854. thread.join();
  3855. ASSERT_FALSE(svr.is_running());
  3856. });
  3857. svr.wait_until_ready();
  3858. {
  3859. Client cli(HOST, port);
  3860. cli.set_path_encode(false);
  3861. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3862. EXPECT_FALSE(handle.is_valid());
  3863. EXPECT_EQ(Error::Write, handle.error);
  3864. EXPECT_FALSE(handler_called);
  3865. }
  3866. }
  3867. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3868. // Which of the two branches runs is decided by whether the query component
  3869. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3870. // an empty query and must still fall back to building one from
  3871. // `req.params`, while a non-empty query must win over `req.params`.
  3872. Server svr;
  3873. std::string target;
  3874. svr.Get("/foo", [&](const Request &req, Response &res) {
  3875. target = req.target;
  3876. res.status = StatusCode::OK_200;
  3877. });
  3878. auto port = svr.bind_to_any_port(HOST);
  3879. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3880. auto se = detail::scope_exit([&] {
  3881. svr.stop();
  3882. thread.join();
  3883. ASSERT_FALSE(svr.is_running());
  3884. });
  3885. svr.wait_until_ready();
  3886. {
  3887. // Trailing `?` -> empty query component -> `req.params` is used.
  3888. Client cli(HOST, port);
  3889. Request req;
  3890. req.method = "GET";
  3891. req.path = "/foo?";
  3892. req.params.emplace("a", "1");
  3893. target.clear();
  3894. auto res = cli.send(req);
  3895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3896. EXPECT_EQ("/foo?a=1", target);
  3897. }
  3898. {
  3899. // Non-empty query in `req.path` -> `req.params` is not appended.
  3900. Client cli(HOST, port);
  3901. Request req;
  3902. req.method = "GET";
  3903. req.path = "/foo?b=2";
  3904. req.params.emplace("a", "1");
  3905. target.clear();
  3906. auto res = cli.send(req);
  3907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3908. EXPECT_EQ("/foo?b=2", target);
  3909. }
  3910. }
  3911. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3912. Server svr;
  3913. svr.Get("/", [](const Request &req, Response &) {
  3914. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3915. });
  3916. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3917. auto se = detail::scope_exit([&] {
  3918. svr.stop();
  3919. thread.join();
  3920. ASSERT_FALSE(svr.is_running());
  3921. });
  3922. svr.wait_until_ready();
  3923. {
  3924. Client cli(HOST, PORT);
  3925. cli.set_path_encode(false);
  3926. auto res = cli.Get("/?something=%0A");
  3927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3928. EXPECT_EQ(StatusCode::OK_200, res->status);
  3929. }
  3930. }
  3931. TEST(BindServerTest, BindDualStack) {
  3932. Server svr;
  3933. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3934. res.set_content("Hello World!", "text/plain");
  3935. });
  3936. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3937. auto se = detail::scope_exit([&] {
  3938. svr.stop();
  3939. thread.join();
  3940. ASSERT_FALSE(svr.is_running());
  3941. });
  3942. svr.wait_until_ready();
  3943. {
  3944. Client cli("127.0.0.1", PORT);
  3945. auto res = cli.Get("/1");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. EXPECT_EQ("Hello World!", res->body);
  3949. }
  3950. {
  3951. Client cli("::1", PORT);
  3952. auto res = cli.Get("/1");
  3953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. }
  3958. TEST(BindServerTest, BindAndListenSeparately) {
  3959. Server svr;
  3960. int port = svr.bind_to_any_port("0.0.0.0");
  3961. ASSERT_TRUE(svr.is_valid());
  3962. ASSERT_TRUE(port > 0);
  3963. svr.stop();
  3964. }
  3965. // Reports whether anything is still listening on a loopback port. A plain
  3966. // connect() is used instead of a Client request because a socket left bound by
  3967. // mistake accepts the connection into its backlog and never answers, which
  3968. // would hang the test instead of failing it.
  3969. static bool is_loopback_port_accepting(int port) {
  3970. sockaddr_in addr{};
  3971. addr.sin_family = AF_INET;
  3972. addr.sin_port = htons(static_cast<uint16_t>(port));
  3973. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3974. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3975. EXPECT_NE(sock, INVALID_SOCKET);
  3976. if (sock == INVALID_SOCKET) { return false; }
  3977. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3978. static_cast<socklen_t>(sizeof(addr)));
  3979. detail::close_socket(sock);
  3980. return ret == 0;
  3981. }
  3982. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3983. Server svr;
  3984. auto port = svr.bind_to_any_port("127.0.0.1");
  3985. ASSERT_TRUE(port > 0);
  3986. svr.stop();
  3987. // bind_to_any_port() already called listen(2), so until stop() closed the
  3988. // descriptor the port kept accepting connections into the backlog. ASSERT
  3989. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3990. // below blocks forever in the accept loop.
  3991. ASSERT_FALSE(is_loopback_port_accepting(port));
  3992. // Nothing is left to accept on, so listen_after_bind() must report failure
  3993. // instead of returning success without ever serving.
  3994. EXPECT_FALSE(svr.listen_after_bind());
  3995. // The failed listen marks the server decommissioned, so a waiter returns
  3996. // instead of spinning forever.
  3997. svr.wait_until_ready();
  3998. }
  3999. #ifdef CPPHTTPLIB_SSL_ENABLED
  4000. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4002. CLIENT_CA_CERT_DIR);
  4003. int port = svr.bind_to_any_port("0.0.0.0");
  4004. ASSERT_TRUE(svr.is_valid());
  4005. ASSERT_TRUE(port > 0);
  4006. svr.stop();
  4007. }
  4008. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4009. // or a rejected CustomRoute() registration would not stop the server binding.
  4010. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4012. CLIENT_CA_CERT_DIR);
  4013. ASSERT_TRUE(svr.is_valid());
  4014. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4015. EXPECT_FALSE(svr.is_valid());
  4016. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4017. }
  4018. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4019. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4020. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4021. int port = svr.bind_to_any_port("0.0.0.0");
  4022. ASSERT_TRUE(svr.is_valid());
  4023. ASSERT_TRUE(port > 0);
  4024. svr.stop();
  4025. }
  4026. TEST(BindServerTest, UpdateCertsPem) {
  4027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4028. int port = svr.bind_to_any_port("0.0.0.0");
  4029. ASSERT_TRUE(svr.is_valid());
  4030. ASSERT_TRUE(port > 0);
  4031. // Read PEM files
  4032. std::string cert_pem, key_pem, ca_pem;
  4033. read_file(SERVER_CERT_FILE, cert_pem);
  4034. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4035. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4036. // Update server certificates using PEM API
  4037. ASSERT_TRUE(
  4038. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4039. ASSERT_TRUE(svr.is_valid());
  4040. svr.stop();
  4041. }
  4042. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4043. // Start server with client CA (enables client auth)
  4044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4045. ASSERT_TRUE(svr.is_valid());
  4046. bool handler_called = false;
  4047. svr.Get("/test", [&](const Request &req, Response &res) {
  4048. handler_called = true;
  4049. // Verify client certificate is present
  4050. auto cert = req.peer_cert();
  4051. EXPECT_TRUE(static_cast<bool>(cert));
  4052. res.set_content("ok", "text/plain");
  4053. });
  4054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4055. auto se = detail::scope_exit([&] {
  4056. svr.stop();
  4057. t.join();
  4058. ASSERT_FALSE(svr.is_running());
  4059. });
  4060. svr.wait_until_ready();
  4061. // Read PEM files
  4062. std::string cert_pem, key_pem, ca_pem;
  4063. read_file(SERVER_CERT_FILE, cert_pem);
  4064. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4065. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4066. // Update server certificates and client CA using PEM API while server running
  4067. ASSERT_TRUE(
  4068. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4069. // Connect with client certificate
  4070. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4071. cli.enable_server_certificate_verification(false);
  4072. cli.set_connection_timeout(30);
  4073. auto res = cli.Get("/test");
  4074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4075. ASSERT_EQ(StatusCode::OK_200, res->status);
  4076. ASSERT_TRUE(handler_called);
  4077. EXPECT_EQ("ok", res->body);
  4078. }
  4079. // Puts a CA that did not sign the client's certificate in the old one's place.
  4080. static bool replace_client_ca(SSLServer &svr) {
  4081. std::string cert_pem, key_pem, ca_pem;
  4082. read_file(SERVER_CERT_FILE, cert_pem);
  4083. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4084. read_file(SERVER_CERT2_FILE, ca_pem);
  4085. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4086. ca_pem.c_str());
  4087. }
  4088. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4089. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4090. ASSERT_TRUE(svr.is_valid());
  4091. svr.Get("/test", [](const Request &, Response &res) {
  4092. res.set_content("ok", "text/plain");
  4093. });
  4094. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. t.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. auto get = [] {
  4102. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4103. cli.enable_server_certificate_verification(false);
  4104. return cli.Get("/test");
  4105. };
  4106. ASSERT_TRUE(get());
  4107. ASSERT_TRUE(replace_client_ca(svr));
  4108. EXPECT_FALSE(get());
  4109. }
  4110. TEST(SSLClientServerTest, VerifyCallbackKeepsClientCertificateRequired) {
  4111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4112. ASSERT_TRUE(svr.is_valid());
  4113. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4114. return v.preverify_ok;
  4115. });
  4116. svr.Get("/test", [](const Request &, Response &res) {
  4117. res.set_content("ok", "text/plain");
  4118. });
  4119. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4120. auto se = detail::scope_exit([&] {
  4121. svr.stop();
  4122. t.join();
  4123. ASSERT_FALSE(svr.is_running());
  4124. });
  4125. svr.wait_until_ready();
  4126. SSLClient without_cert(HOST, PORT);
  4127. without_cert.enable_server_certificate_verification(false);
  4128. EXPECT_FALSE(without_cert.Get("/test"));
  4129. SSLClient with_cert(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4130. with_cert.enable_server_certificate_verification(false);
  4131. auto res = with_cert.Get("/test");
  4132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4133. EXPECT_EQ("ok", res->body);
  4134. }
  4135. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4136. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4137. ASSERT_TRUE(svr.is_valid());
  4138. tls::set_verify_callback(svr.tls_context(),
  4139. [](const tls::VerifyContext &) -> bool {
  4140. throw std::runtime_error("verify");
  4141. });
  4142. svr.Get("/test", [](const Request &, Response &res) {
  4143. res.set_content("ok", "text/plain");
  4144. });
  4145. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4146. auto se = detail::scope_exit([&] {
  4147. svr.stop();
  4148. t.join();
  4149. ASSERT_FALSE(svr.is_running());
  4150. });
  4151. svr.wait_until_ready();
  4152. auto get = [] {
  4153. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4154. cli.enable_server_certificate_verification(false);
  4155. return cli.Get("/test");
  4156. };
  4157. EXPECT_FALSE(get());
  4158. // The handshake is over, so an update does not wait for it.
  4159. std::string cert_pem, key_pem;
  4160. read_file(SERVER_CERT_FILE, cert_pem);
  4161. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4162. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4163. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4164. return v.preverify_ok;
  4165. });
  4166. auto res = get();
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ("ok", res->body);
  4169. }
  4170. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4171. // A client that resumes its session gets through, but not once the client CA
  4172. // has changed, as a resumed session does not show the certificate again.
  4173. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4175. ASSERT_TRUE(svr.is_valid());
  4176. svr.Get("/test", [](const Request &, Response &res) {
  4177. res.set_content("ok", "text/plain");
  4178. });
  4179. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4180. auto se = detail::scope_exit([&] {
  4181. svr.stop();
  4182. t.join();
  4183. ASSERT_FALSE(svr.is_running());
  4184. });
  4185. svr.wait_until_ready();
  4186. auto ctx = SSL_CTX_new(TLS_client_method());
  4187. auto ctx_se = detail::scope_exit([&] { SSL_CTX_free(ctx); });
  4188. ASSERT_EQ(
  4189. 1, SSL_CTX_use_certificate_file(ctx, CLIENT_CERT_FILE, SSL_FILETYPE_PEM));
  4190. ASSERT_EQ(1, SSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4191. SSL_FILETYPE_PEM));
  4192. SSL_SESSION *session = nullptr;
  4193. auto session_se = detail::scope_exit([&] { SSL_SESSION_free(session); });
  4194. // A request over a new connection, resuming `session` when there is one and
  4195. // keeping the connection's own in its place. Tells whether it was answered.
  4196. auto reused = false;
  4197. auto get = [&]() {
  4198. auto error = Error::Success;
  4199. auto sock = detail::create_client_socket(
  4200. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4201. /*connection_timeout_sec=*/5, 0,
  4202. /*read_timeout_sec=*/5, 0,
  4203. /*write_timeout_sec=*/5, 0, std::string(), error);
  4204. if (sock == INVALID_SOCKET) { return false; }
  4205. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4206. auto ssl = SSL_new(ctx);
  4207. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4208. SSL_set_fd(ssl, static_cast<int>(sock));
  4209. if (session) { SSL_set_session(ssl, session); }
  4210. if (SSL_connect(ssl) != 1) { return false; }
  4211. reused = SSL_session_reused(ssl) == 1;
  4212. // Reading the response also takes in a TLS 1.3 session ticket.
  4213. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4214. "Connection: close\r\n\r\n";
  4215. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4216. std::string res;
  4217. char buf[256];
  4218. int n;
  4219. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4220. res.append(buf, static_cast<size_t>(n));
  4221. }
  4222. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4223. SSL_shutdown(ssl);
  4224. SSL_SESSION_free(session);
  4225. session = SSL_get1_session(ssl);
  4226. return res.find("200 OK") != std::string::npos;
  4227. };
  4228. ASSERT_TRUE(get());
  4229. ASSERT_TRUE(get());
  4230. EXPECT_TRUE(reused);
  4231. ASSERT_TRUE(replace_client_ca(svr));
  4232. EXPECT_FALSE(get());
  4233. }
  4234. #endif
  4235. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4236. // wolfSSL shares its session cache between contexts, so a resumed session
  4237. // could carry a client certificate checked against another server's CA, or
  4238. // against a client CA since replaced.
  4239. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4240. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4241. ASSERT_TRUE(svr.is_valid());
  4242. // Trusts a CA that did not sign the client's certificate.
  4243. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4244. ASSERT_TRUE(other.is_valid());
  4245. for (auto s : {&svr, &other}) {
  4246. s->Get("/test", [](const Request &, Response &res) {
  4247. res.set_content("ok", "text/plain");
  4248. });
  4249. }
  4250. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4251. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4252. auto se = detail::scope_exit([&] {
  4253. other.stop();
  4254. svr.stop();
  4255. t2.join();
  4256. t.join();
  4257. });
  4258. svr.wait_until_ready();
  4259. other.wait_until_ready();
  4260. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4261. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4262. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4263. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4264. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4265. ASSERT_EQ(WOLFSSL_SUCCESS,
  4266. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4267. WOLFSSL_FILETYPE_PEM));
  4268. WOLFSSL_SESSION *session = nullptr;
  4269. auto session_se = detail::scope_exit([&] {
  4270. if (session) { wolfSSL_SESSION_free(session); }
  4271. });
  4272. // A request over a new connection, resuming `session` when there is one and
  4273. // keeping the connection's own in its place. Tells whether it was answered.
  4274. auto get = [&](int port) {
  4275. auto error = Error::Success;
  4276. auto sock = detail::create_client_socket(
  4277. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4278. /*connection_timeout_sec=*/5, 0,
  4279. /*read_timeout_sec=*/5, 0,
  4280. /*write_timeout_sec=*/5, 0, std::string(), error);
  4281. if (sock == INVALID_SOCKET) { return false; }
  4282. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4283. auto ssl = wolfSSL_new(ctx);
  4284. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4285. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4286. if (session) { wolfSSL_set_session(ssl, session); }
  4287. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4288. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4289. "Connection: close\r\n\r\n";
  4290. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4291. std::string res;
  4292. char buf[256];
  4293. int n;
  4294. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4295. res.append(buf, static_cast<size_t>(n));
  4296. }
  4297. wolfSSL_shutdown(ssl);
  4298. if (session) { wolfSSL_SESSION_free(session); }
  4299. session = wolfSSL_get1_session(ssl);
  4300. return res.find("200 OK") != std::string::npos;
  4301. };
  4302. ASSERT_TRUE(get(PORT));
  4303. EXPECT_FALSE(get(PORT + 1));
  4304. ASSERT_TRUE(get(PORT));
  4305. ASSERT_TRUE(replace_client_ca(svr));
  4306. EXPECT_FALSE(get(PORT));
  4307. }
  4308. #endif
  4309. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4311. ASSERT_TRUE(svr.is_valid());
  4312. svr.Get("/test", [](const Request &, Response &res) {
  4313. res.set_content("ok", "text/plain");
  4314. });
  4315. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4316. auto se = detail::scope_exit([&] {
  4317. svr.stop();
  4318. t.join();
  4319. ASSERT_FALSE(svr.is_running());
  4320. });
  4321. svr.wait_until_ready();
  4322. // A connection that sends no ClientHello keeps its handshake in progress,
  4323. // once the server has had a moment to start it.
  4324. auto error = Error::Success;
  4325. auto sock = detail::create_client_socket(
  4326. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4327. /*connection_timeout_sec=*/5, 0,
  4328. /*read_timeout_sec=*/5, 0,
  4329. /*write_timeout_sec=*/5, 0, std::string(), error);
  4330. ASSERT_NE(INVALID_SOCKET, sock);
  4331. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4332. std::string cert_pem, key_pem;
  4333. read_file(SERVER_CERT_FILE, cert_pem);
  4334. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4335. auto update = std::async(std::launch::async, [&]() {
  4336. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4337. });
  4338. EXPECT_EQ(std::future_status::timeout,
  4339. update.wait_for(std::chrono::milliseconds(200)));
  4340. detail::close_socket(sock);
  4341. EXPECT_TRUE(update.get());
  4342. SSLClient cli(HOST, PORT);
  4343. cli.enable_server_certificate_verification(false);
  4344. auto res = cli.Get("/test");
  4345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4346. EXPECT_EQ(StatusCode::OK_200, res->status);
  4347. }
  4348. #endif
  4349. TEST(ErrorHandlerTest, ContentLength) {
  4350. Server svr;
  4351. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4352. res.status = StatusCode::OK_200;
  4353. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4354. "text/html"); // <= Content-Length still 13
  4355. });
  4356. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4357. res.set_content("Hello World!\n", "text/plain");
  4358. res.status = 524;
  4359. });
  4360. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4361. auto se = detail::scope_exit([&] {
  4362. svr.stop();
  4363. thread.join();
  4364. ASSERT_FALSE(svr.is_running());
  4365. });
  4366. svr.wait_until_ready();
  4367. {
  4368. Client cli(HOST, PORT);
  4369. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4371. EXPECT_EQ(StatusCode::OK_200, res->status);
  4372. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4373. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4374. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4375. }
  4376. }
  4377. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4378. TEST(ExceptionTest, WithoutExceptionHandler) {
  4379. Server svr;
  4380. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4381. throw std::runtime_error("exception...");
  4382. });
  4383. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4384. throw std::runtime_error("exception\r\n...");
  4385. });
  4386. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4387. auto se = detail::scope_exit([&] {
  4388. svr.stop();
  4389. listen_thread.join();
  4390. ASSERT_FALSE(svr.is_running());
  4391. });
  4392. svr.wait_until_ready();
  4393. Client cli("localhost", PORT);
  4394. {
  4395. auto res = cli.Get("/exception");
  4396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4397. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4398. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4399. }
  4400. {
  4401. auto res = cli.Get("/unknown");
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4404. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4405. }
  4406. }
  4407. TEST(ExceptionTest, WithExceptionHandler) {
  4408. Server svr;
  4409. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4410. std::exception_ptr ep) {
  4411. EXPECT_FALSE(ep == nullptr);
  4412. try {
  4413. std::rethrow_exception(ep);
  4414. } catch (std::exception &e) {
  4415. EXPECT_EQ("abc", std::string(e.what()));
  4416. } catch (...) {}
  4417. res.status = StatusCode::InternalServerError_500;
  4418. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4419. "text/html"); // <= Content-Length still 13 at this point
  4420. });
  4421. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4422. res.set_content("Hello World!\n", "text/plain");
  4423. throw std::runtime_error("abc");
  4424. });
  4425. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4426. auto se = detail::scope_exit([&] {
  4427. svr.stop();
  4428. thread.join();
  4429. ASSERT_FALSE(svr.is_running());
  4430. });
  4431. svr.wait_until_ready();
  4432. for (size_t i = 0; i < 10; i++) {
  4433. Client cli(HOST, PORT);
  4434. for (size_t j = 0; j < 100; j++) {
  4435. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4437. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4438. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4439. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4440. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4441. }
  4442. cli.set_keep_alive(true);
  4443. for (size_t j = 0; j < 100; j++) {
  4444. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4446. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4447. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4448. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4449. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4450. }
  4451. }
  4452. }
  4453. TEST(ExceptionTest, AndErrorHandler) {
  4454. Server svr;
  4455. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4456. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4457. });
  4458. svr.set_exception_handler(
  4459. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4460. EXPECT_FALSE(ep == nullptr);
  4461. try {
  4462. std::rethrow_exception(ep);
  4463. } catch (std::exception &e) {
  4464. res.set_content(e.what(), "text/html");
  4465. } catch (...) {}
  4466. res.status = StatusCode::InternalServerError_500;
  4467. });
  4468. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4469. throw std::runtime_error("EXCEPTION");
  4470. });
  4471. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4472. res.set_content("ERROR", "text/html");
  4473. res.status = StatusCode::InternalServerError_500;
  4474. });
  4475. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4476. auto se = detail::scope_exit([&] {
  4477. svr.stop();
  4478. thread.join();
  4479. ASSERT_FALSE(svr.is_running());
  4480. });
  4481. svr.wait_until_ready();
  4482. Client cli(HOST, PORT);
  4483. {
  4484. auto res = cli.Get("/exception");
  4485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4486. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4487. EXPECT_EQ("EXCEPTION", res->body);
  4488. }
  4489. {
  4490. auto res = cli.Get("/error");
  4491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4492. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4493. EXPECT_EQ("ERROR", res->body);
  4494. }
  4495. {
  4496. auto res = cli.Get("/invalid");
  4497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4499. EXPECT_EQ("NOT_FOUND", res->body);
  4500. }
  4501. }
  4502. #endif
  4503. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4504. // process_request() wraps only routing() in a try/catch, so an exception from
  4505. // any other user callback used to unwind into the task queue - which does not
  4506. // catch - and terminate the process. Each test below runs the server on a
  4507. // single worker thread: a guard that catches the exception but still loses the
  4508. // thread would otherwise be hidden by a spare worker serving the follow-up
  4509. // request. Note that a regression here aborts the whole test binary rather
  4510. // than failing one test.
  4511. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4512. Server svr;
  4513. svr.new_task_queue = [] { return new ThreadPool(1); };
  4514. std::atomic<int> reported{0};
  4515. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4516. if (err == Error::UserCallbackException) { reported++; }
  4517. });
  4518. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4519. res.set_content_provider(
  4520. 1024, "text/plain",
  4521. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4522. sink.write("hello", 5);
  4523. throw std::runtime_error("from the content provider");
  4524. });
  4525. });
  4526. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4527. res.set_content("ok", "text/plain");
  4528. });
  4529. auto port = svr.bind_to_any_port(HOST);
  4530. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4531. auto se = detail::scope_exit([&] {
  4532. svr.stop();
  4533. listen_thread.join();
  4534. ASSERT_FALSE(svr.is_running());
  4535. });
  4536. svr.wait_until_ready();
  4537. {
  4538. Client cli(HOST, port);
  4539. cli.set_read_timeout(5, 0);
  4540. EXPECT_FALSE(cli.Get("/throw"));
  4541. }
  4542. EXPECT_TRUE(svr.is_running());
  4543. EXPECT_EQ(1, reported.load());
  4544. // A request on a fresh connection is still served.
  4545. {
  4546. Client cli(HOST, port);
  4547. auto res = cli.Get("/ok");
  4548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4549. EXPECT_EQ(StatusCode::OK_200, res->status);
  4550. EXPECT_EQ("ok", res->body);
  4551. }
  4552. }
  4553. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4554. Server svr;
  4555. svr.new_task_queue = [] { return new ThreadPool(1); };
  4556. std::atomic<bool> should_throw{true};
  4557. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4558. res.set_content("hi", "text/plain");
  4559. });
  4560. svr.set_post_routing_handler(
  4561. [&](const Request & /*req*/, Response & /*res*/) {
  4562. if (should_throw) {
  4563. throw std::runtime_error("from the post-routing handler");
  4564. }
  4565. });
  4566. auto port = svr.bind_to_any_port(HOST);
  4567. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4568. auto se = detail::scope_exit([&] {
  4569. svr.stop();
  4570. listen_thread.join();
  4571. ASSERT_FALSE(svr.is_running());
  4572. });
  4573. svr.wait_until_ready();
  4574. {
  4575. Client cli(HOST, port);
  4576. cli.set_read_timeout(5, 0);
  4577. EXPECT_FALSE(cli.Get("/hi"));
  4578. }
  4579. EXPECT_TRUE(svr.is_running());
  4580. should_throw = false;
  4581. {
  4582. Client cli(HOST, port);
  4583. auto res = cli.Get("/hi");
  4584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. EXPECT_EQ("hi", res->body);
  4587. }
  4588. }
  4589. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4590. // The guard reports the caught exception through the error logger, which is
  4591. // a user callback too. A logger that throws has to be contained as well, or
  4592. // the process would terminate from inside the catch.
  4593. Server svr;
  4594. svr.new_task_queue = [] { return new ThreadPool(1); };
  4595. std::atomic<int> reported{0};
  4596. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4597. if (err == Error::UserCallbackException) {
  4598. reported++;
  4599. throw std::runtime_error("from the error logger");
  4600. }
  4601. });
  4602. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4603. res.set_content_provider(
  4604. 1024, "text/plain",
  4605. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4606. sink.write("hello", 5);
  4607. throw std::runtime_error("from the content provider");
  4608. });
  4609. });
  4610. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4611. res.set_content("ok", "text/plain");
  4612. });
  4613. auto port = svr.bind_to_any_port(HOST);
  4614. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4615. auto se = detail::scope_exit([&] {
  4616. svr.stop();
  4617. listen_thread.join();
  4618. ASSERT_FALSE(svr.is_running());
  4619. });
  4620. svr.wait_until_ready();
  4621. {
  4622. Client cli(HOST, port);
  4623. cli.set_read_timeout(5, 0);
  4624. EXPECT_FALSE(cli.Get("/throw"));
  4625. }
  4626. EXPECT_TRUE(svr.is_running());
  4627. EXPECT_EQ(1, reported.load());
  4628. {
  4629. Client cli(HOST, port);
  4630. auto res = cli.Get("/ok");
  4631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4632. EXPECT_EQ(StatusCode::OK_200, res->status);
  4633. EXPECT_EQ("ok", res->body);
  4634. }
  4635. }
  4636. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4637. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4638. // so the exception unwinds through the ws::WebSocket object on its way to
  4639. // the guard. None of the HTTP cases above cross that.
  4640. Server svr;
  4641. svr.new_task_queue = [] { return new ThreadPool(1); };
  4642. std::atomic<int> reported{0};
  4643. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4644. if (err == Error::UserCallbackException) { reported++; }
  4645. });
  4646. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4647. throw std::runtime_error("from the WebSocket handler");
  4648. });
  4649. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4650. res.set_content("ok", "text/plain");
  4651. });
  4652. auto port = svr.bind_to_any_port(HOST);
  4653. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4654. auto se = detail::scope_exit([&] {
  4655. svr.stop();
  4656. listen_thread.join();
  4657. ASSERT_FALSE(svr.is_running());
  4658. });
  4659. svr.wait_until_ready();
  4660. {
  4661. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4662. "/ws");
  4663. auto res = client.connect();
  4664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4665. // The server dropped the connection instead of dying.
  4666. std::string msg;
  4667. EXPECT_FALSE(client.read(msg));
  4668. client.close();
  4669. }
  4670. EXPECT_TRUE(svr.is_running());
  4671. EXPECT_EQ(1, reported.load());
  4672. {
  4673. Client cli(HOST, port);
  4674. auto res = cli.Get("/ok");
  4675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4676. EXPECT_EQ(StatusCode::OK_200, res->status);
  4677. EXPECT_EQ("ok", res->body);
  4678. }
  4679. }
  4680. #ifdef CPPHTTPLIB_SSL_ENABLED
  4681. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4682. // SSLServer::process_and_close_socket() is a separate overload with its own
  4683. // guard, so it is exercised on its own.
  4684. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4685. ASSERT_TRUE(svr.is_valid());
  4686. svr.new_task_queue = [] { return new ThreadPool(1); };
  4687. std::atomic<int> reported{0};
  4688. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4689. if (err == Error::UserCallbackException) { reported++; }
  4690. });
  4691. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4692. res.set_content_provider(
  4693. 1024, "text/plain",
  4694. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4695. sink.write("hello", 5);
  4696. throw std::runtime_error("from the content provider");
  4697. });
  4698. });
  4699. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4700. res.set_content("ok", "text/plain");
  4701. });
  4702. auto port = svr.bind_to_any_port(HOST);
  4703. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4704. auto se = detail::scope_exit([&] {
  4705. svr.stop();
  4706. listen_thread.join();
  4707. ASSERT_FALSE(svr.is_running());
  4708. });
  4709. svr.wait_until_ready();
  4710. {
  4711. SSLClient cli(HOST, port);
  4712. cli.enable_server_certificate_verification(false);
  4713. cli.set_read_timeout(5, 0);
  4714. EXPECT_FALSE(cli.Get("/throw"));
  4715. }
  4716. EXPECT_TRUE(svr.is_running());
  4717. EXPECT_EQ(1, reported.load());
  4718. {
  4719. SSLClient cli(HOST, port);
  4720. cli.enable_server_certificate_verification(false);
  4721. auto res = cli.Get("/ok");
  4722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4723. EXPECT_EQ(StatusCode::OK_200, res->status);
  4724. EXPECT_EQ("ok", res->body);
  4725. }
  4726. }
  4727. #endif
  4728. #endif
  4729. TEST(NoContentTest, ContentLength) {
  4730. Server svr;
  4731. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4732. res.status = StatusCode::NoContent_204;
  4733. });
  4734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4735. auto se = detail::scope_exit([&] {
  4736. svr.stop();
  4737. thread.join();
  4738. ASSERT_FALSE(svr.is_running());
  4739. });
  4740. svr.wait_until_ready();
  4741. {
  4742. Client cli(HOST, PORT);
  4743. auto res = cli.Get("/hi");
  4744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4745. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4746. // RFC 9110 8.6: none in a 204 response
  4747. EXPECT_FALSE(res->has_header("Content-Length"));
  4748. }
  4749. }
  4750. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4751. Server svr;
  4752. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4753. res.set_header("Content-Length", "5");
  4754. res.set_content("hello world", "text/plain");
  4755. });
  4756. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4757. // A body that reads as the last chunk, were it taken as chunked
  4758. res.set_header("Transfer-Encoding", "chunked");
  4759. res.set_content("0\r\n\r\n", "text/plain");
  4760. });
  4761. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4762. res.set_header("Content-Length", "2");
  4763. res.set_content_provider(5, "text/plain",
  4764. [](size_t offset, size_t length, DataSink &sink) {
  4765. sink.write(&"hello"[offset], length);
  4766. return true;
  4767. });
  4768. });
  4769. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4770. res.set_header("Content-Length", "1234");
  4771. });
  4772. thread t = thread([&] { svr.listen(HOST, PORT); });
  4773. auto se = detail::scope_exit([&] {
  4774. svr.stop();
  4775. t.join();
  4776. ASSERT_FALSE(svr.is_running());
  4777. });
  4778. svr.wait_until_ready();
  4779. Client cli(HOST, PORT);
  4780. cli.set_read_timeout(1, 0);
  4781. auto expect_body = [&](const Result &res, const std::string &body) {
  4782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4783. EXPECT_EQ(body, res->body);
  4784. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4785. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4786. };
  4787. Headers identity{{"Accept-Encoding", ""}};
  4788. expect_body(cli.Get("/body", identity), "hello world");
  4789. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4790. expect_body(cli.Get("/body",
  4791. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4792. "he");
  4793. expect_body(cli.Get("/provider", identity), "hello");
  4794. expect_body(cli.Get("/empty", identity), "");
  4795. // A HEAD response may give the length of the body a GET would get.
  4796. auto res = cli.Head("/empty");
  4797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4798. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4799. }
  4800. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4801. Server svr;
  4802. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4803. res.set_content("short", "text/plain");
  4804. });
  4805. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4806. res.body += " with a footer";
  4807. res.set_header("Transfer-Encoding", "chunked");
  4808. });
  4809. thread t = thread([&] { svr.listen(HOST, PORT); });
  4810. auto se = detail::scope_exit([&] {
  4811. svr.stop();
  4812. t.join();
  4813. ASSERT_FALSE(svr.is_running());
  4814. });
  4815. svr.wait_until_ready();
  4816. Client cli(HOST, PORT);
  4817. cli.set_read_timeout(1, 0);
  4818. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. EXPECT_EQ("short with a footer", res->body);
  4821. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4822. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4823. }
  4824. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4825. Server svr;
  4826. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4827. res.set_header("Content-Length", "3");
  4828. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4829. sink.write("abc", 3);
  4830. sink.done();
  4831. return true;
  4832. });
  4833. });
  4834. thread t = thread([&] { svr.listen(HOST, PORT); });
  4835. auto se = detail::scope_exit([&] {
  4836. svr.stop();
  4837. t.join();
  4838. ASSERT_FALSE(svr.is_running());
  4839. });
  4840. svr.wait_until_ready();
  4841. Client cli(HOST, PORT);
  4842. cli.set_keep_alive(true);
  4843. auto res = cli.Get("/");
  4844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4845. EXPECT_EQ("abc", res->body);
  4846. EXPECT_FALSE(res->has_header("Content-Length"));
  4847. EXPECT_EQ("close", res->get_header_value("Connection"));
  4848. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4849. // No body to delimit
  4850. auto head = cli.Head("/");
  4851. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4852. EXPECT_FALSE(head->has_header("Connection"));
  4853. }
  4854. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4855. #ifdef CPPHTTPLIB_SSL_ENABLED
  4856. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4857. ASSERT_TRUE(svr.is_valid());
  4858. #else
  4859. Server svr;
  4860. #endif
  4861. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4862. if (req.path == "/routing_handler") {
  4863. res.set_header("PRE_ROUTING", "on");
  4864. res.set_content("Routing Handler", "text/plain");
  4865. return httplib::Server::HandlerResponse::Handled;
  4866. }
  4867. return httplib::Server::HandlerResponse::Unhandled;
  4868. });
  4869. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4870. res.set_content("Error", "text/html");
  4871. });
  4872. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4873. if (req.path == "/routing_handler") {
  4874. res.set_header("POST_ROUTING", "on");
  4875. }
  4876. });
  4877. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4878. res.set_content("Hello World!\n", "text/plain");
  4879. });
  4880. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4881. auto se = detail::scope_exit([&] {
  4882. svr.stop();
  4883. thread.join();
  4884. ASSERT_FALSE(svr.is_running());
  4885. });
  4886. svr.wait_until_ready();
  4887. {
  4888. #ifdef CPPHTTPLIB_SSL_ENABLED
  4889. SSLClient cli(HOST, PORT);
  4890. cli.enable_server_certificate_verification(false);
  4891. #else
  4892. Client cli(HOST, PORT);
  4893. #endif
  4894. auto res = cli.Get("/routing_handler");
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. EXPECT_EQ(StatusCode::OK_200, res->status);
  4897. EXPECT_EQ("Routing Handler", res->body);
  4898. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4899. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4900. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4901. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4902. }
  4903. {
  4904. #ifdef CPPHTTPLIB_SSL_ENABLED
  4905. SSLClient cli(HOST, PORT);
  4906. cli.enable_server_certificate_verification(false);
  4907. #else
  4908. Client cli(HOST, PORT);
  4909. #endif
  4910. auto res = cli.Get("/hi");
  4911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4912. EXPECT_EQ(StatusCode::OK_200, res->status);
  4913. EXPECT_EQ("Hello World!\n", res->body);
  4914. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4915. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4916. }
  4917. {
  4918. #ifdef CPPHTTPLIB_SSL_ENABLED
  4919. SSLClient cli(HOST, PORT);
  4920. cli.enable_server_certificate_verification(false);
  4921. #else
  4922. Client cli(HOST, PORT);
  4923. #endif
  4924. auto res = cli.Get("/aaa");
  4925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4926. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4927. EXPECT_EQ("Error", res->body);
  4928. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4929. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4930. }
  4931. }
  4932. TEST(RequestHandlerTest, PreRequestHandler) {
  4933. auto route_path = "/user/:user";
  4934. Server svr;
  4935. svr.Get("/hi", [](const Request &, Response &res) {
  4936. res.set_content("hi", "text/plain");
  4937. });
  4938. svr.Get(route_path, [](const Request &req, Response &res) {
  4939. res.set_content(req.path_params.at("user"), "text/plain");
  4940. });
  4941. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4942. if (req.matched_route == route_path) {
  4943. auto user = req.path_params.at("user");
  4944. if (user != "john") {
  4945. res.status = StatusCode::Forbidden_403;
  4946. res.set_content("error", "text/html");
  4947. return Server::HandlerResponse::Handled;
  4948. }
  4949. }
  4950. return Server::HandlerResponse::Unhandled;
  4951. });
  4952. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4953. auto se = detail::scope_exit([&] {
  4954. svr.stop();
  4955. thread.join();
  4956. ASSERT_FALSE(svr.is_running());
  4957. });
  4958. svr.wait_until_ready();
  4959. Client cli(HOST, PORT);
  4960. {
  4961. auto res = cli.Get("/hi");
  4962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4963. EXPECT_EQ(StatusCode::OK_200, res->status);
  4964. EXPECT_EQ("hi", res->body);
  4965. }
  4966. {
  4967. auto res = cli.Get("/user/john");
  4968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("john", res->body);
  4971. }
  4972. {
  4973. auto res = cli.Get("/user/invalid-user");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4976. EXPECT_EQ("error", res->body);
  4977. }
  4978. }
  4979. // The pre-request handler must run before the request body is read, so a
  4980. // rejected request never forces the server to buffer a (potentially large)
  4981. // body. Here the posted body is larger than the payload limit: if the body
  4982. // were read first the server would answer 413, but because the pre-request
  4983. // handler runs first it answers 403 and the body is never read.
  4984. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4985. Server svr;
  4986. svr.set_payload_max_length(8);
  4987. auto handler_ran = false;
  4988. svr.Post("/reject", [&](const Request &req, Response &res) {
  4989. handler_ran = true;
  4990. res.set_content(req.body, "text/plain");
  4991. });
  4992. svr.Post("/accept", [](const Request &req, Response &res) {
  4993. res.set_content(req.body, "text/plain");
  4994. });
  4995. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4996. if (req.matched_route == "/reject") {
  4997. res.status = StatusCode::Forbidden_403;
  4998. res.set_content("denied", "text/plain");
  4999. return Server::HandlerResponse::Handled;
  5000. }
  5001. return Server::HandlerResponse::Unhandled;
  5002. });
  5003. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5004. auto se = detail::scope_exit([&] {
  5005. svr.stop();
  5006. thread.join();
  5007. ASSERT_FALSE(svr.is_running());
  5008. });
  5009. svr.wait_until_ready();
  5010. Client cli(HOST, PORT);
  5011. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5012. // rejects with 403 before the body is read, so 413 is never reached.
  5013. {
  5014. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5016. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5017. EXPECT_EQ("denied", res->body);
  5018. EXPECT_FALSE(handler_ran);
  5019. }
  5020. // An approved route still reads the body and enforces the payload limit.
  5021. {
  5022. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5024. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5025. }
  5026. }
  5027. TEST(UserDataTest, BasicOperations) {
  5028. httplib::UserData ud;
  5029. // Initially empty
  5030. EXPECT_FALSE(ud.has("key"));
  5031. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5032. // set and get
  5033. ud.set("key", 42);
  5034. EXPECT_TRUE(ud.has("key"));
  5035. auto *p = ud.get<int>("key");
  5036. ASSERT_NE(nullptr, p);
  5037. EXPECT_EQ(42, *p);
  5038. // Type mismatch → nullptr
  5039. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5040. // Overwrite with different type
  5041. ud.set("key", std::string("hello"));
  5042. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5043. auto *s = ud.get<std::string>("key");
  5044. ASSERT_NE(nullptr, s);
  5045. EXPECT_EQ("hello", *s);
  5046. // erase
  5047. ud.erase("key");
  5048. EXPECT_FALSE(ud.has("key"));
  5049. // clear
  5050. ud.set("a", 1);
  5051. ud.set("b", 2);
  5052. ud.clear();
  5053. EXPECT_FALSE(ud.has("a"));
  5054. EXPECT_FALSE(ud.has("b"));
  5055. }
  5056. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5057. struct AuthCtx {
  5058. std::string user_id;
  5059. };
  5060. Server svr;
  5061. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5062. res.user_data.set("auth", AuthCtx{"alice"});
  5063. return Server::HandlerResponse::Unhandled;
  5064. });
  5065. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5066. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5067. ASSERT_NE(nullptr, ctx);
  5068. res.set_content("Hello " + ctx->user_id, "text/plain");
  5069. });
  5070. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5071. auto se = detail::scope_exit([&] {
  5072. svr.stop();
  5073. thread.join();
  5074. ASSERT_FALSE(svr.is_running());
  5075. });
  5076. svr.wait_until_ready();
  5077. Client cli(HOST, PORT);
  5078. auto res = cli.Get("/me");
  5079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5080. EXPECT_EQ(StatusCode::OK_200, res->status);
  5081. EXPECT_EQ("Hello alice", res->body);
  5082. }
  5083. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5084. struct RoleCtx {
  5085. std::string role;
  5086. };
  5087. Server svr;
  5088. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5089. res.user_data.set("role", RoleCtx{"admin"});
  5090. return Server::HandlerResponse::Unhandled;
  5091. });
  5092. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5093. auto *ctx = res.user_data.get<RoleCtx>("role");
  5094. ASSERT_NE(nullptr, ctx);
  5095. res.set_content(ctx->role, "text/plain");
  5096. });
  5097. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5098. auto se = detail::scope_exit([&] {
  5099. svr.stop();
  5100. thread.join();
  5101. ASSERT_FALSE(svr.is_running());
  5102. });
  5103. svr.wait_until_ready();
  5104. Client cli(HOST, PORT);
  5105. auto res = cli.Get("/role");
  5106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5107. EXPECT_EQ(StatusCode::OK_200, res->status);
  5108. EXPECT_EQ("admin", res->body);
  5109. }
  5110. TEST(InvalidFormatTest, StatusCode) {
  5111. Server svr;
  5112. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5113. res.set_content("Hello World!\n", "text/plain");
  5114. res.status = 9999; // Status should be a three-digit code...
  5115. });
  5116. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5117. auto se = detail::scope_exit([&] {
  5118. svr.stop();
  5119. thread.join();
  5120. ASSERT_FALSE(svr.is_running());
  5121. });
  5122. svr.wait_until_ready();
  5123. {
  5124. Client cli(HOST, PORT);
  5125. auto res = cli.Get("/hi");
  5126. ASSERT_FALSE(res);
  5127. }
  5128. }
  5129. TEST(URLFragmentTest, WithFragment) {
  5130. Server svr;
  5131. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5132. EXPECT_TRUE(req.target == "/hi");
  5133. });
  5134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5135. auto se = detail::scope_exit([&] {
  5136. svr.stop();
  5137. thread.join();
  5138. ASSERT_FALSE(svr.is_running());
  5139. });
  5140. svr.wait_until_ready();
  5141. {
  5142. Client cli(HOST, PORT);
  5143. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5144. EXPECT_TRUE(res);
  5145. EXPECT_EQ(StatusCode::OK_200, res->status);
  5146. res = cli.Get("/hi%23key1=val1=key2=val2");
  5147. EXPECT_TRUE(res);
  5148. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5149. }
  5150. }
  5151. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5152. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5153. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5154. Server svr;
  5155. std::vector<std::string> targets;
  5156. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5157. targets.push_back(req.target);
  5158. });
  5159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5160. auto se = detail::scope_exit([&] {
  5161. svr.stop();
  5162. thread.join();
  5163. ASSERT_FALSE(svr.is_running());
  5164. });
  5165. svr.wait_until_ready();
  5166. Client cli(HOST, PORT);
  5167. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5168. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5169. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5170. // A '?' after the '#' belongs to the fragment, not to the query.
  5171. Request req;
  5172. req.method = "GET";
  5173. req.path = "/hi#f?x=1";
  5174. req.params.emplace("a", "1");
  5175. Response res;
  5176. auto error = Error::Success;
  5177. EXPECT_TRUE(cli.send(req, res, error));
  5178. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5179. "/hi?a=1"}),
  5180. targets);
  5181. }
  5182. TEST(HeaderWriter, SetHeaderWriter) {
  5183. Server svr;
  5184. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5185. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5186. return detail::write_headers(strm, hdrs);
  5187. });
  5188. svr.Get("/hi", [](const Request &req, Response &res) {
  5189. auto it = req.headers.find("CustomClientHeader");
  5190. EXPECT_TRUE(it != req.headers.end());
  5191. EXPECT_EQ(it->second, "CustomClientValue");
  5192. res.set_content("Hello World!\n", "text/plain");
  5193. });
  5194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5195. auto se = detail::scope_exit([&] {
  5196. svr.stop();
  5197. thread.join();
  5198. ASSERT_FALSE(svr.is_running());
  5199. });
  5200. svr.wait_until_ready();
  5201. {
  5202. Client cli(HOST, PORT);
  5203. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5204. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5205. return detail::write_headers(strm, hdrs);
  5206. });
  5207. auto res = cli.Get("/hi");
  5208. EXPECT_TRUE(res);
  5209. EXPECT_EQ(StatusCode::OK_200, res->status);
  5210. auto it = res->headers.find("CustomServerHeader");
  5211. EXPECT_TRUE(it != res->headers.end());
  5212. EXPECT_EQ(it->second, "CustomServerValue");
  5213. }
  5214. }
  5215. class ServerTest : public ::testing::Test {
  5216. protected:
  5217. ServerTest()
  5218. : cli_(HOST, PORT)
  5219. #ifdef CPPHTTPLIB_SSL_ENABLED
  5220. ,
  5221. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5222. #endif
  5223. {
  5224. #ifdef CPPHTTPLIB_SSL_ENABLED
  5225. cli_.enable_server_certificate_verification(false);
  5226. #endif
  5227. // Allow LARGE_DATA (100MB) responses
  5228. cli_.set_payload_max_length(200 * 1024 * 1024);
  5229. }
  5230. virtual void SetUp() {
  5231. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5232. svr_.set_payload_max_length(200 * 1024 * 1024);
  5233. svr_.set_mount_point("/", "./www");
  5234. svr_.set_mount_point("/mount", "./www2");
  5235. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5236. svr_.Get("/hi",
  5237. [&](const Request & /*req*/, Response &res) {
  5238. res.set_content("Hello World!", "text/plain");
  5239. })
  5240. .Get("/file_content",
  5241. [&](const Request & /*req*/, Response &res) {
  5242. res.set_file_content("./www/dir/test.html");
  5243. })
  5244. .Get("/file_content_with_content_type",
  5245. [&](const Request & /*req*/, Response &res) {
  5246. res.set_file_content("./www/file", "text/plain");
  5247. })
  5248. .Get("/invalid_file_content",
  5249. [&](const Request & /*req*/, Response &res) {
  5250. res.set_file_content("./www/dir/invalid_file_path");
  5251. })
  5252. .Get("/http_response_splitting",
  5253. [&](const Request & /*req*/, Response &res) {
  5254. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5255. EXPECT_EQ(0U, res.headers.size());
  5256. EXPECT_FALSE(res.has_header("a"));
  5257. res.set_header("a", "1\nSet-Cookie: a=1");
  5258. EXPECT_EQ(0U, res.headers.size());
  5259. EXPECT_FALSE(res.has_header("a"));
  5260. res.set_header("a", "1\rSet-Cookie: a=1");
  5261. EXPECT_EQ(0U, res.headers.size());
  5262. EXPECT_FALSE(res.has_header("a"));
  5263. res.set_header("a\r\nb", "0");
  5264. EXPECT_EQ(0U, res.headers.size());
  5265. EXPECT_FALSE(res.has_header("a"));
  5266. res.set_header("a\rb", "0");
  5267. EXPECT_EQ(0U, res.headers.size());
  5268. EXPECT_FALSE(res.has_header("a"));
  5269. res.set_header("a\nb", "0");
  5270. EXPECT_EQ(0U, res.headers.size());
  5271. EXPECT_FALSE(res.has_header("a"));
  5272. res.set_redirect("1\r\nSet-Cookie: a=1");
  5273. EXPECT_EQ(0U, res.headers.size());
  5274. EXPECT_FALSE(res.has_header("Location"));
  5275. })
  5276. .Get("/slow",
  5277. [&](const Request & /*req*/, Response &res) {
  5278. std::this_thread::sleep_for(std::chrono::seconds(4));
  5279. res.set_content("slow", "text/plain");
  5280. })
  5281. #if 0
  5282. .Post("/slowpost",
  5283. [&](const Request & /*req*/, Response &res) {
  5284. std::this_thread::sleep_for(std::chrono::seconds(2));
  5285. res.set_content("slow", "text/plain");
  5286. })
  5287. #endif
  5288. .Get("/remote_addr",
  5289. [&](const Request &req, Response &res) {
  5290. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5291. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5292. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5293. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5294. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5295. #endif
  5296. res.set_content(req.remote_addr, "text/plain");
  5297. })
  5298. .Get("/local_addr",
  5299. [&](const Request &req, Response &res) {
  5300. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5301. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5302. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5303. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5304. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5305. #endif
  5306. auto local_addr = req.local_addr;
  5307. auto local_port = std::to_string(req.local_port);
  5308. res.set_content(local_addr.append(":").append(local_port),
  5309. "text/plain");
  5310. })
  5311. .Get("/endwith%",
  5312. [&](const Request & /*req*/, Response &res) {
  5313. res.set_content("Hello World!", "text/plain");
  5314. })
  5315. .Get("/a\\+\\+b",
  5316. [&](const Request &req, Response &res) {
  5317. ASSERT_TRUE(req.has_param("a +b"));
  5318. auto val = req.get_param_value("a +b");
  5319. res.set_content(val, "text/plain");
  5320. })
  5321. .Get("/", [&](const Request & /*req*/,
  5322. Response &res) { res.set_redirect("/hi"); })
  5323. .Post("/1",
  5324. [](const Request & /*req*/, Response &res) {
  5325. res.set_redirect("/2", StatusCode::SeeOther_303);
  5326. })
  5327. .Get("/2",
  5328. [](const Request & /*req*/, Response &res) {
  5329. res.set_content("redirected.", "text/plain");
  5330. res.status = StatusCode::OK_200;
  5331. })
  5332. .Post("/person",
  5333. [&](const Request &req, Response &res) {
  5334. if (req.has_param("name") && req.has_param("note")) {
  5335. persons_[req.get_param_value("name")] =
  5336. req.get_param_value("note");
  5337. } else {
  5338. res.status = StatusCode::BadRequest_400;
  5339. }
  5340. })
  5341. .Put("/person",
  5342. [&](const Request &req, Response &res) {
  5343. if (req.has_param("name") && req.has_param("note")) {
  5344. persons_[req.get_param_value("name")] =
  5345. req.get_param_value("note");
  5346. } else {
  5347. res.status = StatusCode::BadRequest_400;
  5348. }
  5349. })
  5350. .Get("/person/(.*)",
  5351. [&](const Request &req, Response &res) {
  5352. string name = req.matches[1];
  5353. if (persons_.find(name) != persons_.end()) {
  5354. auto note = persons_[name];
  5355. res.set_content(note, "text/plain");
  5356. } else {
  5357. res.status = StatusCode::NotFound_404;
  5358. }
  5359. })
  5360. .Delete("/person",
  5361. [&](const Request &req, Response &res) {
  5362. if (req.has_param("name")) {
  5363. string name = req.get_param_value("name");
  5364. if (persons_.find(name) != persons_.end()) {
  5365. persons_.erase(name);
  5366. res.set_content("DELETED", "text/plain");
  5367. } else {
  5368. res.status = StatusCode::NotFound_404;
  5369. }
  5370. } else {
  5371. res.status = StatusCode::BadRequest_400;
  5372. }
  5373. })
  5374. .Post("/x-www-form-urlencoded-json",
  5375. [&](const Request &req, Response &res) {
  5376. auto json = req.get_param_value("json");
  5377. ASSERT_EQ(JSON_DATA, json);
  5378. res.set_content(json, "appliation/json");
  5379. res.status = StatusCode::OK_200;
  5380. })
  5381. .Get("/streamed-chunked",
  5382. [&](const Request & /*req*/, Response &res) {
  5383. res.set_chunked_content_provider(
  5384. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5385. sink.os << "123";
  5386. sink.os << "456";
  5387. sink.os << "789";
  5388. sink.done();
  5389. return true;
  5390. });
  5391. })
  5392. .Get("/streamed-chunked-with-prohibited-trailer",
  5393. [&](const Request & /*req*/, Response &res) {
  5394. auto i = new int(0);
  5395. // Declare both a prohibited trailer (Content-Length) and an
  5396. // allowed one
  5397. res.set_header("Trailer", "Content-Length, X-Allowed");
  5398. res.set_chunked_content_provider(
  5399. "text/plain",
  5400. [i](size_t /*offset*/, DataSink &sink) {
  5401. switch (*i) {
  5402. case 0: sink.os << "123"; break;
  5403. case 1: sink.os << "456"; break;
  5404. case 2: sink.os << "789"; break;
  5405. case 3: {
  5406. sink.done_with_trailer(
  5407. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5408. } break;
  5409. }
  5410. (*i)++;
  5411. return true;
  5412. },
  5413. [i](bool success) {
  5414. EXPECT_TRUE(success);
  5415. delete i;
  5416. });
  5417. })
  5418. .Get("/streamed-chunked2",
  5419. [&](const Request & /*req*/, Response &res) {
  5420. auto i = new int(0);
  5421. res.set_chunked_content_provider(
  5422. "text/plain",
  5423. [i](size_t /*offset*/, DataSink &sink) {
  5424. switch (*i) {
  5425. case 0: sink.os << "123"; break;
  5426. case 1: sink.os << "456"; break;
  5427. case 2: sink.os << "789"; break;
  5428. case 3: sink.done(); break;
  5429. }
  5430. (*i)++;
  5431. return true;
  5432. },
  5433. [i](bool success) {
  5434. EXPECT_TRUE(success);
  5435. delete i;
  5436. });
  5437. })
  5438. .Get("/streamed-chunked-with-trailer",
  5439. [&](const Request & /*req*/, Response &res) {
  5440. auto i = new int(0);
  5441. res.set_header("Trailer", "Dummy1, Dummy2");
  5442. res.set_chunked_content_provider(
  5443. "text/plain",
  5444. [i](size_t /*offset*/, DataSink &sink) {
  5445. switch (*i) {
  5446. case 0: sink.os << "123"; break;
  5447. case 1: sink.os << "456"; break;
  5448. case 2: sink.os << "789"; break;
  5449. case 3: {
  5450. sink.done_with_trailer(
  5451. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5452. } break;
  5453. }
  5454. (*i)++;
  5455. return true;
  5456. },
  5457. [i](bool success) {
  5458. EXPECT_TRUE(success);
  5459. delete i;
  5460. });
  5461. })
  5462. .Get("/streamed",
  5463. [&](const Request & /*req*/, Response &res) {
  5464. res.set_content_provider(
  5465. 6, "text/plain",
  5466. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5467. sink.os << (offset < 3 ? "a" : "b");
  5468. return true;
  5469. });
  5470. })
  5471. .Get("/streamed-without-length",
  5472. [&](const Request & /*req*/, Response &res) {
  5473. auto data = new std::string("abcdefg");
  5474. res.set_content_provider(
  5475. "text/plain",
  5476. [data](size_t offset, DataSink &sink) {
  5477. if (offset < data->size()) {
  5478. sink.os << data->substr(offset);
  5479. }
  5480. sink.done();
  5481. return true;
  5482. },
  5483. [data](bool success) {
  5484. EXPECT_TRUE(success);
  5485. delete data;
  5486. });
  5487. })
  5488. .Get("/streamed-with-range",
  5489. [&](const Request &req, Response &res) {
  5490. auto data = new std::string("abcdefg");
  5491. // An explicit status keeps the server from picking the 206 it
  5492. // would otherwise choose for a ranged request, so the response
  5493. // is not a partial representation.
  5494. auto status = req.get_param_value("status");
  5495. if (status == "200") {
  5496. res.status = StatusCode::OK_200;
  5497. } else if (status == "403") {
  5498. res.status = StatusCode::Forbidden_403;
  5499. }
  5500. res.set_content_provider(
  5501. data->size(), "text/plain",
  5502. [data](size_t offset, size_t length, DataSink &sink) {
  5503. size_t DATA_CHUNK_SIZE = 4;
  5504. const auto &d = *data;
  5505. auto out_len =
  5506. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5507. auto ret =
  5508. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5509. EXPECT_TRUE(ret);
  5510. return true;
  5511. },
  5512. [data, &req](bool success) {
  5513. EXPECT_EQ(success, !req.has_param("error"));
  5514. delete data;
  5515. });
  5516. })
  5517. .Get("/streamed-cancel",
  5518. [&](const Request & /*req*/, Response &res) {
  5519. res.set_content_provider(
  5520. size_t(-1), "text/plain",
  5521. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5522. sink.os << "data_chunk";
  5523. return true;
  5524. });
  5525. })
  5526. .Get("/regex-with-delimiter",
  5527. [&](const Request &req, Response & /*res*/) {
  5528. ASSERT_TRUE(req.has_param("key"));
  5529. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5530. })
  5531. .Get("/with-range",
  5532. [&](const Request & /*req*/, Response &res) {
  5533. res.set_content("abcdefg", "text/plain");
  5534. })
  5535. .Get("/test-start-time",
  5536. [&](const Request &req, Response & /*res*/) {
  5537. EXPECT_NE(req.start_time_,
  5538. std::chrono::steady_clock::time_point::min());
  5539. })
  5540. .Get("/with-range-customized-response",
  5541. [&](const Request & /*req*/, Response &res) {
  5542. res.status = StatusCode::BadRequest_400;
  5543. res.set_content(JSON_DATA, "application/json");
  5544. })
  5545. .Post("/chunked",
  5546. [&](const Request &req, Response & /*res*/) {
  5547. EXPECT_EQ(req.body, "dechunked post body");
  5548. })
  5549. .Post("/large-chunked",
  5550. [&](const Request &req, Response & /*res*/) {
  5551. std::string expected(6 * 30 * 1024u, 'a');
  5552. EXPECT_EQ(req.body, expected);
  5553. })
  5554. .Post("/multipart",
  5555. [&](const Request &req, Response & /*res*/) {
  5556. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5557. req.form.get_field_count("text2") +
  5558. req.form.get_field_count("file3") +
  5559. req.form.get_field_count("file4"));
  5560. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5561. req.form.get_file_count("file2"));
  5562. ASSERT_TRUE(!req.form.has_file("???"));
  5563. ASSERT_TRUE(!req.form.has_field("???"));
  5564. ASSERT_TRUE(req.body.empty());
  5565. {
  5566. const auto &text = req.form.get_field("text1");
  5567. EXPECT_EQ("text default", text);
  5568. }
  5569. {
  5570. const auto &text = req.form.get_field("text2");
  5571. EXPECT_EQ("aωb", text);
  5572. }
  5573. {
  5574. const auto &file = req.form.get_file("file1");
  5575. EXPECT_EQ("hello.txt", file.filename);
  5576. EXPECT_EQ("text/plain", file.content_type);
  5577. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5578. }
  5579. {
  5580. const auto &file = req.form.get_file("file2");
  5581. EXPECT_EQ("world.json", file.filename);
  5582. EXPECT_EQ("application/json", file.content_type);
  5583. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5584. }
  5585. {
  5586. const auto &text = req.form.get_field("file3");
  5587. EXPECT_EQ(0u, text.size());
  5588. }
  5589. {
  5590. const auto &text = req.form.get_field("file4");
  5591. EXPECT_EQ(0u, text.size());
  5592. }
  5593. })
  5594. .Post("/multipart/multi_file_values",
  5595. [&](const Request &req, Response & /*res*/) {
  5596. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5597. req.form.get_field_count("multi_text1"));
  5598. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5599. ASSERT_TRUE(!req.form.has_file("???"));
  5600. ASSERT_TRUE(!req.form.has_field("???"));
  5601. ASSERT_TRUE(req.body.empty());
  5602. {
  5603. const auto &text = req.form.get_field("text");
  5604. EXPECT_EQ("default text", text);
  5605. }
  5606. {
  5607. const auto &text1_values = req.form.get_fields("multi_text1");
  5608. EXPECT_EQ(2u, text1_values.size());
  5609. EXPECT_EQ("aaaaa", text1_values[0]);
  5610. EXPECT_EQ("bbbbb", text1_values[1]);
  5611. }
  5612. {
  5613. const auto &file1_values = req.form.get_files("multi_file1");
  5614. EXPECT_EQ(2u, file1_values.size());
  5615. auto file1 = file1_values[0];
  5616. EXPECT_EQ(file1.filename, "hello.txt");
  5617. EXPECT_EQ(file1.content_type, "text/plain");
  5618. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5619. auto file2 = file1_values[1];
  5620. EXPECT_EQ(file2.filename, "world.json");
  5621. EXPECT_EQ(file2.content_type, "application/json");
  5622. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5623. }
  5624. })
  5625. .Post("/empty",
  5626. [&](const Request &req, Response &res) {
  5627. EXPECT_EQ(req.body, "");
  5628. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5629. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5630. res.set_content("empty", "text/plain");
  5631. })
  5632. .Post("/empty-no-content-type",
  5633. [&](const Request &req, Response &res) {
  5634. EXPECT_EQ(req.body, "");
  5635. EXPECT_FALSE(req.has_header("Content-Type"));
  5636. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5637. res.set_content("empty-no-content-type", "text/plain");
  5638. })
  5639. .Post("/path-only",
  5640. [&](const Request &req, Response &res) {
  5641. EXPECT_EQ(req.body, "");
  5642. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5643. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5644. res.set_content("path-only", "text/plain");
  5645. })
  5646. .Post("/path-headers-only",
  5647. [&](const Request &req, Response &res) {
  5648. EXPECT_EQ(req.body, "");
  5649. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5650. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5651. EXPECT_EQ("world", req.get_header_value("hello"));
  5652. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5653. res.set_content("path-headers-only", "text/plain");
  5654. })
  5655. .Post("/post-large",
  5656. [&](const Request &req, Response &res) {
  5657. EXPECT_EQ(req.body, LARGE_DATA);
  5658. res.set_content(req.body, "text/plain");
  5659. })
  5660. .Post("/post-loopback",
  5661. [&](const Request &, Response &res,
  5662. ContentReader const &content_reader) {
  5663. std::string body;
  5664. content_reader([&](const char *data, size_t data_length) {
  5665. body.append(data, data_length);
  5666. return true;
  5667. });
  5668. res.set_content(body, "text/plain");
  5669. })
  5670. .Put("/put-loopback",
  5671. [&](const Request &, Response &res,
  5672. ContentReader const &content_reader) {
  5673. std::string body;
  5674. content_reader([&](const char *data, size_t data_length) {
  5675. body.append(data, data_length);
  5676. return true;
  5677. });
  5678. res.set_content(body, "text/plain");
  5679. })
  5680. .Patch("/patch-loopback",
  5681. [&](const Request &, Response &res,
  5682. ContentReader const &content_reader) {
  5683. std::string body;
  5684. content_reader([&](const char *data, size_t data_length) {
  5685. body.append(data, data_length);
  5686. return true;
  5687. });
  5688. res.set_content(body, "text/plain");
  5689. })
  5690. .Put("/empty-no-content-type",
  5691. [&](const Request &req, Response &res) {
  5692. EXPECT_EQ(req.body, "");
  5693. EXPECT_FALSE(req.has_header("Content-Type"));
  5694. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5695. res.set_content("empty-no-content-type", "text/plain");
  5696. })
  5697. .Put("/put",
  5698. [&](const Request &req, Response &res) {
  5699. EXPECT_EQ(req.body, "PUT");
  5700. res.set_content(req.body, "text/plain");
  5701. })
  5702. .Put("/put-large",
  5703. [&](const Request &req, Response &res) {
  5704. EXPECT_EQ(req.body, LARGE_DATA);
  5705. res.set_content(req.body, "text/plain");
  5706. })
  5707. .Patch("/patch",
  5708. [&](const Request &req, Response &res) {
  5709. EXPECT_EQ(req.body, "PATCH");
  5710. res.set_content(req.body, "text/plain");
  5711. })
  5712. .Delete("/delete",
  5713. [&](const Request & /*req*/, Response &res) {
  5714. res.set_content("DELETE", "text/plain");
  5715. })
  5716. .Delete("/delete-body",
  5717. [&](const Request &req, Response &res) {
  5718. EXPECT_EQ(req.body, "content");
  5719. res.set_content(req.body, "text/plain");
  5720. })
  5721. .Options(R"(\*)",
  5722. [&](const Request & /*req*/, Response &res) {
  5723. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5724. })
  5725. .CustomRoute("PROPFIND", "/dav/:id",
  5726. [&](const Request &req, Response &res) {
  5727. res.set_header("x-body-size",
  5728. std::to_string(req.body.size()));
  5729. res.set_header("x-matched-route", req.matched_route);
  5730. res.set_header("x-dav-id", req.path_params.at("id"));
  5731. res.status = StatusCode::MultiStatus_207;
  5732. res.set_content(req.body, "application/xml");
  5733. })
  5734. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5735. [&](const Request &req, Response &res) {
  5736. res.set_header("x-dav-match", req.matches[1]);
  5737. res.status = StatusCode::MultiStatus_207;
  5738. })
  5739. .CustomRoute("MKCOL", "/dav-mkcol",
  5740. [&](const Request &req, Response &res) {
  5741. EXPECT_TRUE(req.body.empty());
  5742. res.status = StatusCode::Created_201;
  5743. })
  5744. .CustomRoute(
  5745. "REPORT", "/dav-report",
  5746. [&](const Request & /*req*/, Response &res,
  5747. const ContentReader &content_reader) {
  5748. std::string body;
  5749. content_reader([&](const char *data, size_t data_length) {
  5750. body.append(data, data_length);
  5751. return true;
  5752. });
  5753. res.set_header("x-body-size", std::to_string(body.size()));
  5754. res.status = StatusCode::MultiStatus_207;
  5755. res.set_content(body, "application/xml");
  5756. })
  5757. .Get("/request-target",
  5758. [&](const Request &req, Response & /*res*/) {
  5759. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5760. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5761. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5762. })
  5763. .Get("/long-query-value",
  5764. [&](const Request &req, Response & /*res*/) {
  5765. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5766. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5767. })
  5768. .Get("/too-long-query-value",
  5769. [&](const Request &req, Response & /*res*/) {
  5770. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5771. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5772. })
  5773. .Get("/array-param",
  5774. [&](const Request &req, Response & /*res*/) {
  5775. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5776. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5777. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5778. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5779. })
  5780. .Get("/array-param-values",
  5781. [&](const Request &req, Response & /*res*/) {
  5782. auto values = req.get_param_values("array");
  5783. EXPECT_EQ(3u, values.size());
  5784. EXPECT_EQ("value1", values[0]);
  5785. EXPECT_EQ("value2", values[1]);
  5786. EXPECT_EQ("value3", values[2]);
  5787. auto empty = req.get_param_values("nonexistent");
  5788. EXPECT_TRUE(empty.empty());
  5789. })
  5790. .Post("/validate-no-multiple-headers",
  5791. [&](const Request &req, Response & /*res*/) {
  5792. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5793. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5794. })
  5795. .Post("/content_receiver",
  5796. [&](const Request &req, Response &res,
  5797. const ContentReader &content_reader) {
  5798. if (req.is_multipart_form_data()) {
  5799. std::vector<FormData> items;
  5800. content_reader(
  5801. [&](const FormData &file) {
  5802. items.push_back(file);
  5803. return true;
  5804. },
  5805. [&](const char *data, size_t data_length) {
  5806. items.back().content.append(data, data_length);
  5807. return true;
  5808. });
  5809. EXPECT_EQ(5u, items.size());
  5810. {
  5811. const auto &file = get_file_value(items, "text1");
  5812. EXPECT_TRUE(file.filename.empty());
  5813. EXPECT_EQ("text default", file.content);
  5814. }
  5815. {
  5816. const auto &file = get_file_value(items, "text2");
  5817. EXPECT_TRUE(file.filename.empty());
  5818. EXPECT_EQ("aωb", file.content);
  5819. }
  5820. {
  5821. const auto &file = get_file_value(items, "file1");
  5822. EXPECT_EQ("hello.txt", file.filename);
  5823. EXPECT_EQ("text/plain", file.content_type);
  5824. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5825. }
  5826. {
  5827. const auto &file = get_file_value(items, "file2");
  5828. EXPECT_EQ("world.json", file.filename);
  5829. EXPECT_EQ("application/json", file.content_type);
  5830. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5831. }
  5832. {
  5833. const auto &file = get_file_value(items, "file3");
  5834. EXPECT_TRUE(file.filename.empty());
  5835. EXPECT_EQ("application/octet-stream", file.content_type);
  5836. EXPECT_EQ(0u, file.content.size());
  5837. }
  5838. } else {
  5839. std::string body;
  5840. content_reader([&](const char *data, size_t data_length) {
  5841. EXPECT_EQ(7U, data_length);
  5842. body.append(data, data_length);
  5843. return true;
  5844. });
  5845. EXPECT_EQ(body, "content");
  5846. res.set_content(body, "text/plain");
  5847. }
  5848. })
  5849. .Put("/content_receiver",
  5850. [&](const Request & /*req*/, Response &res,
  5851. const ContentReader &content_reader) {
  5852. std::string body;
  5853. content_reader([&](const char *data, size_t data_length) {
  5854. body.append(data, data_length);
  5855. return true;
  5856. });
  5857. EXPECT_EQ(body, "content");
  5858. res.set_content(body, "text/plain");
  5859. })
  5860. .Patch("/content_receiver",
  5861. [&](const Request & /*req*/, Response &res,
  5862. const ContentReader &content_reader) {
  5863. std::string body;
  5864. content_reader([&](const char *data, size_t data_length) {
  5865. body.append(data, data_length);
  5866. return true;
  5867. });
  5868. EXPECT_EQ(body, "content");
  5869. res.set_content(body, "text/plain");
  5870. })
  5871. .Post("/query-string-and-body",
  5872. [&](const Request &req, Response & /*res*/) {
  5873. ASSERT_TRUE(req.has_param("key"));
  5874. EXPECT_EQ(req.get_param_value("key"), "value");
  5875. EXPECT_EQ(req.body, "content");
  5876. })
  5877. .Get("/last-request",
  5878. [&](const Request &req, Response & /*res*/) {
  5879. EXPECT_EQ("close", req.get_header_value("Connection"));
  5880. })
  5881. .Get(R"(/redirect/(\d+))",
  5882. [&](const Request &req, Response &res) {
  5883. auto num = std::stoi(req.matches[1]) + 1;
  5884. std::string url = "/redirect/" + std::to_string(num);
  5885. res.set_redirect(url);
  5886. })
  5887. .Post("/binary",
  5888. [&](const Request &req, Response &res) {
  5889. EXPECT_EQ(4U, req.body.size());
  5890. EXPECT_EQ("application/octet-stream",
  5891. req.get_header_value("Content-Type"));
  5892. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5893. res.set_content(req.body, "application/octet-stream");
  5894. })
  5895. .Put("/binary",
  5896. [&](const Request &req, Response &res) {
  5897. EXPECT_EQ(4U, req.body.size());
  5898. EXPECT_EQ("application/octet-stream",
  5899. req.get_header_value("Content-Type"));
  5900. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5901. res.set_content(req.body, "application/octet-stream");
  5902. })
  5903. .Patch("/binary",
  5904. [&](const Request &req, Response &res) {
  5905. EXPECT_EQ(4U, req.body.size());
  5906. EXPECT_EQ("application/octet-stream",
  5907. req.get_header_value("Content-Type"));
  5908. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5909. res.set_content(req.body, "application/octet-stream");
  5910. })
  5911. .Delete("/binary",
  5912. [&](const Request &req, Response &res) {
  5913. EXPECT_EQ(4U, req.body.size());
  5914. EXPECT_EQ("application/octet-stream",
  5915. req.get_header_value("Content-Type"));
  5916. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5917. res.set_content(req.body, "application/octet-stream");
  5918. })
  5919. .Get("/issue1772",
  5920. [&](const Request & /*req*/, Response &res) {
  5921. res.status = 401;
  5922. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5923. })
  5924. .Delete("/issue609",
  5925. [](const httplib::Request &, httplib::Response &res,
  5926. const httplib::ContentReader &) {
  5927. res.set_content("ok", "text/plain");
  5928. })
  5929. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5930. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5931. .Get("/compress",
  5932. [&](const Request & /*req*/, Response &res) {
  5933. res.set_content(
  5934. "12345678901234567890123456789012345678901234567890123456789"
  5935. "01234567890123456789012345678901234567890",
  5936. "text/plain");
  5937. })
  5938. .Get("/compress-with-charset",
  5939. [&](const Request & /*req*/, Response &res) {
  5940. res.set_content(
  5941. "12345678901234567890123456789012345678901234567890123456789"
  5942. "01234567890123456789012345678901234567890",
  5943. "application/json; charset=utf-8");
  5944. })
  5945. .Get("/nocompress",
  5946. [&](const Request & /*req*/, Response &res) {
  5947. res.set_content(
  5948. "12345678901234567890123456789012345678901234567890123456789"
  5949. "01234567890123456789012345678901234567890",
  5950. "application/octet-stream");
  5951. })
  5952. .Post("/compress-multipart",
  5953. [&](const Request &req, Response & /*res*/) {
  5954. EXPECT_EQ(2u, req.form.fields.size());
  5955. ASSERT_TRUE(!req.form.has_field("???"));
  5956. {
  5957. const auto &text = req.form.get_field("key1");
  5958. EXPECT_EQ("test", text);
  5959. }
  5960. {
  5961. const auto &text = req.form.get_field("key2");
  5962. EXPECT_EQ("--abcdefg123", text);
  5963. }
  5964. })
  5965. #endif
  5966. ;
  5967. persons_["john"] = "programmer";
  5968. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5969. svr_.wait_until_ready();
  5970. }
  5971. virtual void TearDown() {
  5972. svr_.stop();
  5973. if (!request_threads_.empty()) {
  5974. std::this_thread::sleep_for(std::chrono::seconds(1));
  5975. for (auto &t : request_threads_) {
  5976. t.join();
  5977. }
  5978. }
  5979. t_.join();
  5980. }
  5981. map<string, string> persons_;
  5982. #ifdef CPPHTTPLIB_SSL_ENABLED
  5983. SSLClient cli_;
  5984. SSLServer svr_;
  5985. #else
  5986. Client cli_;
  5987. Server svr_;
  5988. #endif
  5989. thread t_;
  5990. std::vector<thread> request_threads_;
  5991. };
  5992. TEST_F(ServerTest, GetMethod200) {
  5993. auto res = cli_.Get("/hi");
  5994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5995. EXPECT_EQ("HTTP/1.1", res->version);
  5996. EXPECT_EQ(StatusCode::OK_200, res->status);
  5997. EXPECT_EQ("OK", res->reason);
  5998. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5999. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6000. EXPECT_EQ("Hello World!", res->body);
  6001. }
  6002. TEST_F(ServerTest, GetEmptyFile) {
  6003. auto res = cli_.Get("/empty_file");
  6004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6005. EXPECT_EQ(StatusCode::OK_200, res->status);
  6006. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6007. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6008. EXPECT_EQ("", res->body);
  6009. }
  6010. TEST_F(ServerTest, GetFileContent) {
  6011. auto res = cli_.Get("/file_content");
  6012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6013. EXPECT_EQ(StatusCode::OK_200, res->status);
  6014. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6015. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6016. EXPECT_EQ("test.html", res->body);
  6017. }
  6018. TEST_F(ServerTest, GetFileContentWithRange) {
  6019. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6022. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6023. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6024. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6025. EXPECT_EQ("est", res->body);
  6026. }
  6027. TEST_F(ServerTest, GetFileContentWithContentType) {
  6028. auto res = cli_.Get("/file_content_with_content_type");
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. EXPECT_EQ(StatusCode::OK_200, res->status);
  6031. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6032. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6033. EXPECT_EQ("file\n", res->body);
  6034. }
  6035. TEST_F(ServerTest, GetInvalidFileContent) {
  6036. auto res = cli_.Get("/invalid_file_content");
  6037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6038. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6039. }
  6040. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6041. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6043. EXPECT_EQ("HTTP/1.1", res->version);
  6044. EXPECT_EQ(StatusCode::OK_200, res->status);
  6045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6046. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6047. EXPECT_EQ("Hello World!", res->body);
  6048. }
  6049. TEST_F(ServerTest, GetMethod302) {
  6050. auto res = cli_.Get("/");
  6051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6052. EXPECT_EQ(StatusCode::Found_302, res->status);
  6053. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6054. }
  6055. TEST_F(ServerTest, GetMethod302Redirect) {
  6056. cli_.set_follow_location(true);
  6057. auto res = cli_.Get("/");
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ(StatusCode::OK_200, res->status);
  6060. EXPECT_EQ("Hello World!", res->body);
  6061. EXPECT_EQ("/hi", res->location);
  6062. }
  6063. TEST_F(ServerTest, GetMethod404) {
  6064. auto res = cli_.Get("/invalid");
  6065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6066. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6067. }
  6068. TEST_F(ServerTest, HeadMethod200) {
  6069. auto res = cli_.Head("/hi");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ(StatusCode::OK_200, res->status);
  6072. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6073. EXPECT_TRUE(res->body.empty());
  6074. }
  6075. TEST_F(ServerTest, HeadMethod200Static) {
  6076. auto res = cli_.Head("/mount/dir/index.html");
  6077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6078. EXPECT_EQ(StatusCode::OK_200, res->status);
  6079. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6080. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6081. EXPECT_TRUE(res->body.empty());
  6082. }
  6083. TEST_F(ServerTest, HeadMethod404) {
  6084. auto res = cli_.Head("/invalid");
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6087. EXPECT_TRUE(res->body.empty());
  6088. }
  6089. TEST_F(ServerTest, GetMethodPersonJohn) {
  6090. auto res = cli_.Get("/person/john");
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::OK_200, res->status);
  6093. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6094. EXPECT_EQ("programmer", res->body);
  6095. }
  6096. TEST_F(ServerTest, PostMethod1) {
  6097. auto res = cli_.Get("/person/john1");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6100. res = cli_.Post("/person", "name=john1&note=coder",
  6101. "application/x-www-form-urlencoded");
  6102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6103. ASSERT_EQ(StatusCode::OK_200, res->status);
  6104. res = cli_.Get("/person/john1");
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. ASSERT_EQ(StatusCode::OK_200, res->status);
  6107. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6108. ASSERT_EQ("coder", res->body);
  6109. }
  6110. TEST_F(ServerTest, PostMethod2) {
  6111. auto res = cli_.Get("/person/john2");
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6114. Params params;
  6115. params.emplace("name", "john2");
  6116. params.emplace("note", "coder");
  6117. res = cli_.Post("/person", params);
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. ASSERT_EQ(StatusCode::OK_200, res->status);
  6120. res = cli_.Get("/person/john2");
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. ASSERT_EQ(StatusCode::OK_200, res->status);
  6123. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6124. ASSERT_EQ("coder", res->body);
  6125. }
  6126. TEST_F(ServerTest, PutMethod3) {
  6127. auto res = cli_.Get("/person/john3");
  6128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6129. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6130. Params params;
  6131. params.emplace("name", "john3");
  6132. params.emplace("note", "coder");
  6133. res = cli_.Put("/person", params);
  6134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6135. ASSERT_EQ(StatusCode::OK_200, res->status);
  6136. res = cli_.Get("/person/john3");
  6137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6138. ASSERT_EQ(StatusCode::OK_200, res->status);
  6139. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6140. ASSERT_EQ("coder", res->body);
  6141. }
  6142. TEST_F(ServerTest, DeleteMethod1) {
  6143. auto res = cli_.Get("/person/john4");
  6144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6145. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6146. Params params;
  6147. params.emplace("name", "john4");
  6148. params.emplace("note", "coder");
  6149. res = cli_.Post("/person", params);
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. ASSERT_EQ(StatusCode::OK_200, res->status);
  6152. res = cli_.Get("/person/john4");
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. ASSERT_EQ(StatusCode::OK_200, res->status);
  6155. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6156. ASSERT_EQ("coder", res->body);
  6157. Params delete_params;
  6158. delete_params.emplace("name", "john4");
  6159. res = cli_.Delete("/person", delete_params);
  6160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6161. ASSERT_EQ(StatusCode::OK_200, res->status);
  6162. ASSERT_EQ("DELETED", res->body);
  6163. res = cli_.Get("/person/john4");
  6164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6165. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6166. }
  6167. TEST_F(ServerTest, DeleteMethod2) {
  6168. auto res = cli_.Get("/person/john5");
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6171. Params params;
  6172. params.emplace("name", "john5");
  6173. params.emplace("note", "developer");
  6174. res = cli_.Post("/person", params);
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. ASSERT_EQ(StatusCode::OK_200, res->status);
  6177. res = cli_.Get("/person/john5");
  6178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6179. ASSERT_EQ(StatusCode::OK_200, res->status);
  6180. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6181. ASSERT_EQ("developer", res->body);
  6182. Params delete_params;
  6183. delete_params.emplace("name", "john5");
  6184. Headers headers;
  6185. headers.emplace("Custom-Header", "test-value");
  6186. res = cli_.Delete("/person", headers, delete_params);
  6187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6188. ASSERT_EQ(StatusCode::OK_200, res->status);
  6189. ASSERT_EQ("DELETED", res->body);
  6190. res = cli_.Get("/person/john5");
  6191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6192. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6193. }
  6194. TEST_F(ServerTest, DeleteMethod3) {
  6195. auto res = cli_.Get("/person/john6");
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6198. Params params;
  6199. params.emplace("name", "john6");
  6200. params.emplace("note", "tester");
  6201. res = cli_.Post("/person", params);
  6202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6203. ASSERT_EQ(StatusCode::OK_200, res->status);
  6204. res = cli_.Get("/person/john6");
  6205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6206. ASSERT_EQ(StatusCode::OK_200, res->status);
  6207. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6208. ASSERT_EQ("tester", res->body);
  6209. Params delete_params;
  6210. delete_params.emplace("name", "john6");
  6211. Headers headers;
  6212. headers.emplace("Custom-Header", "test-value");
  6213. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6215. ASSERT_EQ(StatusCode::OK_200, res->status);
  6216. ASSERT_EQ("DELETED", res->body);
  6217. res = cli_.Get("/person/john6");
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6220. }
  6221. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6222. Params params;
  6223. params.emplace("json", JSON_DATA);
  6224. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. ASSERT_EQ(StatusCode::OK_200, res->status);
  6227. ASSERT_EQ(JSON_DATA, res->body);
  6228. }
  6229. TEST_F(ServerTest, PostEmptyContent) {
  6230. auto res = cli_.Post("/empty", "", "text/plain");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. ASSERT_EQ("empty", res->body);
  6234. }
  6235. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6236. auto res = cli_.Post("/empty-no-content-type");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. ASSERT_EQ(StatusCode::OK_200, res->status);
  6239. ASSERT_EQ("empty-no-content-type", res->body);
  6240. }
  6241. TEST_F(ServerTest, PostPathOnly) {
  6242. auto res = cli_.Post("/path-only");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. ASSERT_EQ(StatusCode::OK_200, res->status);
  6245. ASSERT_EQ("path-only", res->body);
  6246. }
  6247. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6248. auto res = cli_.Post("/path-headers-only",
  6249. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6251. ASSERT_EQ(StatusCode::OK_200, res->status);
  6252. ASSERT_EQ("path-headers-only", res->body);
  6253. }
  6254. TEST_F(ServerTest, PostLarge) {
  6255. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. ASSERT_EQ(StatusCode::OK_200, res->status);
  6258. EXPECT_EQ(LARGE_DATA, res->body);
  6259. }
  6260. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6261. auto res = cli_.Put("/empty-no-content-type");
  6262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6263. ASSERT_EQ(StatusCode::OK_200, res->status);
  6264. ASSERT_EQ("empty-no-content-type", res->body);
  6265. }
  6266. TEST_F(ServerTest, GetMethodDir) {
  6267. auto res = cli_.Get("/dir/");
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. EXPECT_EQ(StatusCode::OK_200, res->status);
  6270. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6271. auto body = R"(<html>
  6272. <head>
  6273. </head>
  6274. <body>
  6275. <a href="/dir/test.html">Test</a>
  6276. <a href="/hi">hi</a>
  6277. </body>
  6278. </html>
  6279. )";
  6280. EXPECT_EQ(body, res->body);
  6281. }
  6282. TEST_F(ServerTest, GetMethodDirTest) {
  6283. auto res = cli_.Get("/dir/test.html");
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::OK_200, res->status);
  6286. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6287. EXPECT_EQ("test.html", res->body);
  6288. }
  6289. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6290. auto res = cli_.Get("/dir/../dir/test.html");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::OK_200, res->status);
  6293. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6294. EXPECT_EQ("test.html", res->body);
  6295. }
  6296. TEST_F(ServerTest, GetMethodInvalidPath) {
  6297. auto res = cli_.Get("/dir/../test.html");
  6298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6299. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6300. }
  6301. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6302. auto res = cli_.Get("/../www/dir/test.html");
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6305. }
  6306. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6307. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6310. }
  6311. TEST_F(ServerTest, GetMethodDirMountTest) {
  6312. auto res = cli_.Get("/mount/dir/test.html");
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. EXPECT_EQ(StatusCode::OK_200, res->status);
  6315. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6316. EXPECT_EQ("test.html", res->body);
  6317. }
  6318. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6319. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::OK_200, res->status);
  6322. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6323. EXPECT_EQ("test.html", res->body);
  6324. }
  6325. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6326. auto res = cli_.Get("/mount/dir/../test.html");
  6327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6328. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6329. }
  6330. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6331. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6334. }
  6335. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6336. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6338. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6339. }
  6340. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6341. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6344. }
  6345. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6346. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6349. }
  6350. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6351. auto res = cli_.Get("/mount/dir");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6354. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6355. }
  6356. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6357. auto res = cli_.Get("//dir");
  6358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6359. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6360. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6361. }
  6362. TEST_F(ServerTest, PostMethod303) {
  6363. auto res = cli_.Post("/1", "body", "text/plain");
  6364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6365. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6366. EXPECT_EQ("/2", res->get_header_value("Location"));
  6367. }
  6368. TEST_F(ServerTest, PostMethod303Redirect) {
  6369. cli_.set_follow_location(true);
  6370. auto res = cli_.Post("/1", "body", "text/plain");
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. EXPECT_EQ(StatusCode::OK_200, res->status);
  6373. EXPECT_EQ("redirected.", res->body);
  6374. EXPECT_EQ("/2", res->location);
  6375. }
  6376. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6377. auto res = cli_.Get("/dir/test.abcde");
  6378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6381. EXPECT_EQ("abcde", res->body);
  6382. }
  6383. TEST_F(ServerTest, StaticFileRange) {
  6384. auto res =
  6385. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6387. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6388. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6389. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6390. EXPECT_EQ(true, res->has_header("Content-Range"));
  6391. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6392. EXPECT_EQ(std::string("cd"), res->body);
  6393. }
  6394. TEST_F(ServerTest, StaticFileRanges) {
  6395. auto res = cli_.Get("/dir/test.abcde",
  6396. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6398. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6399. EXPECT_TRUE(
  6400. res->get_header_value("Content-Type")
  6401. .find(
  6402. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6403. 0);
  6404. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6405. }
  6406. TEST_F(ServerTest, StaticFileRangeHead) {
  6407. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6410. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6411. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6412. EXPECT_EQ(true, res->has_header("Content-Range"));
  6413. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6414. }
  6415. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6416. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6419. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6420. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6421. EXPECT_EQ(true, res->has_header("Content-Range"));
  6422. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6423. res->get_header_value("Content-Range"));
  6424. EXPECT_EQ("LAST\n", res->body);
  6425. }
  6426. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6427. auto res =
  6428. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6431. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6432. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6433. EXPECT_EQ(true, res->has_header("Content-Range"));
  6434. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6435. }
  6436. TEST_F(ServerTest, StaticFileBigFile) {
  6437. auto res = cli_.Get("/dir/1MB.txt");
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::OK_200, res->status);
  6440. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6441. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6442. }
  6443. TEST_F(ServerTest, InvalidBaseDirMount) {
  6444. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6445. }
  6446. TEST_F(ServerTest, Binary) {
  6447. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6448. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6449. "application/octet-stream");
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. ASSERT_EQ(StatusCode::OK_200, res->status);
  6452. ASSERT_EQ(4U, res->body.size());
  6453. res = cli_.Put("/binary", binary.data(), binary.size(),
  6454. "application/octet-stream");
  6455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6456. ASSERT_EQ(StatusCode::OK_200, res->status);
  6457. ASSERT_EQ(4U, res->body.size());
  6458. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6459. "application/octet-stream");
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. ASSERT_EQ(StatusCode::OK_200, res->status);
  6462. ASSERT_EQ(4U, res->body.size());
  6463. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6464. "application/octet-stream");
  6465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6466. ASSERT_EQ(StatusCode::OK_200, res->status);
  6467. ASSERT_EQ(4U, res->body.size());
  6468. }
  6469. TEST_F(ServerTest, BinaryString) {
  6470. auto binary = std::string("\x00\x01\x02\x03", 4);
  6471. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. ASSERT_EQ(StatusCode::OK_200, res->status);
  6474. ASSERT_EQ(4U, res->body.size());
  6475. res = cli_.Put("/binary", binary, "application/octet-stream");
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. ASSERT_EQ(StatusCode::OK_200, res->status);
  6478. ASSERT_EQ(4U, res->body.size());
  6479. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6481. ASSERT_EQ(StatusCode::OK_200, res->status);
  6482. ASSERT_EQ(4U, res->body.size());
  6483. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. ASSERT_EQ(StatusCode::OK_200, res->status);
  6486. ASSERT_EQ(4U, res->body.size());
  6487. }
  6488. TEST_F(ServerTest, EmptyRequest) {
  6489. auto res = cli_.Get("");
  6490. ASSERT_TRUE(!res);
  6491. EXPECT_EQ(Error::Connection, res.error());
  6492. }
  6493. TEST_F(ServerTest, LongRequest) {
  6494. std::string request;
  6495. for (size_t i = 0; i < 545; i++) {
  6496. request += "/TooLongRequest";
  6497. }
  6498. request += "OK";
  6499. auto res = cli_.Get(request.c_str());
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6502. }
  6503. TEST_F(ServerTest, TooLongRequest) {
  6504. std::string request;
  6505. for (size_t i = 0; i < 546; i++) {
  6506. request += "/TooLongRequest";
  6507. }
  6508. request += "_NG";
  6509. auto start = std::chrono::high_resolution_clock::now();
  6510. cli_.set_keep_alive(true);
  6511. auto res = cli_.Get(request.c_str());
  6512. auto end = std::chrono::high_resolution_clock::now();
  6513. auto elapsed =
  6514. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6515. .count();
  6516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6517. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6518. EXPECT_LE(elapsed, 1000);
  6519. EXPECT_EQ("close", res->get_header_value("Connection"));
  6520. EXPECT_FALSE(cli_.is_socket_open());
  6521. }
  6522. TEST_F(ServerTest, AlmostTooLongRequest) {
  6523. // test for #2046 - URI length check shouldn't include other content on req
  6524. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6525. // leading /, space, HTTP/1.1)
  6526. std::string request =
  6527. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6528. auto res = cli_.Get(request.c_str());
  6529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6530. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6531. }
  6532. TEST_F(ServerTest, LongHeader) {
  6533. Request req;
  6534. req.method = "GET";
  6535. req.path = "/hi";
  6536. std::string host_and_port;
  6537. host_and_port += HOST;
  6538. host_and_port += ":";
  6539. host_and_port += std::to_string(PORT);
  6540. req.headers.emplace("Host", host_and_port.c_str());
  6541. req.headers.emplace("Accept", "*/*");
  6542. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6543. req.headers.emplace(
  6544. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@");
  6574. auto res = std::make_shared<Response>();
  6575. auto error = Error::Success;
  6576. auto ret = cli_.send(req, *res, error);
  6577. ASSERT_TRUE(ret);
  6578. EXPECT_EQ(StatusCode::OK_200, res->status);
  6579. }
  6580. TEST_F(ServerTest, LongQueryValue) {
  6581. auto start = std::chrono::high_resolution_clock::now();
  6582. cli_.set_keep_alive(true);
  6583. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6584. auto end = std::chrono::high_resolution_clock::now();
  6585. auto elapsed =
  6586. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6587. .count();
  6588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6589. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6590. EXPECT_LE(elapsed, 1000);
  6591. EXPECT_EQ("close", res->get_header_value("Connection"));
  6592. EXPECT_FALSE(cli_.is_socket_open());
  6593. }
  6594. TEST_F(ServerTest, TooLongQueryValue) {
  6595. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6596. ASSERT_FALSE(res);
  6597. EXPECT_EQ(Error::Read, res.error());
  6598. }
  6599. TEST_F(ServerTest, TooLongHeader) {
  6600. Request req;
  6601. req.method = "GET";
  6602. req.path = "/hi";
  6603. std::string host_and_port;
  6604. host_and_port += HOST;
  6605. host_and_port += ":";
  6606. host_and_port += std::to_string(PORT);
  6607. req.headers.emplace("Host", host_and_port.c_str());
  6608. req.headers.emplace("Accept", "*/*");
  6609. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6610. req.headers.emplace(
  6611. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@");
  6641. auto res = std::make_shared<Response>();
  6642. auto error = Error::Success;
  6643. auto ret = cli_.send(req, *res, error);
  6644. ASSERT_TRUE(ret);
  6645. EXPECT_EQ(StatusCode::OK_200, res->status);
  6646. }
  6647. TEST_F(ServerTest, HeaderCountAtLimit) {
  6648. // Test with headers just under the 100 limit
  6649. httplib::Headers headers;
  6650. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6651. // This should keep us just under the 100 header limit
  6652. for (int i = 0; i < 95; i++) {
  6653. std::string name = "X-Test-Header-" + std::to_string(i);
  6654. std::string value = "value" + std::to_string(i);
  6655. headers.emplace(name, value);
  6656. }
  6657. // This should work fine as we're under the limit
  6658. auto res = cli_.Get("/hi", headers);
  6659. EXPECT_TRUE(res);
  6660. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6661. }
  6662. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6663. // Test with many headers to exceed the 100 limit
  6664. httplib::Headers headers;
  6665. // Add 150 headers to definitely exceed the 100 limit
  6666. for (int i = 0; i < 150; i++) {
  6667. std::string name = "X-Test-Header-" + std::to_string(i);
  6668. std::string value = "value" + std::to_string(i);
  6669. headers.emplace(name, value);
  6670. }
  6671. // This should fail due to exceeding header count limit
  6672. cli_.set_keep_alive(true);
  6673. auto res = cli_.Get("/hi", headers);
  6674. // The server should respond with 400 Bad Request
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6677. EXPECT_EQ("close", res->get_header_value("Connection"));
  6678. EXPECT_FALSE(cli_.is_socket_open());
  6679. }
  6680. TEST_F(ServerTest, PercentEncoding) {
  6681. auto res = cli_.Get("/e%6edwith%");
  6682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. }
  6685. TEST_F(ServerTest, PercentEncodingUnicode) {
  6686. auto res = cli_.Get("/e%u006edwith%");
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::OK_200, res->status);
  6689. }
  6690. TEST_F(ServerTest, InvalidPercentEncoding) {
  6691. auto res = cli_.Get("/%endwith%");
  6692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6693. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6694. }
  6695. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6696. auto res = cli_.Get("/%uendwith%");
  6697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6699. }
  6700. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6701. auto res = cli_.Get("/hello?aaa=bbb%");
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6704. }
  6705. TEST_F(ServerTest, PlusSignEncoding) {
  6706. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6708. EXPECT_EQ(StatusCode::OK_200, res->status);
  6709. EXPECT_EQ("a +b", res->body);
  6710. }
  6711. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6712. // This test simulates a potential DoS attack using many headers
  6713. // to verify our security fix prevents memory exhaustion
  6714. httplib::Headers attack_headers;
  6715. // Attempt to add many headers like an attacker would (200 headers to far
  6716. // exceed limit)
  6717. for (int i = 0; i < 200; i++) {
  6718. std::string name = "X-Attack-Header-" + std::to_string(i);
  6719. std::string value = "attack_payload_" + std::to_string(i);
  6720. attack_headers.emplace(name, value);
  6721. }
  6722. // Try to POST with excessive headers
  6723. cli_.set_keep_alive(true);
  6724. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6725. // Should either fail or return 400 Bad Request due to security limit
  6726. if (res) {
  6727. // If we get a response, it should be 400 Bad Request
  6728. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6729. EXPECT_EQ("close", res->get_header_value("Connection"));
  6730. }
  6731. EXPECT_FALSE(cli_.is_socket_open());
  6732. }
  6733. TEST_F(ServerTest, MultipartFormData) {
  6734. UploadFormDataItems items = {
  6735. {"text1", "text default", "", ""},
  6736. {"text2", "aωb", "", ""},
  6737. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6738. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6739. {"file3", "", "", "application/octet-stream"},
  6740. {"file4", "", "", " application/json tmp-string "}};
  6741. auto res = cli_.Post("/multipart", items);
  6742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6743. EXPECT_EQ(StatusCode::OK_200, res->status);
  6744. }
  6745. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6746. UploadFormDataItems items = {
  6747. {"text", "default text", "", ""},
  6748. {"multi_text1", "aaaaa", "", ""},
  6749. {"multi_text1", "bbbbb", "", ""},
  6750. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6751. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6752. "application/json"},
  6753. };
  6754. auto res = cli_.Post("/multipart/multi_file_values", items);
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. EXPECT_EQ(StatusCode::OK_200, res->status);
  6757. }
  6758. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6759. auto res = cli_.Get("/hi");
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6763. EXPECT_EQ("Hello World!", res->body);
  6764. }
  6765. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6766. Request req;
  6767. req.method = "POST";
  6768. req.path = "/chunked";
  6769. std::string host_and_port;
  6770. host_and_port += HOST;
  6771. host_and_port += ":";
  6772. host_and_port += std::to_string(PORT);
  6773. req.headers.emplace("Host", host_and_port.c_str());
  6774. req.headers.emplace("Accept", "*/*");
  6775. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6776. req.headers.emplace("Content-Type", "text/plain");
  6777. req.headers.emplace("Content-Length", "0");
  6778. req.headers.emplace(
  6779. "Transfer-Encoding",
  6780. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6781. // Client does not chunk, so make a chunked body manually.
  6782. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6783. auto res = std::make_shared<Response>();
  6784. auto error = Error::Success;
  6785. auto ret = cli_.send(req, *res, error);
  6786. ASSERT_TRUE(ret);
  6787. EXPECT_EQ(StatusCode::OK_200, res->status);
  6788. }
  6789. template <typename ClientT>
  6790. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6791. int expected_status) {
  6792. Request req;
  6793. req.method = "POST";
  6794. req.path = "/chunked";
  6795. std::string host_and_port;
  6796. host_and_port += HOST;
  6797. host_and_port += ":";
  6798. host_and_port += std::to_string(PORT);
  6799. req.headers.emplace("Host", host_and_port.c_str());
  6800. req.headers.emplace("Content-Length", "0");
  6801. req.headers.emplace("Transfer-Encoding", "chunked");
  6802. req.body = body;
  6803. auto res = std::make_shared<Response>();
  6804. auto error = Error::Success;
  6805. ASSERT_TRUE(cli.send(req, *res, error));
  6806. EXPECT_EQ(expected_status, res->status);
  6807. }
  6808. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6809. // rather than treat them as valid lengths.
  6810. template <typename ClientT>
  6811. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6812. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6813. }
  6814. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6815. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6816. }
  6817. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6818. expect_chunked_body_rejected(
  6819. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6820. }
  6821. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6822. // chunk-size line carries no CR, LF or other control character ahead of its
  6823. // terminator. Such a line must be refused rather than read as extension text.
  6824. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6825. expect_chunked_body_rejected(
  6826. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6827. }
  6828. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6829. expect_chunked_body_rejected(
  6830. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6831. }
  6832. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6833. expect_chunked_body_rejected(
  6834. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6835. }
  6836. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6837. // The literal stays split: a hex escape consumes every hex digit that
  6838. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6839. expect_chunked_body_rejected(
  6840. cli_, "4;a\x01"
  6841. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6842. }
  6843. TEST_F(ServerTest, AcceptsChunkExtension) {
  6844. expect_chunked_body_status(cli_,
  6845. "4;name=value\r\ndech\r\n"
  6846. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6847. "0;last\r\n\r\n",
  6848. StatusCode::OK_200);
  6849. }
  6850. TEST_F(ServerTest, GetStreamed2) {
  6851. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6853. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6854. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6855. EXPECT_EQ(true, res->has_header("Content-Range"));
  6856. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6857. EXPECT_EQ(std::string("ab"), res->body);
  6858. }
  6859. TEST_F(ServerTest, GetStreamed) {
  6860. auto res = cli_.Get("/streamed");
  6861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6862. EXPECT_EQ(StatusCode::OK_200, res->status);
  6863. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6864. EXPECT_EQ(std::string("aaabbb"), res->body);
  6865. }
  6866. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6867. auto res = cli_.Get("/streamed-without-length",
  6868. Headers{make_range_header({{0, -1}})});
  6869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6870. EXPECT_EQ(StatusCode::OK_200, res->status);
  6871. EXPECT_EQ(false, res->has_header("Content-Length"));
  6872. EXPECT_EQ(false, res->has_header("Content-Range"));
  6873. EXPECT_EQ(std::string("abcdefg"), res->body);
  6874. }
  6875. TEST_F(ServerTest, GetStreamedWithRange1) {
  6876. auto res =
  6877. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6879. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6880. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6881. EXPECT_EQ(true, res->has_header("Content-Range"));
  6882. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6883. EXPECT_EQ(std::string("def"), res->body);
  6884. }
  6885. TEST_F(ServerTest, GetStreamedWithRange2) {
  6886. auto res =
  6887. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6889. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6890. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6891. EXPECT_EQ(true, res->has_header("Content-Range"));
  6892. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6893. EXPECT_EQ(std::string("bcdefg"), res->body);
  6894. }
  6895. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6896. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6898. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6899. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6900. EXPECT_EQ(true, res->has_header("Content-Range"));
  6901. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6902. EXPECT_EQ(std::string("efg"), res->body);
  6903. }
  6904. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6905. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6906. // the entire representation.
  6907. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6908. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6910. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6911. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6912. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6913. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6914. }
  6915. }
  6916. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6917. auto res =
  6918. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6920. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6921. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6922. EXPECT_EQ(false, res->has_header("Content-Range"));
  6923. EXPECT_EQ(0U, res->body.size());
  6924. }
  6925. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6926. // Only a 206 is served as a partial representation. Under any other status
  6927. // `apply_ranges()` reported the full content length, so the body must match
  6928. // that header, and the content provider must never be asked for an offset
  6929. // outside the representation.
  6930. auto check = [&](int status, const char *range) {
  6931. auto path =
  6932. std::string("/streamed-with-range?status=") + std::to_string(status);
  6933. auto ctx = path + " Range: " + range;
  6934. auto res = cli_.Get(path, Headers{{"Range", range}});
  6935. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6936. EXPECT_EQ(status, res->status) << ctx;
  6937. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6938. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6939. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6940. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6941. };
  6942. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6943. check(403, "bytes=3-5");
  6944. // The offset is far past the representation.
  6945. check(403, "bytes=100000-100200");
  6946. // `first_pos` is still -1 here, and the bounds asserts in
  6947. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6948. check(403, "bytes=-3");
  6949. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6950. // multipart branch would have written one that is empty.
  6951. check(403, "bytes=1-2, 4-5");
  6952. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6953. // covers the whole representation.
  6954. check(200, "bytes=3-5");
  6955. check(200, "bytes=1-2, 4-5");
  6956. }
  6957. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6958. auto res =
  6959. cli_.Get("/streamed-with-range",
  6960. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6961. "92233720368547758079223372036854775807"}});
  6962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6963. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6964. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6965. EXPECT_EQ(false, res->has_header("Content-Range"));
  6966. EXPECT_EQ(0U, res->body.size());
  6967. }
  6968. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6969. auto res = cli_.Get(
  6970. "/with-range",
  6971. Headers{{"Range",
  6972. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6973. {"Accept-Encoding", ""}});
  6974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6975. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6976. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6977. EXPECT_EQ(true, res->has_header("Content-Range"));
  6978. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6979. EXPECT_EQ(std::string("abcdefg"), res->body);
  6980. }
  6981. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6982. auto res = cli_.Get("/with-range", Headers{
  6983. {"Range", "bytes=0-"},
  6984. {"Accept-Encoding", ""},
  6985. });
  6986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6988. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6989. EXPECT_EQ(true, res->has_header("Content-Range"));
  6990. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6991. EXPECT_EQ(std::string("abcdefg"), res->body);
  6992. }
  6993. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6994. auto res = cli_.Get("/streamed-with-range",
  6995. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6998. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6999. EXPECT_EQ(false, res->has_header("Content-Range"));
  7000. EXPECT_EQ(267U, res->body.size());
  7001. // Check that both range contents are present
  7002. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7003. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7004. // Check that Content-Range headers are present for both ranges
  7005. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7006. std::string::npos);
  7007. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7008. std::string::npos);
  7009. }
  7010. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7011. Ranges ranges;
  7012. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7013. ranges.emplace_back(0, -1);
  7014. }
  7015. auto res = cli_.Get("/streamed-with-range?error",
  7016. Headers{{make_range_header(ranges)}});
  7017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7018. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7019. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7020. EXPECT_EQ(false, res->has_header("Content-Range"));
  7021. EXPECT_EQ(0U, res->body.size());
  7022. }
  7023. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7024. auto res = cli_.Get("/streamed-with-range",
  7025. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7028. EXPECT_EQ(5U, res->body.size());
  7029. // Check that overlapping ranges are coalesced into a single range
  7030. EXPECT_EQ("bcdef", res->body);
  7031. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7032. // Should be single range, not multipart
  7033. EXPECT_TRUE(res->has_header("Content-Range"));
  7034. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7035. }
  7036. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7037. auto res = cli_.Get("/streamed-with-range",
  7038. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7041. EXPECT_EQ(268U, res->body.size());
  7042. // Check that both range contents are present
  7043. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7044. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7045. // Check that Content-Range headers are present for both ranges
  7046. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7047. std::string::npos);
  7048. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7049. std::string::npos);
  7050. }
  7051. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7052. auto res = cli_.Get("/streamed-with-range",
  7053. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7056. EXPECT_EQ(269U, res->body.size());
  7057. // Check that both duplicate range contents are present
  7058. size_t first_abc = res->body.find("abc\r\n");
  7059. EXPECT_TRUE(first_abc != std::string::npos);
  7060. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7061. EXPECT_TRUE(second_abc != std::string::npos);
  7062. // Check that Content-Range headers are present for both ranges
  7063. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7064. EXPECT_TRUE(first_range != std::string::npos);
  7065. size_t second_range =
  7066. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7067. EXPECT_TRUE(second_range != std::string::npos);
  7068. }
  7069. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7070. auto res =
  7071. cli_.Get("/streamed-with-range?error",
  7072. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7074. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7075. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7076. EXPECT_EQ(false, res->has_header("Content-Range"));
  7077. EXPECT_EQ(0U, res->body.size());
  7078. }
  7079. TEST_F(ServerTest, GetStreamedEndless) {
  7080. uint64_t offset = 0;
  7081. auto res = cli_.Get("/streamed-cancel",
  7082. [&](const char * /*data*/, uint64_t data_length) {
  7083. if (offset < 100) {
  7084. offset += data_length;
  7085. return true;
  7086. }
  7087. return false;
  7088. });
  7089. ASSERT_TRUE(!res);
  7090. EXPECT_EQ(Error::Canceled, res.error());
  7091. }
  7092. TEST_F(ServerTest, ClientStop) {
  7093. std::atomic_size_t count{4};
  7094. std::vector<std::thread> threads;
  7095. for (auto i = count.load(); i != 0; --i) {
  7096. threads.emplace_back([&]() {
  7097. auto res = cli_.Get("/streamed-cancel",
  7098. [&](const char *, uint64_t) { return true; });
  7099. --count;
  7100. ASSERT_TRUE(!res);
  7101. EXPECT_TRUE(res.error() == Error::Canceled ||
  7102. res.error() == Error::Read || res.error() == Error::Write);
  7103. });
  7104. }
  7105. std::this_thread::sleep_for(std::chrono::seconds(2));
  7106. while (count != 0) {
  7107. cli_.stop();
  7108. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7109. }
  7110. for (auto &t : threads) {
  7111. t.join();
  7112. }
  7113. }
  7114. TEST_F(ServerTest, GetWithRange1) {
  7115. auto res = cli_.Get("/with-range", Headers{
  7116. make_range_header({{3, 5}}),
  7117. {"Accept-Encoding", ""},
  7118. });
  7119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7121. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7122. EXPECT_EQ(true, res->has_header("Content-Range"));
  7123. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7124. EXPECT_EQ(std::string("def"), res->body);
  7125. }
  7126. TEST_F(ServerTest, GetWithRange2) {
  7127. auto res = cli_.Get("/with-range", Headers{
  7128. make_range_header({{1, -1}}),
  7129. {"Accept-Encoding", ""},
  7130. });
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7133. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7134. EXPECT_EQ(true, res->has_header("Content-Range"));
  7135. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7136. EXPECT_EQ(std::string("bcdefg"), res->body);
  7137. }
  7138. TEST_F(ServerTest, GetWithRange3) {
  7139. auto res = cli_.Get("/with-range", Headers{
  7140. make_range_header({{0, 0}}),
  7141. {"Accept-Encoding", ""},
  7142. });
  7143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7144. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7145. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7146. EXPECT_EQ(true, res->has_header("Content-Range"));
  7147. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7148. EXPECT_EQ(std::string("a"), res->body);
  7149. }
  7150. TEST_F(ServerTest, GetWithRange4) {
  7151. auto res = cli_.Get("/with-range", Headers{
  7152. make_range_header({{-1, 2}}),
  7153. {"Accept-Encoding", ""},
  7154. });
  7155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7157. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7158. EXPECT_EQ(true, res->has_header("Content-Range"));
  7159. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7160. EXPECT_EQ(std::string("fg"), res->body);
  7161. }
  7162. TEST_F(ServerTest, GetWithRange5) {
  7163. auto res = cli_.Get("/with-range", Headers{
  7164. make_range_header({{0, 5}}),
  7165. {"Accept-Encoding", ""},
  7166. });
  7167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7168. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7169. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7170. EXPECT_EQ(true, res->has_header("Content-Range"));
  7171. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7172. EXPECT_EQ(std::string("abcdef"), res->body);
  7173. }
  7174. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7175. auto res =
  7176. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7178. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7179. }
  7180. TEST_F(ServerTest, GetWithRangeMultipart) {
  7181. auto res =
  7182. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7184. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7185. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7186. EXPECT_EQ(false, res->has_header("Content-Range"));
  7187. EXPECT_EQ(267U, res->body.size());
  7188. }
  7189. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7190. auto res = cli_.Get("/with-range",
  7191. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7194. }
  7195. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7196. auto res = cli_.Get("/with-range-customized-response",
  7197. Headers{{make_range_header({{1, 2}})}});
  7198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7199. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7200. EXPECT_EQ(true, res->has_header("Content-Length"));
  7201. EXPECT_EQ(false, res->has_header("Content-Range"));
  7202. EXPECT_EQ(JSON_DATA, res->body);
  7203. }
  7204. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7205. auto res = cli_.Get("/with-range-customized-response",
  7206. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7208. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7209. EXPECT_EQ(true, res->has_header("Content-Length"));
  7210. EXPECT_EQ(false, res->has_header("Content-Range"));
  7211. EXPECT_EQ(JSON_DATA, res->body);
  7212. }
  7213. TEST_F(ServerTest, Issue1772) {
  7214. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7216. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7217. }
  7218. TEST_F(ServerTest, Issue609) {
  7219. auto res = cli_.Delete("/issue609");
  7220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7221. EXPECT_EQ(StatusCode::OK_200, res->status);
  7222. EXPECT_EQ(std::string("ok"), res->body);
  7223. }
  7224. TEST_F(ServerTest, GetStreamedChunked) {
  7225. auto res = cli_.Get("/streamed-chunked");
  7226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7227. EXPECT_EQ(StatusCode::OK_200, res->status);
  7228. EXPECT_EQ(std::string("123456789"), res->body);
  7229. }
  7230. TEST_F(ServerTest, GetStreamedChunked2) {
  7231. auto res = cli_.Get("/streamed-chunked2");
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::OK_200, res->status);
  7234. EXPECT_EQ(std::string("123456789"), res->body);
  7235. }
  7236. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7237. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7239. EXPECT_EQ(StatusCode::OK_200, res->status);
  7240. EXPECT_EQ(std::string("123456789"), res->body);
  7241. EXPECT_TRUE(res->has_header("Trailer"));
  7242. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7243. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7244. // Trailers are now stored separately from headers (security fix)
  7245. EXPECT_EQ(2U, res->trailers.size());
  7246. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7247. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7248. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7249. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7250. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7251. // Verify trailers are NOT in headers (security verification)
  7252. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7253. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7254. }
  7255. TEST_F(ServerTest, LargeChunkedPost) {
  7256. Request req;
  7257. req.method = "POST";
  7258. req.path = "/large-chunked";
  7259. std::string host_and_port;
  7260. host_and_port += HOST;
  7261. host_and_port += ":";
  7262. host_and_port += std::to_string(PORT);
  7263. req.headers.emplace("Host", host_and_port.c_str());
  7264. req.headers.emplace("Accept", "*/*");
  7265. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7266. req.headers.emplace("Content-Type", "text/plain");
  7267. req.headers.emplace("Content-Length", "0");
  7268. req.headers.emplace("Transfer-Encoding", "chunked");
  7269. std::string long_string(30 * 1024u, 'a');
  7270. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7271. // Attempt to make a large enough post to exceed OS buffers, to test that
  7272. // the server handles short reads if the full chunk data isn't available.
  7273. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7274. auto res = std::make_shared<Response>();
  7275. auto error = Error::Success;
  7276. auto ret = cli_.send(req, *res, error);
  7277. ASSERT_TRUE(ret);
  7278. EXPECT_EQ(StatusCode::OK_200, res->status);
  7279. }
  7280. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7281. auto res = cli_.Get("/remote_addr");
  7282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7283. EXPECT_EQ(StatusCode::OK_200, res->status);
  7284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7285. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7286. }
  7287. TEST_F(ServerTest, GetMethodLocalAddr) {
  7288. auto res = cli_.Get("/local_addr");
  7289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7290. EXPECT_EQ(StatusCode::OK_200, res->status);
  7291. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7292. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7293. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7294. }
  7295. TEST_F(ServerTest, HTTPResponseSplitting) {
  7296. auto res = cli_.Get("/http_response_splitting");
  7297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7298. EXPECT_EQ(StatusCode::OK_200, res->status);
  7299. }
  7300. TEST_F(ServerTest, SlowRequest) {
  7301. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7302. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7303. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7304. }
  7305. #if 0
  7306. TEST_F(ServerTest, SlowPost) {
  7307. char buffer[64 * 1024];
  7308. memset(buffer, 0x42, sizeof(buffer));
  7309. auto res = cli_.Post(
  7310. "/slowpost", 64 * 1024 * 1024,
  7311. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7312. auto ret = sink.write(buffer, sizeof(buffer));
  7313. EXPECT_TRUE(ret);
  7314. return true;
  7315. },
  7316. "text/plain");
  7317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7318. EXPECT_EQ(StatusCode::OK_200, res->status);
  7319. }
  7320. TEST_F(ServerTest, SlowPostFail) {
  7321. char buffer[64 * 1024];
  7322. memset(buffer, 0x42, sizeof(buffer));
  7323. cli_.set_write_timeout(std::chrono::seconds(0));
  7324. auto res = cli_.Post(
  7325. "/slowpost", 64 * 1024 * 1024,
  7326. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7327. sink.write(buffer, sizeof(buffer));
  7328. return true;
  7329. },
  7330. "text/plain");
  7331. ASSERT_TRUE(!res);
  7332. EXPECT_EQ(Error::Write, res.error());
  7333. }
  7334. #endif
  7335. TEST_F(ServerTest, Put) {
  7336. auto res = cli_.Put("/put", "PUT", "text/plain");
  7337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7338. EXPECT_EQ(StatusCode::OK_200, res->status);
  7339. EXPECT_EQ("PUT", res->body);
  7340. }
  7341. TEST_F(ServerTest, PutWithContentProvider) {
  7342. auto res = cli_.Put(
  7343. "/put", 3,
  7344. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7345. sink.os << "PUT";
  7346. return true;
  7347. },
  7348. "text/plain");
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::OK_200, res->status);
  7351. EXPECT_EQ("PUT", res->body);
  7352. }
  7353. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7354. auto res = cli_.Post(
  7355. "/post", 42,
  7356. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7357. return false;
  7358. },
  7359. "text/plain");
  7360. ASSERT_TRUE(!res);
  7361. EXPECT_EQ(Error::Canceled, res.error());
  7362. }
  7363. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7364. auto res = cli_.Put(
  7365. "/put",
  7366. [](size_t /*offset*/, DataSink &sink) {
  7367. sink.os << "PUT";
  7368. sink.done();
  7369. return true;
  7370. },
  7371. "text/plain");
  7372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7373. EXPECT_EQ(StatusCode::OK_200, res->status);
  7374. EXPECT_EQ("PUT", res->body);
  7375. }
  7376. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7377. auto res = cli_.Post(
  7378. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7379. "text/plain");
  7380. ASSERT_TRUE(!res);
  7381. EXPECT_EQ(Error::Canceled, res.error());
  7382. }
  7383. TEST_F(ServerTest, PostLoopBack) {
  7384. std::string body;
  7385. auto res = cli_.Post(
  7386. "/post-loopback", 9,
  7387. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7388. EXPECT_EQ(9u, length);
  7389. sink.write("123", 3);
  7390. sink.write("456", 3);
  7391. sink.write("789", 3);
  7392. return true;
  7393. },
  7394. "text/plain",
  7395. [&body](const char *data, size_t data_length) {
  7396. body.append(data, data_length);
  7397. return true;
  7398. });
  7399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7400. EXPECT_EQ(StatusCode::OK_200, res->status);
  7401. EXPECT_EQ("123456789", body);
  7402. }
  7403. TEST_F(ServerTest, PutLoopBack) {
  7404. std::string body;
  7405. auto res = cli_.Put(
  7406. "/put-loopback", 9,
  7407. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7408. EXPECT_EQ(9u, length);
  7409. sink.write("123", 3);
  7410. sink.write("456", 3);
  7411. sink.write("789", 3);
  7412. return true;
  7413. },
  7414. "text/plain",
  7415. [&body](const char *data, size_t data_length) {
  7416. body.append(data, data_length);
  7417. return true;
  7418. });
  7419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7420. EXPECT_EQ(StatusCode::OK_200, res->status);
  7421. EXPECT_EQ("123456789", body);
  7422. }
  7423. TEST_F(ServerTest, PatchLoopBack) {
  7424. std::string body;
  7425. auto res = cli_.Patch(
  7426. "/patch-loopback", 9,
  7427. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7428. EXPECT_EQ(9u, length);
  7429. sink.write("123", 3);
  7430. sink.write("456", 3);
  7431. sink.write("789", 3);
  7432. return true;
  7433. },
  7434. "text/plain",
  7435. [&body](const char *data, size_t data_length) {
  7436. body.append(data, data_length);
  7437. return true;
  7438. });
  7439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7440. EXPECT_EQ(StatusCode::OK_200, res->status);
  7441. EXPECT_EQ("123456789", body);
  7442. }
  7443. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7444. std::string body;
  7445. auto res = cli_.Post(
  7446. "/post-loopback",
  7447. [](size_t /*offset*/, DataSink &sink) {
  7448. sink.write("123", 3);
  7449. sink.write("456", 3);
  7450. sink.write("789", 3);
  7451. sink.done();
  7452. return true;
  7453. },
  7454. "text/plain",
  7455. [&body](const char *data, size_t data_length) {
  7456. body.append(data, data_length);
  7457. return true;
  7458. });
  7459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7460. EXPECT_EQ(StatusCode::OK_200, res->status);
  7461. EXPECT_EQ("123456789", body);
  7462. }
  7463. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7464. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7465. cli_.set_compress(true);
  7466. auto res = cli_.Put(
  7467. "/put", 3,
  7468. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7469. sink.os << "PUT";
  7470. return true;
  7471. },
  7472. "text/plain");
  7473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7474. EXPECT_EQ(StatusCode::OK_200, res->status);
  7475. EXPECT_EQ("PUT", res->body);
  7476. }
  7477. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7478. cli_.set_compress(true);
  7479. auto res = cli_.Post(
  7480. "/post", 42,
  7481. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7482. return false;
  7483. },
  7484. "text/plain");
  7485. ASSERT_TRUE(!res);
  7486. EXPECT_EQ(Error::Canceled, res.error());
  7487. }
  7488. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7489. cli_.set_compress(true);
  7490. auto res = cli_.Put(
  7491. "/put",
  7492. [](size_t /*offset*/, DataSink &sink) {
  7493. sink.os << "PUT";
  7494. sink.done();
  7495. return true;
  7496. },
  7497. "text/plain");
  7498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7499. EXPECT_EQ(StatusCode::OK_200, res->status);
  7500. EXPECT_EQ("PUT", res->body);
  7501. }
  7502. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7503. cli_.set_compress(true);
  7504. auto res = cli_.Post(
  7505. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7506. "text/plain");
  7507. ASSERT_TRUE(!res);
  7508. EXPECT_EQ(Error::Canceled, res.error());
  7509. }
  7510. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7511. cli_.set_compress(true);
  7512. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7514. EXPECT_EQ(StatusCode::OK_200, res->status);
  7515. EXPECT_EQ(LARGE_DATA, res->body);
  7516. }
  7517. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7518. #ifdef CPPHTTPLIB_SSL_ENABLED
  7519. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7520. Client cli(s.c_str());
  7521. cli.enable_server_certificate_verification(false);
  7522. #else
  7523. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7524. Client cli(s.c_str());
  7525. #endif
  7526. cli.set_compress(true);
  7527. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7529. EXPECT_EQ(StatusCode::OK_200, res->status);
  7530. EXPECT_EQ(LARGE_DATA, res->body);
  7531. // The compressed size should be less than a 10th of the original. May vary
  7532. // depending on the zlib library.
  7533. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7534. static_cast<uint64_t>(10 * 1024 * 1024));
  7535. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7536. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7537. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7538. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7539. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7540. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7541. #endif
  7542. }
  7543. TEST_F(ServerTest, PutContentWithDeflate) {
  7544. cli_.set_compress(false);
  7545. Headers headers;
  7546. headers.emplace("Content-Encoding", "deflate");
  7547. // PUT in deflate format:
  7548. auto res = cli_.Put("/put", headers,
  7549. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7551. EXPECT_EQ(StatusCode::OK_200, res->status);
  7552. EXPECT_EQ("PUT", res->body);
  7553. }
  7554. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7555. Headers headers;
  7556. headers.emplace("Accept-Encoding", "gzip, deflate");
  7557. auto res = cli_.Get("/streamed-chunked", headers);
  7558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7559. EXPECT_EQ(StatusCode::OK_200, res->status);
  7560. EXPECT_EQ(std::string("123456789"), res->body);
  7561. }
  7562. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7563. Headers headers;
  7564. headers.emplace("Accept-Encoding", "gzip, deflate");
  7565. auto res = cli_.Get("/streamed-chunked2", headers);
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ(StatusCode::OK_200, res->status);
  7568. EXPECT_EQ(std::string("123456789"), res->body);
  7569. }
  7570. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7571. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7573. EXPECT_EQ(StatusCode::OK_200, res->status);
  7574. }
  7575. TEST(GzipDecompressor, ChunkedDecompression) {
  7576. std::string data;
  7577. for (size_t i = 0; i < 32 * 1024; ++i) {
  7578. data.push_back(static_cast<char>('a' + i % 26));
  7579. }
  7580. std::string compressed_data;
  7581. {
  7582. httplib::detail::gzip_compressor compressor;
  7583. bool result = compressor.compress(
  7584. data.data(), data.size(),
  7585. /*last=*/true,
  7586. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7587. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7588. compressed_data_size);
  7589. return true;
  7590. });
  7591. ASSERT_TRUE(result);
  7592. }
  7593. std::string decompressed_data;
  7594. {
  7595. httplib::detail::gzip_decompressor decompressor;
  7596. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7597. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7598. size_t chunk_size = 130;
  7599. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7600. chunk_begin += chunk_size) {
  7601. size_t current_chunk_size =
  7602. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7603. bool result = decompressor.decompress(
  7604. compressed_data.data() + chunk_begin, current_chunk_size,
  7605. [&](const char *decompressed_data_chunk,
  7606. size_t decompressed_data_chunk_size) {
  7607. decompressed_data.insert(decompressed_data.size(),
  7608. decompressed_data_chunk,
  7609. decompressed_data_chunk_size);
  7610. return true;
  7611. });
  7612. ASSERT_TRUE(result);
  7613. }
  7614. }
  7615. ASSERT_EQ(data, decompressed_data);
  7616. }
  7617. TEST(GzipDecompressor, DeflateDecompression) {
  7618. std::string original_text = "Raw deflate without gzip";
  7619. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7620. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7621. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7622. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7623. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7624. std::string decompressed_data;
  7625. {
  7626. httplib::detail::gzip_decompressor decompressor;
  7627. bool result = decompressor.decompress(
  7628. compressed_data.data(), compressed_data.size(),
  7629. [&](const char *decompressed_data_chunk,
  7630. size_t decompressed_data_chunk_size) {
  7631. decompressed_data.insert(decompressed_data.size(),
  7632. decompressed_data_chunk,
  7633. decompressed_data_chunk_size);
  7634. return true;
  7635. });
  7636. ASSERT_TRUE(result);
  7637. }
  7638. ASSERT_EQ(original_text, decompressed_data);
  7639. }
  7640. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7641. std::string original_text = "Raw deflate without gzip";
  7642. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7643. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7644. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7645. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7646. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7647. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7648. std::string decompressed_data;
  7649. {
  7650. httplib::detail::gzip_decompressor decompressor;
  7651. bool result = decompressor.decompress(
  7652. compressed_data.data(), compressed_data.size(),
  7653. [&](const char *decompressed_data_chunk,
  7654. size_t decompressed_data_chunk_size) {
  7655. decompressed_data.insert(decompressed_data.size(),
  7656. decompressed_data_chunk,
  7657. decompressed_data_chunk_size);
  7658. return true;
  7659. });
  7660. ASSERT_TRUE(result);
  7661. }
  7662. ASSERT_EQ(original_text, decompressed_data);
  7663. }
  7664. #endif
  7665. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7666. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7667. Headers headers;
  7668. headers.emplace("Accept-Encoding", "br");
  7669. auto res = cli_.Get("/streamed-chunked", headers);
  7670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7671. EXPECT_EQ(StatusCode::OK_200, res->status);
  7672. EXPECT_EQ(std::string("123456789"), res->body);
  7673. }
  7674. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7675. Headers headers;
  7676. headers.emplace("Accept-Encoding", "br");
  7677. auto res = cli_.Get("/streamed-chunked2", headers);
  7678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7679. EXPECT_EQ(StatusCode::OK_200, res->status);
  7680. EXPECT_EQ(std::string("123456789"), res->body);
  7681. }
  7682. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7683. cli_.set_compress(true);
  7684. auto res = cli_.Put(
  7685. "/put", 3,
  7686. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7687. sink.os << "PUT";
  7688. return true;
  7689. },
  7690. "text/plain");
  7691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7692. EXPECT_EQ(StatusCode::OK_200, res->status);
  7693. EXPECT_EQ("PUT", res->body);
  7694. }
  7695. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7696. cli_.set_compress(true);
  7697. auto res = cli_.Put(
  7698. "/put",
  7699. [](size_t /*offset*/, DataSink &sink) {
  7700. sink.os << "PUT";
  7701. sink.done();
  7702. return true;
  7703. },
  7704. "text/plain");
  7705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7706. EXPECT_EQ(StatusCode::OK_200, res->status);
  7707. EXPECT_EQ("PUT", res->body);
  7708. }
  7709. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7710. cli_.set_compress(true);
  7711. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ(LARGE_DATA, res->body);
  7715. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7716. }
  7717. #endif
  7718. TEST_F(ServerTest, Patch) {
  7719. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::OK_200, res->status);
  7722. EXPECT_EQ("PATCH", res->body);
  7723. }
  7724. TEST_F(ServerTest, Delete) {
  7725. auto res = cli_.Delete("/delete");
  7726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7727. EXPECT_EQ(StatusCode::OK_200, res->status);
  7728. EXPECT_EQ("DELETE", res->body);
  7729. }
  7730. TEST_F(ServerTest, DeleteContentReceiver) {
  7731. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7733. EXPECT_EQ(StatusCode::OK_200, res->status);
  7734. EXPECT_EQ("content", res->body);
  7735. }
  7736. TEST_F(ServerTest, Options) {
  7737. auto res = cli_.Options("*");
  7738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7739. EXPECT_EQ(StatusCode::OK_200, res->status);
  7740. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7741. EXPECT_TRUE(res->body.empty());
  7742. }
  7743. TEST_F(ServerTest, URL) {
  7744. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7746. EXPECT_EQ(StatusCode::OK_200, res->status);
  7747. }
  7748. TEST_F(ServerTest, ArrayParam) {
  7749. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. }
  7753. TEST_F(ServerTest, ArrayParamValues) {
  7754. auto res =
  7755. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. }
  7759. TEST_F(ServerTest, NoMultipleHeaders) {
  7760. Headers headers = {{"Content-Length", "5"}};
  7761. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7762. "text/plain");
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::OK_200, res->status);
  7765. }
  7766. TEST_F(ServerTest, PostContentReceiver) {
  7767. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. ASSERT_EQ(StatusCode::OK_200, res->status);
  7770. ASSERT_EQ("content", res->body);
  7771. }
  7772. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7773. UploadFormDataItems items = {
  7774. {"text1", "text default", "", ""},
  7775. {"text2", "aωb", "", ""},
  7776. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7777. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7778. {"file3", "", "", "application/octet-stream"},
  7779. };
  7780. auto res = cli_.Post("/content_receiver", items);
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ(StatusCode::OK_200, res->status);
  7783. }
  7784. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7785. UploadFormDataItems items = {
  7786. {"text1", "text default", "", ""},
  7787. {"text2", "aωb", "", ""},
  7788. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7789. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7790. {"file3", "", "", "application/octet-stream"},
  7791. };
  7792. auto boundary = std::string("+++++");
  7793. std::string body;
  7794. for (const auto &item : items) {
  7795. body += "--" + boundary + "\r\n";
  7796. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7797. if (!item.filename.empty()) {
  7798. body += "; filename=\"" + item.filename + "\"";
  7799. }
  7800. body += "\r\n";
  7801. if (!item.content_type.empty()) {
  7802. body += "Content-Type: " + item.content_type + "\r\n";
  7803. }
  7804. body += "\r\n";
  7805. body += item.content + "\r\n";
  7806. }
  7807. body += "--" + boundary + "--\r\n";
  7808. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7809. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7811. EXPECT_EQ(StatusCode::OK_200, res->status);
  7812. }
  7813. TEST(MultipartFormDataTest, FieldEscaping) {
  7814. Server svr;
  7815. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7816. const ContentReader &content_reader) {
  7817. ASSERT_TRUE(req.is_multipart_form_data());
  7818. std::vector<FormData> received;
  7819. content_reader(
  7820. [&](const FormData &file) {
  7821. received.push_back(file);
  7822. return true;
  7823. },
  7824. [&](const char *data, size_t data_length) {
  7825. received.back().content.append(data, data_length);
  7826. return true;
  7827. });
  7828. // '"', CR and LF in names and filenames are escaped following the
  7829. // WHATWG HTML standard, so each part still parses as a single part
  7830. // with no injected headers. Content types get CR/LF escaped too,
  7831. // while '"' (legal there, e.g. quoted charset) is preserved.
  7832. ASSERT_EQ(4U, received.size());
  7833. EXPECT_EQ("na%22me", received[0].name);
  7834. EXPECT_EQ("quoted name", received[0].content);
  7835. EXPECT_EQ("file", received[1].name);
  7836. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7837. received[1].filename);
  7838. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7839. EXPECT_EQ("injected", received[1].content);
  7840. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7841. EXPECT_EQ("my%22file.txt", received[2].filename);
  7842. EXPECT_EQ("cr lf name", received[2].content);
  7843. EXPECT_EQ("typed", received[3].name);
  7844. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7845. received[3].content_type);
  7846. EXPECT_EQ("typed content", received[3].content);
  7847. });
  7848. auto port = svr.bind_to_any_port("localhost");
  7849. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7850. auto se = detail::scope_exit([&] {
  7851. svr.stop();
  7852. t.join();
  7853. ASSERT_FALSE(svr.is_running());
  7854. });
  7855. svr.wait_until_ready();
  7856. Client cli("localhost", port);
  7857. UploadFormDataItems items = {
  7858. {"na\"me", "quoted name", "", ""},
  7859. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7860. "application/octet-stream"},
  7861. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7862. {"typed", "typed content", "",
  7863. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7864. };
  7865. auto res = cli.Post("/post", items);
  7866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7867. EXPECT_EQ(StatusCode::OK_200, res->status);
  7868. }
  7869. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7870. const UploadFormDataItems items = {
  7871. {"name1", "Content 1", "", ""},
  7872. {"name2", "Content 2", "file2.txt", "text/plain"},
  7873. };
  7874. Server svr;
  7875. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7876. const ContentReader &content_reader) {
  7877. ASSERT_TRUE(req.is_multipart_form_data());
  7878. std::vector<FormData> received;
  7879. content_reader(
  7880. [&](const FormData &file) {
  7881. received.push_back(file);
  7882. return true;
  7883. },
  7884. [&](const char *data, size_t data_length) {
  7885. received.back().content.append(data, data_length);
  7886. return true;
  7887. });
  7888. ASSERT_EQ(2U, received.size());
  7889. EXPECT_EQ("name1", received[0].name);
  7890. EXPECT_EQ("Content 1", received[0].content);
  7891. EXPECT_EQ("name2", received[1].name);
  7892. EXPECT_EQ("Content 2", received[1].content);
  7893. EXPECT_EQ("file2.txt", received[1].filename);
  7894. EXPECT_EQ("text/plain", received[1].content_type);
  7895. });
  7896. auto port = svr.bind_to_any_port("localhost");
  7897. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7898. auto se = detail::scope_exit([&] {
  7899. svr.stop();
  7900. t.join();
  7901. ASSERT_FALSE(svr.is_running());
  7902. });
  7903. svr.wait_until_ready();
  7904. Client cli("localhost", port);
  7905. // Whole-body serialization with a generated boundary
  7906. {
  7907. MultipartFormDataWriter writer;
  7908. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7909. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7910. writer.content_type());
  7911. auto body = writer.serialize(items);
  7912. EXPECT_EQ(body.size(), writer.content_length(items));
  7913. auto res = cli.Post("/post", body, writer.content_type());
  7914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7915. EXPECT_EQ(StatusCode::OK_200, res->status);
  7916. }
  7917. // Per-part framing with a custom boundary via a content provider
  7918. {
  7919. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7920. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7921. MultipartFormDataWriter writer("custom-boundary_123");
  7922. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7923. std::string body;
  7924. for (const auto &item : items) {
  7925. body += writer.item_begin(item);
  7926. body += item.content;
  7927. body += MultipartFormDataWriter::item_end();
  7928. }
  7929. body += writer.finish();
  7930. EXPECT_EQ(body.size(), writer.content_length(items));
  7931. auto res = cli.Post(
  7932. "/post", body.size(),
  7933. [&](size_t offset, size_t length, DataSink &sink) {
  7934. sink.write(body.data() + offset, length);
  7935. return true;
  7936. },
  7937. writer.content_type());
  7938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7939. EXPECT_EQ(StatusCode::OK_200, res->status);
  7940. }
  7941. }
  7942. TEST_F(ServerTest, PostContentReceiverGzip) {
  7943. cli_.set_compress(true);
  7944. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7946. ASSERT_EQ(StatusCode::OK_200, res->status);
  7947. ASSERT_EQ("content", res->body);
  7948. }
  7949. TEST_F(ServerTest, PutContentReceiver) {
  7950. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7952. ASSERT_EQ(StatusCode::OK_200, res->status);
  7953. ASSERT_EQ("content", res->body);
  7954. }
  7955. TEST_F(ServerTest, PatchContentReceiver) {
  7956. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7958. ASSERT_EQ(StatusCode::OK_200, res->status);
  7959. ASSERT_EQ("content", res->body);
  7960. }
  7961. template <typename ClientType>
  7962. void TestWithHeadersAndContentReceiver(
  7963. ClientType &cli,
  7964. std::function<Result(ClientType &, const std::string &, const Headers &,
  7965. const std::string &, const std::string &,
  7966. ContentReceiver, DownloadProgress)>
  7967. request_func) {
  7968. Headers headers;
  7969. headers.emplace("X-Custom-Header", "test-value");
  7970. std::string received_body;
  7971. auto res = request_func(
  7972. cli, "/content_receiver", headers, "content", "application/json",
  7973. [&](const char *data, size_t data_length) {
  7974. received_body.append(data, data_length);
  7975. return true;
  7976. },
  7977. nullptr);
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. EXPECT_EQ(StatusCode::OK_200, res->status);
  7980. EXPECT_EQ("content", received_body);
  7981. }
  7982. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7983. #ifdef CPPHTTPLIB_SSL_ENABLED
  7984. using ClientT = SSLClient;
  7985. #else
  7986. using ClientT = Client;
  7987. #endif
  7988. TestWithHeadersAndContentReceiver<ClientT>(
  7989. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7990. const std::string &body, const std::string &content_type,
  7991. ContentReceiver receiver, DownloadProgress progress) {
  7992. return cli.Post(path, headers, body, content_type, receiver, progress);
  7993. });
  7994. }
  7995. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7996. #ifdef CPPHTTPLIB_SSL_ENABLED
  7997. using ClientT = SSLClient;
  7998. #else
  7999. using ClientT = Client;
  8000. #endif
  8001. TestWithHeadersAndContentReceiver<ClientT>(
  8002. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8003. const std::string &body, const std::string &content_type,
  8004. ContentReceiver receiver, DownloadProgress progress) {
  8005. return cli.Put(path, headers, body, content_type, receiver, progress);
  8006. });
  8007. }
  8008. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8009. #ifdef CPPHTTPLIB_SSL_ENABLED
  8010. using ClientT = SSLClient;
  8011. #else
  8012. using ClientT = Client;
  8013. #endif
  8014. TestWithHeadersAndContentReceiver<ClientT>(
  8015. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8016. const std::string &body, const std::string &content_type,
  8017. ContentReceiver receiver, DownloadProgress progress) {
  8018. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8019. });
  8020. }
  8021. template <typename ClientType>
  8022. void TestWithHeadersAndContentReceiverWithProgress(
  8023. ClientType &cli,
  8024. std::function<Result(ClientType &, const std::string &, const Headers &,
  8025. const std::string &, const std::string &,
  8026. ContentReceiver, DownloadProgress)>
  8027. request_func) {
  8028. Headers headers;
  8029. headers.emplace("X-Test-Header", "progress-test");
  8030. std::string received_body;
  8031. auto progress_called = false;
  8032. auto res = request_func(
  8033. cli, "/content_receiver", headers, "content", "text/plain",
  8034. [&](const char *data, size_t data_length) {
  8035. received_body.append(data, data_length);
  8036. return true;
  8037. },
  8038. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8039. progress_called = true;
  8040. return true;
  8041. });
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(StatusCode::OK_200, res->status);
  8044. EXPECT_EQ("content", received_body);
  8045. EXPECT_TRUE(progress_called);
  8046. }
  8047. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8048. #ifdef CPPHTTPLIB_SSL_ENABLED
  8049. using ClientT = SSLClient;
  8050. #else
  8051. using ClientT = Client;
  8052. #endif
  8053. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8054. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8055. const std::string &body, const std::string &content_type,
  8056. ContentReceiver receiver, DownloadProgress progress) {
  8057. return cli.Post(path, headers, body, content_type, receiver, progress);
  8058. });
  8059. }
  8060. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8061. #ifdef CPPHTTPLIB_SSL_ENABLED
  8062. using ClientT = SSLClient;
  8063. #else
  8064. using ClientT = Client;
  8065. #endif
  8066. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8067. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8068. const std::string &body, const std::string &content_type,
  8069. ContentReceiver receiver, DownloadProgress progress) {
  8070. return cli.Put(path, headers, body, content_type, receiver, progress);
  8071. });
  8072. }
  8073. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8074. #ifdef CPPHTTPLIB_SSL_ENABLED
  8075. using ClientT = SSLClient;
  8076. #else
  8077. using ClientT = Client;
  8078. #endif
  8079. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8080. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8081. const std::string &body, const std::string &content_type,
  8082. ContentReceiver receiver, DownloadProgress progress) {
  8083. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8084. });
  8085. }
  8086. template <typename ClientType>
  8087. void TestWithHeadersAndContentReceiverError(
  8088. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8089. const Headers &, const std::string &,
  8090. const std::string &, ContentReceiver)>
  8091. request_func) {
  8092. Headers headers;
  8093. headers.emplace("X-Error-Test", "true");
  8094. std::string received_body;
  8095. auto receiver_failed = false;
  8096. auto res =
  8097. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8098. [&](const char *data, size_t data_length) {
  8099. received_body.append(data, data_length);
  8100. receiver_failed = true;
  8101. return false;
  8102. });
  8103. ASSERT_FALSE(res);
  8104. EXPECT_TRUE(receiver_failed);
  8105. }
  8106. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8107. #ifdef CPPHTTPLIB_SSL_ENABLED
  8108. using ClientT = SSLClient;
  8109. #else
  8110. using ClientT = Client;
  8111. #endif
  8112. TestWithHeadersAndContentReceiverError<ClientT>(
  8113. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8114. const std::string &body, const std::string &content_type,
  8115. ContentReceiver receiver) {
  8116. return cli.Post(path, headers, body, content_type, receiver);
  8117. });
  8118. }
  8119. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8120. #ifdef CPPHTTPLIB_SSL_ENABLED
  8121. using ClientT = SSLClient;
  8122. #else
  8123. using ClientT = Client;
  8124. #endif
  8125. TestWithHeadersAndContentReceiverError<ClientT>(
  8126. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8127. const std::string &body, const std::string &content_type,
  8128. ContentReceiver receiver) {
  8129. return cli.Put(path, headers, body, content_type, receiver);
  8130. });
  8131. }
  8132. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8133. #ifdef CPPHTTPLIB_SSL_ENABLED
  8134. using ClientT = SSLClient;
  8135. #else
  8136. using ClientT = Client;
  8137. #endif
  8138. TestWithHeadersAndContentReceiverError<ClientT>(
  8139. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8140. const std::string &body, const std::string &content_type,
  8141. ContentReceiver receiver) {
  8142. return cli.Patch(path, headers, body, content_type, receiver);
  8143. });
  8144. }
  8145. TEST_F(ServerTest, PostQueryStringAndBody) {
  8146. auto res =
  8147. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8149. ASSERT_EQ(StatusCode::OK_200, res->status);
  8150. }
  8151. TEST_F(ServerTest, HTTP2Magic) {
  8152. Request req;
  8153. req.method = "PRI";
  8154. req.path = "*";
  8155. req.body = "SM";
  8156. auto res = std::make_shared<Response>();
  8157. auto error = Error::Success;
  8158. auto ret = cli_.send(req, *res, error);
  8159. ASSERT_TRUE(ret);
  8160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8161. }
  8162. TEST_F(ServerTest, KeepAlive) {
  8163. auto res = cli_.Get("/hi");
  8164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8167. EXPECT_EQ("Hello World!", res->body);
  8168. res = cli_.Get("/hi");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8172. EXPECT_EQ("Hello World!", res->body);
  8173. res = cli_.Get("/hi");
  8174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8175. EXPECT_EQ(StatusCode::OK_200, res->status);
  8176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8177. EXPECT_EQ("Hello World!", res->body);
  8178. res = cli_.Get("/not-exist");
  8179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8180. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8181. res = cli_.Post("/empty", "", "text/plain");
  8182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8183. EXPECT_EQ(StatusCode::OK_200, res->status);
  8184. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8185. EXPECT_EQ("empty", res->body);
  8186. EXPECT_EQ("close", res->get_header_value("Connection"));
  8187. res = cli_.Post(
  8188. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8189. "text/plain");
  8190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8191. EXPECT_EQ(StatusCode::OK_200, res->status);
  8192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8193. EXPECT_EQ("empty", res->body);
  8194. cli_.set_keep_alive(false);
  8195. res = cli_.Get("/last-request");
  8196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8197. EXPECT_EQ(StatusCode::OK_200, res->status);
  8198. EXPECT_EQ("close", res->get_header_value("Connection"));
  8199. }
  8200. TEST_F(ServerTest, TooManyRedirect) {
  8201. cli_.set_follow_location(true);
  8202. auto res = cli_.Get("/redirect/0");
  8203. ASSERT_TRUE(!res);
  8204. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8205. }
  8206. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8207. Request req;
  8208. req.method = "FOOBAR";
  8209. req.path = "/hi";
  8210. cli_.set_keep_alive(true);
  8211. auto res = cli_.send(req);
  8212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8214. EXPECT_EQ("close", res->get_header_value("Connection"));
  8215. EXPECT_FALSE(cli_.is_socket_open());
  8216. }
  8217. TEST_F(ServerTest, CustomRouteReadsBody) {
  8218. const std::string xml =
  8219. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8220. Request req;
  8221. req.method = "PROPFIND";
  8222. req.path = "/dav/dir";
  8223. req.set_header("Depth", "1");
  8224. req.body = xml;
  8225. auto res = cli_.send(req);
  8226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8227. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8228. EXPECT_EQ(xml, res->body);
  8229. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8230. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8231. }
  8232. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8233. Request req;
  8234. req.method = "PROPFIND";
  8235. req.path = "/dav/42";
  8236. auto res = cli_.send(req);
  8237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8238. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8239. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8240. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8241. }
  8242. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8243. Request req;
  8244. req.method = "PROPFIND";
  8245. req.path = "/dav-re/123";
  8246. auto res = cli_.send(req);
  8247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8248. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8249. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8250. }
  8251. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8252. Request req;
  8253. req.method = "MKCOL";
  8254. req.path = "/dav-mkcol";
  8255. auto res = cli_.send(req);
  8256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8257. EXPECT_EQ(StatusCode::Created_201, res->status);
  8258. }
  8259. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8260. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8261. Request req;
  8262. req.method = "REPORT";
  8263. req.path = "/dav-report";
  8264. req.body = xml;
  8265. auto res = cli_.send(req);
  8266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8267. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8268. EXPECT_EQ(xml, res->body);
  8269. }
  8270. // A content reader route must fire even when the request carries no body,
  8271. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8272. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8273. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8274. Request req;
  8275. req.method = "REPORT";
  8276. req.path = "/dav-report";
  8277. auto res = cli_.send(req);
  8278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8279. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8280. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8281. }
  8282. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8283. Request req;
  8284. req.method = "PROPFIND";
  8285. req.path = "/not-dav";
  8286. auto res = cli_.send(req);
  8287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8288. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8289. }
  8290. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8291. Request req;
  8292. req.method = "UNLOCK";
  8293. req.path = "/dav/dir";
  8294. cli_.set_keep_alive(true);
  8295. auto res = cli_.send(req);
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8298. EXPECT_EQ("close", res->get_header_value("Connection"));
  8299. EXPECT_FALSE(cli_.is_socket_open());
  8300. }
  8301. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8302. // The mount point serves this path, but only for GET and HEAD.
  8303. auto get_res = cli_.Get("/dir/index.html");
  8304. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8305. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8306. Request req;
  8307. req.method = "PROPFIND";
  8308. req.path = "/dir/index.html";
  8309. auto res = cli_.send(req);
  8310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8311. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8312. }
  8313. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8314. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8315. cli_.set_keep_alive(true);
  8316. for (auto i = 0; i < 2; i++) {
  8317. Request req;
  8318. req.method = "PROPFIND";
  8319. req.path = "/dav/dir";
  8320. req.body = xml;
  8321. auto res = cli_.send(req);
  8322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8323. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8324. EXPECT_EQ(xml, res->body);
  8325. EXPECT_TRUE(cli_.is_socket_open());
  8326. }
  8327. // A built-in method must still be served on the same connection.
  8328. cli_.set_keep_alive(false);
  8329. auto res = cli_.Get("/hi");
  8330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8331. EXPECT_EQ(StatusCode::OK_200, res->status);
  8332. EXPECT_EQ("close", res->get_header_value("Connection"));
  8333. }
  8334. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8335. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8336. Request req;
  8337. req.method = "PROPFIND";
  8338. req.path = "/dav/dir";
  8339. req.set_header("Expect", "100-continue");
  8340. req.body = xml;
  8341. auto res = cli_.send(req);
  8342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8343. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8344. EXPECT_EQ(xml, res->body);
  8345. }
  8346. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8347. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8348. TEST_F(ServerTest, Gzip) {
  8349. Headers headers;
  8350. headers.emplace("Accept-Encoding", "gzip, deflate");
  8351. auto res = cli_.Get("/compress", headers);
  8352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8353. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8354. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8355. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8356. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8357. "7890123456789012345678901234567890",
  8358. res->body);
  8359. EXPECT_EQ(StatusCode::OK_200, res->status);
  8360. }
  8361. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8362. Headers headers;
  8363. headers.emplace("Accept-Encoding", "gzip, deflate");
  8364. auto res = cli_.Get("/compress-with-charset", headers);
  8365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8366. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8367. EXPECT_EQ("application/json; charset=utf-8",
  8368. res->get_header_value("Content-Type"));
  8369. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8370. "7890123456789012345678901234567890",
  8371. res->body);
  8372. EXPECT_EQ(StatusCode::OK_200, res->status);
  8373. }
  8374. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8375. Headers headers;
  8376. headers.emplace("Accept-Encoding", "");
  8377. auto res = cli_.Get("/compress", headers);
  8378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8379. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8380. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8381. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8382. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8383. "7890123456789012345678901234567890",
  8384. res->body);
  8385. EXPECT_EQ(StatusCode::OK_200, res->status);
  8386. }
  8387. TEST_F(ServerTest, GzipWithContentReceiver) {
  8388. Headers headers;
  8389. headers.emplace("Accept-Encoding", "gzip, deflate");
  8390. std::string body;
  8391. auto res = cli_.Get("/compress", headers,
  8392. [&](const char *data, uint64_t data_length) {
  8393. EXPECT_EQ(100U, data_length);
  8394. body.append(data, data_length);
  8395. return true;
  8396. });
  8397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8398. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8399. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8400. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8401. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8402. "7890123456789012345678901234567890",
  8403. body);
  8404. EXPECT_EQ(StatusCode::OK_200, res->status);
  8405. }
  8406. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8407. Headers headers;
  8408. headers.emplace("Accept-Encoding", "gzip, deflate");
  8409. cli_.set_decompress(false);
  8410. auto res = cli_.Get("/compress", headers);
  8411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8412. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8413. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8414. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8415. EXPECT_EQ(33U, res->body.size());
  8416. EXPECT_EQ(StatusCode::OK_200, res->status);
  8417. }
  8418. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8419. Headers headers;
  8420. headers.emplace("Accept-Encoding", "");
  8421. std::string body;
  8422. auto res = cli_.Get("/compress", headers,
  8423. [&](const char *data, uint64_t data_length) {
  8424. EXPECT_EQ(100U, data_length);
  8425. body.append(data, data_length);
  8426. return true;
  8427. });
  8428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8429. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8430. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8431. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8432. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8433. "7890123456789012345678901234567890",
  8434. body);
  8435. EXPECT_EQ(StatusCode::OK_200, res->status);
  8436. }
  8437. TEST_F(ServerTest, NoGzip) {
  8438. Headers headers;
  8439. headers.emplace("Accept-Encoding", "gzip, deflate");
  8440. auto res = cli_.Get("/nocompress", headers);
  8441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8442. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8443. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8444. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8445. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8446. "7890123456789012345678901234567890",
  8447. res->body);
  8448. EXPECT_EQ(StatusCode::OK_200, res->status);
  8449. }
  8450. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8451. Headers headers;
  8452. headers.emplace("Accept-Encoding", "gzip, deflate");
  8453. std::string body;
  8454. auto res = cli_.Get("/nocompress", headers,
  8455. [&](const char *data, uint64_t data_length) {
  8456. EXPECT_EQ(100U, data_length);
  8457. body.append(data, data_length);
  8458. return true;
  8459. });
  8460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8461. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8462. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8463. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8464. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8465. "7890123456789012345678901234567890",
  8466. body);
  8467. EXPECT_EQ(StatusCode::OK_200, res->status);
  8468. }
  8469. TEST_F(ServerTest, MultipartFormDataGzip) {
  8470. UploadFormDataItems items = {
  8471. {"key1", "test", "", ""},
  8472. {"key2", "--abcdefg123", "", ""},
  8473. };
  8474. cli_.set_compress(true);
  8475. auto res = cli_.Post("/compress-multipart", items);
  8476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8477. EXPECT_EQ(StatusCode::OK_200, res->status);
  8478. }
  8479. #endif
  8480. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8481. // Static file compression is opt-in, so these run their own server rather than
  8482. // flipping it on for the shared ServerTest fixture, which would silently
  8483. // rewrite what every other static file test is asserting.
  8484. class StaticFileCompressionTest : public ::testing::Test {
  8485. protected:
  8486. void TearDown() override {
  8487. if (t_.joinable()) {
  8488. svr_.stop();
  8489. t_.join();
  8490. }
  8491. }
  8492. int start(const std::function<void(Server &)> &configure = nullptr) {
  8493. // Serves the same tree as a directory of build-time compressed assets
  8494. // would be served: the mount point names the coding the files are already
  8495. // stored in. Registered before "/" so it is the one that matches.
  8496. svr_.set_mount_point("/pre-encoded", "./www",
  8497. {{"Content-Encoding", "gzip"}});
  8498. svr_.set_mount_point("/", "./www");
  8499. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8500. res.set_file_content("./www/dir/index.html", "text/html");
  8501. });
  8502. svr_.Get("/pre-encoded-file-content",
  8503. [](const Request & /*req*/, Response &res) {
  8504. res.set_header("Content-Encoding", "gzip");
  8505. res.set_file_content("./www/dir/index.html", "text/html");
  8506. });
  8507. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8508. res.set_content_provider(
  8509. 6, "text/plain",
  8510. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8511. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8512. return true;
  8513. });
  8514. });
  8515. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8516. res.set_content_provider(
  8517. 1000, "text/plain",
  8518. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8519. if (offset < 100) {
  8520. std::string data(100, 'A');
  8521. sink.write(data.data(), data.size());
  8522. return true;
  8523. }
  8524. std::this_thread::sleep_for(std::chrono::seconds(2));
  8525. std::string data(900, 'B');
  8526. sink.write(data.data(), data.size());
  8527. return true;
  8528. });
  8529. });
  8530. if (configure) { configure(svr_); }
  8531. auto port = svr_.bind_to_any_port(HOST);
  8532. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8533. svr_.wait_until_ready();
  8534. return port;
  8535. }
  8536. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8537. // Every file under ./www except 1MB.txt is smaller than the default
  8538. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8539. // it out of the way.
  8540. static void enable_without_floor(Server &svr) {
  8541. svr.set_static_file_compression(true);
  8542. svr.set_static_file_compression_min_length(0);
  8543. }
  8544. Server svr_;
  8545. std::thread t_;
  8546. };
  8547. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8548. auto port = start();
  8549. Client cli(HOST, port);
  8550. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8552. EXPECT_EQ(StatusCode::OK_200, res->status);
  8553. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8554. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8555. EXPECT_EQ(1048576U, res->body.size());
  8556. }
  8557. TEST_F(StaticFileCompressionTest, MountPoint) {
  8558. auto port = start(enable);
  8559. Client cli(HOST, port);
  8560. cli.set_decompress(false);
  8561. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8563. EXPECT_EQ(StatusCode::OK_200, res->status);
  8564. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8565. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8566. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8567. // The response stays self-delimiting: a length, not a chunked body.
  8568. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8569. EXPECT_EQ(std::to_string(res->body.size()),
  8570. res->get_header_value("Content-Length"));
  8571. EXPECT_LT(res->body.size(), 1048576U);
  8572. EXPECT_FALSE(res->body.empty());
  8573. }
  8574. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8575. auto port = start(enable);
  8576. Client cli(HOST, port);
  8577. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8579. EXPECT_EQ(StatusCode::OK_200, res->status);
  8580. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8581. EXPECT_EQ(1048576U, res->body.size());
  8582. }
  8583. TEST_F(StaticFileCompressionTest, FileContent) {
  8584. auto port = start(enable_without_floor);
  8585. Client cli(HOST, port);
  8586. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8588. EXPECT_EQ(StatusCode::OK_200, res->status);
  8589. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8590. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8591. EXPECT_EQ(104U, res->body.size());
  8592. }
  8593. // A handler that serves an already-encoded file names the coding itself. The
  8594. // file-backed path decided its coding from Accept-Encoding and the content
  8595. // type alone, so it compressed the stored bytes a second time and appended a
  8596. // second Content-Encoding field line.
  8597. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8598. auto port = start(enable_without_floor);
  8599. Client cli(HOST, port);
  8600. cli.set_decompress(false);
  8601. auto res = cli.Get("/pre-encoded-file-content",
  8602. Headers{{"Accept-Encoding", "gzip"}});
  8603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8604. EXPECT_EQ(StatusCode::OK_200, res->status);
  8605. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8606. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8607. // Vary belongs to a coding the server chose, and it chose none here.
  8608. EXPECT_FALSE(res->has_header("Vary"));
  8609. // The file travels exactly as it is stored on disk.
  8610. EXPECT_EQ(104U, res->body.size());
  8611. }
  8612. // The 1MB file clears the default floor, so this one runs the configuration a
  8613. // deployment would actually have.
  8614. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8615. auto port = start(enable);
  8616. Client cli(HOST, port);
  8617. cli.set_decompress(false);
  8618. auto res =
  8619. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ(StatusCode::OK_200, res->status);
  8622. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8623. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8624. EXPECT_FALSE(res->has_header("Vary"));
  8625. EXPECT_EQ(1048576U, res->body.size());
  8626. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8627. }
  8628. TEST_F(StaticFileCompressionTest, Head) {
  8629. auto port = start(enable);
  8630. Client cli(HOST, port);
  8631. cli.set_decompress(false);
  8632. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8633. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8634. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8636. EXPECT_EQ(StatusCode::OK_200, res->status);
  8637. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8638. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8639. // HEAD still reports the size a GET would return.
  8640. EXPECT_EQ(get->get_header_value("Content-Length"),
  8641. res->get_header_value("Content-Length"));
  8642. EXPECT_TRUE(res->body.empty());
  8643. }
  8644. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8645. auto port = start(enable);
  8646. Client cli(HOST, port);
  8647. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8648. {"Accept-Encoding", "gzip"}});
  8649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8650. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8651. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8652. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8653. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8654. EXPECT_EQ("cd", res->body);
  8655. }
  8656. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8657. auto port = start(enable);
  8658. Client cli(HOST, port);
  8659. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8661. EXPECT_EQ(StatusCode::OK_200, res->status);
  8662. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8663. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8664. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8665. }
  8666. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8667. auto port = start(enable);
  8668. Client cli(HOST, port);
  8669. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8671. EXPECT_EQ(StatusCode::OK_200, res->status);
  8672. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8673. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8674. EXPECT_TRUE(res->body.empty());
  8675. }
  8676. TEST_F(StaticFileCompressionTest, MinLength) {
  8677. auto port = start(enable);
  8678. Client cli(HOST, port);
  8679. // 104 bytes, well under the default floor. Compressing it would add the
  8680. // gzip header and trailer to a body that already fits in one packet.
  8681. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8683. EXPECT_EQ(StatusCode::OK_200, res->status);
  8684. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8685. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8686. }
  8687. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8688. auto port = start([](Server &svr) {
  8689. svr.set_static_file_compression(true);
  8690. svr.set_static_file_compression_min_length(1);
  8691. });
  8692. Client cli(HOST, port);
  8693. cli.set_decompress(false);
  8694. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8696. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8697. // A 9-byte file comes back larger than it went in, because gzip's header and
  8698. // trailer outweigh anything deflate can save. That is the end of the range
  8699. // the floor exists to keep out.
  8700. EXPECT_GT(res->body.size(), 9U);
  8701. }
  8702. TEST_F(StaticFileCompressionTest, MaxLength) {
  8703. auto port = start([](Server &svr) {
  8704. svr.set_static_file_compression(true);
  8705. svr.set_static_file_compression_min_length(0);
  8706. svr.set_static_file_compression_max_length(1024);
  8707. });
  8708. Client cli(HOST, port);
  8709. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8710. // defines `small` as a macro on Windows.
  8711. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8712. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8713. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8714. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8715. // Under it: compressed.
  8716. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8717. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8718. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8719. }
  8720. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8721. auto port = start(enable_without_floor);
  8722. Client cli(HOST, port);
  8723. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8724. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8725. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8726. auto identity_etag = identity->get_header_value("ETag");
  8727. ASSERT_FALSE(identity_etag.empty());
  8728. auto gzipped =
  8729. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8730. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8731. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8732. auto gzip_etag = gzipped->get_header_value("ETag");
  8733. ASSERT_FALSE(gzip_etag.empty());
  8734. // Two representations, two validators.
  8735. EXPECT_NE(identity_etag, gzip_etag);
  8736. // Each one revalidates against the request that would produce it...
  8737. auto fresh =
  8738. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8739. {"If-None-Match", gzip_etag}});
  8740. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8741. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8742. auto fresh_identity =
  8743. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8744. {"If-None-Match", identity_etag}});
  8745. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8746. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8747. // ...and not against the other representation.
  8748. auto crossed =
  8749. cli.Get("/dir/index.html",
  8750. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8751. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8752. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8753. }
  8754. // The opt-in covers responses the server reads off disk itself. A caller's own
  8755. // known-length provider keeps its Content-Length and, more importantly, keeps
  8756. // delivering incrementally: routing it through a compressor would hold every
  8757. // write back until zlib's window filled.
  8758. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8759. auto port = start(enable);
  8760. Client cli(HOST, port);
  8761. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8763. EXPECT_EQ(StatusCode::OK_200, res->status);
  8764. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8765. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8766. EXPECT_EQ("aaabbb", res->body);
  8767. }
  8768. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8769. auto port = start(enable);
  8770. Client cli(HOST, port);
  8771. cli.set_read_timeout(1, 0);
  8772. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8773. Headers{{"Accept-Encoding", "gzip"}});
  8774. ASSERT_TRUE(handle.is_valid());
  8775. // The provider writes 100 bytes and then stalls for longer than the read
  8776. // timeout. Those first bytes have to arrive anyway: run the response through
  8777. // a compressor and zlib holds them until its window fills, so the read would
  8778. // come back empty instead.
  8779. char buf[256];
  8780. auto n = handle.read(buf, sizeof(buf));
  8781. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8782. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8783. }
  8784. #endif
  8785. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8786. TEST_F(ServerTest, Brotli) {
  8787. Headers headers;
  8788. headers.emplace("Accept-Encoding", "br");
  8789. auto res = cli_.Get("/compress", headers);
  8790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8791. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8792. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8793. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8794. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8795. "7890123456789012345678901234567890",
  8796. res->body);
  8797. EXPECT_EQ(StatusCode::OK_200, res->status);
  8798. }
  8799. #endif
  8800. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8801. TEST_F(ServerTest, Zstd) {
  8802. Headers headers;
  8803. headers.emplace("Accept-Encoding", "zstd");
  8804. auto res = cli_.Get("/compress", headers);
  8805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8806. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8807. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8808. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8809. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8810. "7890123456789012345678901234567890",
  8811. res->body);
  8812. EXPECT_EQ(StatusCode::OK_200, res->status);
  8813. }
  8814. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8815. Headers headers;
  8816. headers.emplace("Accept-Encoding", "");
  8817. auto res = cli_.Get("/compress", headers);
  8818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8819. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8820. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8821. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8822. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8823. "7890123456789012345678901234567890",
  8824. res->body);
  8825. EXPECT_EQ(StatusCode::OK_200, res->status);
  8826. }
  8827. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8828. Headers headers;
  8829. headers.emplace("Accept-Encoding", "zstd");
  8830. std::string body;
  8831. auto res = cli_.Get("/compress", headers,
  8832. [&](const char *data, uint64_t data_length) {
  8833. EXPECT_EQ(100U, data_length);
  8834. body.append(data, data_length);
  8835. return true;
  8836. });
  8837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8838. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8839. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8840. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8841. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8842. "7890123456789012345678901234567890",
  8843. body);
  8844. EXPECT_EQ(StatusCode::OK_200, res->status);
  8845. }
  8846. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8847. Headers headers;
  8848. headers.emplace("Accept-Encoding", "zstd");
  8849. cli_.set_decompress(false);
  8850. auto res = cli_.Get("/compress", headers);
  8851. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8852. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8853. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8854. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8856. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8857. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8858. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8859. EXPECT_EQ(StatusCode::OK_200, res->status);
  8860. ASSERT_EQ(26U, res->body.size());
  8861. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8862. 0);
  8863. }
  8864. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8865. Headers headers;
  8866. headers.emplace("Accept-Encoding", "");
  8867. std::string body;
  8868. auto res = cli_.Get("/compress", headers,
  8869. [&](const char *data, uint64_t data_length) {
  8870. EXPECT_EQ(100U, data_length);
  8871. body.append(data, data_length);
  8872. return true;
  8873. });
  8874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8875. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8877. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8878. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8879. "7890123456789012345678901234567890",
  8880. body);
  8881. EXPECT_EQ(StatusCode::OK_200, res->status);
  8882. }
  8883. TEST_F(ServerTest, NoZstd) {
  8884. Headers headers;
  8885. headers.emplace("Accept-Encoding", "zstd");
  8886. auto res = cli_.Get("/nocompress", headers);
  8887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8888. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8889. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8890. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8891. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8892. "7890123456789012345678901234567890",
  8893. res->body);
  8894. EXPECT_EQ(StatusCode::OK_200, res->status);
  8895. }
  8896. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8897. Headers headers;
  8898. headers.emplace("Accept-Encoding", "zstd");
  8899. std::string body;
  8900. auto res = cli_.Get("/nocompress", headers,
  8901. [&](const char *data, uint64_t data_length) {
  8902. EXPECT_EQ(100U, data_length);
  8903. body.append(data, data_length);
  8904. return true;
  8905. });
  8906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8907. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8908. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8909. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8910. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8911. "7890123456789012345678901234567890",
  8912. body);
  8913. EXPECT_EQ(StatusCode::OK_200, res->status);
  8914. }
  8915. // TODO: How to enable zstd ??
  8916. TEST_F(ServerTest, MultipartFormDataZstd) {
  8917. UploadFormDataItems items = {
  8918. {"key1", "test", "", ""},
  8919. {"key2", "--abcdefg123", "", ""},
  8920. };
  8921. Headers headers;
  8922. headers.emplace("Accept-Encoding", "zstd");
  8923. cli_.set_compress(true);
  8924. auto res = cli_.Post("/compress-multipart", headers, items);
  8925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8926. EXPECT_EQ(StatusCode::OK_200, res->status);
  8927. }
  8928. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8929. Headers headers;
  8930. headers.emplace("Accept-Encoding", "zstd");
  8931. cli_.set_compress(true);
  8932. auto res = cli_.Put(
  8933. "/put", headers, 3,
  8934. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8935. sink.os << "PUT";
  8936. return true;
  8937. },
  8938. "text/plain");
  8939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8940. EXPECT_EQ(StatusCode::OK_200, res->status);
  8941. EXPECT_EQ("PUT", res->body);
  8942. }
  8943. // Pre-compression logging tests
  8944. TEST_F(ServerTest, PreCompressionLogging) {
  8945. // Test data for compression (matches the actual /compress endpoint content)
  8946. const std::string test_content =
  8947. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8948. "3456789012345678901234567890";
  8949. // Variables to capture logging data
  8950. std::string pre_compression_body;
  8951. std::string pre_compression_content_type;
  8952. std::string pre_compression_content_encoding;
  8953. std::string post_compression_body;
  8954. std::string post_compression_content_type;
  8955. std::string post_compression_content_encoding;
  8956. // Set up pre-compression logger
  8957. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8958. const Response &res) {
  8959. pre_compression_body = res.body;
  8960. pre_compression_content_type = res.get_header_value("Content-Type");
  8961. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8962. });
  8963. // Set up post-compression logger
  8964. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8965. post_compression_body = res.body;
  8966. post_compression_content_type = res.get_header_value("Content-Type");
  8967. post_compression_content_encoding =
  8968. res.get_header_value("Content-Encoding");
  8969. });
  8970. // Test with gzip compression
  8971. Headers headers;
  8972. headers.emplace("Accept-Encoding", "gzip");
  8973. auto res = cli_.Get("/compress", headers);
  8974. // Verify response was compressed
  8975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8976. EXPECT_EQ(StatusCode::OK_200, res->status);
  8977. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8978. // Verify pre-compression logger captured uncompressed content
  8979. EXPECT_EQ(test_content, pre_compression_body);
  8980. EXPECT_EQ("text/plain", pre_compression_content_type);
  8981. EXPECT_TRUE(pre_compression_content_encoding
  8982. .empty()); // No encoding header before compression
  8983. // Verify post-compression logger captured compressed content
  8984. EXPECT_NE(test_content,
  8985. post_compression_body); // Should be different after compression
  8986. EXPECT_EQ("text/plain", post_compression_content_type);
  8987. EXPECT_EQ("gzip", post_compression_content_encoding);
  8988. // Verify compressed content is smaller
  8989. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8990. }
  8991. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8992. const std::string test_content =
  8993. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8994. "3456789012345678901234567890";
  8995. std::string pre_compression_body;
  8996. std::string post_compression_body;
  8997. svr_.set_pre_compression_logger(
  8998. [&](const Request & /*req*/, const Response &res) {
  8999. pre_compression_body = res.body;
  9000. });
  9001. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9002. post_compression_body = res.body;
  9003. });
  9004. Headers headers;
  9005. headers.emplace("Accept-Encoding", "br");
  9006. auto res = cli_.Get("/compress", headers);
  9007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9008. EXPECT_EQ(StatusCode::OK_200, res->status);
  9009. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9010. // Verify pre-compression content is uncompressed
  9011. EXPECT_EQ(test_content, pre_compression_body);
  9012. // Verify post-compression content is compressed
  9013. EXPECT_NE(test_content, post_compression_body);
  9014. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9015. }
  9016. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9017. const std::string test_content =
  9018. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9019. "3456789012345678901234567890";
  9020. std::string pre_compression_body;
  9021. std::string post_compression_body;
  9022. svr_.set_pre_compression_logger(
  9023. [&](const Request & /*req*/, const Response &res) {
  9024. pre_compression_body = res.body;
  9025. });
  9026. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9027. post_compression_body = res.body;
  9028. });
  9029. // Request without compression (use /nocompress endpoint)
  9030. Headers headers;
  9031. auto res = cli_.Get("/nocompress", headers);
  9032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9033. EXPECT_EQ(StatusCode::OK_200, res->status);
  9034. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9035. // Pre-compression logger should not be called when no compression is applied
  9036. EXPECT_TRUE(
  9037. pre_compression_body.empty()); // Pre-compression logger not called
  9038. EXPECT_EQ(
  9039. test_content,
  9040. post_compression_body); // Post-compression logger captures final content
  9041. }
  9042. TEST_F(ServerTest, LoggerSeesContentLength) {
  9043. size_t logged_content_length = 0;
  9044. std::string logged_content_length_header;
  9045. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9046. logged_content_length = res.content_length_;
  9047. logged_content_length_header = res.get_header_value("Content-Length");
  9048. });
  9049. auto res = cli_.Get("/nocompress");
  9050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9051. EXPECT_EQ(StatusCode::OK_200, res->status);
  9052. EXPECT_EQ(res->body.size(), logged_content_length);
  9053. EXPECT_EQ(std::to_string(logged_content_length),
  9054. logged_content_length_header);
  9055. }
  9056. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9057. const std::string test_content =
  9058. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9059. "3456789012345678901234567890";
  9060. std::string pre_compression_body;
  9061. bool pre_logger_called = false;
  9062. // Set only pre-compression logger
  9063. svr_.set_pre_compression_logger(
  9064. [&](const Request & /*req*/, const Response &res) {
  9065. pre_compression_body = res.body;
  9066. pre_logger_called = true;
  9067. });
  9068. Headers headers;
  9069. headers.emplace("Accept-Encoding", "gzip");
  9070. auto res = cli_.Get("/compress", headers);
  9071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9072. EXPECT_EQ(StatusCode::OK_200, res->status);
  9073. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9074. // Verify pre-compression logger was called
  9075. EXPECT_TRUE(pre_logger_called);
  9076. EXPECT_EQ(test_content, pre_compression_body);
  9077. }
  9078. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9079. {
  9080. // Test with Expect: 100-continue header - success case
  9081. // Server returns 100 Continue, client sends body, server returns 200 OK
  9082. Request req;
  9083. req.method = "POST";
  9084. req.path = "/post-large";
  9085. req.set_header("Expect", "100-continue");
  9086. req.body = LARGE_DATA;
  9087. Response res;
  9088. auto error = Error::Success;
  9089. cli_.set_keep_alive(true);
  9090. auto ret = cli_.send(req, res, error);
  9091. EXPECT_TRUE(ret);
  9092. EXPECT_EQ(StatusCode::OK_200, res.status);
  9093. EXPECT_EQ(LARGE_DATA, res.body);
  9094. }
  9095. {
  9096. // Test with Expect: 100-continue header - error case
  9097. // Client should not send the body when server returns an error
  9098. Request req;
  9099. req.method = "POST";
  9100. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9101. req.set_header("Expect", "100-continue");
  9102. req.body = LARGE_DATA;
  9103. Response res;
  9104. auto error = Error::Success;
  9105. auto start = std::chrono::high_resolution_clock::now();
  9106. cli_.set_keep_alive(true);
  9107. auto ret = cli_.send(req, res, error);
  9108. auto end = std::chrono::high_resolution_clock::now();
  9109. auto elapsed =
  9110. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9111. .count();
  9112. // With Expect: 100-continue, request completes successfully but with error
  9113. EXPECT_TRUE(ret);
  9114. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9115. EXPECT_EQ("close", res.get_header_value("Connection"));
  9116. EXPECT_FALSE(cli_.is_socket_open());
  9117. EXPECT_LE(elapsed, 2000);
  9118. }
  9119. {
  9120. // Send an extra GET request to ensure error recovery without hanging
  9121. Request req;
  9122. req.method = "GET";
  9123. req.path = "/hi";
  9124. auto start = std::chrono::high_resolution_clock::now();
  9125. auto res = cli_.send(req);
  9126. auto end = std::chrono::high_resolution_clock::now();
  9127. auto elapsed =
  9128. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9129. .count();
  9130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9131. EXPECT_EQ(StatusCode::OK_200, res->status);
  9132. EXPECT_EQ("Hello World!", res->body);
  9133. EXPECT_LE(elapsed, 500);
  9134. }
  9135. }
  9136. TEST(ZstdDecompressor, ChunkedDecompression) {
  9137. std::string data;
  9138. for (size_t i = 0; i < 32 * 1024; ++i) {
  9139. data.push_back(static_cast<char>('a' + i % 26));
  9140. }
  9141. std::string compressed_data;
  9142. {
  9143. httplib::detail::zstd_compressor compressor;
  9144. bool result = compressor.compress(
  9145. data.data(), data.size(),
  9146. /*last=*/true,
  9147. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9148. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9149. compressed_data_size);
  9150. return true;
  9151. });
  9152. ASSERT_TRUE(result);
  9153. }
  9154. std::string decompressed_data;
  9155. {
  9156. httplib::detail::zstd_decompressor decompressor;
  9157. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9158. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9159. size_t chunk_size = 130;
  9160. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9161. chunk_begin += chunk_size) {
  9162. size_t current_chunk_size =
  9163. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9164. bool result = decompressor.decompress(
  9165. compressed_data.data() + chunk_begin, current_chunk_size,
  9166. [&](const char *decompressed_data_chunk,
  9167. size_t decompressed_data_chunk_size) {
  9168. decompressed_data.insert(decompressed_data.size(),
  9169. decompressed_data_chunk,
  9170. decompressed_data_chunk_size);
  9171. return true;
  9172. });
  9173. ASSERT_TRUE(result);
  9174. }
  9175. }
  9176. ASSERT_EQ(data, decompressed_data);
  9177. }
  9178. TEST(ZstdDecompressor, Decompress) {
  9179. std::string original_text = "Compressed with ZSTD";
  9180. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9181. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9182. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9183. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9184. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9185. std::string decompressed_data;
  9186. {
  9187. httplib::detail::zstd_decompressor decompressor;
  9188. bool result = decompressor.decompress(
  9189. compressed_data.data(), compressed_data.size(),
  9190. [&](const char *decompressed_data_chunk,
  9191. size_t decompressed_data_chunk_size) {
  9192. decompressed_data.insert(decompressed_data.size(),
  9193. decompressed_data_chunk,
  9194. decompressed_data_chunk_size);
  9195. return true;
  9196. });
  9197. ASSERT_TRUE(result);
  9198. }
  9199. ASSERT_EQ(original_text, decompressed_data);
  9200. }
  9201. #endif
  9202. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9203. // separate chunks so that the server sees each part in its own read(). Used to
  9204. // place a read boundary at a specific offset of a request body.
  9205. static bool send_request_in_parts(time_t read_timeout_sec,
  9206. const std::vector<std::string> &parts,
  9207. std::string *resp = nullptr,
  9208. int port = PORT) {
  9209. auto error = Error::Success;
  9210. auto client_sock = detail::create_client_socket(
  9211. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9212. /*connection_timeout_sec=*/5, 0,
  9213. /*read_timeout_sec=*/5, 0,
  9214. /*write_timeout_sec=*/5, 0, std::string(), error);
  9215. if (client_sock == INVALID_SOCKET) { return false; }
  9216. auto ret = detail::process_client_socket(
  9217. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9218. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9219. for (size_t i = 0; i < parts.size(); i++) {
  9220. const auto &part = parts[i];
  9221. if (part.size() !=
  9222. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9223. return false;
  9224. }
  9225. if (i + 1 < parts.size()) {
  9226. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9227. }
  9228. }
  9229. char buf[512];
  9230. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9231. while (line_reader.getline()) {
  9232. if (resp) { *resp += line_reader.ptr(); }
  9233. }
  9234. return true;
  9235. });
  9236. detail::close_socket(client_sock);
  9237. return ret;
  9238. }
  9239. // Sends a raw request to a server listening at HOST:PORT.
  9240. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9241. std::string *resp = nullptr, int port = PORT) {
  9242. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9243. }
  9244. #ifdef CPPHTTPLIB_SSL_ENABLED
  9245. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9247. ASSERT_TRUE(svr.is_valid());
  9248. svr.set_read_timeout(1, 0);
  9249. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9250. auto se = detail::scope_exit([&] {
  9251. svr.stop();
  9252. t.join();
  9253. ASSERT_FALSE(svr.is_running());
  9254. });
  9255. svr.wait_until_ready();
  9256. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9257. // keeps each wait well within the read timeout. The server gives up a
  9258. // second in, so the bytes sent after that fail.
  9259. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9260. parts.resize(26, std::string(1, '\0'));
  9261. EXPECT_FALSE(send_request_in_parts(5, parts));
  9262. }
  9263. #endif
  9264. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9265. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9266. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9267. const std::vector<std::string> &parts,
  9268. std::string *resp = nullptr,
  9269. int port = PORT) {
  9270. auto error = Error::Success;
  9271. auto sock = detail::create_client_socket(
  9272. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9273. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9274. /*write_timeout_sec=*/5, 0, std::string(), error);
  9275. if (sock == INVALID_SOCKET) { return false; }
  9276. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9277. auto ctx = SSL_CTX_new(TLS_client_method());
  9278. auto ssl = SSL_new(ctx);
  9279. auto ssl_se = detail::scope_exit([&] {
  9280. SSL_free(ssl);
  9281. SSL_CTX_free(ctx);
  9282. });
  9283. SSL_set_fd(ssl, static_cast<int>(sock));
  9284. if (SSL_connect(ssl) != 1) { return false; }
  9285. for (size_t i = 0; i < parts.size(); i++) {
  9286. const auto &part = parts[i];
  9287. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9288. static_cast<int>(part.size())) {
  9289. return false;
  9290. }
  9291. if (i + 1 < parts.size()) {
  9292. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9293. }
  9294. }
  9295. char buf[512];
  9296. int n;
  9297. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9298. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9299. }
  9300. return true;
  9301. }
  9302. #endif
  9303. // The request line, then a header value a byte at a time.
  9304. static std::vector<std::string> slow_request_head_parts() {
  9305. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9306. parts.resize(26, "a");
  9307. parts.emplace_back("\r\n\r\n");
  9308. return parts;
  9309. }
  9310. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9311. // within the one-second read timeout. The server gives up a second in, before
  9312. // the head is complete.
  9313. static void
  9314. expect_slow_request_head_dropped(Server &svr,
  9315. const std::function<std::string()> &send) {
  9316. std::atomic<bool> handled(false);
  9317. svr.Get("/", [&](const Request &, Response &res) {
  9318. handled = true;
  9319. res.set_content("ok", "text/plain");
  9320. });
  9321. svr.set_read_timeout(1, 0);
  9322. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9323. auto se = detail::scope_exit([&] {
  9324. svr.stop();
  9325. t.join();
  9326. ASSERT_FALSE(svr.is_running());
  9327. });
  9328. svr.wait_until_ready();
  9329. auto resp = send();
  9330. EXPECT_FALSE(handled);
  9331. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9332. }
  9333. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9334. Server svr;
  9335. expect_slow_request_head_dropped(svr, [] {
  9336. std::string resp;
  9337. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9338. return resp;
  9339. });
  9340. }
  9341. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9342. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9344. ASSERT_TRUE(svr.is_valid());
  9345. expect_slow_request_head_dropped(svr, [] {
  9346. std::string resp;
  9347. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9348. return resp;
  9349. });
  9350. }
  9351. #endif
  9352. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9353. Server svr;
  9354. std::string header_value;
  9355. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9356. header_value = req.get_header_value("foo");
  9357. res.set_content("ok", "text/plain");
  9358. });
  9359. thread t = thread([&] { svr.listen(HOST, PORT); });
  9360. auto se = detail::scope_exit([&] {
  9361. svr.stop();
  9362. t.join();
  9363. ASSERT_FALSE(svr.is_running());
  9364. });
  9365. svr.wait_until_ready();
  9366. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9367. // like characters are not treated the same - use vertical tab and escape.
  9368. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9369. "foo: \t \v bar \x1B\t \r\n"
  9370. "Connection: close\r\n"
  9371. "\r\n";
  9372. std::string res;
  9373. ASSERT_TRUE(send_request(5, req, &res));
  9374. EXPECT_EQ(header_value, "");
  9375. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9376. }
  9377. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9378. Server svr;
  9379. std::string received;
  9380. svr.Get("/order", [&](const Request &req, Response &res) {
  9381. received = entries_to_string(req.headers);
  9382. res.set_content("ok", "text/plain");
  9383. });
  9384. auto port = svr.bind_to_any_port(HOST);
  9385. thread t = thread([&] { svr.listen_after_bind(); });
  9386. auto se = detail::scope_exit([&] {
  9387. svr.stop();
  9388. t.join();
  9389. ASSERT_FALSE(svr.is_running());
  9390. });
  9391. svr.wait_until_ready();
  9392. const std::string req = "GET /order HTTP/1.1\r\n"
  9393. "Host: localhost\r\n"
  9394. "X-First: 1\r\n"
  9395. "X-Dup: a\r\n"
  9396. "X-Second: 2\r\n"
  9397. "X-Dup: b\r\n"
  9398. "Connection: close\r\n"
  9399. "\r\n";
  9400. std::string res;
  9401. ASSERT_TRUE(send_request(5, req, &res, port));
  9402. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9403. EXPECT_EQ(
  9404. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9405. received);
  9406. }
  9407. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9408. Server svr;
  9409. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9410. res.set_header("Set-Cookie", "first=1");
  9411. res.set_header("X-Between", "y");
  9412. res.set_header("Set-Cookie", "second=2");
  9413. res.set_content("ok", "text/plain");
  9414. });
  9415. auto port = svr.bind_to_any_port(HOST);
  9416. thread t = thread([&] { svr.listen_after_bind(); });
  9417. auto se = detail::scope_exit([&] {
  9418. svr.stop();
  9419. t.join();
  9420. ASSERT_FALSE(svr.is_running());
  9421. });
  9422. svr.wait_until_ready();
  9423. Client cli(HOST, port);
  9424. auto res = cli.Get("/cookies");
  9425. ASSERT_TRUE(res);
  9426. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9427. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9428. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9429. }
  9430. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9431. Server svr;
  9432. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9433. auto i = new int(0);
  9434. res.set_header("Trailer", "X-Safe, X-Reflected");
  9435. res.set_chunked_content_provider(
  9436. "text/plain",
  9437. [i](size_t /*offset*/, DataSink &sink) {
  9438. if (*i == 0) {
  9439. sink.os << "body";
  9440. } else {
  9441. Headers trailer;
  9442. // A valid trailer that must survive.
  9443. trailer.emplace("X-Safe", "safe");
  9444. // Attacker-controlled value carrying CR/LF (response splitting).
  9445. trailer.emplace("X-Reflected",
  9446. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9447. // Attacker-controlled name carrying CR/LF.
  9448. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9449. sink.done_with_trailer(trailer);
  9450. }
  9451. (*i)++;
  9452. return true;
  9453. },
  9454. [i](bool /*success*/) { delete i; });
  9455. });
  9456. thread t = thread([&] { svr.listen(HOST, PORT); });
  9457. auto se = detail::scope_exit([&] {
  9458. svr.stop();
  9459. t.join();
  9460. ASSERT_FALSE(svr.is_running());
  9461. });
  9462. svr.wait_until_ready();
  9463. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9464. "Host: " + HOST +
  9465. "\r\n"
  9466. "Connection: close\r\n"
  9467. "\r\n";
  9468. std::string res;
  9469. ASSERT_TRUE(send_request(5, req, &res));
  9470. // The injected fields must not appear anywhere in the raw response.
  9471. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9472. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9473. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9474. // Invalid trailers are dropped entirely, matching set_header().
  9475. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9476. // The valid trailer still passes through.
  9477. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9478. }
  9479. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9480. Server svr;
  9481. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9482. // res.headers is a public field an application can populate directly,
  9483. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9484. // A valid header that must survive.
  9485. res.headers.emplace("X-Safe", "safe");
  9486. // Attacker-controlled value carrying CR/LF (response splitting).
  9487. res.headers.emplace("X-Reflected",
  9488. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9489. // Attacker-controlled name carrying CR/LF.
  9490. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9491. res.set_content("body", "text/plain");
  9492. });
  9493. thread t = thread([&] { svr.listen(HOST, PORT); });
  9494. auto se = detail::scope_exit([&] {
  9495. svr.stop();
  9496. t.join();
  9497. ASSERT_FALSE(svr.is_running());
  9498. });
  9499. svr.wait_until_ready();
  9500. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9501. "Host: " + HOST +
  9502. "\r\n"
  9503. "Connection: close\r\n"
  9504. "\r\n";
  9505. std::string res;
  9506. ASSERT_TRUE(send_request(5, req, &res));
  9507. // The injected fields must not appear anywhere in the raw response.
  9508. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9509. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9510. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9511. // Invalid headers are dropped entirely, matching set_header().
  9512. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9513. // The valid header still passes through.
  9514. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9515. }
  9516. // Forward declaration: in split builds split.py strips `inline` and moves the
  9517. // definition into httplib.cc, so detail::write_request_line is not visible from
  9518. // the public httplib.h. Re-declaring it here lets the tests link against the
  9519. // symbol in both header-only and split builds.
  9520. namespace httplib {
  9521. namespace detail {
  9522. ssize_t write_request_line(Stream &strm, const std::string &method,
  9523. const std::string &path);
  9524. } // namespace detail
  9525. } // namespace httplib
  9526. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9527. // A well-formed target is written verbatim.
  9528. {
  9529. detail::BufferStream strm;
  9530. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9531. EXPECT_GT(n, 0);
  9532. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9533. }
  9534. // A target carrying CR/LF, SP or other control octets must be rejected
  9535. // before anything reaches the wire, otherwise it splits the request line and
  9536. // injects a header or a whole request.
  9537. const std::string evil_targets[] = {
  9538. "/a\r\nInjected: pwned",
  9539. "/a\rInjected",
  9540. "/a\nInjected",
  9541. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9542. "/a b",
  9543. "/a\tb",
  9544. "/a\x7f",
  9545. };
  9546. for (const auto &evil : evil_targets) {
  9547. detail::BufferStream strm;
  9548. auto n = detail::write_request_line(strm, "GET", evil);
  9549. EXPECT_LT(n, 0);
  9550. EXPECT_TRUE(strm.get_buffer().empty());
  9551. }
  9552. }
  9553. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9554. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9555. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9556. // target reaches write_request. The client must fail cleanly with
  9557. // Error::Write instead of putting a request-line-less, header-injecting
  9558. // request on the wire.
  9559. Server svr;
  9560. svr.Get("/a", [](const Request &, Response &res) {
  9561. res.set_content("ok", "text/plain");
  9562. });
  9563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9564. auto se = detail::scope_exit([&] {
  9565. svr.stop();
  9566. thread.join();
  9567. ASSERT_FALSE(svr.is_running());
  9568. });
  9569. svr.wait_until_ready();
  9570. {
  9571. Client cli(HOST, PORT);
  9572. cli.set_path_encode(false);
  9573. // The request is rejected before anything is written, so the connection
  9574. // stays silent and the subsequent response read would otherwise block for
  9575. // the full default read timeout. Shorten it -- the assertion is on the
  9576. // error, not the timeout.
  9577. cli.set_read_timeout(1, 0);
  9578. auto res = cli.Get("/a\r\nInjected: pwned");
  9579. EXPECT_FALSE(res);
  9580. EXPECT_EQ(Error::Write, res.error());
  9581. }
  9582. }
  9583. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9584. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9585. // including extension methods.
  9586. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9587. for (const auto &method : good_methods) {
  9588. detail::BufferStream strm;
  9589. auto n = detail::write_request_line(strm, method, "/");
  9590. EXPECT_GT(n, 0);
  9591. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9592. }
  9593. // A method carrying CR/LF would split the request line and smuggle a whole
  9594. // request ahead of the real one. A space or an empty method corrupts the
  9595. // request line. All must be rejected before anything reaches the wire.
  9596. const std::string evil_methods[] = {
  9597. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9598. "GET\r\nInjected: pwned",
  9599. "GET\r",
  9600. "GET\n",
  9601. "GE T",
  9602. "",
  9603. };
  9604. for (const auto &evil : evil_methods) {
  9605. detail::BufferStream strm;
  9606. auto n = detail::write_request_line(strm, evil, "/");
  9607. EXPECT_LT(n, 0);
  9608. EXPECT_TRUE(strm.get_buffer().empty());
  9609. }
  9610. }
  9611. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9612. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9613. // through Client::send must fail with Error::Write and no request, neither
  9614. // the smuggled one nor the real one, may reach the server.
  9615. Server svr;
  9616. std::atomic<int> request_count(0);
  9617. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9618. request_count++;
  9619. res.status = StatusCode::OK_200;
  9620. return Server::HandlerResponse::Handled;
  9621. });
  9622. auto port = svr.bind_to_any_port(HOST);
  9623. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9624. auto se = detail::scope_exit([&] {
  9625. svr.stop();
  9626. thread.join();
  9627. ASSERT_FALSE(svr.is_running());
  9628. });
  9629. svr.wait_until_ready();
  9630. {
  9631. Client cli(HOST, port);
  9632. const std::string evil_methods[] = {
  9633. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9634. "GE T",
  9635. "",
  9636. };
  9637. for (const auto &evil : evil_methods) {
  9638. Request req;
  9639. req.method = evil;
  9640. req.path = "/";
  9641. auto res = cli.send(req);
  9642. EXPECT_FALSE(res);
  9643. EXPECT_EQ(Error::Write, res.error());
  9644. }
  9645. auto handle =
  9646. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9647. EXPECT_FALSE(handle.is_valid());
  9648. EXPECT_EQ(Error::Write, handle.error);
  9649. // A valid request on the same client still goes through.
  9650. auto res = cli.Get("/");
  9651. ASSERT_TRUE(res);
  9652. EXPECT_EQ(StatusCode::OK_200, res->status);
  9653. }
  9654. EXPECT_EQ(1, request_count.load());
  9655. }
  9656. // Sends a raw request and verifies that there isn't a crash or exception.
  9657. static void test_raw_request(const std::string &req,
  9658. std::string *out = nullptr) {
  9659. Server svr;
  9660. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9661. res.set_content("ok", "text/plain");
  9662. });
  9663. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9664. res.set_content("ok", "text/plain");
  9665. });
  9666. svr.Get("/header_field_value_check",
  9667. [&](const Request & /*req*/, Response &res) {
  9668. res.set_content("ok", "text/plain");
  9669. });
  9670. svr.CustomRoute("PROPFIND", "/dav",
  9671. [&](const Request & /*req*/, Response &res) {
  9672. res.status = StatusCode::MultiStatus_207;
  9673. });
  9674. // Server read timeout must be longer than the client read timeout for the
  9675. // bug to reproduce, probably to force the server to process a request
  9676. // without a trailing blank line.
  9677. const time_t client_read_timeout_sec = 1;
  9678. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9679. bool listen_thread_ok = false;
  9680. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9681. auto se = detail::scope_exit([&] {
  9682. svr.stop();
  9683. t.join();
  9684. ASSERT_FALSE(svr.is_running());
  9685. EXPECT_TRUE(listen_thread_ok);
  9686. });
  9687. svr.wait_until_ready();
  9688. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9689. }
  9690. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9691. // A certain header line causes an exception if the header property is parsed
  9692. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9693. test_raw_request(
  9694. "GET /hi HTTP/1.1\r\n"
  9695. " : "
  9696. " "
  9697. " ");
  9698. }
  9699. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9700. // A certain header line causes an exception if the header property *name* is
  9701. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9702. // greedy matcher and requires backtracking when there are a lot of ":"
  9703. // characters.
  9704. // This occurs with libc++ but not libstdc++.
  9705. test_raw_request(
  9706. "GET /hi HTTP/1.1\r\n"
  9707. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9708. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9709. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9710. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9711. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9712. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9713. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9714. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9715. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9716. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9717. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9718. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9719. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9720. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9721. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9722. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9723. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9724. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9725. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9726. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9727. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9728. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9729. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9730. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9731. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9732. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9733. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9734. "&&&%%%");
  9735. }
  9736. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9737. // Make sure this doesn't crash the server.
  9738. // In a previous version of the header line regex, the "\r" rendered the line
  9739. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9740. // a new position where the leading white space ended and the field value
  9741. // began.
  9742. // The crash occurs with libc++ but not libstdc++.
  9743. test_raw_request("GET /hi HTTP/1.1\r\n"
  9744. "a:" +
  9745. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9746. "\r\n"
  9747. "\r\n");
  9748. }
  9749. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9750. const char *rejected[] = {
  9751. // RFC 9112 §3: one SP between the parts, and nothing else
  9752. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9753. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9754. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9755. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9756. // A request-target has no fragment
  9757. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9758. // An HTTP/1.1 request needs a Host
  9759. "GET /hi HTTP/1.1\r\n\r\n",
  9760. };
  9761. for (auto request : rejected) {
  9762. std::string out;
  9763. test_raw_request(request, &out);
  9764. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9765. }
  9766. std::string out;
  9767. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9768. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9769. }
  9770. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9771. // RFC 9112 §6.1
  9772. const char *requests[] = {
  9773. "PUT /put_hi HTTP/1.1\r\n"
  9774. "Host: localhost\r\n"
  9775. "Content-Length: 0\r\n"
  9776. "Transfer-Encoding: chunked\r\n"
  9777. "\r\n"
  9778. "0\r\n\r\n",
  9779. "PUT /put_hi HTTP/1.0\r\n"
  9780. "Connection: keep-alive\r\n"
  9781. "Transfer-Encoding: chunked\r\n"
  9782. "\r\n"
  9783. "0\r\n\r\n",
  9784. };
  9785. for (auto request : requests) {
  9786. std::string out;
  9787. test_raw_request(request, &out);
  9788. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9789. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9790. }
  9791. }
  9792. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9793. std::string out;
  9794. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9795. "Content-Type: text/plain\r\n"
  9796. "Transfer-Encoding: chunked\r\n"
  9797. "\r\n"
  9798. "nothex\r\n",
  9799. &out);
  9800. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9801. }
  9802. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9803. std::string out;
  9804. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9805. "Content-Type: text/plain\r\n"
  9806. "Transfer-Encoding: chunked\r\n"
  9807. "\r\n"
  9808. "3\r\n"
  9809. "xyz\r\n"
  9810. "NaN\r\n",
  9811. &out);
  9812. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9813. }
  9814. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9815. std::string out;
  9816. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9817. "Content-Type: text/plain\r\n"
  9818. "Transfer-Encoding: chunked\r\n"
  9819. "\r\n"
  9820. // Length is too large for 64 bits.
  9821. "1ffffffffffffffff\r\n"
  9822. "xyz\r\n",
  9823. &out);
  9824. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9825. }
  9826. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9827. test_raw_request("GET /hi HTTP/1.1\r\n"
  9828. "Content-Type: text/plain\r\n\r");
  9829. }
  9830. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9831. std::string out;
  9832. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9833. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9834. }
  9835. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9836. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9837. std::string out;
  9838. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9839. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9840. }
  9841. }
  9842. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9843. std::string out;
  9844. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9845. "Host: localhost\r\n"
  9846. "Connection: close\r\n\r\n",
  9847. &out);
  9848. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9849. }
  9850. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9851. Server svr;
  9852. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9853. EXPECT_TRUE(!req.remote_addr.empty());
  9854. });
  9855. thread t = thread([&] { svr.listen(HOST, PORT); });
  9856. auto se = detail::scope_exit([&] {
  9857. svr.stop();
  9858. t.join();
  9859. ASSERT_FALSE(svr.is_running());
  9860. });
  9861. svr.wait_until_ready();
  9862. // Send an invalid request line to trigger Bad Request
  9863. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9864. std::string out;
  9865. ASSERT_TRUE(send_request(5, bad_req, &out));
  9866. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9867. }
  9868. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9869. // answered right away rather than blocking on a read that waits for EOF.
  9870. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9871. std::string out;
  9872. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9873. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9874. }
  9875. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9876. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9877. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9878. for (const auto *method : methods) {
  9879. Server svr;
  9880. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9881. EXPECT_FALSE(svr.is_valid()) << method;
  9882. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9883. }
  9884. }
  9885. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9886. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9887. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9888. for (const auto *method : methods) {
  9889. Server svr;
  9890. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9891. EXPECT_FALSE(svr.is_valid()) << method;
  9892. }
  9893. }
  9894. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9895. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9896. "COPY", "MOVE", "LOCK",
  9897. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9898. Server svr;
  9899. for (const auto *method : methods) {
  9900. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9901. }
  9902. EXPECT_TRUE(svr.is_valid());
  9903. }
  9904. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9905. Server svr;
  9906. svr.CustomRoute("POST", "/x",
  9907. [](const Request &, Response &, const ContentReader &) {});
  9908. EXPECT_FALSE(svr.is_valid());
  9909. }
  9910. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9911. Server svr;
  9912. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9913. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9914. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9915. EXPECT_FALSE(svr.is_valid());
  9916. }
  9917. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9918. Server svr;
  9919. auto captured = Error::Success;
  9920. svr.set_error_logger(
  9921. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9922. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9923. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9924. }
  9925. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9926. std::string out;
  9927. std::string request(
  9928. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9929. test_raw_request(request, &out);
  9930. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9931. }
  9932. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9933. std::string out;
  9934. std::string request(
  9935. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9936. test_raw_request(request, &out);
  9937. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9938. }
  9939. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9940. std::string out;
  9941. std::string request(
  9942. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9943. test_raw_request(request, &out);
  9944. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9945. }
  9946. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9947. std::string out;
  9948. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9949. "Host: localhost\r\n"
  9950. "Test: \r\n\r\n",
  9951. &out);
  9952. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9953. }
  9954. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9955. Server svr;
  9956. std::string x_custom;
  9957. std::string cookie;
  9958. std::string xff;
  9959. std::string x_unicode;
  9960. std::string x_iis;
  9961. svr.Get("/check", [&](const Request &req, Response &res) {
  9962. x_custom = req.get_header_value("X-Custom");
  9963. cookie = req.get_header_value("Cookie");
  9964. xff = req.get_header_value("X-Forwarded-For");
  9965. x_unicode = req.get_header_value("X-Unicode");
  9966. x_iis = req.get_header_value("X-IIS");
  9967. res.set_content("ok", "text/plain");
  9968. });
  9969. thread t = thread([&] { svr.listen(HOST, PORT); });
  9970. auto se = detail::scope_exit([&] {
  9971. svr.stop();
  9972. t.join();
  9973. ASSERT_FALSE(svr.is_running());
  9974. });
  9975. svr.wait_until_ready();
  9976. const std::string req = "GET /check HTTP/1.1\r\n"
  9977. "Host: localhost\r\n"
  9978. "X-Custom: a%0D%0AInjected: b\r\n"
  9979. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9980. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9981. "X-Unicode: %E3%81%82\r\n"
  9982. "X-IIS: %u00E9\r\n"
  9983. "Connection: close\r\n"
  9984. "\r\n";
  9985. std::string res;
  9986. ASSERT_TRUE(send_request(5, req, &res));
  9987. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9988. // Every value must be returned verbatim (wire form), with no decoding.
  9989. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9990. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9991. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9992. EXPECT_EQ("%E3%81%82", x_unicode);
  9993. EXPECT_EQ("%u00E9", x_iis);
  9994. }
  9995. // Applications that previously relied on automatic percent-decoding can
  9996. // reproduce the old behavior by explicitly calling decode_path_component()
  9997. // or, for RFC 3986 conformance, decode_uri_component().
  9998. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9999. Server svr;
  10000. std::string decoded;
  10001. svr.Get("/check", [&](const Request &req, Response &res) {
  10002. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10003. res.set_content("ok", "text/plain");
  10004. });
  10005. thread t = thread([&] { svr.listen(HOST, PORT); });
  10006. auto se = detail::scope_exit([&] {
  10007. svr.stop();
  10008. t.join();
  10009. ASSERT_FALSE(svr.is_running());
  10010. });
  10011. svr.wait_until_ready();
  10012. const std::string req = "GET /check HTTP/1.1\r\n"
  10013. "Host: localhost\r\n"
  10014. "X-Custom: hello%20world\r\n"
  10015. "Connection: close\r\n"
  10016. "\r\n";
  10017. std::string res;
  10018. ASSERT_TRUE(send_request(5, req, &res));
  10019. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10020. EXPECT_EQ("hello world", decoded);
  10021. }
  10022. // Regression test for #2033. Browsers send Referer values that include
  10023. // percent-encoded characters such as %0A inside the URL. Decoding the
  10024. // header value would either trip the post-decode CR/LF/NUL guard (the
  10025. // original bug, returning 400) or, after that guard was relaxed, silently
  10026. // store a literal LF — both unacceptable. The wire form must round-trip.
  10027. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10028. Server svr;
  10029. std::string referer;
  10030. svr.Get("/check", [&](const Request &req, Response &res) {
  10031. referer = req.get_header_value("Referer");
  10032. res.set_content("ok", "text/plain");
  10033. });
  10034. thread t = thread([&] { svr.listen(HOST, PORT); });
  10035. auto se = detail::scope_exit([&] {
  10036. svr.stop();
  10037. t.join();
  10038. ASSERT_FALSE(svr.is_running());
  10039. });
  10040. svr.wait_until_ready();
  10041. const std::string req = "GET /check HTTP/1.1\r\n"
  10042. "Host: localhost\r\n"
  10043. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10044. "Connection: close\r\n"
  10045. "\r\n";
  10046. std::string res;
  10047. ASSERT_TRUE(send_request(5, req, &res));
  10048. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10049. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10050. }
  10051. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10052. Server svr;
  10053. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10054. res.set_header("Cache-Control", "no-cache");
  10055. res.set_chunked_content_provider(
  10056. "text/event-stream", [](size_t offset, DataSink &sink) {
  10057. std::string s = "data:";
  10058. s += std::to_string(offset);
  10059. s += "\n\n";
  10060. auto ret = sink.write(s.data(), s.size());
  10061. EXPECT_TRUE(ret);
  10062. std::this_thread::sleep_for(std::chrono::seconds(1));
  10063. return true;
  10064. });
  10065. });
  10066. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10067. svr.wait_until_ready();
  10068. Client client(HOST, PORT);
  10069. const Headers headers = {{"Accept", "text/event-stream"}};
  10070. auto get_thread = std::thread([&client, &headers]() {
  10071. auto res = client.Get(
  10072. "/events", headers,
  10073. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10074. });
  10075. auto se = detail::scope_exit([&] {
  10076. svr.stop();
  10077. get_thread.join();
  10078. listen_thread.join();
  10079. ASSERT_FALSE(svr.is_running());
  10080. });
  10081. // Give GET time to get a few messages.
  10082. std::this_thread::sleep_for(std::chrono::seconds(2));
  10083. }
  10084. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10085. httplib::Server svr;
  10086. svr.Post("/hi",
  10087. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10088. res.status = StatusCode::OK_200;
  10089. });
  10090. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10091. svr.wait_until_ready();
  10092. Client cli(HOST, PORT);
  10093. auto res = cli.Post("/hi", "data", "text/plain");
  10094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10095. EXPECT_EQ(StatusCode::OK_200, res->status);
  10096. svr.stop();
  10097. thread.join();
  10098. ASSERT_FALSE(svr.is_running());
  10099. res = cli.Post("/hi", "data", "text/plain");
  10100. ASSERT_FALSE(res);
  10101. }
  10102. TEST(ServerStopTest, ListenFailure) {
  10103. Server svr;
  10104. auto t = thread([&]() {
  10105. auto ret = svr.listen("????", PORT);
  10106. EXPECT_FALSE(ret);
  10107. });
  10108. svr.wait_until_ready();
  10109. svr.stop();
  10110. t.join();
  10111. }
  10112. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10113. TEST(ServerStopTest, Decommision) {
  10114. Server svr;
  10115. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10116. for (int i = 0; i < 4; i++) {
  10117. auto is_even = !(i % 2);
  10118. std::thread t{[&] {
  10119. try {
  10120. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10121. if (is_even) {
  10122. throw std::runtime_error("Some thing that happens to go wrong.");
  10123. }
  10124. svr.listen(HOST, PORT);
  10125. } catch (...) { svr.decommission(); }
  10126. }};
  10127. svr.wait_until_ready();
  10128. // Server is up
  10129. {
  10130. Client cli(HOST, PORT);
  10131. auto res = cli.Get("/hi");
  10132. if (is_even) {
  10133. EXPECT_FALSE(res);
  10134. } else {
  10135. EXPECT_TRUE(res);
  10136. EXPECT_EQ("hi...", res->body);
  10137. }
  10138. }
  10139. svr.stop();
  10140. t.join();
  10141. // Server is down...
  10142. {
  10143. Client cli(HOST, PORT);
  10144. auto res = cli.Get("/hi");
  10145. EXPECT_FALSE(res);
  10146. }
  10147. }
  10148. }
  10149. #endif
  10150. // Helper function for string body upload progress tests
  10151. template <typename SetupHandler, typename ClientCall>
  10152. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10153. ClientCall &&client_call,
  10154. const string &body) {
  10155. Server svr;
  10156. setup_handler(svr);
  10157. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10158. auto se = detail::scope_exit([&] {
  10159. svr.stop();
  10160. t.join();
  10161. });
  10162. svr.wait_until_ready();
  10163. Client cli(HOST, PORT);
  10164. vector<uint64_t> progress_values;
  10165. bool progress_called = false;
  10166. auto res =
  10167. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10168. progress_values.push_back(current);
  10169. progress_called = true;
  10170. return true;
  10171. });
  10172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10173. EXPECT_EQ(200, res->status);
  10174. EXPECT_TRUE(progress_called);
  10175. }
  10176. TEST(UploadProgressTest, PostStringBodyBasic) {
  10177. TestStringBodyUploadProgress(
  10178. [](Server &svr) {
  10179. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10180. res.set_content("received", "text/plain");
  10181. });
  10182. },
  10183. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10184. return cli.Post("/test", body, "text/plain", progress_callback);
  10185. },
  10186. "test data for upload progress");
  10187. }
  10188. TEST(UploadProgressTest, PutStringBodyBasic) {
  10189. TestStringBodyUploadProgress(
  10190. [](Server &svr) {
  10191. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10192. res.set_content("put received", "text/plain");
  10193. });
  10194. },
  10195. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10196. return cli.Put("/test", body, "text/plain", progress_callback);
  10197. },
  10198. "put test data for upload progress");
  10199. }
  10200. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10201. TestStringBodyUploadProgress(
  10202. [](Server &svr) {
  10203. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10204. res.set_content("patch received", "text/plain");
  10205. });
  10206. },
  10207. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10208. return cli.Patch("/test", body, "text/plain", progress_callback);
  10209. },
  10210. "patch test data for upload progress");
  10211. }
  10212. // Helper function for content provider upload progress tests
  10213. template <typename SetupHandler, typename ClientCall>
  10214. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10215. ClientCall &&client_call) {
  10216. Server svr;
  10217. setup_handler(svr);
  10218. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10219. auto se = detail::scope_exit([&] {
  10220. svr.stop();
  10221. t.join();
  10222. });
  10223. svr.wait_until_ready();
  10224. Client cli(HOST, PORT);
  10225. vector<uint64_t> progress_values;
  10226. auto res =
  10227. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10228. progress_values.push_back(current);
  10229. return true;
  10230. });
  10231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10232. EXPECT_EQ(200, res->status);
  10233. EXPECT_FALSE(progress_values.empty());
  10234. }
  10235. TEST(UploadProgressTest, PostContentProviderProgress) {
  10236. TestContentProviderUploadProgress(
  10237. [](Server &svr) {
  10238. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10239. res.set_content("provider received", "text/plain");
  10240. });
  10241. },
  10242. [](Client &cli, UploadProgress progress_callback) {
  10243. return cli.Post(
  10244. "/test", 9,
  10245. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10246. sink.os << "test data";
  10247. return true;
  10248. },
  10249. "text/plain", progress_callback);
  10250. });
  10251. }
  10252. // Helper function for multipart upload progress tests
  10253. template <typename SetupHandler, typename ClientCall>
  10254. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10255. ClientCall &&client_call,
  10256. const string &endpoint) {
  10257. Server svr;
  10258. setup_handler(svr);
  10259. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10260. auto se = detail::scope_exit([&] {
  10261. svr.stop();
  10262. t.join();
  10263. });
  10264. svr.wait_until_ready();
  10265. Client cli(HOST, PORT);
  10266. vector<uint64_t> progress_values;
  10267. UploadFormDataItems items = {
  10268. {"field1", "value1", "", ""},
  10269. {"field2", "longer value for progress tracking test", "", ""},
  10270. {"file1", "file content data for upload progress", "test.txt",
  10271. "text/plain"}};
  10272. auto res = client_call(cli, endpoint, items,
  10273. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10274. progress_values.push_back(current);
  10275. return true;
  10276. });
  10277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10278. EXPECT_EQ(200, res->status);
  10279. EXPECT_FALSE(progress_values.empty());
  10280. }
  10281. TEST(UploadProgressTest, PostMultipartProgress) {
  10282. TestMultipartUploadProgress(
  10283. [](Server &svr) {
  10284. svr.Post("/multipart", [](const Request &req, Response &res) {
  10285. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10286. res.set_content("multipart received", "text/plain");
  10287. });
  10288. },
  10289. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10290. UploadProgress progress_callback) {
  10291. return cli.Post(endpoint, items, progress_callback);
  10292. },
  10293. "/multipart");
  10294. }
  10295. // Helper function for basic download progress tests
  10296. template <typename SetupHandler, typename ClientCall>
  10297. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10298. ClientCall &&client_call, const string &endpoint,
  10299. size_t expected_content_size) {
  10300. Server svr;
  10301. setup_handler(svr);
  10302. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10303. auto se = detail::scope_exit([&] {
  10304. svr.stop();
  10305. t.join();
  10306. });
  10307. svr.wait_until_ready();
  10308. Client cli(HOST, PORT);
  10309. vector<uint64_t> progress_values;
  10310. auto res = client_call(cli, endpoint,
  10311. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10312. progress_values.push_back(current);
  10313. return true;
  10314. });
  10315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10316. EXPECT_EQ(200, res->status);
  10317. EXPECT_FALSE(progress_values.empty());
  10318. EXPECT_EQ(expected_content_size, res->body.size());
  10319. }
  10320. TEST(DownloadProgressTest, GetBasic) {
  10321. TestBasicDownloadProgress(
  10322. [](Server &svr) {
  10323. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10324. string content(1000, 'D');
  10325. res.set_content(content, "text/plain");
  10326. });
  10327. },
  10328. [](Client &cli, const string &endpoint,
  10329. DownloadProgress progress_callback) {
  10330. return cli.Get(endpoint, progress_callback);
  10331. },
  10332. "/download", 1000u);
  10333. }
  10334. // Helper function for content receiver download progress tests
  10335. template <typename SetupHandler, typename ClientCall>
  10336. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10337. ClientCall &&client_call,
  10338. const string &endpoint,
  10339. size_t expected_content_size) {
  10340. Server svr;
  10341. setup_handler(svr);
  10342. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10343. auto se = detail::scope_exit([&] {
  10344. svr.stop();
  10345. t.join();
  10346. });
  10347. svr.wait_until_ready();
  10348. Client cli(HOST, PORT);
  10349. vector<uint64_t> progress_values;
  10350. string received_body;
  10351. auto res = client_call(
  10352. cli, endpoint,
  10353. [&](const char *data, size_t data_length) -> bool {
  10354. received_body.append(data, data_length);
  10355. return true;
  10356. },
  10357. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10358. progress_values.push_back(current);
  10359. return true;
  10360. });
  10361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10362. EXPECT_EQ(200, res->status);
  10363. EXPECT_FALSE(progress_values.empty());
  10364. EXPECT_EQ(expected_content_size, received_body.size());
  10365. EXPECT_TRUE(res->body.empty());
  10366. }
  10367. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10368. TestContentReceiverDownloadProgress(
  10369. [](Server &svr) {
  10370. svr.Get("/download-receiver",
  10371. [](const Request & /*req*/, Response &res) {
  10372. string content(2000, 'R');
  10373. res.set_content(content, "text/plain");
  10374. });
  10375. },
  10376. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10377. DownloadProgress progress_callback) {
  10378. return cli.Get(endpoint, content_receiver, progress_callback);
  10379. },
  10380. "/download-receiver", 2000u);
  10381. }
  10382. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10383. // A provider reaching a pass with nothing to hand over - an empty buffer
  10384. // popped off a queue, say - must not be taken to mean the body is finished.
  10385. // It used to end the loop with the terminating chunk unwritten while the
  10386. // server still considered the response complete, so the peer waited for an
  10387. // end that never arrived.
  10388. Server svr;
  10389. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10390. auto step = std::make_shared<int>(0);
  10391. res.set_chunked_content_provider("text/plain",
  10392. [step](size_t /*offset*/, DataSink &sink) {
  10393. switch ((*step)++) {
  10394. case 0: sink.write("", 0); break;
  10395. case 1: sink.write("hello", 5); break;
  10396. default: sink.done(); break;
  10397. }
  10398. return true;
  10399. });
  10400. });
  10401. auto port = svr.bind_to_any_port(HOST);
  10402. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10403. auto listen_se = detail::scope_exit([&] {
  10404. svr.stop();
  10405. listen_thread.join();
  10406. ASSERT_FALSE(svr.is_running());
  10407. });
  10408. svr.wait_until_ready();
  10409. Client cli(HOST, port);
  10410. // Without the fix the body is never terminated, so bound the wait rather
  10411. // than letting the test hang on the default read timeout.
  10412. cli.set_read_timeout(5, 0);
  10413. auto res = cli.Get("/stream");
  10414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10415. EXPECT_EQ(StatusCode::OK_200, res->status);
  10416. EXPECT_EQ("hello", res->body);
  10417. }
  10418. TEST(StreamingTest, NoContentLengthStreaming) {
  10419. Server svr;
  10420. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10421. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10422. if (offset < 6) {
  10423. sink.os << (offset < 3 ? "a" : "b");
  10424. } else {
  10425. sink.done();
  10426. }
  10427. return true;
  10428. });
  10429. });
  10430. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10431. auto listen_se = detail::scope_exit([&] {
  10432. svr.stop();
  10433. listen_thread.join();
  10434. ASSERT_FALSE(svr.is_running());
  10435. });
  10436. svr.wait_until_ready();
  10437. Client client(HOST, PORT);
  10438. auto get_thread = std::thread([&client]() {
  10439. std::string s;
  10440. auto res =
  10441. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10442. s += std::string(data, len);
  10443. return true;
  10444. });
  10445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10446. EXPECT_EQ(StatusCode::OK_200, res->status);
  10447. EXPECT_EQ("aaabbb", s);
  10448. });
  10449. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10450. // Give GET time to get a few messages.
  10451. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10452. }
  10453. TEST(MountTest, Unmount) {
  10454. Server svr;
  10455. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10456. auto se = detail::scope_exit([&] {
  10457. svr.stop();
  10458. listen_thread.join();
  10459. ASSERT_FALSE(svr.is_running());
  10460. });
  10461. svr.wait_until_ready();
  10462. Client cli("localhost", PORT);
  10463. svr.set_mount_point("/mount2", "./www2");
  10464. auto res = cli.Get("/");
  10465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10466. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10467. res = cli.Get("/mount2/dir/test.html");
  10468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10469. EXPECT_EQ(StatusCode::OK_200, res->status);
  10470. svr.set_mount_point("/", "./www");
  10471. res = cli.Get("/dir/");
  10472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10473. EXPECT_EQ(StatusCode::OK_200, res->status);
  10474. svr.remove_mount_point("/");
  10475. res = cli.Get("/dir/");
  10476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10477. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10478. svr.remove_mount_point("/mount2");
  10479. res = cli.Get("/mount2/dir/test.html");
  10480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10481. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10482. }
  10483. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10484. Server svr;
  10485. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10486. svr.Get("/api/hello", [](const Request &, Response &res) {
  10487. res.set_content("api", "text/plain");
  10488. });
  10489. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10490. auto se = detail::scope_exit([&] {
  10491. svr.stop();
  10492. listen_thread.join();
  10493. ASSERT_FALSE(svr.is_running());
  10494. });
  10495. svr.wait_until_ready();
  10496. Client cli(HOST, PORT);
  10497. auto res = cli.Get("/dir/test.html");
  10498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10499. EXPECT_EQ(StatusCode::OK_200, res->status);
  10500. res = cli.Get("/api/hello");
  10501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10502. EXPECT_EQ(StatusCode::OK_200, res->status);
  10503. EXPECT_EQ("api", res->body);
  10504. }
  10505. TEST(MountTest, PathSegmentBoundary) {
  10506. Server svr;
  10507. svr.set_mount_point("/mount2", "./www2");
  10508. svr.set_mount_point("/", "./www");
  10509. auto port = svr.bind_to_any_port(HOST);
  10510. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10511. auto se = detail::scope_exit([&] {
  10512. svr.stop();
  10513. listen_thread.join();
  10514. ASSERT_FALSE(svr.is_running());
  10515. });
  10516. svr.wait_until_ready();
  10517. Client cli(HOST, port);
  10518. auto res = cli.Get("/mount2/dir/test.html");
  10519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10520. EXPECT_EQ(StatusCode::OK_200, res->status);
  10521. // "/mount2" must not match part-way through a path segment.
  10522. res = cli.Get("/mount2dir/test.html");
  10523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10525. // A mount point ending in '/' keeps matching every path below it.
  10526. res = cli.Get("/dir/test.html");
  10527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10528. EXPECT_EQ(StatusCode::OK_200, res->status);
  10529. }
  10530. TEST(MountTest, Redicect) {
  10531. Server svr;
  10532. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10533. auto se = detail::scope_exit([&] {
  10534. svr.stop();
  10535. listen_thread.join();
  10536. ASSERT_FALSE(svr.is_running());
  10537. });
  10538. svr.set_mount_point("/", "./www");
  10539. svr.wait_until_ready();
  10540. Client cli("localhost", PORT);
  10541. auto res = cli.Get("/dir/");
  10542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10543. EXPECT_EQ(StatusCode::OK_200, res->status);
  10544. res = cli.Get("/dir");
  10545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10546. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10547. res = cli.Get("/file");
  10548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10549. EXPECT_EQ(StatusCode::OK_200, res->status);
  10550. res = cli.Get("/file/");
  10551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10552. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10553. cli.set_follow_location(true);
  10554. res = cli.Get("/dir");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::OK_200, res->status);
  10557. }
  10558. TEST(MountTest, MultibytesPathName) {
  10559. Server svr;
  10560. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10561. auto se = detail::scope_exit([&] {
  10562. svr.stop();
  10563. listen_thread.join();
  10564. ASSERT_FALSE(svr.is_running());
  10565. });
  10566. svr.set_mount_point("/", "./www");
  10567. svr.wait_until_ready();
  10568. Client cli("localhost", PORT);
  10569. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10571. EXPECT_EQ(StatusCode::OK_200, res->status);
  10572. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10573. }
  10574. #ifdef _WIN32
  10575. // Issue #2435: mmap::open() must succeed even when another handle holds
  10576. // the file open for writing (e.g. an active log file).
  10577. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10578. const char *path = "mmap_concurrent_writer_test.txt";
  10579. const char *content = "hello";
  10580. {
  10581. std::ofstream f(path, std::ios::binary);
  10582. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10583. }
  10584. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10585. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10586. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10587. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10588. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10589. detail::mmap m(path);
  10590. ASSERT_TRUE(m.is_open());
  10591. EXPECT_EQ(strlen(content), m.size());
  10592. char buf[8];
  10593. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10594. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10595. }
  10596. #endif
  10597. #ifndef _WIN32
  10598. // A directory or a device has no size to serve.
  10599. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10600. const char *path = "./mmap_not_regular_test_dir";
  10601. ASSERT_EQ(0, ::mkdir(path, 0755));
  10602. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10603. for (auto p : {path, "/dev/null"}) {
  10604. detail::mmap m(p);
  10605. EXPECT_FALSE(m.is_open()) << p;
  10606. EXPECT_EQ(0U, m.size()) << p;
  10607. }
  10608. Server svr;
  10609. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10610. res.set_file_content("/dev/null");
  10611. });
  10612. auto port = svr.bind_to_any_port(HOST);
  10613. thread t = thread([&] { svr.listen_after_bind(); });
  10614. auto se = detail::scope_exit([&] {
  10615. svr.stop();
  10616. t.join();
  10617. });
  10618. svr.wait_until_ready();
  10619. auto res = Client(HOST, port).Get("/null");
  10620. ASSERT_TRUE(res);
  10621. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10622. }
  10623. #endif
  10624. #ifdef __linux__
  10625. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10626. TEST(MmapTest, FileIsNotMapped) {
  10627. const char *path = "mmap_not_mapped_test.txt";
  10628. {
  10629. std::ofstream f(path, std::ios::binary);
  10630. f << "hello";
  10631. }
  10632. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10633. detail::mmap m(path);
  10634. ASSERT_TRUE(m.is_open());
  10635. std::ifstream maps("/proc/self/maps");
  10636. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10637. std::istreambuf_iterator<char>());
  10638. EXPECT_EQ(std::string::npos, mappings.find(path));
  10639. }
  10640. #endif
  10641. TEST(KeepAliveTest, ReadTimeout) {
  10642. Server svr;
  10643. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10644. std::this_thread::sleep_for(std::chrono::seconds(2));
  10645. res.set_content("a", "text/plain");
  10646. });
  10647. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10648. res.set_content("b", "text/plain");
  10649. });
  10650. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10651. auto se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. listen_thread.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. Client cli("localhost", PORT);
  10658. cli.set_keep_alive(true);
  10659. cli.set_read_timeout(std::chrono::seconds(1));
  10660. auto resa = cli.Get("/a");
  10661. ASSERT_FALSE(resa);
  10662. EXPECT_EQ(Error::Read, resa.error());
  10663. auto resb = cli.Get("/b");
  10664. ASSERT_TRUE(resb);
  10665. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10666. EXPECT_EQ("b", resb->body);
  10667. }
  10668. TEST(KeepAliveTest, MaxCount) {
  10669. size_t keep_alive_max_count = 3;
  10670. Server svr;
  10671. svr.set_keep_alive_max_count(keep_alive_max_count);
  10672. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10673. res.set_content("Hello World!", "text/plain");
  10674. });
  10675. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. listen_thread.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. Client cli(HOST, PORT);
  10683. cli.set_keep_alive(true);
  10684. for (size_t i = 0; i < 5; i++) {
  10685. auto result = cli.Get("/hi");
  10686. ASSERT_TRUE(result);
  10687. EXPECT_EQ(StatusCode::OK_200, result->status);
  10688. if (i == keep_alive_max_count - 1) {
  10689. EXPECT_EQ("close", result->get_header_value("Connection"));
  10690. } else {
  10691. EXPECT_FALSE(result->has_header("Connection"));
  10692. }
  10693. }
  10694. }
  10695. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10696. // can pull the next one into the server's buffer. The server must serve it
  10697. // without waiting for the socket to become readable again. The keep-alive
  10698. // timeout outlasts the client's read timeout, so a request left waiting for it
  10699. // shows up as a missing response.
  10700. static void serve_pipelining_routes(Server &svr,
  10701. const std::function<void(int)> &client) {
  10702. svr.set_keep_alive_timeout(5);
  10703. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10704. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10705. });
  10706. svr.Post("/echo", [](const Request &req, Response &res) {
  10707. res.set_content("echo " + req.body, "text/plain");
  10708. });
  10709. auto port = svr.bind_to_any_port(HOST);
  10710. thread t = thread([&] { svr.listen_after_bind(); });
  10711. auto se = detail::scope_exit([&] {
  10712. svr.stop();
  10713. t.join();
  10714. });
  10715. svr.wait_until_ready();
  10716. client(port);
  10717. }
  10718. static std::string
  10719. send_pipelined_requests(const std::vector<std::string> &parts) {
  10720. Server svr;
  10721. std::string res;
  10722. serve_pipelining_routes(svr, [&](int port) {
  10723. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10724. });
  10725. return res;
  10726. }
  10727. static void expect_in_order(const std::string &res,
  10728. const std::vector<std::string> &bodies) {
  10729. size_t pos = 0;
  10730. for (const auto &body : bodies) {
  10731. pos = res.find(body, pos);
  10732. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10733. pos += body.size();
  10734. }
  10735. }
  10736. TEST(KeepAliveTest, PipelinedRequests) {
  10737. auto res = send_pipelined_requests(
  10738. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10739. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10740. "Content-Length: 4\r\n\r\nbody"
  10741. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10742. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10743. }
  10744. // The second request starts in the server's buffer and ends on the socket.
  10745. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10746. auto res =
  10747. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10748. "GET /hi/2 HTTP/1.1\r\nHo",
  10749. "st: localhost\r\nConnection: close\r\n\r\n"});
  10750. expect_in_order(res, {"hi 1", "hi 2"});
  10751. }
  10752. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10753. // CRLF after a body does not turn into a 400 for the next request.
  10754. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10755. auto res = send_pipelined_requests(
  10756. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10757. "Content-Length: 4\r\n\r\nbody\r\n"
  10758. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10759. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10760. expect_in_order(res, {"echo body", "hi 2"});
  10761. }
  10762. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10763. // must not be served as the next request.
  10764. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10765. auto res = send_pipelined_requests(
  10766. {"INVALID REQUEST LINE\r\n\r\n"
  10767. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10768. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10769. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10770. }
  10771. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10772. // Over TLS, the next request is held by the TLS library as already decrypted
  10773. // data rather than on the socket.
  10774. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10776. std::string res;
  10777. serve_pipelining_routes(svr, [&](int port) {
  10778. // One part, so all three requests arrive in one TLS record
  10779. EXPECT_TRUE(send_ssl_request_in_parts(
  10780. 2,
  10781. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10782. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10783. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10784. &res, port));
  10785. });
  10786. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10787. }
  10788. #endif
  10789. TEST(KeepAliveTest, Issue1041) {
  10790. Server svr;
  10791. svr.set_keep_alive_timeout(3);
  10792. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10793. res.set_content("Hello World!", "text/plain");
  10794. });
  10795. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10796. auto se = detail::scope_exit([&] {
  10797. svr.stop();
  10798. listen_thread.join();
  10799. ASSERT_FALSE(svr.is_running());
  10800. });
  10801. svr.wait_until_ready();
  10802. Client cli(HOST, PORT);
  10803. cli.set_keep_alive(true);
  10804. auto result = cli.Get("/hi");
  10805. ASSERT_TRUE(result);
  10806. EXPECT_EQ(StatusCode::OK_200, result->status);
  10807. std::this_thread::sleep_for(std::chrono::seconds(5));
  10808. result = cli.Get("/hi");
  10809. ASSERT_TRUE(result);
  10810. EXPECT_EQ(StatusCode::OK_200, result->status);
  10811. }
  10812. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10813. Server svr;
  10814. svr.set_keep_alive_max_count(0);
  10815. std::set<int> remote_ports;
  10816. svr.Get("/hi", [&](const Request &req, Response &res) {
  10817. remote_ports.insert(req.remote_port);
  10818. res.set_content("hi", "text/plain");
  10819. });
  10820. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10821. auto se = detail::scope_exit([&] {
  10822. svr.stop();
  10823. listen_thread.join();
  10824. ASSERT_FALSE(svr.is_running());
  10825. });
  10826. svr.wait_until_ready();
  10827. Client cli(HOST, PORT);
  10828. cli.set_keep_alive(true);
  10829. for (int i = 0; i < 3; i++) {
  10830. auto res = cli.Get("/hi");
  10831. ASSERT_TRUE(res);
  10832. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10833. }
  10834. // All three over one connection
  10835. EXPECT_EQ(1u, remote_ports.size());
  10836. }
  10837. TEST(KeepAliveTest, Issue1959) {
  10838. Server svr;
  10839. svr.set_keep_alive_timeout(5);
  10840. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10841. res.set_content("a", "text/plain");
  10842. });
  10843. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10844. auto se = detail::scope_exit([&] {
  10845. if (!svr.is_running()) return;
  10846. svr.stop();
  10847. listen_thread.join();
  10848. ASSERT_FALSE(svr.is_running());
  10849. });
  10850. svr.wait_until_ready();
  10851. Client cli("localhost", PORT);
  10852. cli.set_keep_alive(true);
  10853. using namespace std::chrono;
  10854. auto start = steady_clock::now();
  10855. cli.Get("/a");
  10856. svr.stop();
  10857. listen_thread.join();
  10858. auto end = steady_clock::now();
  10859. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10860. EXPECT_LT(elapsed, 5000);
  10861. }
  10862. #ifdef CPPHTTPLIB_SSL_ENABLED
  10863. TEST(KeepAliveTest, SSLClientReconnection) {
  10864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10865. ASSERT_TRUE(svr.is_valid());
  10866. svr.set_keep_alive_timeout(1);
  10867. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10868. res.set_content("Hello World!", "text/plain");
  10869. });
  10870. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10871. auto se = detail::scope_exit([&] {
  10872. svr.stop();
  10873. listen_thread.join();
  10874. ASSERT_FALSE(svr.is_running());
  10875. });
  10876. svr.wait_until_ready();
  10877. SSLClient cli(HOST, PORT);
  10878. cli.enable_server_certificate_verification(false);
  10879. cli.set_keep_alive(true);
  10880. auto result = cli.Get("/hi");
  10881. ASSERT_TRUE(result);
  10882. EXPECT_EQ(StatusCode::OK_200, result->status);
  10883. result = cli.Get("/hi");
  10884. ASSERT_TRUE(result);
  10885. EXPECT_EQ(StatusCode::OK_200, result->status);
  10886. std::this_thread::sleep_for(std::chrono::seconds(2));
  10887. // Recoonect
  10888. result = cli.Get("/hi");
  10889. ASSERT_TRUE(result);
  10890. EXPECT_EQ(StatusCode::OK_200, result->status);
  10891. result = cli.Get("/hi");
  10892. ASSERT_TRUE(result);
  10893. EXPECT_EQ(StatusCode::OK_200, result->status);
  10894. }
  10895. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10896. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10897. ASSERT_TRUE(svr.is_valid());
  10898. svr.set_keep_alive_timeout(1);
  10899. std::string content = "reconnect";
  10900. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10901. res.set_content("Hello World!", "text/plain");
  10902. });
  10903. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10904. auto se = detail::scope_exit([&] {
  10905. svr.stop();
  10906. listen_thread.join();
  10907. ASSERT_FALSE(svr.is_running());
  10908. });
  10909. svr.wait_until_ready();
  10910. SSLClient cli(HOST, PORT);
  10911. cli.enable_server_certificate_verification(false);
  10912. cli.set_keep_alive(true);
  10913. auto result = cli.Post(
  10914. "/hi", content.size(),
  10915. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10916. sink.write(content.c_str(), content.size());
  10917. return true;
  10918. },
  10919. "text/plain");
  10920. ASSERT_TRUE(result);
  10921. EXPECT_EQ(200, result->status);
  10922. std::this_thread::sleep_for(std::chrono::seconds(2));
  10923. // Recoonect
  10924. result = cli.Post(
  10925. "/hi", content.size(),
  10926. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10927. sink.write(content.c_str(), content.size());
  10928. return true;
  10929. },
  10930. "text/plain");
  10931. ASSERT_TRUE(result);
  10932. EXPECT_EQ(200, result->status);
  10933. result = cli.Post(
  10934. "/hi", content.size(),
  10935. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10936. sink.write(content.c_str(), content.size());
  10937. return true;
  10938. },
  10939. "text/plain");
  10940. ASSERT_TRUE(result);
  10941. EXPECT_EQ(200, result->status);
  10942. }
  10943. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10944. using namespace httplib::tls;
  10945. {
  10946. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10947. ASSERT_TRUE(svr.is_valid());
  10948. svr.Get("/sni", [&](const Request &req, Response &res) {
  10949. std::string expected = req.sni();
  10950. EXPECT_EQ(expected, req.get_param_value("expected"));
  10951. res.set_content("ok", "text/plain");
  10952. });
  10953. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10954. auto se = detail::scope_exit([&] {
  10955. svr.stop();
  10956. listen_thread.join();
  10957. ASSERT_FALSE(svr.is_running());
  10958. });
  10959. svr.wait_until_ready();
  10960. {
  10961. SSLClient cli("localhost", PORT);
  10962. cli.enable_server_certificate_verification(false);
  10963. auto res = cli.Get("/sni?expected=localhost");
  10964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10965. }
  10966. {
  10967. SSLClient cli("::1", PORT);
  10968. cli.enable_server_certificate_verification(false);
  10969. auto res = cli.Get("/sni?expected=");
  10970. // NOTE: This may fail if the server is listening on IPv4 only
  10971. // (e.g., when localhost resolves to 127.0.0.1 only)
  10972. if (res) {
  10973. EXPECT_EQ(StatusCode::OK_200, res->status);
  10974. } else {
  10975. EXPECT_EQ(Error::Connection, res.error());
  10976. }
  10977. }
  10978. }
  10979. }
  10980. #endif
  10981. TEST(ClientProblemDetectionTest, ContentProvider) {
  10982. Server svr;
  10983. size_t content_length = 1024 * 1024;
  10984. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10985. res.set_content_provider(
  10986. content_length, "text/plain",
  10987. [&](size_t offset, size_t length, DataSink &sink) {
  10988. auto out_len = std::min(length, static_cast<size_t>(1024));
  10989. std::string out(out_len, '@');
  10990. sink.write(out.data(), out_len);
  10991. return offset < 4096;
  10992. },
  10993. [](bool success) { ASSERT_FALSE(success); });
  10994. });
  10995. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10996. res.set_content_provider(
  10997. 0, "text/plain",
  10998. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10999. EXPECT_TRUE(false);
  11000. return true;
  11001. },
  11002. [](bool success) { ASSERT_FALSE(success); });
  11003. });
  11004. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11005. auto se = detail::scope_exit([&] {
  11006. svr.stop();
  11007. listen_thread.join();
  11008. ASSERT_FALSE(svr.is_running());
  11009. });
  11010. svr.wait_until_ready();
  11011. Client cli("localhost", PORT);
  11012. {
  11013. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11014. size_t /*data_length*/) { return false; });
  11015. ASSERT_FALSE(res);
  11016. }
  11017. {
  11018. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11019. size_t /*data_length*/) { return false; });
  11020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11021. }
  11022. }
  11023. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11024. // A provider that reports success without writing anything and without
  11025. // calling done() used to be handed the same offset and length again on every
  11026. // pass, so it spun for as long as the peer stayed connected.
  11027. Server svr;
  11028. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11029. res.set_content("ok", "text/plain");
  11030. });
  11031. auto port = svr.bind_to_any_port(HOST);
  11032. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11033. auto se = detail::scope_exit([&] {
  11034. svr.stop();
  11035. listen_thread.join();
  11036. ASSERT_FALSE(svr.is_running());
  11037. });
  11038. svr.wait_until_ready();
  11039. std::atomic<int> call_count{0};
  11040. Client cli(HOST, port);
  11041. auto res = cli.Post(
  11042. "/", 1024,
  11043. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11044. // Give up after enough passes to show the spin, so that losing the
  11045. // check below fails this test instead of hanging it.
  11046. return ++call_count < 100;
  11047. },
  11048. "text/plain");
  11049. ASSERT_FALSE(res);
  11050. EXPECT_EQ(Error::Write, res.error());
  11051. EXPECT_EQ(1, call_count.load());
  11052. }
  11053. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11054. // A writer only has to assign `write`. The other three used to be left as
  11055. // empty std::functions, so a provider calling one threw
  11056. // std::bad_function_call out of the thread running it and took the whole
  11057. // process down.
  11058. DataSink sink;
  11059. std::string written;
  11060. sink.write = [&](const char *data, size_t data_len) {
  11061. written.append(data, data_len);
  11062. return true;
  11063. };
  11064. EXPECT_TRUE(sink.is_writable());
  11065. sink.done();
  11066. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11067. EXPECT_TRUE(written.empty());
  11068. }
  11069. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11070. // A sink that cannot carry trailers still has to finish.
  11071. DataSink sink;
  11072. auto done_count = 0;
  11073. sink.done = [&]() { done_count++; };
  11074. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11075. EXPECT_EQ(1, done_count);
  11076. }
  11077. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11078. Server svr;
  11079. const std::string body(4096, 'x');
  11080. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11081. res.set_content_provider(body.size(), "text/plain",
  11082. [&](size_t offset, size_t length, DataSink &sink) {
  11083. sink.write(body.data() + offset, length);
  11084. sink.done();
  11085. return true;
  11086. });
  11087. });
  11088. auto port = svr.bind_to_any_port(HOST);
  11089. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11090. auto se = detail::scope_exit([&] {
  11091. svr.stop();
  11092. listen_thread.join();
  11093. ASSERT_FALSE(svr.is_running());
  11094. });
  11095. svr.wait_until_ready();
  11096. Client cli(HOST, port);
  11097. auto res = cli.Get("/");
  11098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11099. EXPECT_EQ(StatusCode::OK_200, res->status);
  11100. EXPECT_EQ(body, res->body);
  11101. }
  11102. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11103. Server svr;
  11104. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11105. res.set_content_provider(
  11106. 1024, "text/plain",
  11107. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11108. sink.write("hello", 5);
  11109. sink.done(); // short of the 1024 bytes the response promised
  11110. return true;
  11111. });
  11112. });
  11113. auto port = svr.bind_to_any_port(HOST);
  11114. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11115. auto se = detail::scope_exit([&] {
  11116. svr.stop();
  11117. listen_thread.join();
  11118. ASSERT_FALSE(svr.is_running());
  11119. });
  11120. svr.wait_until_ready();
  11121. Client cli(HOST, port);
  11122. cli.set_read_timeout(5, 0);
  11123. // The response is short of its Content-Length, so the client cannot read a
  11124. // complete body. What matters is that this returns at all: a no-op done()
  11125. // would leave the writer looping over a provider that never makes progress.
  11126. auto res = cli.Get("/");
  11127. EXPECT_FALSE(res);
  11128. }
  11129. // Read as the next response by a peer that sees it after a framed body.
  11130. static const std::string smuggled_response =
  11131. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11132. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11133. Server svr;
  11134. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11135. res.set_content_provider(
  11136. 5, "text/plain",
  11137. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11138. auto data = "AAAAA" + smuggled_response;
  11139. sink.write(data.data(), data.size());
  11140. return true;
  11141. });
  11142. });
  11143. thread t = thread([&] { svr.listen(HOST, PORT); });
  11144. auto se = detail::scope_exit([&] {
  11145. svr.stop();
  11146. t.join();
  11147. ASSERT_FALSE(svr.is_running());
  11148. });
  11149. svr.wait_until_ready();
  11150. std::string resp;
  11151. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11152. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11153. resp.clear();
  11154. ASSERT_TRUE(send_request(
  11155. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11156. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11157. }
  11158. TEST(NoContentTest, BodyIsNotSent) {
  11159. Server svr;
  11160. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11161. res.status = StatusCode::NoContent_204;
  11162. res.set_content(smuggled_response, "text/plain");
  11163. });
  11164. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11165. res.status = StatusCode::NotModified_304;
  11166. res.set_chunked_content_provider(
  11167. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11168. sink.write(smuggled_response.data(), smuggled_response.size());
  11169. sink.done();
  11170. return true;
  11171. });
  11172. });
  11173. thread t = thread([&] { svr.listen(HOST, PORT); });
  11174. auto se = detail::scope_exit([&] {
  11175. svr.stop();
  11176. t.join();
  11177. ASSERT_FALSE(svr.is_running());
  11178. });
  11179. svr.wait_until_ready();
  11180. for (auto path : {"/204", "/304"}) {
  11181. std::string resp;
  11182. ASSERT_TRUE(send_request(
  11183. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11184. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11185. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11186. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11187. }
  11188. }
  11189. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11190. Server svr;
  11191. std::atomic<bool> smuggled(false);
  11192. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11193. res.set_content("ok", "text/plain");
  11194. });
  11195. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11196. smuggled = true;
  11197. });
  11198. auto port = svr.bind_to_any_port(HOST);
  11199. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11200. auto se = detail::scope_exit([&] {
  11201. svr.stop();
  11202. listen_thread.join();
  11203. ASSERT_FALSE(svr.is_running());
  11204. });
  11205. svr.wait_until_ready();
  11206. // What follows the body would be read as the next request.
  11207. Client cli(HOST, port);
  11208. auto res = cli.Post(
  11209. "/", 5,
  11210. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11211. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11212. sink.write(data.data(), data.size());
  11213. return true;
  11214. },
  11215. "text/plain");
  11216. ASSERT_FALSE(res);
  11217. EXPECT_EQ(Error::Write, res.error());
  11218. EXPECT_FALSE(smuggled);
  11219. }
  11220. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11221. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11222. // The compressed path builds the whole body before connecting, so this
  11223. // fails client-side and never reaches a server.
  11224. Client cli(HOST, PORT);
  11225. cli.set_compress(true);
  11226. auto res = cli.Post(
  11227. "/", 1024,
  11228. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11229. sink.write("hello", 5);
  11230. sink.done(); // short of the 1024 bytes the request announced
  11231. return true;
  11232. },
  11233. "text/plain");
  11234. ASSERT_FALSE(res);
  11235. EXPECT_EQ(Error::Write, res.error());
  11236. }
  11237. #endif
  11238. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11239. Server svr;
  11240. svr.set_error_handler([](Request const &, Response &res) -> void {
  11241. res.set_chunked_content_provider(
  11242. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11243. sink.os << "hello";
  11244. sink.os << "world";
  11245. sink.done();
  11246. return true;
  11247. });
  11248. });
  11249. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11250. auto se = detail::scope_exit([&] {
  11251. svr.stop();
  11252. listen_thread.join();
  11253. ASSERT_FALSE(svr.is_running());
  11254. });
  11255. svr.wait_until_ready();
  11256. Client cli("localhost", PORT);
  11257. auto res = cli.Get("/");
  11258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11259. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11260. EXPECT_EQ("helloworld", res->body);
  11261. }
  11262. // A body set after a content provider must replace it, not be sent through it.
  11263. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11264. Server svr;
  11265. svr.set_mount_point("/", "./www");
  11266. svr.set_file_request_handler([](const Request &req, Response &res) {
  11267. if (req.path == "/dir/test.html") {
  11268. res.status = StatusCode::Forbidden_403;
  11269. res.set_content(std::string(5000, 'D'), "text/plain");
  11270. } else if (req.path == "/file") {
  11271. res.status = StatusCode::Forbidden_403;
  11272. res.body = "Denied";
  11273. }
  11274. });
  11275. auto port = svr.bind_to_any_port(HOST);
  11276. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11277. auto se = detail::scope_exit([&] {
  11278. svr.stop();
  11279. t.join();
  11280. ASSERT_FALSE(svr.is_running());
  11281. });
  11282. svr.wait_until_ready();
  11283. Client cli(HOST, port);
  11284. {
  11285. auto res = cli.Get("/dir/test.html");
  11286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11287. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11288. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11289. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11290. }
  11291. {
  11292. auto res = cli.Get("/file");
  11293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11294. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11295. EXPECT_EQ("Denied", res->body);
  11296. }
  11297. {
  11298. auto res = cli.Get("/dir/index.html");
  11299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11300. EXPECT_EQ(StatusCode::OK_200, res->status);
  11301. EXPECT_EQ(0U, res->body.find("<html>"));
  11302. }
  11303. }
  11304. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11305. Server svr;
  11306. std::vector<bool> released;
  11307. std::mutex released_mutex;
  11308. auto releaser = [&](bool success) {
  11309. std::lock_guard<std::mutex> guard(released_mutex);
  11310. released.push_back(success);
  11311. };
  11312. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11313. return sink.write(&"hello"[offset], length);
  11314. };
  11315. svr.Get("/sized", [&](const Request &, Response &res) {
  11316. res.status = StatusCode::NotFound_404;
  11317. res.set_content_provider(5, "text/plain", provider, releaser);
  11318. });
  11319. svr.Get("/chunked", [&](const Request &, Response &res) {
  11320. res.status = StatusCode::ServiceUnavailable_503;
  11321. res.set_chunked_content_provider(
  11322. "text/plain",
  11323. [](size_t, DataSink &sink) {
  11324. sink.os << "chunk";
  11325. sink.done();
  11326. return true;
  11327. },
  11328. releaser);
  11329. });
  11330. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11331. res.set_content_provider(5, "text/plain", provider, releaser);
  11332. throw std::runtime_error("after the provider");
  11333. });
  11334. svr.set_error_handler([](const Request &req, Response &res) {
  11335. // Leave the exception handler's content to it.
  11336. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11337. res.set_content(std::string(1000, 'E'), "text/html");
  11338. return Server::HandlerResponse::Handled;
  11339. });
  11340. svr.set_exception_handler(
  11341. [](const Request &, Response &res, std::exception_ptr) {
  11342. res.status = StatusCode::InternalServerError_500;
  11343. res.set_content(std::string(1000, 'X'), "text/html");
  11344. });
  11345. auto port = svr.bind_to_any_port(HOST);
  11346. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11347. auto se = detail::scope_exit([&] {
  11348. svr.stop();
  11349. t.join();
  11350. ASSERT_FALSE(svr.is_running());
  11351. });
  11352. svr.wait_until_ready();
  11353. Client cli(HOST, port);
  11354. {
  11355. auto res = cli.Get("/sized");
  11356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11357. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11358. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11359. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11360. }
  11361. {
  11362. auto res = cli.Get("/chunked");
  11363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11364. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11365. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11366. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11367. }
  11368. {
  11369. auto res = cli.Get("/throw");
  11370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11371. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11372. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11373. }
  11374. std::lock_guard<std::mutex> guard(released_mutex);
  11375. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11376. }
  11377. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11378. Server svr;
  11379. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11380. return sink.write(&"abc"[offset], length);
  11381. };
  11382. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11383. res.set_file_content("./www/dir/test.html");
  11384. res.set_content("body", "text/plain");
  11385. });
  11386. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11387. res.set_content(std::string(100, 'B'), "text/plain");
  11388. res.set_file_content("./www/dir/test.html");
  11389. });
  11390. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11391. res.set_content(std::string(100, 'B'), "text/plain");
  11392. res.set_content_provider(3, "text/x-provider", abc);
  11393. });
  11394. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11395. res.set_content_provider(3, "text/x-provider", abc);
  11396. res.set_content(std::string(100, 'B'), "text/plain");
  11397. });
  11398. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11399. res.set_content_provider(3, "text/x-provider", abc);
  11400. res.set_file_content("./www/dir/test.html", "text/x-file");
  11401. });
  11402. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11403. res.set_file_content("./www/dir/test.html");
  11404. res.set_header("Content-Type", "text/x-handler");
  11405. });
  11406. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11407. res.set_content_provider(3, "text/plain", abc);
  11408. res.body = "direct";
  11409. });
  11410. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11411. res.set_file_content("./www/dir/test.html");
  11412. res.body = "direct";
  11413. });
  11414. auto port = svr.bind_to_any_port(HOST);
  11415. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11416. auto se = detail::scope_exit([&] {
  11417. svr.stop();
  11418. t.join();
  11419. ASSERT_FALSE(svr.is_running());
  11420. });
  11421. svr.wait_until_ready();
  11422. Client cli(HOST, port);
  11423. auto expect_body = [&](const char *path, const std::string &body,
  11424. const std::string &type) {
  11425. // Uncompressed, so Content-Length can be compared with the body.
  11426. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11427. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11428. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11429. EXPECT_EQ(body, res->body) << path;
  11430. EXPECT_EQ(std::to_string(body.size()),
  11431. res->get_header_value("Content-Length"))
  11432. << path;
  11433. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11434. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11435. };
  11436. expect_body("/file-then-body", "body", "text/plain");
  11437. expect_body("/body-then-file", "test.html", "text/html");
  11438. expect_body("/body-then-provider", "abc", "text/x-provider");
  11439. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11440. expect_body("/provider-then-file", "test.html", "text/x-file");
  11441. expect_body("/file-then-header", "test.html", "text/x-handler");
  11442. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11443. expect_body("/file-then-direct-body", "direct", "text/plain");
  11444. // Ranges are checked against the body, not the dropped provider.
  11445. {
  11446. auto res = cli.Get("/provider-then-direct-body",
  11447. Headers{{make_range_header({{1, 2}})}});
  11448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11449. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11450. EXPECT_EQ("ir", res->body);
  11451. }
  11452. {
  11453. auto res = cli.Get("/file-then-direct-body",
  11454. Headers{{make_range_header({{7, 8}})}});
  11455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11456. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11457. }
  11458. }
  11459. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11460. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11461. const char *path = "./truncated_while_served.txt";
  11462. const size_t size = 32 * 1024 * 1024;
  11463. {
  11464. std::ofstream f(path, std::ios::binary);
  11465. f << std::string(size, 'x');
  11466. }
  11467. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11468. // Over TLS, where the bytes are encrypted in this process rather than
  11469. // copied by send().
  11470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11471. svr.Get("/file", [&](const Request &, Response &res) {
  11472. res.set_file_content(path, "text/plain");
  11473. });
  11474. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11475. auto se = detail::scope_exit([&] {
  11476. svr.stop();
  11477. thread.join();
  11478. ASSERT_FALSE(svr.is_running());
  11479. });
  11480. svr.wait_until_ready();
  11481. // The file shrinks once the first bytes are in, as a rewrite in place
  11482. // would, and reading the mapping past its new end used to raise SIGBUS.
  11483. SSLClient cli(HOST, PORT);
  11484. cli.enable_server_certificate_verification(false);
  11485. size_t received = 0;
  11486. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11487. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11488. received += len;
  11489. return true;
  11490. });
  11491. EXPECT_FALSE(res);
  11492. EXPECT_LT(received, size);
  11493. }
  11494. #endif
  11495. // Forward declaration (see the base64_encode note).
  11496. namespace httplib {
  11497. namespace detail {
  11498. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11499. const std::string &content_type,
  11500. EncodingType encoding);
  11501. } // namespace detail
  11502. } // namespace httplib
  11503. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11504. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11505. ASSERT_TRUE(mm->is_open());
  11506. Response res;
  11507. detail::set_file_content_provider(res, mm, "text/html",
  11508. detail::EncodingType::None);
  11509. std::string out;
  11510. DataSink sink;
  11511. sink.write = [&](const char *d, size_t l) {
  11512. out.append(d, l);
  11513. return true;
  11514. };
  11515. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11516. EXPECT_EQ("test.html", out);
  11517. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11518. EXPECT_EQ("test.html", out);
  11519. }
  11520. TEST(LongPollingTest, ClientCloseDetection) {
  11521. Server svr;
  11522. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11523. res.set_chunked_content_provider(
  11524. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11525. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11526. sink.os << "hello";
  11527. auto count = 10;
  11528. while (count > 0 && sink.is_writable()) {
  11529. this_thread::sleep_for(chrono::milliseconds(10));
  11530. count--;
  11531. }
  11532. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11533. return true;
  11534. });
  11535. });
  11536. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11537. auto se = detail::scope_exit([&] {
  11538. svr.stop();
  11539. listen_thread.join();
  11540. ASSERT_FALSE(svr.is_running());
  11541. });
  11542. svr.wait_until_ready();
  11543. Client cli("localhost", PORT);
  11544. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11545. EXPECT_EQ("hello", string(data, data_length));
  11546. return false; // close the socket immediately.
  11547. });
  11548. ASSERT_FALSE(res);
  11549. }
  11550. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11551. Server svr;
  11552. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11553. res.set_chunked_content_provider(
  11554. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11555. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11556. sink.os << "hello";
  11557. EXPECT_TRUE(sink.os.good());
  11558. // Wait for the client to close the connection
  11559. auto count = 10;
  11560. while (count > 0 && sink.is_writable()) {
  11561. this_thread::sleep_for(chrono::milliseconds(10));
  11562. count--;
  11563. }
  11564. // After client disconnect, write repeatedly until the socket
  11565. // write actually fails (small writes may be absorbed by the
  11566. // kernel buffer)
  11567. std::string chunk(1024, 'x');
  11568. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11569. sink.os << chunk;
  11570. }
  11571. EXPECT_TRUE(sink.os.fail());
  11572. return true;
  11573. });
  11574. });
  11575. auto port = svr.bind_to_any_port("localhost");
  11576. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11577. auto se = detail::scope_exit([&] {
  11578. svr.stop();
  11579. listen_thread.join();
  11580. ASSERT_FALSE(svr.is_running());
  11581. });
  11582. svr.wait_until_ready();
  11583. Client cli("localhost", port);
  11584. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11585. EXPECT_EQ("hello", string(data, data_length));
  11586. return false; // close the socket immediately.
  11587. });
  11588. ASSERT_FALSE(res);
  11589. }
  11590. TEST(GetWithParametersTest, GetWithParameters) {
  11591. Server svr;
  11592. svr.Get("/", [&](const Request &req, Response &) {
  11593. EXPECT_EQ("world", req.get_param_value("hello"));
  11594. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11595. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11596. });
  11597. svr.Get("/params", [&](const Request &req, Response &) {
  11598. EXPECT_EQ("world", req.get_param_value("hello"));
  11599. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11600. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11601. });
  11602. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11603. EXPECT_EQ("resource-id", req.matches[1]);
  11604. EXPECT_EQ("foo", req.get_param_value("param1"));
  11605. EXPECT_EQ("bar", req.get_param_value("param2"));
  11606. });
  11607. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11608. EXPECT_EQ("user-id", req.path_params.at("id"));
  11609. EXPECT_EQ("foo", req.get_param_value("param1"));
  11610. EXPECT_EQ("bar", req.get_param_value("param2"));
  11611. });
  11612. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11613. auto se = detail::scope_exit([&] {
  11614. svr.stop();
  11615. listen_thread.join();
  11616. ASSERT_FALSE(svr.is_running());
  11617. });
  11618. svr.wait_until_ready();
  11619. {
  11620. Client cli(HOST, PORT);
  11621. Params params;
  11622. params.emplace("hello", "world");
  11623. params.emplace("hello2", "world2");
  11624. params.emplace("hello3", "world3");
  11625. auto res = cli.Get("/", params, Headers{});
  11626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11627. EXPECT_EQ(StatusCode::OK_200, res->status);
  11628. }
  11629. {
  11630. Client cli(HOST, PORT);
  11631. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11633. EXPECT_EQ(StatusCode::OK_200, res->status);
  11634. }
  11635. {
  11636. Client cli(HOST, PORT);
  11637. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11639. EXPECT_EQ(StatusCode::OK_200, res->status);
  11640. }
  11641. {
  11642. Client cli(HOST, PORT);
  11643. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11645. EXPECT_EQ(StatusCode::OK_200, res->status);
  11646. }
  11647. }
  11648. TEST(GetWithParametersTest, GetWithParameters2) {
  11649. Server svr;
  11650. svr.Get("/", [&](const Request &req, Response &res) {
  11651. auto text = req.get_param_value("hello");
  11652. res.set_content(text, "text/plain");
  11653. });
  11654. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11655. auto se = detail::scope_exit([&] {
  11656. svr.stop();
  11657. listen_thread.join();
  11658. ASSERT_FALSE(svr.is_running());
  11659. });
  11660. svr.wait_until_ready();
  11661. Client cli("localhost", PORT);
  11662. Params params;
  11663. params.emplace("hello", "world");
  11664. std::string body;
  11665. auto res = cli.Get("/", params, Headers{},
  11666. [&](const char *data, size_t data_length) {
  11667. body.append(data, data_length);
  11668. return true;
  11669. });
  11670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11671. EXPECT_EQ(StatusCode::OK_200, res->status);
  11672. EXPECT_EQ("world", body);
  11673. }
  11674. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11675. Server svr;
  11676. svr.Get("/search", [&](const Request &req, Response &res) {
  11677. auto q = req.get_param_value("q");
  11678. res.set_content(q, "text/plain");
  11679. });
  11680. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11681. auto se = detail::scope_exit([&] {
  11682. svr.stop();
  11683. listen_thread.join();
  11684. ASSERT_FALSE(svr.is_running());
  11685. });
  11686. svr.wait_until_ready();
  11687. Client cli("localhost", PORT);
  11688. // Verify that Get(path, params) works without requiring Headers argument
  11689. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11691. EXPECT_EQ(StatusCode::OK_200, res->status);
  11692. EXPECT_EQ("cpp-httplib", res->body);
  11693. }
  11694. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11695. auto host = "httpbingo.org";
  11696. auto path = std::string{"/range/32"};
  11697. #ifdef CPPHTTPLIB_SSL_ENABLED
  11698. SSLClient cli(host);
  11699. #else
  11700. Client cli(host);
  11701. #endif
  11702. cli.set_default_headers({make_range_header({{1, 10}})});
  11703. cli.set_connection_timeout(5);
  11704. {
  11705. auto res = cli.Get(path);
  11706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11707. EXPECT_EQ("bcdefghijk", res->body);
  11708. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11709. }
  11710. {
  11711. auto res = cli.Get(path);
  11712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11713. EXPECT_EQ("bcdefghijk", res->body);
  11714. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11715. }
  11716. }
  11717. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11718. Server svr;
  11719. svr.set_default_headers({{"Hello", "World"}});
  11720. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11721. res.set_content("ok", "text/plain");
  11722. });
  11723. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11724. auto se = detail::scope_exit([&] {
  11725. svr.stop();
  11726. listen_thread.join();
  11727. ASSERT_FALSE(svr.is_running());
  11728. });
  11729. svr.wait_until_ready();
  11730. Client cli("localhost", PORT);
  11731. auto res = cli.Get("/");
  11732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11733. EXPECT_EQ(StatusCode::OK_200, res->status);
  11734. EXPECT_EQ("ok", res->body);
  11735. EXPECT_EQ("World", res->get_header_value("Hello"));
  11736. }
  11737. #ifdef CPPHTTPLIB_SSL_ENABLED
  11738. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11739. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11740. ASSERT_TRUE(svr.is_valid());
  11741. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11742. std::this_thread::sleep_for(std::chrono::seconds(2));
  11743. res.set_content("a", "text/plain");
  11744. });
  11745. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11746. res.set_content("b", "text/plain");
  11747. });
  11748. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11749. auto se = detail::scope_exit([&] {
  11750. svr.stop();
  11751. listen_thread.join();
  11752. ASSERT_FALSE(svr.is_running());
  11753. });
  11754. svr.wait_until_ready();
  11755. SSLClient cli("localhost", PORT);
  11756. cli.enable_server_certificate_verification(false);
  11757. cli.set_keep_alive(true);
  11758. cli.set_read_timeout(std::chrono::seconds(1));
  11759. auto resa = cli.Get("/a");
  11760. ASSERT_TRUE(!resa);
  11761. EXPECT_EQ(Error::Read, resa.error());
  11762. auto resb = cli.Get("/b");
  11763. ASSERT_TRUE(resb);
  11764. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11765. EXPECT_EQ("b", resb->body);
  11766. }
  11767. // Closing an idle keep-alive connection sends close_notify and returns. The
  11768. // server must not wait for the client's close_notify: an idle client never
  11769. // sends one, so the worker would be held until the read timeout expires, and
  11770. // stop() would wait for it.
  11771. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11772. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11773. ASSERT_TRUE(svr.is_valid());
  11774. svr.set_keep_alive_timeout(1);
  11775. svr.set_read_timeout(10, 0);
  11776. svr.Get("/", [](const Request &, Response &res) {
  11777. res.set_content("ok", "text/plain");
  11778. });
  11779. auto port = svr.bind_to_any_port(HOST);
  11780. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11781. auto se = detail::scope_exit([&] {
  11782. if (listen_thread.joinable()) {
  11783. svr.stop();
  11784. listen_thread.join();
  11785. }
  11786. });
  11787. svr.wait_until_ready();
  11788. SSLClient cli(HOST, port);
  11789. cli.enable_server_certificate_verification(false);
  11790. cli.set_keep_alive(true);
  11791. auto res = cli.Get("/");
  11792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11793. EXPECT_EQ(StatusCode::OK_200, res->status);
  11794. // Stay idle past the keep-alive timeout so the server closes the connection.
  11795. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11796. auto start = std::chrono::steady_clock::now();
  11797. svr.stop();
  11798. listen_thread.join();
  11799. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11800. std::chrono::steady_clock::now() - start)
  11801. .count();
  11802. EXPECT_LT(elapsed, 3000);
  11803. }
  11804. #endif
  11805. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11806. protected:
  11807. ServerTestWithAI_PASSIVE()
  11808. : cli_(HOST, PORT)
  11809. #ifdef CPPHTTPLIB_SSL_ENABLED
  11810. ,
  11811. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11812. #endif
  11813. {
  11814. #ifdef CPPHTTPLIB_SSL_ENABLED
  11815. cli_.enable_server_certificate_verification(false);
  11816. #endif
  11817. }
  11818. virtual void SetUp() {
  11819. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11820. res.set_content("Hello World!", "text/plain");
  11821. });
  11822. t_ = thread(
  11823. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11824. svr_.wait_until_ready();
  11825. }
  11826. virtual void TearDown() {
  11827. svr_.stop();
  11828. t_.join();
  11829. }
  11830. #ifdef CPPHTTPLIB_SSL_ENABLED
  11831. SSLClient cli_;
  11832. SSLServer svr_;
  11833. #else
  11834. Client cli_;
  11835. Server svr_;
  11836. #endif
  11837. thread t_;
  11838. };
  11839. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11840. auto res = cli_.Get("/hi");
  11841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11842. EXPECT_EQ(StatusCode::OK_200, res->status);
  11843. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11844. EXPECT_EQ("Hello World!", res->body);
  11845. }
  11846. class ServerUpDownTest : public ::testing::Test {
  11847. protected:
  11848. ServerUpDownTest() : cli_(HOST, PORT) {}
  11849. virtual void SetUp() {
  11850. t_ = thread([&]() {
  11851. svr_.bind_to_any_port(HOST);
  11852. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11853. ASSERT_TRUE(svr_.listen_after_bind());
  11854. });
  11855. svr_.wait_until_ready();
  11856. }
  11857. virtual void TearDown() {
  11858. svr_.stop();
  11859. t_.join();
  11860. }
  11861. Client cli_;
  11862. Server svr_;
  11863. thread t_;
  11864. };
  11865. TEST_F(ServerUpDownTest, QuickStartStop) {
  11866. // Should not crash, especially when run with
  11867. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11868. }
  11869. class PayloadMaxLengthTest : public ::testing::Test {
  11870. protected:
  11871. PayloadMaxLengthTest()
  11872. : cli_(HOST, PORT)
  11873. #ifdef CPPHTTPLIB_SSL_ENABLED
  11874. ,
  11875. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11876. #endif
  11877. {
  11878. #ifdef CPPHTTPLIB_SSL_ENABLED
  11879. cli_.enable_server_certificate_verification(false);
  11880. #endif
  11881. }
  11882. virtual void SetUp() {
  11883. svr_.set_payload_max_length(8);
  11884. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11885. res.set_content("test", "text/plain");
  11886. });
  11887. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11888. svr_.wait_until_ready();
  11889. }
  11890. virtual void TearDown() {
  11891. svr_.stop();
  11892. t_.join();
  11893. }
  11894. #ifdef CPPHTTPLIB_SSL_ENABLED
  11895. SSLClient cli_;
  11896. SSLServer svr_;
  11897. #else
  11898. Client cli_;
  11899. Server svr_;
  11900. #endif
  11901. thread t_;
  11902. };
  11903. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11904. auto res = cli_.Post("/test", "123456789", "text/plain");
  11905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11906. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11907. res = cli_.Post("/test", "12345678", "text/plain");
  11908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11909. EXPECT_EQ(StatusCode::OK_200, res->status);
  11910. }
  11911. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11912. // Test chunked encoding with payload exceeding the 8-byte limit
  11913. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11914. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11916. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11917. }
  11918. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11919. // Test chunked encoding with payload within the 8-byte limit
  11920. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11921. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11923. EXPECT_EQ(StatusCode::OK_200, res->status);
  11924. }
  11925. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11926. // Test using send_request to send chunked data exceeding payload limit
  11927. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11928. "Host: " +
  11929. std::string(HOST) + ":" + std::to_string(PORT) +
  11930. "\r\n"
  11931. "Transfer-Encoding: chunked\r\n"
  11932. "Connection: close\r\n"
  11933. "\r\n"
  11934. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11935. "0123456789\r\n"
  11936. "0\r\n" // End chunk
  11937. "\r\n";
  11938. std::string response;
  11939. bool result = send_request(1, chunked_request, &response);
  11940. if (!result) {
  11941. // If send_request fails, it might be because the server closed the
  11942. // connection due to payload limit enforcement, which is acceptable
  11943. SUCCEED()
  11944. << "Server rejected oversized chunked request (connection closed)";
  11945. } else {
  11946. // If we got a response, check if it's an error response or connection was
  11947. // closed early Short response length indicates connection was closed due to
  11948. // payload limit
  11949. if (response.length() <= 10) {
  11950. SUCCEED() << "Server closed connection for oversized chunked request";
  11951. } else {
  11952. // Check for error status codes
  11953. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11954. response.find("Payload Too Large") != std::string::npos ||
  11955. response.find("400") != std::string::npos);
  11956. }
  11957. }
  11958. }
  11959. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11960. // Test request without Content-Length header exceeding payload limit
  11961. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11962. "Host: " +
  11963. std::string(HOST) + ":" +
  11964. std::to_string(PORT) +
  11965. "\r\n"
  11966. "Connection: close\r\n"
  11967. "\r\n";
  11968. // Add payload exceeding the 8-byte limit
  11969. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11970. request_without_content_length += large_payload;
  11971. std::string response;
  11972. bool result = send_request(1, request_without_content_length, &response);
  11973. if (!result) {
  11974. // If send_request fails, server likely closed connection due to payload
  11975. // limit
  11976. SUCCEED() << "Server rejected oversized request without Content-Length "
  11977. "(connection closed)";
  11978. } else {
  11979. // Check if server responded with error or closed connection early
  11980. if (response.length() <= 10) {
  11981. SUCCEED() << "Server closed connection for oversized request without "
  11982. "Content-Length";
  11983. } else {
  11984. // Check for error status codes
  11985. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11986. response.find("Payload Too Large") != std::string::npos ||
  11987. response.find("400") != std::string::npos);
  11988. }
  11989. }
  11990. }
  11991. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11992. // Test request without Content-Length header within payload limit
  11993. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11994. "Host: " +
  11995. std::string(HOST) + ":" +
  11996. std::to_string(PORT) +
  11997. "\r\n"
  11998. "Connection: close\r\n"
  11999. "\r\n";
  12000. // Add payload within the 8-byte limit
  12001. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12002. request_without_content_length += small_payload;
  12003. std::string response;
  12004. bool result = send_request(1, request_without_content_length, &response);
  12005. // For requests without Content-Length, the server may have different behavior
  12006. // The key is that it should not reject due to payload limit for small
  12007. // payloads
  12008. if (result) {
  12009. // Check for any HTTP response (success or error, but not connection closed)
  12010. if (response.length() > 10) {
  12011. SUCCEED()
  12012. << "Server processed request without Content-Length within limit";
  12013. } else {
  12014. // Short response might indicate connection closed, which is acceptable
  12015. SUCCEED() << "Server closed connection for request without "
  12016. "Content-Length (acceptable behavior)";
  12017. }
  12018. } else {
  12019. // Connection failure might be due to protocol requirements
  12020. SUCCEED() << "Connection issue with request without Content-Length "
  12021. "(environment-specific)";
  12022. }
  12023. }
  12024. class LargePayloadMaxLengthTest : public ::testing::Test {
  12025. protected:
  12026. LargePayloadMaxLengthTest()
  12027. : cli_(HOST, PORT)
  12028. #ifdef CPPHTTPLIB_SSL_ENABLED
  12029. ,
  12030. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12031. #endif
  12032. {
  12033. #ifdef CPPHTTPLIB_SSL_ENABLED
  12034. cli_.enable_server_certificate_verification(false);
  12035. #endif
  12036. }
  12037. virtual void SetUp() {
  12038. // Set 10MB payload limit
  12039. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12040. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12041. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12042. res.set_content("Large payload test", "text/plain");
  12043. });
  12044. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12045. svr_.wait_until_ready();
  12046. }
  12047. virtual void TearDown() {
  12048. svr_.stop();
  12049. t_.join();
  12050. }
  12051. #ifdef CPPHTTPLIB_SSL_ENABLED
  12052. SSLClient cli_;
  12053. SSLServer svr_;
  12054. #else
  12055. Client cli_;
  12056. Server svr_;
  12057. #endif
  12058. thread t_;
  12059. };
  12060. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12061. // Test chunked encoding with payload within 10MB limit
  12062. std::string medium_payload(5 * 1024 * 1024,
  12063. 'A'); // 5MB payload, within 10MB limit
  12064. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12066. EXPECT_EQ(StatusCode::OK_200, res->status);
  12067. }
  12068. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12069. // Test chunked encoding with payload exceeding 10MB limit
  12070. std::string large_payload(12 * 1024 * 1024,
  12071. 'B'); // 12MB payload, exceeds 10MB limit
  12072. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12073. // Server may either return 413 or close the connection
  12074. if (res) {
  12075. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12076. } else {
  12077. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12078. }
  12079. }
  12080. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12081. // Test request without Content-Length header within 10MB limit
  12082. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12083. "Host: " +
  12084. std::string(HOST) + ":" +
  12085. std::to_string(PORT) +
  12086. "\r\n"
  12087. "Connection: close\r\n"
  12088. "\r\n";
  12089. // Add 1MB payload (within 10MB limit)
  12090. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12091. request_without_content_length += medium_payload;
  12092. std::string response;
  12093. bool result = send_request(5, request_without_content_length, &response);
  12094. if (result) {
  12095. // Should get a proper HTTP response for payloads within limit
  12096. if (response.length() > 10) {
  12097. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12098. "10MB limit";
  12099. } else {
  12100. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12101. "Content-Length)";
  12102. }
  12103. } else {
  12104. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12105. }
  12106. }
  12107. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12108. // Test request without Content-Length header exceeding 10MB limit
  12109. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12110. "Host: " +
  12111. std::string(HOST) + ":" +
  12112. std::to_string(PORT) +
  12113. "\r\n"
  12114. "Connection: close\r\n"
  12115. "\r\n";
  12116. // Add 12MB payload (exceeds 10MB limit)
  12117. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12118. request_without_content_length += large_payload;
  12119. std::string response;
  12120. bool result = send_request(10, request_without_content_length, &response);
  12121. if (!result) {
  12122. // Server should close connection due to payload limit
  12123. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12124. "(connection closed)";
  12125. } else {
  12126. // Check for error response
  12127. if (response.length() <= 10) {
  12128. SUCCEED()
  12129. << "Server closed connection for 12MB request exceeding 10MB limit";
  12130. } else {
  12131. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12132. response.find("Payload Too Large") != std::string::npos ||
  12133. response.find("400") != std::string::npos);
  12134. }
  12135. }
  12136. }
  12137. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12138. Server svr;
  12139. svr.Get("/", [](const Request &, Response &res) {
  12140. // Claims far more than it sends, then drops the connection.
  12141. res.set_content_provider(size_t(1) << 41, "text/plain",
  12142. [](size_t, size_t, DataSink &sink) {
  12143. sink.write("abc", 3);
  12144. return false;
  12145. });
  12146. });
  12147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12148. auto se = detail::scope_exit([&] {
  12149. svr.stop();
  12150. thread.join();
  12151. ASSERT_FALSE(svr.is_running());
  12152. });
  12153. svr.wait_until_ready();
  12154. Client cli(HOST, PORT);
  12155. cli.set_payload_max_length(0);
  12156. EXPECT_FALSE(cli.Get("/"));
  12157. }
  12158. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12159. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12160. // path.
  12161. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12162. Server svr;
  12163. const size_t LIMIT = 64 * 1024; // 64KB
  12164. svr.set_payload_max_length(LIMIT);
  12165. size_t total = 0;
  12166. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12167. const ContentReader &content_reader) {
  12168. content_reader([&](const char * /*data*/, size_t len) {
  12169. total += len;
  12170. return true;
  12171. });
  12172. res.status = 200;
  12173. res.set_content("stream_ok", "text/plain");
  12174. });
  12175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12176. auto se = detail::scope_exit([&] {
  12177. svr.stop();
  12178. thread.join();
  12179. ASSERT_FALSE(svr.is_running());
  12180. });
  12181. svr.wait_until_ready();
  12182. // Prepare 256KB raw data and gzip-compress it
  12183. std::string raw(256 * 1024, 'A');
  12184. std::string gz;
  12185. {
  12186. z_stream zs{};
  12187. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12188. Z_DEFAULT_STRATEGY);
  12189. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12190. zs.avail_in = static_cast<uInt>(raw.size());
  12191. char outbuf[4096];
  12192. int ret;
  12193. do {
  12194. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12195. zs.avail_out = sizeof(outbuf);
  12196. ret = deflate(&zs, Z_FINISH);
  12197. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12198. } while (ret != Z_STREAM_END);
  12199. deflateEnd(&zs);
  12200. }
  12201. Client cli(HOST, PORT);
  12202. cli.set_connection_timeout(std::chrono::seconds(5));
  12203. Headers headers = {{"Content-Encoding", "gzip"}};
  12204. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12205. "application/octet-stream");
  12206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12207. // Server must reject oversized decompressed payloads with 413.
  12208. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12209. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12210. EXPECT_LE(total, LIMIT);
  12211. }
  12212. #ifndef CPPHTTPLIB_SSL_ENABLED
  12213. // For a request with neither Content-Length nor Transfer-Encoding, the
  12214. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12215. // compressed wire bytes straight to the ContentReader without ever routing
  12216. // them through the decompressor, so payload_max_length_ only bounded the
  12217. // compressed size on the wire, not the decompressed size.
  12218. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12219. Server svr;
  12220. const size_t LIMIT = 64 * 1024; // 64KB
  12221. svr.set_payload_max_length(LIMIT);
  12222. size_t total = 0;
  12223. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12224. const ContentReader &content_reader) {
  12225. content_reader([&](const char * /*data*/, size_t len) {
  12226. total += len;
  12227. return true;
  12228. });
  12229. res.status = 200;
  12230. res.set_content("stream_ok", "text/plain");
  12231. });
  12232. auto port = svr.bind_to_any_port(HOST);
  12233. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12234. auto se = detail::scope_exit([&] {
  12235. svr.stop();
  12236. thread.join();
  12237. ASSERT_FALSE(svr.is_running());
  12238. });
  12239. svr.wait_until_ready();
  12240. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12241. // StreamingGzipDecompression test above.
  12242. std::string raw(256 * 1024, 'A');
  12243. std::string gz;
  12244. {
  12245. httplib::detail::gzip_compressor compressor;
  12246. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12247. [&](const char *chunk, size_t len) {
  12248. gz.append(chunk, len);
  12249. return true;
  12250. });
  12251. ASSERT_TRUE(result);
  12252. }
  12253. // Send the gzip body over raw TCP with neither Content-Length nor
  12254. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12255. // kicks in.
  12256. std::string req = "POST /stream HTTP/1.1\r\n"
  12257. "Host: " +
  12258. std::string(HOST) + ":" + std::to_string(port) +
  12259. "\r\n"
  12260. "Content-Encoding: gzip\r\n"
  12261. "Connection: close\r\n"
  12262. "\r\n" +
  12263. gz;
  12264. std::string response;
  12265. ASSERT_TRUE(send_request(5, req, &response, port));
  12266. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12267. EXPECT_LE(total, LIMIT);
  12268. }
  12269. #endif
  12270. #endif
  12271. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12272. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12273. // the payload must be passed through untouched instead of being rejected.
  12274. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12275. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12276. Server svr;
  12277. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12278. res.set_content(body, "image/jpeg");
  12279. res.set_header("Content-Encoding", "UTF-8");
  12280. });
  12281. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12282. res.set_content(body, "image/jpeg");
  12283. res.set_header("Content-Encoding", "identity");
  12284. });
  12285. svr.Post("/echo", [](const Request &req, Response &res) {
  12286. res.set_content(req.body, "image/jpeg");
  12287. });
  12288. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12289. auto se = detail::scope_exit([&] {
  12290. svr.stop();
  12291. t.join();
  12292. ASSERT_FALSE(svr.is_running());
  12293. });
  12294. svr.wait_until_ready();
  12295. Client cli(HOST, PORT);
  12296. {
  12297. auto res = cli.Get("/image");
  12298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12299. EXPECT_EQ(StatusCode::OK_200, res->status);
  12300. EXPECT_EQ(body, res->body);
  12301. }
  12302. {
  12303. auto res = cli.Get("/identity");
  12304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12305. EXPECT_EQ(StatusCode::OK_200, res->status);
  12306. EXPECT_EQ(body, res->body);
  12307. }
  12308. {
  12309. // The same applies to a request body reaching the server.
  12310. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12311. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12313. EXPECT_EQ(StatusCode::OK_200, res->status);
  12314. EXPECT_EQ(body, res->body);
  12315. }
  12316. }
  12317. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12318. // gzip-encoded response even when the build has no zlib support.
  12319. static const char GZIPPED_HELLO_WORLD[] = {
  12320. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12321. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12322. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12323. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12324. // A content coding is a whole token, not something the field value merely
  12325. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12326. // as "fibre" look like Brotli, and turned a multi-coding value like
  12327. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12328. // it was never meant to see.
  12329. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12330. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12331. Server svr;
  12332. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12333. res.set_content(body, "image/jpeg");
  12334. res.set_header("Content-Encoding", "fibre");
  12335. });
  12336. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12337. res.set_content(body, "image/jpeg");
  12338. res.set_header("Content-Encoding", "gzip, br");
  12339. });
  12340. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12341. res.set_content(body, "image/jpeg");
  12342. res.set_header("Content-Encoding", "x-zstd-ish");
  12343. });
  12344. auto port = svr.bind_to_any_port(HOST);
  12345. thread t = thread([&]() { svr.listen_after_bind(); });
  12346. auto se = detail::scope_exit([&] {
  12347. svr.stop();
  12348. t.join();
  12349. ASSERT_FALSE(svr.is_running());
  12350. });
  12351. svr.wait_until_ready();
  12352. Client cli(HOST, port);
  12353. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12354. auto res = cli.Get(path);
  12355. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12356. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12357. // Not a coding we recognize, so the payload comes back untouched
  12358. EXPECT_EQ(body, res->body) << path;
  12359. }
  12360. }
  12361. // A content coding cpp-httplib recognizes but was not built with must be
  12362. // reported as such. Handing the still-compressed payload back to the caller
  12363. // would silently corrupt it.
  12364. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12365. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12366. Server svr;
  12367. // "image/jpeg" keeps the server from applying a content coding of its own,
  12368. // so the hand-crafted Content-Encoding below survives.
  12369. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12370. res.set_content(gzipped, "image/jpeg");
  12371. res.set_header("Content-Encoding", "gzip");
  12372. });
  12373. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12374. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12375. res.set_content(gzipped, "image/jpeg");
  12376. res.set_header("Content-Encoding", "GZIP");
  12377. });
  12378. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12379. auto se = detail::scope_exit([&] {
  12380. svr.stop();
  12381. t.join();
  12382. ASSERT_FALSE(svr.is_running());
  12383. });
  12384. svr.wait_until_ready();
  12385. Client cli(HOST, PORT);
  12386. {
  12387. auto res = cli.Get("/gzipped");
  12388. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12390. EXPECT_EQ("Hello World!", res->body);
  12391. #else
  12392. ASSERT_FALSE(res);
  12393. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12394. #endif
  12395. }
  12396. {
  12397. // open_stream() must behave the same way.
  12398. auto handle = cli.open_stream("GET", "/gzipped");
  12399. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12400. ASSERT_TRUE(handle.is_valid());
  12401. std::string received;
  12402. char buf[256];
  12403. ssize_t n;
  12404. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12405. received.append(buf, static_cast<size_t>(n));
  12406. }
  12407. EXPECT_EQ("Hello World!", received);
  12408. #else
  12409. EXPECT_FALSE(handle.is_valid());
  12410. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12411. #endif
  12412. }
  12413. {
  12414. // A differently-cased coding must not be mistaken for an unknown one, or
  12415. // the body would be handed back still compressed.
  12416. auto res = cli.Get("/gzipped-uppercase");
  12417. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12419. EXPECT_EQ("Hello World!", res->body);
  12420. #else
  12421. ASSERT_FALSE(res);
  12422. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12423. #endif
  12424. }
  12425. }
  12426. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12427. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12428. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12429. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12430. // body a second time and appending a second Content-Encoding field line, so
  12431. // clients that decode one coding per listed value handed back raw gzip bytes.
  12432. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12433. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12434. Server svr;
  12435. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12436. // keeps the server from applying a coding of its own.
  12437. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12438. res.set_content(gzipped, "text/plain");
  12439. res.set_header("Content-Encoding", "gzip");
  12440. });
  12441. auto port = svr.bind_to_any_port(HOST);
  12442. thread t = thread([&]() { svr.listen_after_bind(); });
  12443. auto se = detail::scope_exit([&] {
  12444. svr.stop();
  12445. t.join();
  12446. ASSERT_FALSE(svr.is_running());
  12447. });
  12448. svr.wait_until_ready();
  12449. Client cli(HOST, port);
  12450. Headers headers = {{"Accept-Encoding", "gzip"}};
  12451. auto res = cli.Get("/pre-gzipped", headers);
  12452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12453. EXPECT_EQ(StatusCode::OK_200, res->status);
  12454. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12455. EXPECT_EQ("Hello World!", res->body);
  12456. }
  12457. // A chunked provider settles its coding where the headers are written and
  12458. // reuses it at write time. Both ends of that have to hold: a handler's own
  12459. // Content-Encoding suppresses the coding, and a response without one is still
  12460. // compressed as it always was.
  12461. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12462. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12463. const std::string plain = "Hello World! Hello World! Hello World!";
  12464. Server svr;
  12465. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12466. res.set_header("Content-Encoding", "gzip");
  12467. res.set_chunked_content_provider(
  12468. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12469. sink.write(gzipped.data(), gzipped.size());
  12470. sink.done();
  12471. return true;
  12472. });
  12473. });
  12474. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12475. res.set_chunked_content_provider(
  12476. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12477. sink.write(plain.data(), plain.size());
  12478. sink.done();
  12479. return true;
  12480. });
  12481. });
  12482. auto port = svr.bind_to_any_port(HOST);
  12483. thread t = thread([&]() { svr.listen_after_bind(); });
  12484. auto se = detail::scope_exit([&] {
  12485. svr.stop();
  12486. t.join();
  12487. ASSERT_FALSE(svr.is_running());
  12488. });
  12489. svr.wait_until_ready();
  12490. Client cli(HOST, port);
  12491. Headers headers = {{"Accept-Encoding", "gzip"}};
  12492. {
  12493. auto res = cli.Get("/pre-gzipped", headers);
  12494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12495. EXPECT_EQ(StatusCode::OK_200, res->status);
  12496. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12497. EXPECT_EQ("Hello World!", res->body);
  12498. }
  12499. {
  12500. auto res = cli.Get("/negotiated", headers);
  12501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12502. EXPECT_EQ(StatusCode::OK_200, res->status);
  12503. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12504. EXPECT_EQ(plain, res->body);
  12505. }
  12506. }
  12507. #endif
  12508. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12509. // the same message as the comma-joined one, so both have to be read the same
  12510. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12511. // single gzip coding, and a body the sender says was encoded twice was handed
  12512. // back after one pass, still compressed but presented as decoded.
  12513. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12514. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12515. Server svr;
  12516. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12517. res.set_content(body, "image/jpeg");
  12518. res.headers.emplace("Content-Encoding", "gzip");
  12519. res.headers.emplace("Content-Encoding", "gzip");
  12520. });
  12521. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12522. res.set_content(body, "image/jpeg");
  12523. res.set_header("Content-Encoding", "gzip, gzip");
  12524. });
  12525. auto port = svr.bind_to_any_port(HOST);
  12526. thread t = thread([&]() { svr.listen_after_bind(); });
  12527. auto se = detail::scope_exit([&] {
  12528. svr.stop();
  12529. t.join();
  12530. ASSERT_FALSE(svr.is_running());
  12531. });
  12532. svr.wait_until_ready();
  12533. Client cli(HOST, port);
  12534. // Two codings is not something cpp-httplib decodes, so both representations
  12535. // take the pass-through path rather than one of them being gunzipped once.
  12536. for (const char *path : {"/split", "/joined"}) {
  12537. auto res = cli.Get(path);
  12538. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12539. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12540. EXPECT_EQ(body, res->body) << path;
  12541. }
  12542. }
  12543. // Regression test for DoS vulnerability: a malicious server sending a response
  12544. // without Content-Length header must not cause unbounded memory consumption on
  12545. // the client side. The client should stop reading after a reasonable limit,
  12546. // similar to the server-side set_payload_max_length protection.
  12547. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12548. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12549. #ifndef _WIN32
  12550. signal(SIGPIPE, SIG_IGN);
  12551. #endif
  12552. auto server_thread = std::thread([] {
  12553. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12554. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12555. default_socket_options(srv);
  12556. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12557. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12558. sockaddr_in addr{};
  12559. addr.sin_family = AF_INET;
  12560. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12561. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12562. int opt = 1;
  12563. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12564. #ifdef _WIN32
  12565. reinterpret_cast<const char *>(&opt),
  12566. #else
  12567. &opt,
  12568. #endif
  12569. sizeof(opt));
  12570. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12571. ::listen(srv, 1);
  12572. sockaddr_in cli_addr{};
  12573. socklen_t cli_len = sizeof(cli_addr);
  12574. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12575. if (cli != INVALID_SOCKET) {
  12576. char buf[4096];
  12577. ::recv(cli, buf, sizeof(buf), 0);
  12578. // Malicious response: no Content-Length, no chunked encoding
  12579. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12580. "Connection: close\r\n"
  12581. "\r\n";
  12582. ::send(cli,
  12583. #ifdef _WIN32
  12584. static_cast<const char *>(response_header.c_str()),
  12585. static_cast<int>(response_header.size()),
  12586. #else
  12587. response_header.c_str(), response_header.size(),
  12588. #endif
  12589. 0);
  12590. // Send 10MB of data
  12591. std::string chunk(64 * 1024, 'A');
  12592. size_t total_sent = 0;
  12593. while (total_sent < MALICIOUS_DATA_SIZE) {
  12594. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12595. auto sent = ::send(cli,
  12596. #ifdef _WIN32
  12597. static_cast<const char *>(chunk.c_str()),
  12598. static_cast<int>(to_send),
  12599. #else
  12600. chunk.c_str(), to_send,
  12601. #endif
  12602. 0);
  12603. if (sent <= 0) break;
  12604. total_sent += static_cast<size_t>(sent);
  12605. }
  12606. detail::close_socket(cli);
  12607. }
  12608. detail::close_socket(srv);
  12609. });
  12610. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12611. size_t total_read = 0;
  12612. {
  12613. Client cli("127.0.0.1", PORT + 2);
  12614. cli.set_read_timeout(5, 0);
  12615. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12616. auto stream = cli.open_stream("GET", "/malicious");
  12617. ASSERT_TRUE(stream.is_valid());
  12618. char buffer[64 * 1024];
  12619. ssize_t n;
  12620. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12621. total_read += static_cast<size_t>(n);
  12622. }
  12623. } // StreamHandle and Client destroyed here, closing the socket
  12624. server_thread.join();
  12625. // With set_payload_max_length, the client must stop reading before consuming
  12626. // all 10MB. The read loop should be cut off at or near the configured limit.
  12627. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12628. << "Client read " << total_read << " bytes, exceeding the configured "
  12629. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12630. }
  12631. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12632. // the entire response body without truncation.
  12633. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12634. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12635. #ifndef _WIN32
  12636. signal(SIGPIPE, SIG_IGN);
  12637. #endif
  12638. auto server_thread = std::thread([] {
  12639. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12640. default_socket_options(srv);
  12641. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12642. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12643. sockaddr_in addr{};
  12644. addr.sin_family = AF_INET;
  12645. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12646. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12647. int opt = 1;
  12648. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12649. #ifdef _WIN32
  12650. reinterpret_cast<const char *>(&opt),
  12651. #else
  12652. &opt,
  12653. #endif
  12654. sizeof(opt));
  12655. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12656. ::listen(srv, 1);
  12657. sockaddr_in cli_addr{};
  12658. socklen_t cli_len = sizeof(cli_addr);
  12659. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12660. if (cli != INVALID_SOCKET) {
  12661. char buf[4096];
  12662. ::recv(cli, buf, sizeof(buf), 0);
  12663. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12664. "Connection: close\r\n"
  12665. "\r\n";
  12666. ::send(cli,
  12667. #ifdef _WIN32
  12668. static_cast<const char *>(response_header.c_str()),
  12669. static_cast<int>(response_header.size()),
  12670. #else
  12671. response_header.c_str(), response_header.size(),
  12672. #endif
  12673. 0);
  12674. std::string chunk(64 * 1024, 'A');
  12675. size_t total_sent = 0;
  12676. while (total_sent < DATA_SIZE) {
  12677. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12678. auto sent = ::send(cli,
  12679. #ifdef _WIN32
  12680. static_cast<const char *>(chunk.c_str()),
  12681. static_cast<int>(to_send),
  12682. #else
  12683. chunk.c_str(), to_send,
  12684. #endif
  12685. 0);
  12686. if (sent <= 0) break;
  12687. total_sent += static_cast<size_t>(sent);
  12688. }
  12689. #ifdef _WIN32
  12690. ::shutdown(cli, SD_SEND);
  12691. #else
  12692. ::shutdown(cli, SHUT_WR);
  12693. #endif
  12694. // Drain until the client closes its end, ensuring all data is delivered
  12695. char drain[1024];
  12696. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12697. detail::close_socket(cli);
  12698. }
  12699. detail::close_socket(srv);
  12700. });
  12701. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12702. size_t total_read = 0;
  12703. {
  12704. Client cli("127.0.0.1", PORT + 2);
  12705. cli.set_read_timeout(5, 0);
  12706. cli.set_payload_max_length(0); // 0 means no limit
  12707. auto stream = cli.open_stream("GET", "/data");
  12708. ASSERT_TRUE(stream.is_valid());
  12709. char buffer[64 * 1024];
  12710. ssize_t n;
  12711. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12712. total_read += static_cast<size_t>(n);
  12713. }
  12714. }
  12715. server_thread.join();
  12716. EXPECT_EQ(total_read, DATA_SIZE)
  12717. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12718. << " bytes without truncation, but only read " << total_read << " bytes.";
  12719. }
  12720. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12721. // enormous Content-Length must not cause the client to pre-allocate a huge
  12722. // response body buffer. The reservation is capped at payload_max_length_, and
  12723. // the read itself fails when the body exceeds the limit.
  12724. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12725. #ifndef _WIN32
  12726. signal(SIGPIPE, SIG_IGN);
  12727. #endif
  12728. auto server_thread = std::thread([] {
  12729. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12730. default_socket_options(srv);
  12731. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12732. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12733. sockaddr_in addr{};
  12734. addr.sin_family = AF_INET;
  12735. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12736. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12737. int opt = 1;
  12738. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12739. #ifdef _WIN32
  12740. reinterpret_cast<const char *>(&opt),
  12741. #else
  12742. &opt,
  12743. #endif
  12744. sizeof(opt));
  12745. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12746. ::listen(srv, 1);
  12747. sockaddr_in cli_addr{};
  12748. socklen_t cli_len = sizeof(cli_addr);
  12749. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12750. if (cli != INVALID_SOCKET) {
  12751. char buf[4096];
  12752. ::recv(cli, buf, sizeof(buf), 0);
  12753. // Malicious response: claim a 20GB body but send only a tiny payload.
  12754. std::string response = "HTTP/1.1 200 OK\r\n"
  12755. "Content-Length: 20000000000\r\n"
  12756. "\r\n"
  12757. "abc";
  12758. ::send(cli,
  12759. #ifdef _WIN32
  12760. static_cast<const char *>(response.c_str()),
  12761. static_cast<int>(response.size()),
  12762. #else
  12763. response.c_str(), response.size(),
  12764. #endif
  12765. 0);
  12766. detail::close_socket(cli);
  12767. }
  12768. detail::close_socket(srv);
  12769. });
  12770. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12771. {
  12772. Client cli("127.0.0.1", PORT + 2);
  12773. cli.set_read_timeout(5, 0);
  12774. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12775. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12776. // (server claims more bytes than payload_max_length permits), but it must
  12777. // not exhaust memory before getting there.
  12778. auto res = cli.Get("/malicious");
  12779. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12780. }
  12781. server_thread.join();
  12782. }
  12783. // Verify that content_receiver bypasses the default payload_max_length,
  12784. // allowing streaming downloads larger than 100MB without requiring an explicit
  12785. // set_payload_max_length call.
  12786. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12787. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12788. #ifndef _WIN32
  12789. signal(SIGPIPE, SIG_IGN);
  12790. #endif
  12791. auto server_thread = std::thread([] {
  12792. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12793. default_socket_options(srv);
  12794. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12795. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12796. sockaddr_in addr{};
  12797. addr.sin_family = AF_INET;
  12798. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12799. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12800. int opt = 1;
  12801. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12802. #ifdef _WIN32
  12803. reinterpret_cast<const char *>(&opt),
  12804. #else
  12805. &opt,
  12806. #endif
  12807. sizeof(opt));
  12808. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12809. ::listen(srv, 1);
  12810. sockaddr_in cli_addr{};
  12811. socklen_t cli_len = sizeof(cli_addr);
  12812. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12813. if (cli != INVALID_SOCKET) {
  12814. char buf[4096];
  12815. ::recv(cli, buf, sizeof(buf), 0);
  12816. // Response with Content-Length larger than default 100MB limit
  12817. auto content_length = std::to_string(DATA_SIZE);
  12818. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12819. "Content-Length: " +
  12820. content_length +
  12821. "\r\n"
  12822. "Connection: close\r\n"
  12823. "\r\n";
  12824. ::send(cli,
  12825. #ifdef _WIN32
  12826. static_cast<const char *>(response_header.c_str()),
  12827. static_cast<int>(response_header.size()),
  12828. #else
  12829. response_header.c_str(), response_header.size(),
  12830. #endif
  12831. 0);
  12832. std::string chunk(64 * 1024, 'A');
  12833. size_t total_sent = 0;
  12834. while (total_sent < DATA_SIZE) {
  12835. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12836. auto sent = ::send(cli,
  12837. #ifdef _WIN32
  12838. static_cast<const char *>(chunk.c_str()),
  12839. static_cast<int>(to_send),
  12840. #else
  12841. chunk.c_str(), to_send,
  12842. #endif
  12843. 0);
  12844. if (sent <= 0) break;
  12845. total_sent += static_cast<size_t>(sent);
  12846. }
  12847. detail::close_socket(cli);
  12848. }
  12849. detail::close_socket(srv);
  12850. });
  12851. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12852. size_t total_received = 0;
  12853. {
  12854. Client cli("127.0.0.1", PORT + 2);
  12855. cli.set_read_timeout(10, 0);
  12856. // Do NOT call set_payload_max_length — use the default 100MB limit
  12857. auto res =
  12858. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12859. total_received += data_length;
  12860. return true;
  12861. });
  12862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12863. EXPECT_EQ(StatusCode::OK_200, res->status);
  12864. }
  12865. server_thread.join();
  12866. EXPECT_EQ(total_received, DATA_SIZE)
  12867. << "With content_receiver, the client should read all " << DATA_SIZE
  12868. << " bytes despite the default 100MB payload_max_length, but only read "
  12869. << total_received << " bytes.";
  12870. }
  12871. // Verify that an explicit set_payload_max_length smaller than the response is
  12872. // enforced even when a content_receiver is used.
  12873. TEST(ClientVulnerabilityTest,
  12874. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12875. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12876. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12877. #ifndef _WIN32
  12878. signal(SIGPIPE, SIG_IGN);
  12879. #endif
  12880. auto server_thread = std::thread([] {
  12881. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12882. default_socket_options(srv);
  12883. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12884. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12885. sockaddr_in addr{};
  12886. addr.sin_family = AF_INET;
  12887. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12888. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12889. int opt = 1;
  12890. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12891. #ifdef _WIN32
  12892. reinterpret_cast<const char *>(&opt),
  12893. #else
  12894. &opt,
  12895. #endif
  12896. sizeof(opt));
  12897. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12898. ::listen(srv, 1);
  12899. sockaddr_in cli_addr{};
  12900. socklen_t cli_len = sizeof(cli_addr);
  12901. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12902. if (cli != INVALID_SOCKET) {
  12903. char buf[4096];
  12904. ::recv(cli, buf, sizeof(buf), 0);
  12905. auto content_length = std::to_string(DATA_SIZE);
  12906. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12907. "Content-Length: " +
  12908. content_length +
  12909. "\r\n"
  12910. "Connection: close\r\n"
  12911. "\r\n";
  12912. ::send(cli,
  12913. #ifdef _WIN32
  12914. static_cast<const char *>(response_header.c_str()),
  12915. static_cast<int>(response_header.size()),
  12916. #else
  12917. response_header.c_str(), response_header.size(),
  12918. #endif
  12919. 0);
  12920. std::string chunk(64 * 1024, 'A');
  12921. size_t total_sent = 0;
  12922. while (total_sent < DATA_SIZE) {
  12923. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12924. auto sent = ::send(cli,
  12925. #ifdef _WIN32
  12926. static_cast<const char *>(chunk.c_str()),
  12927. static_cast<int>(to_send),
  12928. #else
  12929. chunk.c_str(), to_send,
  12930. #endif
  12931. 0);
  12932. if (sent <= 0) break;
  12933. total_sent += static_cast<size_t>(sent);
  12934. }
  12935. detail::close_socket(cli);
  12936. }
  12937. detail::close_socket(srv);
  12938. });
  12939. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12940. size_t total_received = 0;
  12941. {
  12942. Client cli("127.0.0.1", PORT + 2);
  12943. cli.set_read_timeout(10, 0);
  12944. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12945. auto res =
  12946. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12947. total_received += data_length;
  12948. return true;
  12949. });
  12950. // Should fail because 200MB exceeds the explicit 150MB limit
  12951. EXPECT_FALSE(res);
  12952. }
  12953. server_thread.join();
  12954. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12955. << "Client with content_receiver should respect the explicit "
  12956. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12957. << total_received << " bytes.";
  12958. }
  12959. // Verify that an explicit set_payload_max_length larger than the response
  12960. // allows the content_receiver to read all data successfully.
  12961. TEST(ClientVulnerabilityTest,
  12962. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12963. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12964. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12965. #ifndef _WIN32
  12966. signal(SIGPIPE, SIG_IGN);
  12967. #endif
  12968. auto server_thread = std::thread([] {
  12969. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12970. default_socket_options(srv);
  12971. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12972. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12973. sockaddr_in addr{};
  12974. addr.sin_family = AF_INET;
  12975. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12976. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12977. int opt = 1;
  12978. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12979. #ifdef _WIN32
  12980. reinterpret_cast<const char *>(&opt),
  12981. #else
  12982. &opt,
  12983. #endif
  12984. sizeof(opt));
  12985. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12986. ::listen(srv, 1);
  12987. sockaddr_in cli_addr{};
  12988. socklen_t cli_len = sizeof(cli_addr);
  12989. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12990. if (cli != INVALID_SOCKET) {
  12991. char buf[4096];
  12992. ::recv(cli, buf, sizeof(buf), 0);
  12993. auto content_length = std::to_string(DATA_SIZE);
  12994. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12995. "Content-Length: " +
  12996. content_length +
  12997. "\r\n"
  12998. "Connection: close\r\n"
  12999. "\r\n";
  13000. ::send(cli,
  13001. #ifdef _WIN32
  13002. static_cast<const char *>(response_header.c_str()),
  13003. static_cast<int>(response_header.size()),
  13004. #else
  13005. response_header.c_str(), response_header.size(),
  13006. #endif
  13007. 0);
  13008. std::string chunk(64 * 1024, 'A');
  13009. size_t total_sent = 0;
  13010. while (total_sent < DATA_SIZE) {
  13011. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13012. auto sent = ::send(cli,
  13013. #ifdef _WIN32
  13014. static_cast<const char *>(chunk.c_str()),
  13015. static_cast<int>(to_send),
  13016. #else
  13017. chunk.c_str(), to_send,
  13018. #endif
  13019. 0);
  13020. if (sent <= 0) break;
  13021. total_sent += static_cast<size_t>(sent);
  13022. }
  13023. #ifdef _WIN32
  13024. ::shutdown(cli, SD_SEND);
  13025. #else
  13026. ::shutdown(cli, SHUT_WR);
  13027. #endif
  13028. char drain[1024];
  13029. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13030. detail::close_socket(cli);
  13031. }
  13032. detail::close_socket(srv);
  13033. });
  13034. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13035. size_t total_received = 0;
  13036. {
  13037. Client cli("127.0.0.1", PORT + 2);
  13038. cli.set_read_timeout(10, 0);
  13039. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13040. auto res =
  13041. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13042. total_received += data_length;
  13043. return true;
  13044. });
  13045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13046. EXPECT_EQ(StatusCode::OK_200, res->status);
  13047. }
  13048. server_thread.join();
  13049. EXPECT_EQ(total_received, DATA_SIZE)
  13050. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13051. << " bytes (larger than " << DATA_SIZE
  13052. << " bytes response), content_receiver should read all data, but only "
  13053. "read "
  13054. << total_received << " bytes.";
  13055. }
  13056. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13057. // Regression test for "zip bomb" attack on the client side: a malicious server
  13058. // sends a small gzip-compressed response that decompresses to a huge payload.
  13059. // The client must enforce payload_max_length on the decompressed size.
  13060. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13061. constexpr size_t DECOMPRESSED_SIZE =
  13062. 10 * 1024 * 1024; // 10MB after decompression
  13063. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13064. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13065. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13066. std::string compressed;
  13067. {
  13068. httplib::detail::gzip_compressor compressor;
  13069. bool ok =
  13070. compressor.compress(uncompressed.data(), uncompressed.size(),
  13071. /*last=*/true, [&](const char *buf, size_t len) {
  13072. compressed.append(buf, len);
  13073. return true;
  13074. });
  13075. ASSERT_TRUE(ok);
  13076. }
  13077. // Sanity: compressed data should be much smaller than the decompressed size
  13078. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13079. #ifndef _WIN32
  13080. signal(SIGPIPE, SIG_IGN);
  13081. #endif
  13082. // Set up the listening socket in the main thread so the server is guaranteed
  13083. // to be ready before the client connects (eliminates race condition).
  13084. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13085. default_socket_options(srv);
  13086. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13087. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13088. sockaddr_in addr{};
  13089. addr.sin_family = AF_INET;
  13090. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13091. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13092. int opt = 1;
  13093. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13094. #ifdef _WIN32
  13095. reinterpret_cast<const char *>(&opt),
  13096. #else
  13097. &opt,
  13098. #endif
  13099. sizeof(opt));
  13100. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13101. ASSERT_EQ(0, ::listen(srv, 1));
  13102. auto server_thread = std::thread([&compressed, srv] {
  13103. sockaddr_in cli_addr{};
  13104. socklen_t cli_len = sizeof(cli_addr);
  13105. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13106. if (cli != INVALID_SOCKET) {
  13107. // Read the full HTTP request (until \r\n\r\n)
  13108. char buf[4096];
  13109. size_t total = 0;
  13110. while (total < sizeof(buf)) {
  13111. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13112. if (n <= 0) break;
  13113. total += static_cast<size_t>(n);
  13114. // Check for end of headers
  13115. if (total >= 4) {
  13116. std::string req(buf, total);
  13117. if (req.find("\r\n\r\n") != std::string::npos) break;
  13118. }
  13119. }
  13120. // Malicious response: gzip-compressed body, no Content-Length
  13121. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13122. "Content-Encoding: gzip\r\n"
  13123. "Connection: close\r\n"
  13124. "\r\n";
  13125. ::send(cli,
  13126. #ifdef _WIN32
  13127. static_cast<const char *>(response_header.c_str()),
  13128. static_cast<int>(response_header.size()),
  13129. #else
  13130. response_header.c_str(), response_header.size(),
  13131. #endif
  13132. 0);
  13133. // Send the compressed payload (small on the wire, huge when decompressed)
  13134. size_t total_sent = 0;
  13135. while (total_sent < compressed.size()) {
  13136. auto to_send = std::min(compressed.size() - total_sent,
  13137. static_cast<size_t>(64 * 1024));
  13138. auto sent =
  13139. ::send(cli,
  13140. #ifdef _WIN32
  13141. static_cast<const char *>(compressed.c_str() + total_sent),
  13142. static_cast<int>(to_send),
  13143. #else
  13144. compressed.c_str() + total_sent, to_send,
  13145. #endif
  13146. 0);
  13147. if (sent <= 0) break;
  13148. total_sent += static_cast<size_t>(sent);
  13149. }
  13150. detail::close_socket(cli);
  13151. }
  13152. });
  13153. auto se = detail::scope_exit([&] {
  13154. detail::close_socket(srv);
  13155. server_thread.join();
  13156. });
  13157. size_t total_decompressed = 0;
  13158. {
  13159. Client cli("127.0.0.1", PORT + 3);
  13160. cli.set_read_timeout(5, 0);
  13161. cli.set_decompress(true);
  13162. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13163. auto stream = cli.open_stream("GET", "/zipbomb");
  13164. ASSERT_TRUE(stream.is_valid());
  13165. char buffer[64 * 1024];
  13166. ssize_t n;
  13167. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13168. total_decompressed += static_cast<size_t>(n);
  13169. }
  13170. }
  13171. // The decompressed size must be capped by payload_max_length. Without
  13172. // protection, the client would decompress the full 10MB from a tiny
  13173. // compressed payload, enabling a zip bomb DoS attack.
  13174. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13175. << "Client decompressed " << total_decompressed
  13176. << " bytes from a gzip response. The decompressed size should be "
  13177. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13178. }
  13179. #endif
  13180. TEST(HostAndPortPropertiesTest, NoSSL) {
  13181. httplib::Client cli("www.google.com", 1234);
  13182. ASSERT_EQ("www.google.com", cli.host());
  13183. ASSERT_EQ(1234, cli.port());
  13184. }
  13185. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13186. httplib::Client cli("www.google.com:1234");
  13187. ASSERT_EQ("www.google.com", cli.host());
  13188. ASSERT_EQ(1234, cli.port());
  13189. }
  13190. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13191. // Port number that overflows int — should not crash, client becomes invalid
  13192. httplib::Client cli("http://www.google.com:99999999999999999999");
  13193. ASSERT_FALSE(cli.is_valid());
  13194. }
  13195. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13196. // Port 99999 exceeds valid range (1-65535) — should not crash
  13197. httplib::Client cli("http://www.google.com:99999");
  13198. ASSERT_FALSE(cli.is_valid());
  13199. auto res = cli.Get("/");
  13200. EXPECT_FALSE(res);
  13201. EXPECT_EQ(Error::Connection, res.error());
  13202. }
  13203. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13204. httplib::Client cli("http://user:pass@localhost:1234");
  13205. ASSERT_FALSE(cli.is_valid());
  13206. EXPECT_FALSE(cli.Get("/"));
  13207. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13208. }
  13209. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13210. httplib::Client cli("http://www.google.com:80abc");
  13211. ASSERT_FALSE(cli.is_valid());
  13212. }
  13213. #ifdef CPPHTTPLIB_SSL_ENABLED
  13214. TEST(HostAndPortPropertiesTest, SSL) {
  13215. httplib::SSLClient cli("www.google.com");
  13216. ASSERT_EQ("www.google.com", cli.host());
  13217. ASSERT_EQ(443, cli.port());
  13218. }
  13219. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13220. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13221. std::string cert;
  13222. read_file(CA_CERT_FILE, cert);
  13223. httplib::SSLClient httplib_client("www.google.com");
  13224. // Load CA store first time
  13225. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13226. // Load CA store second time (update)
  13227. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13228. // Verify client is still valid and can make connections
  13229. httplib_client.enable_server_certificate_verification(true);
  13230. auto res = httplib_client.Get("/");
  13231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13232. // Google may return 200 or 301 depending on various factors
  13233. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13234. res->status == StatusCode::MovedPermanently_301);
  13235. }
  13236. TEST(SSLClientTest, ServerNameIndication_Online) {
  13237. auto host = "httpbingo.org";
  13238. auto path = std::string{"/get"};
  13239. SSLClient cli(host, 443);
  13240. auto res = cli.Get(path);
  13241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13242. ASSERT_EQ(StatusCode::OK_200, res->status);
  13243. }
  13244. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13245. // Use a site that will cause SSL verification failure due to self-signed cert
  13246. SSLClient cli("self-signed.badssl.com", 443);
  13247. cli.enable_server_certificate_verification(true);
  13248. auto res = cli.Get("/");
  13249. ASSERT_TRUE(!res);
  13250. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13251. // Verify backend error is captured for SSLServerVerification
  13252. // This occurs when certificate verification fails
  13253. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13254. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13255. EXPECT_NE(0UL, res.ssl_backend_error());
  13256. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13257. // For OpenSSL, ssl_error is 0 for verification errors
  13258. EXPECT_EQ(0, res.ssl_error());
  13259. #if !defined(_WIN32) || \
  13260. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13261. // On non-Windows or when Windows Schannel is disabled, the error comes
  13262. // from OpenSSL's verification
  13263. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13264. res.ssl_backend_error());
  13265. #endif
  13266. #endif
  13267. }
  13268. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13269. // Use a site where hostname doesn't match the certificate
  13270. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13271. SSLClient cli("wrong.host.badssl.com", 443);
  13272. cli.enable_server_certificate_verification(true);
  13273. cli.enable_server_hostname_verification(true);
  13274. auto res = cli.Get("/");
  13275. ASSERT_TRUE(!res);
  13276. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13277. // Verify backend error is captured for hostname verification failure
  13278. EXPECT_NE(0UL, res.ssl_backend_error());
  13279. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13280. // For OpenSSL, ssl_error is 0 for verification errors
  13281. EXPECT_EQ(0, res.ssl_error());
  13282. #if !defined(_WIN32) || \
  13283. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13284. // On non-Windows or when Windows Schannel is disabled, the error comes
  13285. // from OpenSSL's hostname verification
  13286. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13287. res.ssl_backend_error());
  13288. #endif
  13289. #endif
  13290. }
  13291. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13292. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13293. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13294. SSLClient cli("www.google.com", 443);
  13295. cli.enable_server_certificate_verification(true);
  13296. auto res = cli.Get("/");
  13297. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13298. }
  13299. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13300. SSLClient cli("www.google.com", 443);
  13301. cli.enable_server_certificate_verification(true);
  13302. cli.enable_windows_certificate_verification(false);
  13303. auto res = cli.Get("/");
  13304. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13305. }
  13306. // The server sends an intermediate cross-signed by a root Windows trusts,
  13307. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13308. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13309. SSLClient cli("accounts.spotify.com", 443);
  13310. auto res = cli.Get("/");
  13311. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13312. << " ssl_backend_error=" << res.ssl_backend_error();
  13313. }
  13314. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13315. // policy status, which no backend reports for a self-signed certificate.
  13316. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13317. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13318. ASSERT_TRUE(svr.is_valid());
  13319. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13320. auto se = detail::scope_exit([&] {
  13321. svr.stop();
  13322. t.join();
  13323. ASSERT_FALSE(svr.is_running());
  13324. });
  13325. svr.wait_until_ready();
  13326. SSLClient cli("127.0.0.1", PORT);
  13327. cli.set_connection_timeout(30);
  13328. auto res = cli.Get("/");
  13329. ASSERT_FALSE(res);
  13330. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13331. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13332. }
  13333. #endif
  13334. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13335. Client cli("https://google.com");
  13336. auto res = cli.Get("/");
  13337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13338. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13339. }
  13340. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13341. SSLClient cli("google.com");
  13342. cli.set_ca_cert_path(CA_CERT_FILE);
  13343. auto res = cli.Get("/");
  13344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13345. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13346. }
  13347. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13348. SSLClient cli("google.com");
  13349. cli.enable_server_certificate_verification(true);
  13350. cli.set_ca_cert_path("hello");
  13351. auto res = cli.Get("/");
  13352. ASSERT_TRUE(!res);
  13353. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13354. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13355. // should be set
  13356. EXPECT_EQ(0, res.ssl_error());
  13357. // Verify backend error is captured for SSLLoadingCerts
  13358. // This error occurs when loading CA certificates fails
  13359. EXPECT_NE(0UL, res.ssl_backend_error());
  13360. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13361. // OpenSSL specific error codes:
  13362. // > openssl errstr 0x80000002
  13363. // error:80000002:system library::No such file or directory
  13364. // > openssl errstr 0xA000126
  13365. // error:0A000126:SSL routines::unexpected eof while reading
  13366. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13367. res.ssl_backend_error() == 0xA000126);
  13368. #endif
  13369. }
  13370. TEST(SSLClientTest, ServerCertificateVerification4) {
  13371. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13372. ASSERT_TRUE(svr.is_valid());
  13373. svr.Get("/test", [&](const Request &, Response &res) {
  13374. res.set_content("test", "text/plain");
  13375. svr.stop();
  13376. ASSERT_TRUE(true);
  13377. });
  13378. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13379. auto se = detail::scope_exit([&] {
  13380. t.join();
  13381. ASSERT_FALSE(svr.is_running());
  13382. });
  13383. svr.wait_until_ready();
  13384. SSLClient cli("127.0.0.1", PORT);
  13385. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13386. cli.enable_server_certificate_verification(true);
  13387. cli.set_connection_timeout(30);
  13388. auto res = cli.Get("/test");
  13389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13390. ASSERT_EQ(StatusCode::OK_200, res->status);
  13391. }
  13392. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13393. std::string cert;
  13394. read_file(CA_CERT_FILE, cert);
  13395. SSLClient cli("google.com");
  13396. cli.load_ca_cert_store(cert.data(), cert.size());
  13397. const auto res = cli.Get("/");
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13399. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13400. }
  13401. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13402. // clang-format off
  13403. static constexpr char cert[] =
  13404. "GlobalSign Root CA\n"
  13405. "==================\n"
  13406. "-----BEGIN CERTIFICATE-----\n"
  13407. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13408. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13409. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13410. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13411. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13412. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13413. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13414. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13415. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13416. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13417. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13418. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13419. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13420. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13421. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13422. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13423. "-----END CERTIFICATE-----\n";
  13424. // clang-format on
  13425. SSLClient cli("google.com");
  13426. cli.load_ca_cert_store(cert, sizeof(cert));
  13427. const auto res = cli.Get("/");
  13428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13429. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13430. }
  13431. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13432. SSLClient cli("www.youtube.com");
  13433. cli.set_ca_cert_path(CA_CERT_FILE);
  13434. cli.enable_server_certificate_verification(true);
  13435. cli.set_follow_location(true);
  13436. auto res = cli.Get("/");
  13437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13438. ASSERT_EQ(StatusCode::OK_200, res->status);
  13439. }
  13440. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13441. SSLClient cli("wWw.YouTube.Com");
  13442. cli.set_ca_cert_path(CA_CERT_FILE);
  13443. cli.enable_server_certificate_verification(true);
  13444. cli.enable_server_hostname_verification(true);
  13445. cli.set_follow_location(true);
  13446. auto res = cli.Get("/");
  13447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13448. ASSERT_EQ(StatusCode::OK_200, res->status);
  13449. }
  13450. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13451. SSLClient cli("gOoGlE.COm");
  13452. cli.enable_server_certificate_verification(true);
  13453. cli.enable_server_hostname_verification(true);
  13454. cli.set_follow_location(true);
  13455. auto res = cli.Get("/");
  13456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13457. ASSERT_EQ(StatusCode::OK_200, res->status);
  13458. }
  13459. TEST(SSLClientTest, Issue2004_Online) {
  13460. Client client("https://google.com");
  13461. client.set_follow_location(true);
  13462. auto res = client.Get("/");
  13463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13464. ASSERT_EQ(StatusCode::OK_200, res->status);
  13465. auto body = res->body;
  13466. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13467. }
  13468. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13469. // Create SSLClient with invalid cert/key to make is_valid() return false
  13470. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13471. "nonexistent_key.pem");
  13472. // is_valid() should be false due to cert loading failure
  13473. ASSERT_FALSE(cli.is_valid());
  13474. auto res = cli.Get("/");
  13475. ASSERT_FALSE(res);
  13476. EXPECT_EQ(Error::SSLConnection, res.error());
  13477. }
  13478. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13479. // Test for Issue #2251: SSL error not properly reported when client cert
  13480. // and key paths are swapped or mismatched
  13481. // This simulates the scenario where user accidentally swaps the cert and key
  13482. // files
  13483. // Using client cert file as private key and vice versa (completely wrong)
  13484. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13485. // Should fail validation due to cert/key mismatch
  13486. ASSERT_FALSE(cli.is_valid());
  13487. // Attempt to make a request should fail with proper error
  13488. auto res = cli.Get("/");
  13489. ASSERT_FALSE(res);
  13490. EXPECT_EQ(Error::SSLConnection, res.error());
  13491. // SSL error should be recorded in the Result object (this is the key fix for
  13492. // Issue #2251)
  13493. auto backend_error = res.ssl_backend_error();
  13494. EXPECT_NE(0u, backend_error);
  13495. }
  13496. // Tests cert/key mismatch detection at the TLS context level
  13497. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13498. // Test that using mismatched cert/key causes connection failure.
  13499. // We verify this at the SSLClient level rather than through internal
  13500. // TLS API functions.
  13501. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13502. cli.enable_server_certificate_verification(false);
  13503. cli.set_connection_timeout(2);
  13504. // The mismatch should cause a connection or handshake error
  13505. auto res = cli.Get("/test");
  13506. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13507. // Either way, the request should fail
  13508. EXPECT_FALSE(res);
  13509. }
  13510. #endif
  13511. #if 0
  13512. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13513. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13514. ASSERT_TRUE(cli != nullptr);
  13515. cli->set_address_family(AF_INET6);
  13516. cli->set_interface("en0");
  13517. auto res = cli->Get("/get");
  13518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13519. ASSERT_EQ(StatusCode::OK_200, res->status);
  13520. }
  13521. #endif
  13522. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13523. #ifdef CPPHTTPLIB_SSL_ENABLED
  13524. void ClientCertPresent(
  13525. const std::string &client_cert_file,
  13526. const std::string &client_private_key_file,
  13527. const std::string &client_encrypted_private_key_pass = std::string()) {
  13528. using namespace httplib::tls;
  13529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13530. CLIENT_CA_CERT_DIR);
  13531. ASSERT_TRUE(svr.is_valid());
  13532. svr.Get("/test", [&](const Request &req, Response &res) {
  13533. res.set_content("test", "text/plain");
  13534. auto cert = req.peer_cert();
  13535. ASSERT_TRUE(static_cast<bool>(cert));
  13536. std::string common_name = cert.subject_cn();
  13537. EXPECT_EQ("Common Name", common_name);
  13538. });
  13539. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13540. auto se = detail::scope_exit([&] {
  13541. svr.stop();
  13542. t.join();
  13543. ASSERT_FALSE(svr.is_running());
  13544. });
  13545. svr.wait_until_ready();
  13546. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13547. client_encrypted_private_key_pass);
  13548. cli.enable_server_certificate_verification(false);
  13549. cli.set_connection_timeout(30);
  13550. auto res = cli.Get("/test");
  13551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13552. ASSERT_EQ(StatusCode::OK_200, res->status);
  13553. }
  13554. TEST(SSLClientServerTest, ClientCertPresent) {
  13555. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13556. }
  13557. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13558. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13559. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13560. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13561. }
  13562. // PEM memory-based constructor tests (works with all TLS backends)
  13563. void PemMemoryClientCertPresent(
  13564. const std::string &client_cert_file,
  13565. const std::string &client_private_key_file,
  13566. const std::string &client_encrypted_private_key_pass = std::string()) {
  13567. // Read PEM files into memory
  13568. std::string server_cert_pem, server_key_pem;
  13569. std::string client_ca_pem;
  13570. std::string client_cert_pem, client_key_pem;
  13571. read_file(SERVER_CERT_FILE, server_cert_pem);
  13572. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13573. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13574. read_file(client_cert_file, client_cert_pem);
  13575. read_file(client_private_key_file, client_key_pem);
  13576. // Create server with PEM memory
  13577. SSLServer::PemMemory server_pem = {
  13578. server_cert_pem.c_str(),
  13579. server_cert_pem.size(),
  13580. server_key_pem.c_str(),
  13581. server_key_pem.size(),
  13582. client_ca_pem.c_str(),
  13583. client_ca_pem.size(),
  13584. nullptr // no password for server key
  13585. };
  13586. SSLServer svr(server_pem);
  13587. ASSERT_TRUE(svr.is_valid());
  13588. svr.Get("/test", [&](const Request &, Response &res) {
  13589. res.set_content("test", "text/plain");
  13590. });
  13591. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13592. auto se = detail::scope_exit([&] {
  13593. svr.stop();
  13594. t.join();
  13595. ASSERT_FALSE(svr.is_running());
  13596. });
  13597. svr.wait_until_ready();
  13598. // Create client with PEM memory
  13599. const char *password = client_encrypted_private_key_pass.empty()
  13600. ? nullptr
  13601. : client_encrypted_private_key_pass.c_str();
  13602. SSLClient::PemMemory client_pem = {
  13603. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13604. client_key_pem.size(), password};
  13605. SSLClient cli(HOST, PORT, client_pem);
  13606. cli.enable_server_certificate_verification(false);
  13607. cli.set_connection_timeout(30);
  13608. auto res = cli.Get("/test");
  13609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13610. ASSERT_EQ(StatusCode::OK_200, res->status);
  13611. }
  13612. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13613. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13614. }
  13615. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13616. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13617. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13618. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13619. }
  13620. TEST(SSLClientServerTest, ClientCertMissing) {
  13621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13622. CLIENT_CA_CERT_DIR);
  13623. ASSERT_TRUE(svr.is_valid());
  13624. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13625. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13626. auto se = detail::scope_exit([&] {
  13627. svr.stop();
  13628. t.join();
  13629. ASSERT_FALSE(svr.is_running());
  13630. });
  13631. svr.wait_until_ready();
  13632. SSLClient cli(HOST, PORT);
  13633. cli.set_connection_timeout(30);
  13634. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13635. // the chain check on Windows, so the result does not depend on the order.
  13636. cli.enable_server_hostname_verification(false);
  13637. auto res = cli.Get("/test");
  13638. ASSERT_TRUE(!res);
  13639. // When client cert is missing and server requires it, connection fails
  13640. // Error type depends on backend implementation
  13641. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13642. res.error() == Error::SSLConnection);
  13643. // Verify backend error is captured
  13644. // Note: This test may have different error codes depending on the exact
  13645. // verification failure
  13646. EXPECT_NE(0UL, res.ssl_backend_error());
  13647. }
  13648. TEST(SSLClientServerTest, TrustDirOptional) {
  13649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13650. ASSERT_TRUE(svr.is_valid());
  13651. svr.Get("/test", [&](const Request &, Response &res) {
  13652. res.set_content("test", "text/plain");
  13653. });
  13654. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13655. auto se = detail::scope_exit([&] {
  13656. svr.stop();
  13657. t.join();
  13658. ASSERT_FALSE(svr.is_running());
  13659. });
  13660. svr.wait_until_ready();
  13661. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13662. cli.enable_server_certificate_verification(false);
  13663. cli.set_connection_timeout(30);
  13664. auto res = cli.Get("/test");
  13665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13666. ASSERT_EQ(StatusCode::OK_200, res->status);
  13667. }
  13668. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13669. class NoListenSSLServer : public SSLServer {
  13670. public:
  13671. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13672. const char *client_ca_cert_file_path,
  13673. const char *client_ca_cert_dir_path = nullptr)
  13674. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13675. client_ca_cert_dir_path),
  13676. stop_(false) {}
  13677. std::atomic_bool stop_;
  13678. private:
  13679. bool process_and_close_socket(socket_t /*sock*/) override {
  13680. // Don't create SSL context
  13681. while (!stop_.load()) {
  13682. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13683. }
  13684. return true;
  13685. }
  13686. };
  13687. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13688. CLIENT_CA_CERT_FILE);
  13689. ASSERT_TRUE(svr.is_valid());
  13690. svr.Get("/test", [&](const Request &, Response &res) {
  13691. res.set_content("test", "text/plain");
  13692. });
  13693. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13694. auto se = detail::scope_exit([&] {
  13695. svr.stop_ = true;
  13696. svr.stop();
  13697. t.join();
  13698. ASSERT_FALSE(svr.is_running());
  13699. });
  13700. svr.wait_until_ready();
  13701. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13702. cli.enable_server_certificate_verification(false);
  13703. cli.set_connection_timeout(1);
  13704. auto res = cli.Get("/test");
  13705. ASSERT_TRUE(!res);
  13706. EXPECT_EQ(Error::SSLConnection, res.error());
  13707. // Timeout results in WantRead error code (maps to backend-specific value)
  13708. EXPECT_NE(0, res.ssl_error());
  13709. }
  13710. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13711. // Test SSLServer with client certificate verification using the standard
  13712. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13713. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13714. CLIENT_CA_CERT_DIR);
  13715. ASSERT_TRUE(svr.is_valid());
  13716. svr.Get("/test", [&](const Request &req, Response &res) {
  13717. res.set_content("test", "text/plain");
  13718. auto cert = req.peer_cert();
  13719. ASSERT_TRUE(static_cast<bool>(cert));
  13720. auto common_name = cert.subject_cn();
  13721. EXPECT_EQ("Common Name", common_name);
  13722. });
  13723. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13724. auto se = detail::scope_exit([&] {
  13725. svr.stop();
  13726. t.join();
  13727. ASSERT_FALSE(svr.is_running());
  13728. });
  13729. svr.wait_until_ready();
  13730. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13731. cli.enable_server_certificate_verification(false);
  13732. cli.set_connection_timeout(30);
  13733. auto res = cli.Get("/test");
  13734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13735. ASSERT_EQ(StatusCode::OK_200, res->status);
  13736. }
  13737. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13738. // Verifies that wildcard matching and exact matching work consistently
  13739. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13740. using namespace httplib::tls;
  13741. // We need a running server to test against
  13742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13743. ASSERT_TRUE(svr.is_valid());
  13744. svr.Get("/test", [](const Request &, Response &res) {
  13745. res.set_content("ok", "text/plain");
  13746. });
  13747. thread t([&]() { svr.listen(HOST, PORT); });
  13748. auto se = detail::scope_exit([&] {
  13749. svr.stop();
  13750. t.join();
  13751. });
  13752. svr.wait_until_ready();
  13753. bool verify_callback_called = false;
  13754. bool verify_result_wrong = false;
  13755. SSLClient cli(HOST, PORT);
  13756. cli.enable_server_certificate_verification(true);
  13757. cli.set_ca_cert_path(CA_CERT_FILE);
  13758. cli.set_connection_timeout(5);
  13759. // Note: Test certificate has CN="Common Name", not "localhost"
  13760. bool verify_result_cn = false;
  13761. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13762. verify_callback_called = true;
  13763. if (!ctx.cert) return false;
  13764. // Test 1: "Common Name" should match (our test server cert CN)
  13765. verify_result_cn = ctx.check_hostname("Common Name");
  13766. // Test 2: wrong hostname should not match
  13767. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13768. return true; // Accept for the purpose of this test
  13769. });
  13770. auto res = cli.Get("/test");
  13771. // The request may succeed or fail depending on cert configuration
  13772. // but the callback should have been called
  13773. ASSERT_TRUE(verify_callback_called)
  13774. << "Verify callback should have been called";
  13775. // CN="Common Name" should match our test certificate
  13776. //
  13777. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13778. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13779. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13780. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13781. // <openssl/base.h>, which is included transitively when
  13782. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13783. #if defined(OPENSSL_IS_BORINGSSL)
  13784. EXPECT_FALSE(verify_result_cn)
  13785. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13786. #else
  13787. EXPECT_TRUE(verify_result_cn)
  13788. << "verify_hostname should match 'Common Name' (certificate CN)";
  13789. #endif
  13790. // Wrong hostname should not match
  13791. EXPECT_FALSE(verify_result_wrong)
  13792. << "verify_hostname should not match 'wronghost.example.com'";
  13793. }
  13794. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13795. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13796. // X509_check_ip behavior and must hold for every backend.
  13797. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13798. using namespace httplib::tls;
  13799. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13800. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13801. ASSERT_TRUE(svr.is_valid());
  13802. svr.Get("/test", [](const Request &, Response &res) {
  13803. res.set_content("ok", "text/plain");
  13804. });
  13805. thread t([&]() { svr.listen(HOST, PORT); });
  13806. auto se = detail::scope_exit([&] {
  13807. svr.stop();
  13808. t.join();
  13809. });
  13810. svr.wait_until_ready();
  13811. bool verify_callback_called = false;
  13812. bool ip_matched_via_cn = true;
  13813. SSLClient cli(HOST, PORT);
  13814. cli.enable_server_certificate_verification(true);
  13815. cli.set_ca_cert_path(CA_CERT_FILE);
  13816. cli.set_connection_timeout(5);
  13817. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13818. verify_callback_called = true;
  13819. if (!ctx.cert) return false;
  13820. // The IP appears only in the CN, so it must NOT be accepted.
  13821. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13822. return true; // Accept for the purpose of this test
  13823. });
  13824. cli.Get("/test");
  13825. ASSERT_TRUE(verify_callback_called)
  13826. << "Verify callback should have been called";
  13827. EXPECT_FALSE(ip_matched_via_cn)
  13828. << "An IP host must not be authenticated via the certificate CN";
  13829. }
  13830. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13831. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13832. using namespace httplib::tls;
  13833. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13834. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13835. ASSERT_TRUE(svr.is_valid());
  13836. svr.Get("/test", [](const Request &, Response &res) {
  13837. res.set_content("ok", "text/plain");
  13838. });
  13839. thread t([&]() { svr.listen(HOST, PORT); });
  13840. auto se = detail::scope_exit([&] {
  13841. svr.stop();
  13842. t.join();
  13843. });
  13844. svr.wait_until_ready();
  13845. bool verify_callback_called = false;
  13846. bool san_matched = false;
  13847. bool wrong_ipv6_matched = true;
  13848. bool cn_ipv6_matched = true;
  13849. SSLClient cli(HOST, PORT);
  13850. cli.enable_server_certificate_verification(true);
  13851. cli.set_ca_cert_path(CA_CERT_FILE);
  13852. cli.set_connection_timeout(5);
  13853. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13854. verify_callback_called = true;
  13855. if (!ctx.cert) return false;
  13856. // Matches the IPv6 iPAddress SAN.
  13857. san_matched = ctx.check_hostname("2001:db8::1");
  13858. // A different IPv6 address must not match.
  13859. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13860. // "::1" lives only in the CN, so it must not be accepted.
  13861. cn_ipv6_matched = ctx.check_hostname("::1");
  13862. return true; // Accept for the purpose of this test
  13863. });
  13864. cli.Get("/test");
  13865. ASSERT_TRUE(verify_callback_called)
  13866. << "Verify callback should have been called";
  13867. EXPECT_TRUE(san_matched)
  13868. << "verify_hostname should match an IPv6 iPAddress SAN";
  13869. EXPECT_FALSE(wrong_ipv6_matched)
  13870. << "verify_hostname should not match a non-matching IPv6 address";
  13871. EXPECT_FALSE(cn_ipv6_matched)
  13872. << "An IPv6 host must not be authenticated via the certificate CN";
  13873. }
  13874. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13875. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13876. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13877. using namespace httplib::tls;
  13878. // SANs: DNS:a.zz, IP:42.46.122.122
  13879. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13880. ASSERT_TRUE(svr.is_valid());
  13881. svr.Get("/test", [](const Request &, Response &res) {
  13882. res.set_content("ok", "text/plain");
  13883. });
  13884. auto port = svr.bind_to_any_port(HOST);
  13885. thread t([&]() { svr.listen_after_bind(); });
  13886. auto se = detail::scope_exit([&] {
  13887. svr.stop();
  13888. t.join();
  13889. });
  13890. svr.wait_until_ready();
  13891. bool verify_callback_called = false;
  13892. bool dns_san_matched = false;
  13893. bool ip_san_matched = false;
  13894. bool ip_matched_via_dns_san = true;
  13895. bool dns_matched_via_ip_san = true;
  13896. bool cn_matched_next_to_dns_san = true;
  13897. SSLClient cli(HOST, port);
  13898. cli.enable_server_certificate_verification(true);
  13899. cli.set_ca_cert_path(CA_CERT_FILE);
  13900. cli.set_connection_timeout(5);
  13901. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13902. verify_callback_called = true;
  13903. if (!ctx.cert) return false;
  13904. dns_san_matched = ctx.check_hostname("a.zz");
  13905. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13906. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13907. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13908. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  13909. return true; // Accept for the purpose of this test
  13910. });
  13911. cli.Get("/test");
  13912. ASSERT_TRUE(verify_callback_called)
  13913. << "Verify callback should have been called";
  13914. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13915. EXPECT_TRUE(ip_san_matched)
  13916. << "verify_hostname should match an iPAddress SAN";
  13917. EXPECT_FALSE(ip_matched_via_dns_san)
  13918. << "An IP host must not be authenticated via a dNSName SAN";
  13919. EXPECT_FALSE(dns_matched_via_ip_san)
  13920. << "A DNS host must not be authenticated via an iPAddress SAN";
  13921. EXPECT_FALSE(cn_matched_next_to_dns_san)
  13922. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  13923. }
  13924. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13925. // "www.*.example.test" names one host and not every host under example.test.
  13926. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13927. using namespace httplib::tls;
  13928. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13929. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13930. ASSERT_TRUE(svr.is_valid());
  13931. svr.Get("/test", [](const Request &, Response &res) {
  13932. res.set_content("ok", "text/plain");
  13933. });
  13934. auto port = svr.bind_to_any_port(HOST);
  13935. thread t([&]() { svr.listen_after_bind(); });
  13936. auto se = detail::scope_exit([&] {
  13937. svr.stop();
  13938. t.join();
  13939. });
  13940. svr.wait_until_ready();
  13941. bool verify_callback_called = false;
  13942. bool leftmost_wildcard_matched = false;
  13943. bool wildcard_spanned_labels = true;
  13944. bool inner_wildcard_matched = true;
  13945. SSLClient cli(HOST, port);
  13946. cli.enable_server_certificate_verification(true);
  13947. cli.set_ca_cert_path(CA_CERT_FILE);
  13948. cli.set_connection_timeout(5);
  13949. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13950. verify_callback_called = true;
  13951. if (!ctx.cert) return false;
  13952. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13953. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13954. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13955. return true; // Accept for the purpose of this test
  13956. });
  13957. cli.Get("/test");
  13958. ASSERT_TRUE(verify_callback_called)
  13959. << "Verify callback should have been called";
  13960. EXPECT_TRUE(leftmost_wildcard_matched)
  13961. << "A leftmost wildcard should match a single label";
  13962. EXPECT_FALSE(wildcard_spanned_labels)
  13963. << "A wildcard label must not match more than one label";
  13964. EXPECT_FALSE(inner_wildcard_matched)
  13965. << "A wildcard outside the leftmost label must not be honoured";
  13966. }
  13967. // sans() must report each SAN entry under its own type.
  13968. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13969. using namespace httplib::tls;
  13970. // SANs: DNS:a.zz, IP:42.46.122.122
  13971. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13972. ASSERT_TRUE(svr.is_valid());
  13973. svr.Get("/test", [](const Request &, Response &res) {
  13974. res.set_content("ok", "text/plain");
  13975. });
  13976. auto port = svr.bind_to_any_port(HOST);
  13977. thread t([&]() { svr.listen_after_bind(); });
  13978. auto se = detail::scope_exit([&] {
  13979. svr.stop();
  13980. t.join();
  13981. });
  13982. svr.wait_until_ready();
  13983. bool verify_callback_called = false;
  13984. std::vector<SanEntry> sans;
  13985. SSLClient cli(HOST, port);
  13986. cli.enable_server_certificate_verification(true);
  13987. cli.set_ca_cert_path(CA_CERT_FILE);
  13988. cli.set_connection_timeout(5);
  13989. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13990. verify_callback_called = true;
  13991. if (!ctx.cert) return false;
  13992. sans = ctx.sans();
  13993. return true; // Accept for the purpose of this test
  13994. });
  13995. cli.Get("/test");
  13996. ASSERT_TRUE(verify_callback_called)
  13997. << "Verify callback should have been called";
  13998. auto has_san = [&](SanType type, const std::string &value) {
  13999. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14000. return san.type == type && san.value == value;
  14001. });
  14002. };
  14003. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14004. << "sans() should report the dNSName SAN";
  14005. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14006. << "sans() should report the iPAddress SAN";
  14007. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14008. << "sans() must not report the dNSName SAN as an address";
  14009. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14010. << "sans() must not report the iPAddress SAN as a DNS name";
  14011. }
  14012. #endif
  14013. // mbedTLS-specific callback constructor test
  14014. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14015. #ifdef CPPHTTPLIB_SSL_ENABLED
  14016. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14018. ASSERT_TRUE(svr.is_valid());
  14019. // Set up a handler to verify client certificate is present
  14020. bool client_cert_verified = false;
  14021. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14022. // Verify that client certificate was provided
  14023. client_cert_verified = true;
  14024. res.set_content("success", "text/plain");
  14025. });
  14026. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14027. auto se = detail::scope_exit([&] {
  14028. svr.stop();
  14029. t.join();
  14030. ASSERT_FALSE(svr.is_running());
  14031. });
  14032. svr.wait_until_ready();
  14033. // Client with certificate
  14034. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14035. cli.enable_server_certificate_verification(false);
  14036. cli.set_connection_timeout(30);
  14037. auto res = cli.Get("/test");
  14038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14039. ASSERT_EQ(StatusCode::OK_200, res->status);
  14040. ASSERT_TRUE(client_cert_verified);
  14041. EXPECT_EQ("success", res->body);
  14042. }
  14043. #endif
  14044. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14045. // backends
  14046. #ifdef CPPHTTPLIB_SSL_ENABLED
  14047. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14048. using namespace httplib::tls;
  14049. // Test that when client CA cert file is provided,
  14050. // the server properly requests and validates client certificates
  14051. // Create a server with client authentication
  14052. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14053. ASSERT_TRUE(svr.is_valid());
  14054. bool handler_called = false;
  14055. svr.Get("/test", [&](const Request &req, Response &res) {
  14056. handler_called = true;
  14057. // Verify that a client certificate was provided
  14058. auto cert = req.peer_cert();
  14059. ASSERT_TRUE(static_cast<bool>(cert));
  14060. // Get the issuer name
  14061. std::string issuer_str = cert.issuer_name();
  14062. ASSERT_FALSE(issuer_str.empty());
  14063. // The client certificate should be issued by our test CA
  14064. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14065. res.set_content("authenticated", "text/plain");
  14066. });
  14067. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14068. auto se = detail::scope_exit([&] {
  14069. svr.stop();
  14070. t.join();
  14071. ASSERT_FALSE(svr.is_running());
  14072. });
  14073. svr.wait_until_ready();
  14074. // Connect with a client certificate issued by the CA
  14075. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14076. cli.enable_server_certificate_verification(false);
  14077. cli.set_connection_timeout(30);
  14078. auto res = cli.Get("/test");
  14079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14080. ASSERT_EQ(StatusCode::OK_200, res->status);
  14081. ASSERT_TRUE(handler_called);
  14082. EXPECT_EQ("authenticated", res->body);
  14083. }
  14084. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14085. using namespace httplib::tls;
  14086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14087. ASSERT_TRUE(svr.is_valid());
  14088. svr.Get("/test", [](const Request &, Response &res) {
  14089. res.set_content("ok", "text/plain");
  14090. });
  14091. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14092. auto se = detail::scope_exit([&] {
  14093. svr.stop();
  14094. t.join();
  14095. });
  14096. svr.wait_until_ready();
  14097. SSLClient cli(HOST, PORT);
  14098. cli.enable_server_certificate_verification(false);
  14099. cli.set_connection_timeout(30);
  14100. bool cert_checked = false;
  14101. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14102. if (ctx.cert) {
  14103. auto sans = ctx.sans();
  14104. // Test certificate may or may not have SANs - just verify the API
  14105. // works If SANs exist, verify the types are valid
  14106. for (const auto &san : sans) {
  14107. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14108. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14109. san.type == SanType::OTHER);
  14110. EXPECT_FALSE(san.value.empty());
  14111. }
  14112. cert_checked = true;
  14113. }
  14114. return true;
  14115. });
  14116. auto res = cli.Get("/test");
  14117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14118. EXPECT_TRUE(cert_checked);
  14119. }
  14120. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14121. using namespace httplib::tls;
  14122. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14123. ASSERT_TRUE(svr.is_valid());
  14124. svr.Get("/test", [](const Request &, Response &res) {
  14125. res.set_content("ok", "text/plain");
  14126. });
  14127. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14128. auto se = detail::scope_exit([&] {
  14129. svr.stop();
  14130. t.join();
  14131. });
  14132. svr.wait_until_ready();
  14133. SSLClient cli(HOST, PORT);
  14134. cli.enable_server_certificate_verification(false);
  14135. cli.set_connection_timeout(30);
  14136. bool validity_checked = false;
  14137. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14138. if (ctx.cert) {
  14139. time_t not_before = 0, not_after = 0;
  14140. bool result = ctx.validity(not_before, not_after);
  14141. EXPECT_TRUE(result);
  14142. // Verify that not_before < now < not_after for a valid cert
  14143. time_t now = time(nullptr);
  14144. EXPECT_LT(not_before, now);
  14145. EXPECT_GT(not_after, now);
  14146. validity_checked = true;
  14147. }
  14148. return true;
  14149. });
  14150. auto res = cli.Get("/test");
  14151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14152. EXPECT_TRUE(validity_checked);
  14153. }
  14154. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14155. using namespace httplib::tls;
  14156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14157. ASSERT_TRUE(svr.is_valid());
  14158. svr.Get("/test", [](const Request &, Response &res) {
  14159. res.set_content("ok", "text/plain");
  14160. });
  14161. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14162. auto se = detail::scope_exit([&] {
  14163. svr.stop();
  14164. t.join();
  14165. });
  14166. svr.wait_until_ready();
  14167. SSLClient cli(HOST, PORT);
  14168. cli.enable_server_certificate_verification(false);
  14169. cli.set_connection_timeout(30);
  14170. bool serial_checked = false;
  14171. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14172. if (ctx.cert) {
  14173. std::string serial = ctx.serial();
  14174. EXPECT_FALSE(serial.empty());
  14175. // Serial should be a hex string
  14176. for (char c : serial) {
  14177. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14178. (c >= 'a' && c <= 'f'));
  14179. }
  14180. serial_checked = true;
  14181. }
  14182. return true;
  14183. });
  14184. auto res = cli.Get("/test");
  14185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14186. EXPECT_TRUE(serial_checked);
  14187. }
  14188. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14189. // Test 1: Valid CA file - no error should be recorded
  14190. {
  14191. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14192. CLIENT_CA_CERT_FILE);
  14193. ASSERT_TRUE(svr.is_valid());
  14194. // With valid setup, last_ssl_error should be 0
  14195. EXPECT_EQ(0, svr.ssl_last_error());
  14196. }
  14197. // Test 2: Invalid CA file content
  14198. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14199. {
  14200. // Create a temporary file with completely invalid content
  14201. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14202. {
  14203. std::ofstream ofs(temp_invalid_ca);
  14204. ofs << "This is not a certificate file at all\n";
  14205. ofs << "Just plain text content\n";
  14206. }
  14207. // Create server with invalid CA file
  14208. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14209. // Clean up temporary file
  14210. std::remove(temp_invalid_ca);
  14211. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14212. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14213. // Note: SSL_CTX_load_verify_locations typically fails first,
  14214. // but our error handling code path is still exercised
  14215. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14216. }
  14217. }
  14218. TEST(VerifyCallbackTest, VerifyContextFields) {
  14219. using namespace httplib::tls;
  14220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14221. ASSERT_TRUE(svr.is_valid());
  14222. svr.Get("/test", [](const Request &, Response &res) {
  14223. res.set_content("ok", "text/plain");
  14224. });
  14225. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14226. auto se = detail::scope_exit([&] {
  14227. svr.stop();
  14228. t.join();
  14229. });
  14230. svr.wait_until_ready();
  14231. SSLClient cli(HOST, PORT);
  14232. cli.enable_server_certificate_verification(false);
  14233. cli.set_connection_timeout(30);
  14234. int callback_count = 0;
  14235. bool saw_leaf_cert = false;
  14236. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14237. if (ctx.cert) {
  14238. callback_count++;
  14239. // We should see at least one certificate (the leaf)
  14240. std::string cn = ctx.subject_cn();
  14241. if (!cn.empty()) { saw_leaf_cert = true; }
  14242. // Verify context fields are populated
  14243. EXPECT_NE(ctx.session, nullptr);
  14244. EXPECT_GE(ctx.depth, 0);
  14245. }
  14246. return true;
  14247. });
  14248. auto res = cli.Get("/test");
  14249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14250. EXPECT_GT(callback_count, 0);
  14251. EXPECT_TRUE(saw_leaf_cert);
  14252. }
  14253. // A verifier belongs to the client that set it, not to the thread that set it.
  14254. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14255. using namespace httplib::tls;
  14256. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14257. ASSERT_TRUE(svr.is_valid());
  14258. svr.Get("/test", [](const Request &, Response &res) {
  14259. res.set_content("ok", "text/plain");
  14260. });
  14261. auto port = svr.bind_to_any_port(HOST);
  14262. thread t([&]() { svr.listen_after_bind(); });
  14263. auto se = detail::scope_exit([&] {
  14264. svr.stop();
  14265. t.join();
  14266. });
  14267. svr.wait_until_ready();
  14268. auto rejecting_calls = 0;
  14269. SSLClient rejecting(HOST, port);
  14270. rejecting.enable_server_certificate_verification(false);
  14271. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14272. rejecting_calls++;
  14273. return false;
  14274. });
  14275. auto accepting_calls = 0;
  14276. SSLClient accepting(HOST, port);
  14277. accepting.enable_server_certificate_verification(false);
  14278. // Set on another thread than the requests below.
  14279. thread([&]() {
  14280. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14281. accepting_calls++;
  14282. return true;
  14283. });
  14284. }).join();
  14285. // Requested on another thread than the verifier was set on.
  14286. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14287. EXPECT_GT(rejecting_calls, 0);
  14288. auto res = accepting.Get("/test");
  14289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14290. EXPECT_GT(accepting_calls, 0);
  14291. }
  14292. // A verifier replaced while a handshake runs it lives until it returns.
  14293. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14294. using namespace httplib::tls;
  14295. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14296. ASSERT_TRUE(svr.is_valid());
  14297. svr.Get("/test", [](const Request &, Response &res) {
  14298. res.set_content("ok", "text/plain");
  14299. });
  14300. auto port = svr.bind_to_any_port(HOST);
  14301. thread t([&]() { svr.listen_after_bind(); });
  14302. auto se = detail::scope_exit([&] {
  14303. svr.stop();
  14304. t.join();
  14305. });
  14306. svr.wait_until_ready();
  14307. SSLClient cli(HOST, port);
  14308. cli.enable_server_certificate_verification(false);
  14309. std::promise<void> entered;
  14310. std::promise<void> replaced;
  14311. auto replaced_future = replaced.get_future();
  14312. auto first_call = true;
  14313. // Long enough to live on the heap
  14314. std::string expected(64, 'v');
  14315. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14316. if (first_call) {
  14317. first_call = false;
  14318. entered.set_value();
  14319. replaced_future.wait();
  14320. }
  14321. return expected == std::string(64, 'v');
  14322. });
  14323. thread request([&]() {
  14324. auto res = cli.Get("/test");
  14325. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14326. });
  14327. entered.get_future().wait();
  14328. cli.set_server_certificate_verifier(
  14329. [](const VerifyContext &) { return true; });
  14330. replaced.set_value();
  14331. request.join();
  14332. }
  14333. // VerifyContext::session is the same handle the other tls:: functions take.
  14334. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14335. using namespace httplib::tls;
  14336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14337. ASSERT_TRUE(svr.is_valid());
  14338. svr.Get("/test", [](const Request &, Response &res) {
  14339. res.set_content("ok", "text/plain");
  14340. });
  14341. auto port = svr.bind_to_any_port(HOST);
  14342. thread t([&]() { svr.listen_after_bind(); });
  14343. auto se = detail::scope_exit([&] {
  14344. svr.stop();
  14345. t.join();
  14346. });
  14347. svr.wait_until_ready();
  14348. SSLClient cli(HOST, port);
  14349. cli.enable_server_certificate_verification(false);
  14350. session_t verifier_session = nullptr;
  14351. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14352. verifier_session = ctx.session;
  14353. return true;
  14354. });
  14355. session_t session_verifier_session = nullptr;
  14356. cli.set_session_verifier([&](session_t session) {
  14357. session_verifier_session = session;
  14358. return SSLVerifierResponse::NoDecisionMade;
  14359. });
  14360. auto res = cli.Get("/test");
  14361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14362. EXPECT_NE(nullptr, verifier_session);
  14363. EXPECT_EQ(session_verifier_session, verifier_session);
  14364. }
  14365. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14366. using httplib::tls::TlsError;
  14367. // Test that verify_error_to_string returns empty for success
  14368. std::string success_str = TlsError::verify_error_to_string(0);
  14369. EXPECT_TRUE(success_str.empty());
  14370. // Test that verify_error_to_string returns non-empty for error codes
  14371. // Using a common error code (certificate expired)
  14372. std::string error_str =
  14373. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14374. EXPECT_FALSE(error_str.empty());
  14375. }
  14376. TEST(SessionVerifierTest, CertificateAccepted) {
  14377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14378. ASSERT_TRUE(svr.is_valid());
  14379. svr.Get("/test", [](const Request &, Response &res) {
  14380. res.set_content("ok", "text/plain");
  14381. });
  14382. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14383. auto se = detail::scope_exit([&] {
  14384. svr.stop();
  14385. t.join();
  14386. });
  14387. svr.wait_until_ready();
  14388. SSLClient cli(HOST, PORT);
  14389. cli.enable_server_certificate_verification(false);
  14390. cli.set_connection_timeout(30);
  14391. bool callback_called = false;
  14392. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14393. EXPECT_NE(session, nullptr);
  14394. callback_called = true;
  14395. return SSLVerifierResponse::CertificateAccepted;
  14396. });
  14397. auto res = cli.Get("/test");
  14398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14399. EXPECT_EQ(200, res->status);
  14400. EXPECT_TRUE(callback_called);
  14401. }
  14402. TEST(SessionVerifierTest, CertificateRejected) {
  14403. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14404. ASSERT_TRUE(svr.is_valid());
  14405. svr.Get("/test", [](const Request &, Response &res) {
  14406. res.set_content("ok", "text/plain");
  14407. });
  14408. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14409. auto se = detail::scope_exit([&] {
  14410. svr.stop();
  14411. t.join();
  14412. });
  14413. svr.wait_until_ready();
  14414. SSLClient cli(HOST, PORT);
  14415. cli.enable_server_certificate_verification(false);
  14416. cli.set_connection_timeout(30);
  14417. bool callback_called = false;
  14418. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14419. EXPECT_NE(session, nullptr);
  14420. callback_called = true;
  14421. return SSLVerifierResponse::CertificateRejected;
  14422. });
  14423. auto res = cli.Get("/test");
  14424. EXPECT_FALSE(res);
  14425. EXPECT_TRUE(callback_called);
  14426. }
  14427. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14428. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14429. ASSERT_TRUE(svr.is_valid());
  14430. svr.Get("/test", [](const Request &, Response &res) {
  14431. res.set_content("ok", "text/plain");
  14432. });
  14433. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14434. auto se = detail::scope_exit([&] {
  14435. svr.stop();
  14436. t.join();
  14437. });
  14438. svr.wait_until_ready();
  14439. // NoDecisionMade with verification disabled should succeed (no default check)
  14440. SSLClient cli(HOST, PORT);
  14441. cli.enable_server_certificate_verification(false);
  14442. cli.set_connection_timeout(30);
  14443. bool callback_called = false;
  14444. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14445. EXPECT_NE(session, nullptr);
  14446. callback_called = true;
  14447. return SSLVerifierResponse::NoDecisionMade;
  14448. });
  14449. auto res = cli.Get("/test");
  14450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14451. EXPECT_EQ(200, res->status);
  14452. EXPECT_TRUE(callback_called);
  14453. }
  14454. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14456. ASSERT_TRUE(svr.is_valid());
  14457. svr.Get("/test", [](const Request &, Response &res) {
  14458. res.set_content("ok", "text/plain");
  14459. });
  14460. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14461. auto se = detail::scope_exit([&] {
  14462. svr.stop();
  14463. t.join();
  14464. });
  14465. svr.wait_until_ready();
  14466. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14467. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14468. // so we only check that the request fails, not whether the callback was
  14469. // called.
  14470. SSLClient cli(HOST, PORT);
  14471. cli.enable_server_certificate_verification(true);
  14472. cli.set_connection_timeout(30);
  14473. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14474. EXPECT_NE(session, nullptr);
  14475. return SSLVerifierResponse::NoDecisionMade;
  14476. });
  14477. auto res = cli.Get("/test");
  14478. EXPECT_FALSE(res);
  14479. }
  14480. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14481. // Test SSL server using PemMemory constructor with client CA certificates
  14482. // Read PEM files
  14483. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14484. read_file(SERVER_CERT_FILE, server_cert_pem);
  14485. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14486. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14487. // Create SSLServer with PemMemory constructor including client CA
  14488. SSLServer::PemMemory server_pem = {
  14489. server_cert_pem.c_str(),
  14490. server_cert_pem.size(),
  14491. server_key_pem.c_str(),
  14492. server_key_pem.size(),
  14493. client_ca_pem.c_str(),
  14494. client_ca_pem.size(),
  14495. nullptr // no password for server key
  14496. };
  14497. SSLServer svr(server_pem);
  14498. ASSERT_TRUE(svr.is_valid());
  14499. // No SSL error should be recorded for valid setup
  14500. EXPECT_EQ(0, svr.ssl_last_error());
  14501. // Set up server endpoints
  14502. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14503. res.set_content("ok", "text/plain");
  14504. });
  14505. // Start server in a thread
  14506. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14507. svr.wait_until_ready();
  14508. // Connect with client certificate (using constructor with paths)
  14509. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14510. cli.enable_server_certificate_verification(false);
  14511. auto res = cli.Get("/test-pem-ca");
  14512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14513. EXPECT_EQ(200, res->status);
  14514. EXPECT_EQ("ok", res->body);
  14515. svr.stop();
  14516. server_thread.join();
  14517. }
  14518. #endif
  14519. #ifdef _WIN32
  14520. TEST(CleanupTest, WSACleanup) {
  14521. int ret = WSACleanup();
  14522. ASSERT_EQ(0, ret);
  14523. }
  14524. #endif
  14525. #ifndef CPPHTTPLIB_SSL_ENABLED
  14526. TEST(NoSSLSupport, SimpleInterface) {
  14527. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14528. }
  14529. #endif
  14530. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14531. TEST(InvalidScheme, SimpleInterface) {
  14532. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14533. }
  14534. #endif
  14535. TEST(NoScheme, SimpleInterface) {
  14536. Client cli("yahoo.com:80");
  14537. ASSERT_TRUE(cli.is_valid());
  14538. }
  14539. TEST(SendAPI, SimpleInterface_Online) {
  14540. Client cli("http://yahoo.com");
  14541. Request req;
  14542. req.method = "GET";
  14543. req.path = "/";
  14544. auto res = cli.send(req);
  14545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14546. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14547. }
  14548. TEST(SendAPI, WithParamsInRequest) {
  14549. Server svr;
  14550. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14551. EXPECT_TRUE(req.has_param("test"));
  14552. EXPECT_EQ("test_value", req.get_param_value("test"));
  14553. });
  14554. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14555. auto se = detail::scope_exit([&] {
  14556. svr.stop();
  14557. t.join();
  14558. ASSERT_FALSE(svr.is_running());
  14559. });
  14560. svr.wait_until_ready();
  14561. Client cli(HOST, PORT);
  14562. {
  14563. Request req;
  14564. req.method = "GET";
  14565. req.path = "/";
  14566. req.params.emplace("test", "test_value");
  14567. auto res = cli.send(req);
  14568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14569. }
  14570. {
  14571. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14573. }
  14574. }
  14575. TEST(ClientImplMethods, GetSocketTest) {
  14576. httplib::Server svr;
  14577. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14578. res.status = StatusCode::OK_200;
  14579. });
  14580. auto port = svr.bind_to_any_port("127.0.0.1");
  14581. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14582. auto se = detail::scope_exit([&] {
  14583. svr.stop();
  14584. thread.join();
  14585. ASSERT_FALSE(svr.is_running());
  14586. });
  14587. svr.wait_until_ready();
  14588. {
  14589. httplib::Client cli("127.0.0.1", port);
  14590. cli.set_keep_alive(true);
  14591. // Use the behavior of cpp-httplib of opening the connection
  14592. // only when the first request happens. If that changes,
  14593. // this test would be obsolete.
  14594. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14595. // This also implicitly tests the server. But other tests would fail much
  14596. // earlier than this one to be considered.
  14597. auto res = cli.Get("/");
  14598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14599. EXPECT_EQ(StatusCode::OK_200, res->status);
  14600. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14601. }
  14602. }
  14603. #ifdef CPPHTTPLIB_SSL_ENABLED
  14604. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14605. Client cli("http://yahoo.com");
  14606. auto res = cli.Get("/");
  14607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14608. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14609. cli.set_follow_location(true);
  14610. res = cli.Get("/");
  14611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14612. EXPECT_EQ(StatusCode::OK_200, res->status);
  14613. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14614. }
  14615. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14616. Client cli("https://yahoo.com");
  14617. auto res = cli.Get("/");
  14618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14619. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14620. cli.set_follow_location(true);
  14621. res = cli.Get("/");
  14622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14623. EXPECT_EQ(StatusCode::OK_200, res->status);
  14624. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14625. }
  14626. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14627. Client cli("https://yahoo.com");
  14628. auto res = cli.Get("/");
  14629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14630. ASSERT_FALSE(!res);
  14631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14632. ASSERT_FALSE(res == nullptr);
  14633. ASSERT_TRUE(res != nullptr);
  14634. EXPECT_EQ(Error::Success, res.error());
  14635. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14636. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14637. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14638. cli.set_follow_location(true);
  14639. res = cli.Get("/");
  14640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14641. EXPECT_EQ(Error::Success, res.error());
  14642. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14643. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14644. EXPECT_EQ(StatusCode::OK_200, res->status);
  14645. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14646. }
  14647. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14648. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14649. Client cli("https://cdnjs.cloudflare.com");
  14650. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14651. Headers{{"Accept-Encoding", "br"}});
  14652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14653. EXPECT_EQ(StatusCode::OK_200, res->status);
  14654. EXPECT_EQ(287630U, res->body.size());
  14655. EXPECT_EQ("application/javascript; charset=utf-8",
  14656. res->get_header_value("Content-Type"));
  14657. }
  14658. #endif
  14659. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14660. #undef REDIR_HOST // Silence compiler warning
  14661. #define REDIR_HOST "https://httpbingo.org"
  14662. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14663. Client cli(REDIR_HOST);
  14664. cli.set_follow_location(true);
  14665. auto res =
  14666. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14668. EXPECT_EQ(StatusCode::OK_200, res->status);
  14669. }
  14670. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14671. Client cli(REDIR_HOST);
  14672. cli.set_follow_location(true);
  14673. Params params;
  14674. params.emplace("url", "http://example.com");
  14675. params.emplace("status_code", "302");
  14676. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14678. EXPECT_EQ(StatusCode::OK_200, res->status);
  14679. }
  14680. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14681. Client cli(REDIR_HOST);
  14682. cli.set_follow_location(true);
  14683. Params params;
  14684. params.emplace("url", "http://example.com");
  14685. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14687. EXPECT_EQ(StatusCode::OK_200, res->status);
  14688. }
  14689. TEST(HttpToHttpsRedirectTest, CertFile) {
  14690. auto ssl_port = PORT + 1;
  14691. Server svr;
  14692. ASSERT_TRUE(svr.is_valid());
  14693. svr.Get("/index", [&](const Request &, Response &res) {
  14694. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14695. "/index");
  14696. svr.stop();
  14697. });
  14698. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14699. ASSERT_TRUE(ssl_svr.is_valid());
  14700. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14701. res.set_content("test", "text/plain");
  14702. ssl_svr.stop();
  14703. });
  14704. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14705. thread t2 =
  14706. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14707. auto se = detail::scope_exit([&] {
  14708. t2.join();
  14709. t.join();
  14710. ASSERT_FALSE(svr.is_running());
  14711. });
  14712. svr.wait_until_ready();
  14713. ssl_svr.wait_until_ready();
  14714. Client cli("127.0.0.1", PORT);
  14715. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14716. cli.enable_server_certificate_verification(true);
  14717. cli.set_follow_location(true);
  14718. cli.set_connection_timeout(30);
  14719. auto res = cli.Get("/index");
  14720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14721. ASSERT_EQ(StatusCode::OK_200, res->status);
  14722. }
  14723. TEST(SSLClientRedirectTest, CertFile) {
  14724. auto ssl_port = PORT + 1;
  14725. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14726. ASSERT_TRUE(ssl_svr1.is_valid());
  14727. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14728. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14729. "/index");
  14730. ssl_svr1.stop();
  14731. });
  14732. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14733. ASSERT_TRUE(ssl_svr2.is_valid());
  14734. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14735. res.set_content("test", "text/plain");
  14736. ssl_svr2.stop();
  14737. });
  14738. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14739. thread t2 =
  14740. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14741. auto se = detail::scope_exit([&] {
  14742. t2.join();
  14743. t.join();
  14744. ASSERT_FALSE(ssl_svr1.is_running());
  14745. });
  14746. ssl_svr1.wait_until_ready();
  14747. ssl_svr2.wait_until_ready();
  14748. SSLClient cli("127.0.0.1", PORT);
  14749. std::string cert;
  14750. read_file(SERVER_CERT2_FILE, cert);
  14751. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14752. cli.enable_server_certificate_verification(true);
  14753. cli.set_follow_location(true);
  14754. cli.set_connection_timeout(30);
  14755. auto res = cli.Get("/index");
  14756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14757. ASSERT_EQ(StatusCode::OK_200, res->status);
  14758. }
  14759. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14760. // another port, so the client follows it with a new client.
  14761. static Result GetThroughTlsRedirectToDifferentPort(
  14762. const std::function<void(SSLClient &)> &setup,
  14763. const char *target_cert = SERVER_CERT2_FILE,
  14764. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14765. auto ssl_port = PORT + 1;
  14766. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14767. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14768. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14769. "/index");
  14770. });
  14771. SSLServer ssl_svr2(target_cert, target_key);
  14772. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14773. res.set_content("test", "text/plain");
  14774. });
  14775. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14776. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14777. auto se = detail::scope_exit([&] {
  14778. ssl_svr2.stop();
  14779. ssl_svr1.stop();
  14780. t2.join();
  14781. t.join();
  14782. });
  14783. ssl_svr1.wait_until_ready();
  14784. ssl_svr2.wait_until_ready();
  14785. SSLClient cli("127.0.0.1", PORT);
  14786. cli.set_follow_location(true);
  14787. cli.set_connection_timeout(30);
  14788. setup(cli);
  14789. return cli.Get("/index");
  14790. }
  14791. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14792. auto calls = 0;
  14793. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14794. cli.enable_server_certificate_verification(false);
  14795. // Accept the first server only.
  14796. cli.set_session_verifier([&](tls::session_t) {
  14797. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14798. : SSLVerifierResponse::CertificateRejected;
  14799. });
  14800. });
  14801. EXPECT_FALSE(res);
  14802. EXPECT_EQ(2, calls);
  14803. }
  14804. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14805. std::string pinned;
  14806. auto res = GetThroughTlsRedirectToDifferentPort(
  14807. [&](SSLClient &cli) {
  14808. cli.enable_server_certificate_verification(false);
  14809. // Pin the first certificate seen.
  14810. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14811. if (pinned.empty()) { pinned = ctx.serial(); }
  14812. return ctx.serial() == pinned;
  14813. });
  14814. },
  14815. // A certificate other than the first server's.
  14816. SERVER_CERT_FILE);
  14817. EXPECT_FALSE(res);
  14818. EXPECT_FALSE(pinned.empty());
  14819. }
  14820. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14821. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14822. std::string cert;
  14823. read_file(SERVER_CERT2_FILE, cert);
  14824. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14825. });
  14826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14827. EXPECT_EQ(StatusCode::OK_200, res->status);
  14828. }
  14829. // The target's certificate is signed by the root CA, which the first server's
  14830. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14831. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14832. auto res = GetThroughTlsRedirectToDifferentPort(
  14833. [](SSLClient &cli) {
  14834. std::string root_ca, cert;
  14835. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14836. read_file(SERVER_CERT2_FILE, cert);
  14837. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14838. cli.load_ca_cert_store(cert.data(), cert.size());
  14839. cli.enable_server_hostname_verification(false);
  14840. },
  14841. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14843. EXPECT_EQ(StatusCode::OK_200, res->status);
  14844. }
  14845. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14846. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14847. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14848. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14849. auto res = GetThroughTlsRedirectToDifferentPort(
  14850. [](SSLClient &cli) {
  14851. std::string root_ca, cert;
  14852. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14853. read_file(SERVER_CERT2_FILE, cert);
  14854. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14855. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14856. cli.enable_server_hostname_verification(false);
  14857. },
  14858. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14859. ASSERT_FALSE(res);
  14860. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14861. }
  14862. #endif
  14863. #endif
  14864. #ifdef CPPHTTPLIB_SSL_ENABLED
  14865. // Test that set_ca_cert_store() skips system certs (consistent with
  14866. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14867. // should be trusted - system certs should NOT be loaded.
  14868. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14869. // Load a specific cert that is NOT a system CA cert
  14870. std::string cert;
  14871. read_file(SERVER_CERT2_FILE, cert);
  14872. SSLClient cli("google.com");
  14873. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14874. cli.enable_server_certificate_verification(true);
  14875. // This should FAIL because:
  14876. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14877. // 2. System certs should NOT be loaded when custom store is set
  14878. // If system certs WERE loaded, this would succeed
  14879. auto res = cli.Get("/");
  14880. ASSERT_FALSE(res);
  14881. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14882. }
  14883. // Same as above, but through the native store handle path. Regression test:
  14884. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14885. // merged system certs into the user-provided store.
  14886. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14887. std::string cert;
  14888. read_file(SERVER_CERT2_FILE, cert);
  14889. SSLClient cli("google.com");
  14890. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14891. cli.enable_server_certificate_verification(true);
  14892. auto res = cli.Get("/");
  14893. ASSERT_FALSE(res);
  14894. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14895. }
  14896. // A custom store set via the native handle must still verify a server whose
  14897. // cert it does contain.
  14898. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14899. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14900. ASSERT_TRUE(svr.is_valid());
  14901. svr.Get("/test", [&](const Request &, Response &res) {
  14902. res.set_content("test", "text/plain");
  14903. });
  14904. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14905. auto se = detail::scope_exit([&] {
  14906. svr.stop();
  14907. t.join();
  14908. ASSERT_FALSE(svr.is_running());
  14909. });
  14910. svr.wait_until_ready();
  14911. SSLClient cli("127.0.0.1", PORT);
  14912. std::string cert;
  14913. read_file(SERVER_CERT2_FILE, cert);
  14914. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14915. cli.enable_server_certificate_verification(true);
  14916. cli.set_connection_timeout(30);
  14917. auto res = cli.Get("/test");
  14918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14919. ASSERT_EQ(StatusCode::OK_200, res->status);
  14920. }
  14921. // CA certs loaded through the universal Client must be transferred to the
  14922. // client created internally for following an HTTPS redirect. Regression test:
  14923. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14924. // the CA data for redirect transfer.
  14925. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14926. auto ssl_port = PORT + 1;
  14927. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14928. ASSERT_TRUE(ssl_svr1.is_valid());
  14929. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14930. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14931. "/index");
  14932. });
  14933. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14934. ASSERT_TRUE(ssl_svr2.is_valid());
  14935. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14936. res.set_content("test", "text/plain");
  14937. });
  14938. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14939. thread t2 =
  14940. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14941. auto se = detail::scope_exit([&] {
  14942. ssl_svr2.stop();
  14943. ssl_svr1.stop();
  14944. t2.join();
  14945. t.join();
  14946. ASSERT_FALSE(ssl_svr1.is_running());
  14947. });
  14948. ssl_svr1.wait_until_ready();
  14949. ssl_svr2.wait_until_ready();
  14950. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14951. std::string cert;
  14952. read_file(SERVER_CERT2_FILE, cert);
  14953. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14954. cli.enable_server_certificate_verification(true);
  14955. cli.set_follow_location(true);
  14956. cli.set_connection_timeout(30);
  14957. auto res = cli.Get("/index");
  14958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14959. ASSERT_EQ(StatusCode::OK_200, res->status);
  14960. }
  14961. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14962. // so a host signed by a system CA verifies even though a custom CA is set
  14963. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14964. std::string cert;
  14965. read_file(SERVER_CERT2_FILE, cert);
  14966. SSLClient cli("google.com");
  14967. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14968. cli.enable_system_ca(true);
  14969. cli.enable_server_certificate_verification(true);
  14970. auto res = cli.Get("/");
  14971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14972. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14973. }
  14974. // The custom CA remains effective when combined with the system CA
  14975. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14976. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14977. ASSERT_TRUE(svr.is_valid());
  14978. svr.Get("/test", [&](const Request &, Response &res) {
  14979. res.set_content("test", "text/plain");
  14980. });
  14981. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14982. auto se = detail::scope_exit([&] {
  14983. svr.stop();
  14984. t.join();
  14985. ASSERT_FALSE(svr.is_running());
  14986. });
  14987. svr.wait_until_ready();
  14988. SSLClient cli("127.0.0.1", PORT);
  14989. std::string cert;
  14990. read_file(SERVER_CERT2_FILE, cert);
  14991. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14992. cli.enable_system_ca(true);
  14993. cli.enable_server_certificate_verification(true);
  14994. cli.set_connection_timeout(30);
  14995. auto res = cli.Get("/test");
  14996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14997. ASSERT_EQ(StatusCode::OK_200, res->status);
  14998. }
  14999. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15000. // skip chain verification entirely (only the certificate identity was
  15001. // checked), so a server presenting an untrusted certificate with a matching
  15002. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15003. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15004. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15005. ASSERT_TRUE(svr.is_valid());
  15006. svr.Get("/test", [&](const Request &, Response &res) {
  15007. res.set_content("test", "text/plain");
  15008. });
  15009. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15010. auto se = detail::scope_exit([&] {
  15011. svr.stop();
  15012. t.join();
  15013. ASSERT_FALSE(svr.is_running());
  15014. });
  15015. svr.wait_until_ready();
  15016. SSLClient cli("127.0.0.1", PORT);
  15017. std::string cert;
  15018. // A trusted CA that did not sign the server certificate. The server cert
  15019. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15020. // this connection.
  15021. read_file(CLIENT_CA_CERT_FILE, cert);
  15022. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15023. cli.enable_server_certificate_verification(true);
  15024. cli.set_connection_timeout(30);
  15025. auto res = cli.Get("/test");
  15026. ASSERT_FALSE(res);
  15027. }
  15028. // enable_system_ca(false) prevents system CA loading entirely
  15029. TEST(SSLClientTest, DisableSystemCa_Online) {
  15030. SSLClient cli("google.com");
  15031. cli.enable_system_ca(false);
  15032. cli.enable_server_certificate_verification(true);
  15033. auto res = cli.Get("/");
  15034. ASSERT_FALSE(res);
  15035. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15036. // itself when the CA chain is empty
  15037. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15038. res.error() == Error::SSLConnection);
  15039. }
  15040. // The universal Client forwards enable_system_ca()
  15041. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15042. std::string cert;
  15043. read_file(SERVER_CERT2_FILE, cert);
  15044. Client cli("https://google.com");
  15045. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15046. cli.enable_system_ca(true);
  15047. cli.enable_server_certificate_verification(true);
  15048. auto res = cli.Get("/");
  15049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15050. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15051. }
  15052. // The system CA policy must carry over to the client created internally for
  15053. // following a cross-host HTTPS redirect
  15054. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15055. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15056. ASSERT_TRUE(svr.is_valid());
  15057. svr.Get("/index", [&](const Request &, Response &res) {
  15058. res.set_redirect("https://www.google.com/");
  15059. });
  15060. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15061. auto se = detail::scope_exit([&] {
  15062. svr.stop();
  15063. t.join();
  15064. ASSERT_FALSE(svr.is_running());
  15065. });
  15066. svr.wait_until_ready();
  15067. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15068. std::string cert;
  15069. read_file(SERVER_CERT2_FILE, cert);
  15070. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15071. cli.enable_system_ca(true);
  15072. cli.enable_server_certificate_verification(true);
  15073. cli.set_follow_location(true);
  15074. cli.set_connection_timeout(30);
  15075. // Receiving any response proves the redirect client completed the TLS
  15076. // handshake with a system-CA-signed host
  15077. auto res = cli.Get("/index");
  15078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15079. }
  15080. TEST(MultipartFormDataTest, LargeData) {
  15081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15082. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15083. const ContentReader &content_reader) {
  15084. if (req.is_multipart_form_data()) {
  15085. std::vector<FormData> items;
  15086. content_reader(
  15087. [&](const FormData &file) {
  15088. items.push_back(file);
  15089. return true;
  15090. },
  15091. [&](const char *data, size_t data_length) {
  15092. items.back().content.append(data, data_length);
  15093. return true;
  15094. });
  15095. EXPECT_TRUE(std::string(items[0].name) == "document");
  15096. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15097. EXPECT_TRUE(items[0].filename == "2MB_data");
  15098. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15099. EXPECT_TRUE(items[1].name == "hello");
  15100. EXPECT_TRUE(items[1].content == "world");
  15101. EXPECT_TRUE(items[1].filename == "");
  15102. EXPECT_TRUE(items[1].content_type == "");
  15103. } else {
  15104. std::string body;
  15105. content_reader([&](const char *data, size_t data_length) {
  15106. body.append(data, data_length);
  15107. return true;
  15108. });
  15109. }
  15110. });
  15111. auto port = svr.bind_to_any_port(HOST);
  15112. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15113. auto se = detail::scope_exit([&] {
  15114. svr.stop();
  15115. t.join();
  15116. ASSERT_FALSE(svr.is_running());
  15117. });
  15118. svr.wait_until_ready();
  15119. {
  15120. std::string data(1024 * 1024 * 2, '.');
  15121. std::stringstream buffer;
  15122. buffer << data;
  15123. SSLClient cli(HOST, port);
  15124. cli.enable_server_certificate_verification(false);
  15125. UploadFormDataItems items{
  15126. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15127. {"hello", "world", "", ""},
  15128. };
  15129. auto res = cli.Post("/post", items);
  15130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15131. ASSERT_EQ(StatusCode::OK_200, res->status);
  15132. }
  15133. }
  15134. TEST(MultipartFormDataTest, DataProviderItems) {
  15135. std::random_device seed_gen;
  15136. std::mt19937 random(seed_gen());
  15137. std::string rand1;
  15138. rand1.resize(1000);
  15139. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15140. std::string rand2;
  15141. rand2.resize(3000);
  15142. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15144. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15145. const ContentReader &content_reader) {
  15146. ASSERT_FALSE(req.is_multipart_form_data());
  15147. std::string body;
  15148. content_reader([&](const char *data, size_t data_length) {
  15149. body.append(data, data_length);
  15150. return true;
  15151. });
  15152. EXPECT_EQ(body, "");
  15153. });
  15154. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15155. const ContentReader &content_reader) {
  15156. ASSERT_TRUE(req.is_multipart_form_data());
  15157. std::vector<FormData> items;
  15158. content_reader(
  15159. [&](const FormData &file) {
  15160. items.push_back(file);
  15161. return true;
  15162. },
  15163. [&](const char *data, size_t data_length) {
  15164. items.back().content.append(data, data_length);
  15165. return true;
  15166. });
  15167. ASSERT_TRUE(items.size() == 2);
  15168. EXPECT_EQ(std::string(items[0].name), "name1");
  15169. EXPECT_EQ(items[0].content, "Testing123");
  15170. EXPECT_EQ(items[0].filename, "filename1");
  15171. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15172. EXPECT_EQ(items[1].name, "name2");
  15173. EXPECT_EQ(items[1].content, "Testing456");
  15174. EXPECT_EQ(items[1].filename, "");
  15175. EXPECT_EQ(items[1].content_type, "");
  15176. });
  15177. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15178. const ContentReader &content_reader) {
  15179. ASSERT_TRUE(req.is_multipart_form_data());
  15180. std::vector<FormData> items;
  15181. content_reader(
  15182. [&](const FormData &file) {
  15183. items.push_back(file);
  15184. return true;
  15185. },
  15186. [&](const char *data, size_t data_length) {
  15187. items.back().content.append(data, data_length);
  15188. return true;
  15189. });
  15190. ASSERT_TRUE(items.size() == 2);
  15191. EXPECT_EQ(items[0].name, "name3");
  15192. EXPECT_EQ(items[0].content, rand1);
  15193. EXPECT_EQ(items[0].filename, "filename3");
  15194. EXPECT_EQ(items[0].content_type, "");
  15195. EXPECT_EQ(items[1].name, "name4");
  15196. EXPECT_EQ(items[1].content, rand2);
  15197. EXPECT_EQ(items[1].filename, "filename4");
  15198. EXPECT_EQ(items[1].content_type, "");
  15199. });
  15200. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15201. const ContentReader &content_reader) {
  15202. ASSERT_TRUE(req.is_multipart_form_data());
  15203. std::vector<FormData> items;
  15204. content_reader(
  15205. [&](const FormData &file) {
  15206. items.push_back(file);
  15207. return true;
  15208. },
  15209. [&](const char *data, size_t data_length) {
  15210. items.back().content.append(data, data_length);
  15211. return true;
  15212. });
  15213. ASSERT_TRUE(items.size() == 4);
  15214. EXPECT_EQ(std::string(items[0].name), "name1");
  15215. EXPECT_EQ(items[0].content, "Testing123");
  15216. EXPECT_EQ(items[0].filename, "filename1");
  15217. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15218. EXPECT_EQ(items[1].name, "name2");
  15219. EXPECT_EQ(items[1].content, "Testing456");
  15220. EXPECT_EQ(items[1].filename, "");
  15221. EXPECT_EQ(items[1].content_type, "");
  15222. EXPECT_EQ(items[2].name, "name3");
  15223. EXPECT_EQ(items[2].content, rand1);
  15224. EXPECT_EQ(items[2].filename, "filename3");
  15225. EXPECT_EQ(items[2].content_type, "");
  15226. EXPECT_EQ(items[3].name, "name4");
  15227. EXPECT_EQ(items[3].content, rand2);
  15228. EXPECT_EQ(items[3].filename, "filename4");
  15229. EXPECT_EQ(items[3].content_type, "");
  15230. });
  15231. auto port = svr.bind_to_any_port("localhost");
  15232. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15233. auto se = detail::scope_exit([&] {
  15234. svr.stop();
  15235. t.join();
  15236. ASSERT_FALSE(svr.is_running());
  15237. });
  15238. svr.wait_until_ready();
  15239. {
  15240. SSLClient cli("localhost", port);
  15241. cli.enable_server_certificate_verification(false);
  15242. UploadFormDataItems items{
  15243. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15244. {"name2", "Testing456", "", ""}, // not a file
  15245. };
  15246. {
  15247. auto res = cli.Post("/post-none", {}, {}, {});
  15248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15249. ASSERT_EQ(StatusCode::OK_200, res->status);
  15250. }
  15251. FormDataProviderItems providers;
  15252. {
  15253. auto res =
  15254. cli.Post("/post-items", {}, items, providers); // empty providers
  15255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15256. ASSERT_EQ(StatusCode::OK_200, res->status);
  15257. }
  15258. providers.push_back({"name3",
  15259. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15260. // test the offset is given correctly at each step
  15261. if (!offset)
  15262. sink.os.write(rand1.data(), 30);
  15263. else if (offset == 30)
  15264. sink.os.write(rand1.data() + 30, 300);
  15265. else if (offset == 330)
  15266. sink.os.write(rand1.data() + 330, 670);
  15267. else if (offset == rand1.size())
  15268. sink.done();
  15269. return true;
  15270. },
  15271. "filename3",
  15272. {}});
  15273. providers.push_back({"name4",
  15274. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15275. // test the offset is given correctly at each step
  15276. if (!offset)
  15277. sink.os.write(rand2.data(), 2000);
  15278. else if (offset == 2000)
  15279. sink.os.write(rand2.data() + 2000, 1);
  15280. else if (offset == 2001)
  15281. sink.os.write(rand2.data() + 2001, 999);
  15282. else if (offset == rand2.size())
  15283. sink.done();
  15284. return true;
  15285. },
  15286. "filename4",
  15287. {}});
  15288. {
  15289. auto res = cli.Post("/post-providers", {}, {}, providers);
  15290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15291. ASSERT_EQ(StatusCode::OK_200, res->status);
  15292. }
  15293. {
  15294. auto res = cli.Post("/post-both", {}, items, providers);
  15295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15296. ASSERT_EQ(StatusCode::OK_200, res->status);
  15297. }
  15298. }
  15299. }
  15300. TEST(MultipartFormDataTest, BadHeader) {
  15301. Server svr;
  15302. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15303. res.set_content("ok", "text/plain");
  15304. });
  15305. thread t = thread([&] { svr.listen(HOST, PORT); });
  15306. auto se = detail::scope_exit([&] {
  15307. svr.stop();
  15308. t.join();
  15309. ASSERT_FALSE(svr.is_running());
  15310. });
  15311. svr.wait_until_ready();
  15312. const std::string body =
  15313. "This is the preamble. It is to be ignored, though it\r\n"
  15314. "is a handy place for composition agents to include an\r\n"
  15315. "explanatory note to non-MIME conformant readers.\r\n"
  15316. "\r\n"
  15317. "\r\n"
  15318. "--simple boundary\r\n"
  15319. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15320. ": BAD...\r\n"
  15321. "\r\n"
  15322. "value1\r\n"
  15323. "--simple boundary\r\n"
  15324. "Content-Disposition: form-data; name=\"field2\"; "
  15325. "filename=\"example.txt\"\r\n"
  15326. "\r\n"
  15327. "value2\r\n"
  15328. "--simple boundary--\r\n"
  15329. "This is the epilogue. It is also to be ignored.\r\n";
  15330. std::string content_type =
  15331. R"(multipart/form-data; boundary="simple boundary")";
  15332. Client cli(HOST, PORT);
  15333. auto res = cli.Post("/post", body, content_type.c_str());
  15334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15335. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15336. }
  15337. TEST(MultipartFormDataTest, WithPreamble) {
  15338. Server svr;
  15339. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15340. res.set_content("ok", "text/plain");
  15341. });
  15342. thread t = thread([&] { svr.listen(HOST, PORT); });
  15343. auto se = detail::scope_exit([&] {
  15344. svr.stop();
  15345. t.join();
  15346. ASSERT_FALSE(svr.is_running());
  15347. });
  15348. svr.wait_until_ready();
  15349. const std::string body =
  15350. "This is the preamble. It is to be ignored, though it\r\n"
  15351. "is a handy place for composition agents to include an\r\n"
  15352. "explanatory note to non-MIME conformant readers.\r\n"
  15353. "\r\n"
  15354. "\r\n"
  15355. "--simple boundary\r\n"
  15356. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15357. "\r\n"
  15358. "value1\r\n"
  15359. "--simple boundary\r\n"
  15360. "Content-Disposition: form-data; name=\"field2\"; "
  15361. "filename=\"example.txt\"\r\n"
  15362. "\r\n"
  15363. "value2\r\n"
  15364. "--simple boundary--\r\n"
  15365. "This is the epilogue. It is also to be ignored.\r\n";
  15366. std::string content_type =
  15367. R"(multipart/form-data; boundary="simple boundary")";
  15368. Client cli(HOST, PORT);
  15369. auto res = cli.Post("/post", body, content_type.c_str());
  15370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15371. EXPECT_EQ(StatusCode::OK_200, res->status);
  15372. }
  15373. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15375. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15376. const ContentReader &content_reader) {
  15377. if (req.is_multipart_form_data()) {
  15378. std::vector<FormData> items;
  15379. content_reader(
  15380. [&](const FormData &file) {
  15381. items.push_back(file);
  15382. return true;
  15383. },
  15384. [&](const char *data, size_t data_length) {
  15385. items.back().content.append(data, data_length);
  15386. return true;
  15387. });
  15388. EXPECT_TRUE(std::string(items[0].name) == "document");
  15389. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15390. EXPECT_TRUE(items[0].filename == "2MB_data");
  15391. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15392. EXPECT_TRUE(items[1].name == "hello");
  15393. EXPECT_TRUE(items[1].content == "world");
  15394. EXPECT_TRUE(items[1].filename == "");
  15395. EXPECT_TRUE(items[1].content_type == "");
  15396. } else {
  15397. std::string body;
  15398. content_reader([&](const char *data, size_t data_length) {
  15399. body.append(data, data_length);
  15400. return true;
  15401. });
  15402. }
  15403. });
  15404. auto port = svr.bind_to_any_port("localhost");
  15405. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15406. auto se = detail::scope_exit([&] {
  15407. svr.stop();
  15408. t.join();
  15409. ASSERT_FALSE(svr.is_running());
  15410. });
  15411. svr.wait_until_ready();
  15412. {
  15413. std::string data(1024 * 1024 * 2, '.');
  15414. std::stringstream buffer;
  15415. buffer << data;
  15416. SSLClient cli("localhost", port);
  15417. cli.enable_server_certificate_verification(false);
  15418. UploadFormDataItems items{
  15419. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15420. {"hello", "world", "", ""},
  15421. };
  15422. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15424. ASSERT_EQ(StatusCode::OK_200, res->status);
  15425. }
  15426. }
  15427. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15428. std::string data(1024 * 1024 * 2, '&');
  15429. std::stringstream buffer;
  15430. buffer << data;
  15431. Client cli("https://localhost:8080");
  15432. UploadFormDataItems items{
  15433. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15434. {"hello", "world", "", ""},
  15435. };
  15436. for (const char &c : " \t\r\n") {
  15437. auto res =
  15438. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15439. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15440. ASSERT_FALSE(res);
  15441. }
  15442. }
  15443. TEST(MultipartFormDataTest, PutFormData) {
  15444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15445. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15446. const ContentReader &content_reader) {
  15447. if (req.is_multipart_form_data()) {
  15448. std::vector<FormData> items;
  15449. content_reader(
  15450. [&](const FormData &file) {
  15451. items.push_back(file);
  15452. return true;
  15453. },
  15454. [&](const char *data, size_t data_length) {
  15455. items.back().content.append(data, data_length);
  15456. return true;
  15457. });
  15458. EXPECT_TRUE(std::string(items[0].name) == "document");
  15459. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15460. EXPECT_TRUE(items[0].filename == "2MB_data");
  15461. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15462. EXPECT_TRUE(items[1].name == "hello");
  15463. EXPECT_TRUE(items[1].content == "world");
  15464. EXPECT_TRUE(items[1].filename == "");
  15465. EXPECT_TRUE(items[1].content_type == "");
  15466. } else {
  15467. std::string body;
  15468. content_reader([&](const char *data, size_t data_length) {
  15469. body.append(data, data_length);
  15470. return true;
  15471. });
  15472. }
  15473. });
  15474. auto port = svr.bind_to_any_port("localhost");
  15475. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15476. auto se = detail::scope_exit([&] {
  15477. svr.stop();
  15478. t.join();
  15479. ASSERT_FALSE(svr.is_running());
  15480. });
  15481. svr.wait_until_ready();
  15482. {
  15483. std::string data(1024 * 1024 * 2, '&');
  15484. std::stringstream buffer;
  15485. buffer << data;
  15486. SSLClient cli("localhost", port);
  15487. cli.enable_server_certificate_verification(false);
  15488. UploadFormDataItems items{
  15489. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15490. {"hello", "world", "", ""},
  15491. };
  15492. auto res = cli.Put("/put", items);
  15493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15494. ASSERT_EQ(StatusCode::OK_200, res->status);
  15495. }
  15496. }
  15497. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15498. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15499. svr.Put("/put_customboundary",
  15500. [&](const Request &req, const Response & /*res*/,
  15501. const ContentReader &content_reader) {
  15502. if (req.is_multipart_form_data()) {
  15503. std::vector<FormData> items;
  15504. content_reader(
  15505. [&](const FormData &file) {
  15506. items.push_back(file);
  15507. return true;
  15508. },
  15509. [&](const char *data, size_t data_length) {
  15510. items.back().content.append(data, data_length);
  15511. return true;
  15512. });
  15513. EXPECT_TRUE(std::string(items[0].name) == "document");
  15514. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15515. EXPECT_TRUE(items[0].filename == "2MB_data");
  15516. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15517. EXPECT_TRUE(items[1].name == "hello");
  15518. EXPECT_TRUE(items[1].content == "world");
  15519. EXPECT_TRUE(items[1].filename == "");
  15520. EXPECT_TRUE(items[1].content_type == "");
  15521. } else {
  15522. std::string body;
  15523. content_reader([&](const char *data, size_t data_length) {
  15524. body.append(data, data_length);
  15525. return true;
  15526. });
  15527. }
  15528. });
  15529. auto port = svr.bind_to_any_port("localhost");
  15530. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15531. auto se = detail::scope_exit([&] {
  15532. svr.stop();
  15533. t.join();
  15534. ASSERT_FALSE(svr.is_running());
  15535. });
  15536. svr.wait_until_ready();
  15537. {
  15538. std::string data(1024 * 1024 * 2, '&');
  15539. std::stringstream buffer;
  15540. buffer << data;
  15541. SSLClient cli("localhost", port);
  15542. cli.enable_server_certificate_verification(false);
  15543. UploadFormDataItems items{
  15544. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15545. {"hello", "world", "", ""},
  15546. };
  15547. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15549. ASSERT_EQ(StatusCode::OK_200, res->status);
  15550. }
  15551. }
  15552. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15553. std::string data(1024 * 1024 * 2, '&');
  15554. std::stringstream buffer;
  15555. buffer << data;
  15556. Client cli("https://localhost:8080");
  15557. cli.enable_server_certificate_verification(false);
  15558. UploadFormDataItems items{
  15559. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15560. {"hello", "world", "", ""},
  15561. };
  15562. for (const char &c : " \t\r\n") {
  15563. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15564. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15565. ASSERT_FALSE(res);
  15566. }
  15567. }
  15568. TEST(MultipartFormDataTest, AlternateFilename) {
  15569. auto handled = false;
  15570. Server svr;
  15571. svr.Post("/test", [&](const Request &req, Response &res) {
  15572. ASSERT_EQ(2u, req.form.files.size());
  15573. ASSERT_EQ(1u, req.form.fields.size());
  15574. // Test files
  15575. const auto &file1 = req.form.get_file("file1");
  15576. ASSERT_EQ("file1", file1.name);
  15577. ASSERT_EQ("A.txt", file1.filename);
  15578. ASSERT_EQ("text/plain", file1.content_type);
  15579. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15580. const auto &file2 = req.form.get_file("file2");
  15581. ASSERT_EQ("file2", file2.name);
  15582. ASSERT_EQ("a.html", file2.filename);
  15583. ASSERT_EQ("text/html", file2.content_type);
  15584. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15585. file2.content);
  15586. // Test text field
  15587. const auto &text = req.form.get_field("text");
  15588. ASSERT_EQ("text default", text);
  15589. res.set_content("ok", "text/plain");
  15590. handled = true;
  15591. });
  15592. thread t = thread([&] { svr.listen(HOST, PORT); });
  15593. auto se = detail::scope_exit([&] {
  15594. svr.stop();
  15595. t.join();
  15596. ASSERT_FALSE(svr.is_running());
  15597. ASSERT_TRUE(handled);
  15598. });
  15599. svr.wait_until_ready();
  15600. auto req = "POST /test HTTP/1.1\r\n"
  15601. "Host: localhost\r\n"
  15602. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15603. "Content-Length: 399\r\n"
  15604. "\r\n"
  15605. "----------\r\n"
  15606. "Content-Disposition: form-data; name=\"text\"\r\n"
  15607. "\r\n"
  15608. "text default\r\n"
  15609. "----------\r\n"
  15610. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15611. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15612. "Content-Type: text/plain\r\n"
  15613. "\r\n"
  15614. "Content of a.txt.\r\n"
  15615. "\r\n"
  15616. "----------\r\n"
  15617. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15618. "\"a.html\"\r\n"
  15619. "Content-Type: text/html\r\n"
  15620. "\r\n"
  15621. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15622. "\r\n"
  15623. "------------\r\n";
  15624. ASSERT_TRUE(send_request(1, req));
  15625. }
  15626. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15627. auto handled = false;
  15628. Server svr;
  15629. svr.Post("/test", [&](const Request &req, Response &res) {
  15630. // Case-insensitive "utf-8''" prefix with a long value
  15631. const auto &file = req.form.get_file("file1");
  15632. ASSERT_EQ("file1", file.name);
  15633. // 8000 chars exercises both the Content-Disposition parser and the
  15634. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15635. // Prior to the fix, std::regex_match on this header would cause O(N)
  15636. // stack recursion in libstdc++, leading to SIGSEGV.
  15637. std::string expected_filename(8000, 'A');
  15638. ASSERT_EQ(expected_filename, file.filename);
  15639. res.set_content("ok", "text/plain");
  15640. handled = true;
  15641. });
  15642. thread t = thread([&] { svr.listen(HOST, PORT); });
  15643. auto se = detail::scope_exit([&] {
  15644. svr.stop();
  15645. t.join();
  15646. ASSERT_FALSE(svr.is_running());
  15647. ASSERT_TRUE(handled);
  15648. });
  15649. svr.wait_until_ready();
  15650. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15651. // Regression test for GHSA-qq6v-r583-3h69
  15652. std::string long_filename(8000, 'A');
  15653. std::string body = "----------\r\n"
  15654. "Content-Disposition: form-data; name=\"file1\"; "
  15655. "filename*=\"Utf-8''" +
  15656. long_filename +
  15657. "\"\r\n"
  15658. "\r\n"
  15659. "hello\r\n"
  15660. "------------\r\n";
  15661. auto req = "POST /test HTTP/1.1\r\n"
  15662. "Host: localhost\r\n"
  15663. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15664. "Content-Length: " +
  15665. std::to_string(body.size()) + "\r\n\r\n" + body;
  15666. ASSERT_TRUE(send_request(1, req));
  15667. }
  15668. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15669. auto handled = false;
  15670. Server svr;
  15671. svr.Post("/test", [&](const Request &req, Response &) {
  15672. ASSERT_EQ(2u, req.form.fields.size());
  15673. const auto &text1 = req.form.get_field("text1");
  15674. ASSERT_EQ("text1", text1);
  15675. const auto &text2 = req.form.get_field("text2");
  15676. ASSERT_EQ("text2", text2);
  15677. handled = true;
  15678. });
  15679. thread t = thread([&] { svr.listen(HOST, PORT); });
  15680. auto se = detail::scope_exit([&] {
  15681. svr.stop();
  15682. t.join();
  15683. ASSERT_FALSE(svr.is_running());
  15684. ASSERT_TRUE(handled);
  15685. });
  15686. svr.wait_until_ready();
  15687. auto req = "POST /test HTTP/1.1\r\n"
  15688. "Host: localhost\r\n"
  15689. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15690. "Content-Length: 146\r\n"
  15691. "\r\n----------\r\n"
  15692. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15693. "\r\n"
  15694. "text1"
  15695. "\r\n----------\r\n"
  15696. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15697. "\r\n"
  15698. "text2"
  15699. "\r\n------------";
  15700. std::string response;
  15701. ASSERT_TRUE(send_request(1, req, &response));
  15702. ASSERT_EQ("200", response.substr(9, 3));
  15703. }
  15704. TEST(MultipartFormDataTest, ContentLength) {
  15705. auto handled = false;
  15706. Server svr;
  15707. svr.Post("/test", [&](const Request &req, Response &) {
  15708. ASSERT_EQ(2u, req.form.fields.size());
  15709. const auto &text1 = req.form.get_field("text1");
  15710. ASSERT_EQ("text1", text1);
  15711. const auto &text2 = req.form.get_field("text2");
  15712. ASSERT_EQ("text2", text2);
  15713. handled = true;
  15714. });
  15715. thread t = thread([&] { svr.listen(HOST, PORT); });
  15716. auto se = detail::scope_exit([&] {
  15717. svr.stop();
  15718. t.join();
  15719. ASSERT_FALSE(svr.is_running());
  15720. ASSERT_TRUE(handled);
  15721. });
  15722. svr.wait_until_ready();
  15723. auto req = "POST /test HTTP/1.1\r\n"
  15724. "Host: localhost\r\n"
  15725. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15726. "Content-Length: 167\r\n"
  15727. "\r\n----------\r\n"
  15728. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15729. "Content-Length: 5\r\n"
  15730. "\r\n"
  15731. "text1"
  15732. "\r\n----------\r\n"
  15733. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15734. "\r\n"
  15735. "text2"
  15736. "\r\n------------\r\n";
  15737. std::string response;
  15738. ASSERT_TRUE(send_request(1, req, &response));
  15739. ASSERT_EQ("200", response.substr(9, 3));
  15740. }
  15741. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15742. auto handled = false;
  15743. Server svr;
  15744. svr.Post("/test", [&](const Request &req, Response &) {
  15745. ASSERT_EQ(2u, req.form.fields.size());
  15746. const auto &text1 = req.form.get_field("text1");
  15747. ASSERT_EQ("text1", text1);
  15748. // TODO: Add header access for text fields if needed
  15749. const auto &text2 = req.form.get_field("text2");
  15750. ASSERT_EQ("text2", text2);
  15751. // TODO: Header access for text fields needs to be implemented
  15752. // auto &headers = it->second.headers;
  15753. // ASSERT_EQ(3U, headers.size());
  15754. // auto custom_header = headers.find("x-whatever");
  15755. // ASSERT_TRUE(custom_header != headers.end());
  15756. // ASSERT_NE("customvalue", custom_header->second);
  15757. // ASSERT_EQ("CustomValue", custom_header->second);
  15758. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15759. handled = true;
  15760. });
  15761. thread t = thread([&] { svr.listen(HOST, PORT); });
  15762. auto se = detail::scope_exit([&] {
  15763. svr.stop();
  15764. t.join();
  15765. ASSERT_FALSE(svr.is_running());
  15766. ASSERT_TRUE(handled);
  15767. });
  15768. svr.wait_until_ready();
  15769. auto req = "POST /test HTTP/1.1\r\n"
  15770. "Host: localhost\r\n"
  15771. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15772. "Content-Length: 232\r\n"
  15773. "\r\n----------\r\n"
  15774. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15775. "Content-Length: 5\r\n"
  15776. "X-Test: 1\r\n"
  15777. "\r\n"
  15778. "text1"
  15779. "\r\n----------\r\n"
  15780. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15781. "Content-Type: text/plain\r\n"
  15782. "X-Whatever: CustomValue\r\n"
  15783. "\r\n"
  15784. "text2"
  15785. "\r\n------------\r\n"
  15786. "That should be disregarded. Not even read";
  15787. std::string response;
  15788. ASSERT_TRUE(send_request(1, req, &response));
  15789. ASSERT_EQ("200", response.substr(9, 3));
  15790. }
  15791. TEST(MultipartFormDataTest, LargeHeader) {
  15792. auto handled = false;
  15793. Server svr;
  15794. svr.Post("/test", [&](const Request &req, Response &) {
  15795. ASSERT_EQ(1u, req.form.fields.size());
  15796. const auto &text = req.form.get_field("name1");
  15797. ASSERT_EQ("text1", text);
  15798. handled = true;
  15799. });
  15800. thread t = thread([&] { svr.listen(HOST, PORT); });
  15801. auto se = detail::scope_exit([&] {
  15802. svr.stop();
  15803. t.join();
  15804. ASSERT_FALSE(svr.is_running());
  15805. ASSERT_TRUE(handled);
  15806. });
  15807. svr.wait_until_ready();
  15808. auto boundary = std::string("cpp-httplib-multipart-data");
  15809. std::string content = "--" + boundary +
  15810. "\r\n"
  15811. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15812. "\r\n"
  15813. "text1\r\n"
  15814. "--" +
  15815. boundary + "--\r\n";
  15816. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15817. "Host: localhost\r\n"
  15818. "Content-Type: multipart/form-data;boundary=" +
  15819. boundary +
  15820. "\r\n"
  15821. "Content-Length: " +
  15822. std::to_string(content.size()) +
  15823. "\r\n"
  15824. "Dummy-Header: ";
  15825. std::string header_suffix = "\r\n"
  15826. "\r\n";
  15827. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15828. size_t header_dummy_size =
  15829. read_buff_size -
  15830. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15831. auto header_dummy = std::string(header_dummy_size, '@');
  15832. auto req = header_prefix + header_dummy + header_suffix + content;
  15833. std::string response;
  15834. ASSERT_TRUE(send_request(1, req, &response));
  15835. ASSERT_EQ("200", response.substr(9, 3));
  15836. }
  15837. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15838. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15839. // (not chunked Transfer-Encoding) after the streaming refactor.
  15840. auto handled = false;
  15841. Server svr;
  15842. svr.Post("/upload", [&](const Request &req, Response &res) {
  15843. auto cl_it = req.headers.find("Content-Length");
  15844. EXPECT_TRUE(cl_it != req.headers.end());
  15845. auto te_it = req.headers.find("Transfer-Encoding");
  15846. EXPECT_TRUE(te_it == req.headers.end());
  15847. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15848. res.set_content("ok", "text/plain");
  15849. handled = true;
  15850. });
  15851. auto port = svr.bind_to_any_port(HOST);
  15852. auto t = thread([&] { svr.listen_after_bind(); });
  15853. auto se = detail::scope_exit([&] {
  15854. svr.stop();
  15855. t.join();
  15856. ASSERT_FALSE(svr.is_running());
  15857. ASSERT_TRUE(handled);
  15858. });
  15859. svr.wait_until_ready();
  15860. UploadFormDataItems items = {
  15861. {"field1", "hello", "", "text/plain"},
  15862. {"file1", "world", "test.txt", "application/octet-stream"},
  15863. };
  15864. Client cli(HOST, port);
  15865. auto res = cli.Post("/upload", {}, items);
  15866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15867. EXPECT_EQ(StatusCode::OK_200, res->status);
  15868. }
  15869. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15870. // Verify that make_multipart_content_provider coalesces many small segments
  15871. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15872. constexpr size_t kItemCount = 1000;
  15873. UploadFormDataItems items;
  15874. items.reserve(kItemCount);
  15875. for (size_t i = 0; i < kItemCount; i++) {
  15876. items.push_back(
  15877. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15878. }
  15879. const std::string boundary = "----test-boundary";
  15880. auto content_length = detail::get_multipart_content_length(items, boundary);
  15881. auto provider = detail::make_multipart_content_provider(items, boundary);
  15882. // Drive the provider the same way write_content_with_progress does
  15883. size_t write_count = 0;
  15884. size_t total_bytes = 0;
  15885. DataSink sink;
  15886. size_t offset = 0;
  15887. sink.write = [&](const char *d, size_t l) -> bool {
  15888. (void)d;
  15889. write_count++;
  15890. total_bytes += l;
  15891. offset += l;
  15892. return true;
  15893. };
  15894. sink.is_writable = []() -> bool { return true; };
  15895. while (offset < content_length) {
  15896. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15897. }
  15898. EXPECT_EQ(content_length, total_bytes);
  15899. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15900. // With buffering into 64KB blocks, write_count should be much smaller.
  15901. auto segment_count = 3 * kItemCount + 1;
  15902. EXPECT_LT(write_count, segment_count / 10);
  15903. }
  15904. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15905. // Integration test: send many UploadFormDataItems and verify the server
  15906. // receives all of them correctly (#2410).
  15907. constexpr size_t kItemCount = 500;
  15908. auto handled = false;
  15909. Server svr;
  15910. svr.Post("/upload", [&](const Request &req, Response &res) {
  15911. EXPECT_EQ(kItemCount, req.form.fields.size());
  15912. for (size_t i = 0; i < kItemCount; i++) {
  15913. auto key = "field" + std::to_string(i);
  15914. auto val = "value" + std::to_string(i);
  15915. auto it = req.form.fields.find(key);
  15916. if (it != req.form.fields.end()) {
  15917. EXPECT_EQ(val, it->second.content);
  15918. } else {
  15919. ADD_FAILURE() << "Missing field: " << key;
  15920. }
  15921. }
  15922. res.set_content("ok", "text/plain");
  15923. handled = true;
  15924. });
  15925. auto port = svr.bind_to_any_port(HOST);
  15926. auto t = thread([&] { svr.listen_after_bind(); });
  15927. auto se = detail::scope_exit([&] {
  15928. svr.stop();
  15929. t.join();
  15930. ASSERT_FALSE(svr.is_running());
  15931. ASSERT_TRUE(handled);
  15932. });
  15933. svr.wait_until_ready();
  15934. UploadFormDataItems items;
  15935. items.reserve(kItemCount);
  15936. for (size_t i = 0; i < kItemCount; i++) {
  15937. items.push_back(
  15938. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15939. }
  15940. Client cli(HOST, port);
  15941. auto res = cli.Post("/upload", items);
  15942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15943. EXPECT_EQ(StatusCode::OK_200, res->status);
  15944. }
  15945. TEST(MultipartFormDataTest, MakeFileProvider) {
  15946. // Verify make_file_provider sends a file's contents correctly.
  15947. const std::string file_content(4096, 'Z');
  15948. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15949. {
  15950. std::ofstream ofs(tmp_path, std::ios::binary);
  15951. ofs.write(file_content.data(),
  15952. static_cast<std::streamsize>(file_content.size()));
  15953. }
  15954. auto handled = false;
  15955. Server svr;
  15956. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15957. const ContentReader &content_reader) {
  15958. ASSERT_TRUE(req.is_multipart_form_data());
  15959. std::vector<FormData> items;
  15960. content_reader(
  15961. [&](const FormData &file) {
  15962. items.push_back(file);
  15963. return true;
  15964. },
  15965. [&](const char *data, size_t data_length) {
  15966. items.back().content.append(data, data_length);
  15967. return true;
  15968. });
  15969. ASSERT_EQ(1u, items.size());
  15970. EXPECT_EQ("myfile", items[0].name);
  15971. EXPECT_EQ("data.bin", items[0].filename);
  15972. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15973. EXPECT_EQ(file_content, items[0].content);
  15974. handled = true;
  15975. });
  15976. auto port = svr.bind_to_any_port(HOST);
  15977. auto t = thread([&] { svr.listen_after_bind(); });
  15978. auto se = detail::scope_exit([&] {
  15979. svr.stop();
  15980. t.join();
  15981. ASSERT_FALSE(svr.is_running());
  15982. ASSERT_TRUE(handled);
  15983. std::remove(tmp_path.c_str());
  15984. });
  15985. svr.wait_until_ready();
  15986. FormDataProviderItems providers;
  15987. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15988. "application/octet-stream"));
  15989. Client cli(HOST, port);
  15990. auto res = cli.Post("/upload", {}, {}, providers);
  15991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15992. EXPECT_EQ(StatusCode::OK_200, res->status);
  15993. }
  15994. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15995. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15996. // (100) headers is rejected with a 400 Bad Request response.
  15997. Server svr;
  15998. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15999. res.set_content("ok", "text/plain");
  16000. });
  16001. thread t = thread([&] { svr.listen(HOST, PORT); });
  16002. auto se = detail::scope_exit([&] {
  16003. svr.stop();
  16004. t.join();
  16005. ASSERT_FALSE(svr.is_running());
  16006. });
  16007. svr.wait_until_ready();
  16008. // Build a multipart part with 101 custom headers (exceeding
  16009. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16010. std::stringstream body;
  16011. body << "--simpleboundary\r\n"
  16012. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16013. for (int i = 0; i < 101; i++) {
  16014. body << "X-Custom-Header-" << i << ": value\r\n";
  16015. }
  16016. body << "\r\n"
  16017. << "value1\r\n"
  16018. << "--simpleboundary--\r\n";
  16019. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16020. Client cli(HOST, PORT);
  16021. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16023. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16024. }
  16025. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16026. // A body that never contains the declared boundary must not be accumulated
  16027. // while the parser waits for it. Buffering it would also make every read
  16028. // rescan everything seen so far, which is quadratic in the body size.
  16029. Server svr;
  16030. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16031. res.set_content("ok", "text/plain");
  16032. });
  16033. auto port = svr.bind_to_any_port(HOST);
  16034. thread t = thread([&] { svr.listen_after_bind(); });
  16035. auto se = detail::scope_exit([&] {
  16036. svr.stop();
  16037. t.join();
  16038. ASSERT_FALSE(svr.is_running());
  16039. });
  16040. svr.wait_until_ready();
  16041. Client cli(HOST, port);
  16042. cli.set_read_timeout(60, 0);
  16043. cli.set_write_timeout(60, 0);
  16044. // '-' is the worst case: it matches the first character of the boundary, so
  16045. // every position has to be checked against it.
  16046. auto post_dashes = [&](size_t size) {
  16047. const std::string body(size, '-');
  16048. auto start = std::chrono::steady_clock::now();
  16049. auto res =
  16050. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16051. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16052. std::chrono::steady_clock::now() - start)
  16053. .count();
  16054. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16055. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16056. return ms;
  16057. };
  16058. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16059. // Windows.
  16060. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16061. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16062. // Comparing the two sizes rather than checking an absolute duration keeps
  16063. // this meaningful across build types and CI load, both of which move the
  16064. // absolute numbers by more than an order of magnitude. Four times the bytes
  16065. // costs about four times the time when parsing is linear, and about sixteen
  16066. // times when the body is buffered and rescanned.
  16067. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16068. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16069. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16070. << "ms, which suggests the body is being buffered and rescanned";
  16071. }
  16072. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16073. // A boundary can only be followed by CRLF or by "--", so anything else is
  16074. // malformed no matter what comes next. The parser must say so right away
  16075. // instead of buffering the rest of the declared body.
  16076. Server svr;
  16077. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16078. res.set_content("ok", "text/plain");
  16079. });
  16080. auto port = svr.bind_to_any_port(HOST);
  16081. thread t = thread([&] { svr.listen_after_bind(); });
  16082. auto se = detail::scope_exit([&] {
  16083. svr.stop();
  16084. t.join();
  16085. ASSERT_FALSE(svr.is_running());
  16086. });
  16087. svr.wait_until_ready();
  16088. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16089. // buffers instead of failing would still be waiting for the remaining bytes.
  16090. const std::string body = "--zzzz\r\n"
  16091. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16092. "\r\n"
  16093. "text1"
  16094. "\r\n--zzzzXX";
  16095. const std::string req = "POST /post HTTP/1.1\r\n"
  16096. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16097. "Content-Length: 1048576\r\n"
  16098. "\r\n" +
  16099. body;
  16100. std::string response;
  16101. ASSERT_TRUE(send_request(3, req, &response, port));
  16102. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16103. EXPECT_EQ("400", response.substr(9, 3));
  16104. }
  16105. // Posts a multipart body split into two writes, so that the server sees the
  16106. // split at whatever offset the caller chose, and expects the single "text1"
  16107. // field to come through.
  16108. static void expect_split_multipart_ok(const std::string &body1,
  16109. const std::string &body2) {
  16110. auto handled = false;
  16111. Server svr;
  16112. svr.Post("/post", [&](const Request &req, Response &) {
  16113. EXPECT_EQ(1u, req.form.fields.size());
  16114. EXPECT_EQ("text1", req.form.get_field("text1"));
  16115. handled = true;
  16116. });
  16117. auto port = svr.bind_to_any_port(HOST);
  16118. thread t = thread([&] { svr.listen_after_bind(); });
  16119. auto se = detail::scope_exit([&] {
  16120. svr.stop();
  16121. t.join();
  16122. ASSERT_FALSE(svr.is_running());
  16123. ASSERT_TRUE(handled);
  16124. });
  16125. svr.wait_until_ready();
  16126. // "Connection: close" makes the server close once it has answered, so the
  16127. // response drain ends immediately instead of idling until the read timeout.
  16128. const std::string head =
  16129. "POST /post HTTP/1.1\r\n"
  16130. "Host: localhost\r\n"
  16131. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16132. "Connection: close\r\n"
  16133. "Content-Length: " +
  16134. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16135. std::string response;
  16136. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16137. ASSERT_GE(response.size(), 12u) << "no response";
  16138. EXPECT_EQ("200", response.substr(9, 3));
  16139. }
  16140. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16141. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16142. // ignored, including when it does not arrive in the same read as the
  16143. // close-delimiter itself.
  16144. expect_split_multipart_ok("--zzzz\r\n"
  16145. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16146. "\r\n"
  16147. "text1"
  16148. "\r\n--zzzz--",
  16149. "\r\nthis epilogue must be ignored\r\n");
  16150. }
  16151. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16152. // The initial boundary may be preceded by a preamble of any length and may
  16153. // straddle a read boundary. Discarding data while waiting for it must not
  16154. // throw away a partial boundary sitting at the end of the buffer.
  16155. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16156. "zz\r\n"
  16157. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16158. "\r\n"
  16159. "text1"
  16160. "\r\n--zzzz--\r\n");
  16161. }
  16162. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16163. // The received boundary was only checked for being non-empty, so it could be
  16164. // as long as a header is allowed to be. The parser scans the body for
  16165. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16166. // costs a nearly full comparison at nearly every position, making the
  16167. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16168. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16169. Server svr;
  16170. svr.Post("/post", [](const Request &req, Response &res) {
  16171. EXPECT_EQ(1u, req.form.fields.size());
  16172. EXPECT_EQ("text1", req.form.get_field("text1"));
  16173. res.set_content("ok", "text/plain");
  16174. });
  16175. auto port = svr.bind_to_any_port(HOST);
  16176. thread t = thread([&] { svr.listen_after_bind(); });
  16177. auto se = detail::scope_exit([&] {
  16178. svr.stop();
  16179. t.join();
  16180. ASSERT_FALSE(svr.is_running());
  16181. });
  16182. svr.wait_until_ready();
  16183. Client cli(HOST, port);
  16184. auto post_with_boundary_of_length = [&](size_t len) {
  16185. const std::string boundary(len, 'a');
  16186. const std::string body =
  16187. "--" + boundary +
  16188. "\r\n"
  16189. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16190. "\r\n"
  16191. "text1"
  16192. "\r\n--" +
  16193. boundary + "--\r\n";
  16194. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16195. };
  16196. auto res = post_with_boundary_of_length(70);
  16197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16198. EXPECT_EQ(StatusCode::OK_200, res->status);
  16199. res = post_with_boundary_of_length(71);
  16200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16201. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16202. }
  16203. TEST(MakeFileBodyTest, Basic) {
  16204. const std::string file_content(4096, 'Z');
  16205. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16206. {
  16207. std::ofstream ofs(tmp_path, std::ios::binary);
  16208. ofs.write(file_content.data(),
  16209. static_cast<std::streamsize>(file_content.size()));
  16210. }
  16211. auto handled = false;
  16212. Server svr;
  16213. svr.Post("/upload", [&](const Request &req, Response &res) {
  16214. EXPECT_EQ(file_content, req.body);
  16215. handled = true;
  16216. res.status = StatusCode::OK_200;
  16217. });
  16218. auto port = svr.bind_to_any_port(HOST);
  16219. auto t = thread([&] { svr.listen_after_bind(); });
  16220. auto se = detail::scope_exit([&] {
  16221. svr.stop();
  16222. t.join();
  16223. ASSERT_FALSE(svr.is_running());
  16224. ASSERT_TRUE(handled);
  16225. std::remove(tmp_path.c_str());
  16226. });
  16227. svr.wait_until_ready();
  16228. auto fb = make_file_body(tmp_path);
  16229. ASSERT_GT(fb.first, 0u);
  16230. Client cli(HOST, port);
  16231. auto res =
  16232. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16234. EXPECT_EQ(StatusCode::OK_200, res->status);
  16235. }
  16236. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16237. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16238. {
  16239. std::ofstream ofs(path, std::ios::binary);
  16240. const std::string content(100, 'A');
  16241. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16242. }
  16243. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16244. auto body = make_file_body(path);
  16245. ASSERT_EQ(100u, body.first);
  16246. ASSERT_TRUE(static_cast<bool>(body.second));
  16247. // Rewritten shorter after its length was measured - and, on a server, after
  16248. // that length has already gone out as Content-Length.
  16249. {
  16250. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16251. const std::string content(10, 'A');
  16252. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16253. }
  16254. std::string written;
  16255. DataSink sink;
  16256. sink.write = [&](const char *d, size_t l) {
  16257. written.append(d, l);
  16258. return true;
  16259. };
  16260. // The provider has to report failure. write_content_with_progress() advances
  16261. // its offset only by what was written, so a provider that returns true
  16262. // without completing the length it promised is called again straight away,
  16263. // and again.
  16264. EXPECT_FALSE(body.second(0, body.first, sink));
  16265. EXPECT_EQ(std::string(10, 'A'), written);
  16266. }
  16267. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16268. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16269. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16270. {
  16271. std::ofstream ofs(path, std::ios::binary);
  16272. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16273. }
  16274. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16275. auto body = make_file_body(path);
  16276. ASSERT_EQ(content.size(), body.first);
  16277. ASSERT_TRUE(static_cast<bool>(body.second));
  16278. std::string written;
  16279. DataSink sink;
  16280. sink.write = [&](const char *d, size_t l) {
  16281. written.append(d, l);
  16282. return true;
  16283. };
  16284. EXPECT_TRUE(body.second(0, body.first, sink));
  16285. EXPECT_EQ(content, written);
  16286. }
  16287. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16288. static constexpr unsigned int number_of_tasks{1000000};
  16289. std::atomic_uint count{0};
  16290. std::unique_ptr<TaskQueue> task_queue{
  16291. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16292. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16293. auto queued = task_queue->enqueue(
  16294. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16295. EXPECT_TRUE(queued);
  16296. }
  16297. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16298. task_queue->shutdown();
  16299. #else
  16300. EXPECT_NO_THROW(task_queue->shutdown());
  16301. #endif
  16302. EXPECT_EQ(number_of_tasks, count.load());
  16303. }
  16304. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16305. static constexpr unsigned int number_of_tasks{1000000};
  16306. static constexpr unsigned int qlimit{2};
  16307. unsigned int queued_count{0};
  16308. std::atomic_uint count{0};
  16309. std::unique_ptr<TaskQueue> task_queue{
  16310. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16311. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16312. if (task_queue->enqueue(
  16313. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16314. queued_count++;
  16315. }
  16316. }
  16317. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16318. task_queue->shutdown();
  16319. #else
  16320. EXPECT_NO_THROW(task_queue->shutdown());
  16321. #endif
  16322. EXPECT_EQ(queued_count, count.load());
  16323. EXPECT_TRUE(queued_count <= number_of_tasks);
  16324. EXPECT_TRUE(queued_count >= qlimit);
  16325. }
  16326. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16327. // Use a short idle timeout so a dynamic thread spawns, times out and
  16328. // exits during the test, and the pool keeps working afterwards.
  16329. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16330. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16331. /*idle_timeout_sec=*/1}};
  16332. std::atomic_uint count{0};
  16333. std::condition_variable cv;
  16334. std::mutex mtx;
  16335. bool release = false;
  16336. // Block the base thread so the second task spawns a dynamic thread.
  16337. EXPECT_TRUE(task_queue->enqueue([&] {
  16338. std::unique_lock<std::mutex> lock(mtx);
  16339. while (!release) {
  16340. cv.wait(lock);
  16341. }
  16342. count++;
  16343. }));
  16344. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16345. // Let the dynamic thread finish its task and exceed the idle timeout.
  16346. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16347. {
  16348. std::unique_lock<std::mutex> lock(mtx);
  16349. release = true;
  16350. }
  16351. cv.notify_all();
  16352. // The pool must still accept and run tasks after the dynamic thread exited.
  16353. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16354. task_queue->shutdown();
  16355. EXPECT_EQ(3u, count.load());
  16356. }
  16357. TEST(TaskQueueTest, MaxQueuedRequests) {
  16358. static constexpr unsigned int qlimit{3};
  16359. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16360. std::condition_variable sem_cv;
  16361. std::mutex sem_mtx;
  16362. int credits = 0;
  16363. bool queued;
  16364. /* Fill up the queue with tasks that will block until we give them credits to
  16365. * complete. */
  16366. for (unsigned int n = 0; n <= qlimit;) {
  16367. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16368. std::unique_lock<std::mutex> lock(sem_mtx);
  16369. while (credits <= 0) {
  16370. sem_cv.wait(lock);
  16371. }
  16372. /* Consume the credit and signal the test code if they are all gone. */
  16373. if (--credits == 0) { sem_cv.notify_one(); }
  16374. });
  16375. if (n < qlimit) {
  16376. /* The first qlimit enqueues must succeed. */
  16377. EXPECT_TRUE(queued);
  16378. } else {
  16379. /* The last one will succeed only when the worker thread
  16380. * starts and dequeues the first blocking task. Although
  16381. * not necessary for the correctness of this test, we sleep for
  16382. * a short while to avoid busy waiting. */
  16383. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16384. }
  16385. if (queued) { n++; }
  16386. }
  16387. /* Further enqueues must fail since the queue is full. */
  16388. for (auto i = 0; i < 4; i++) {
  16389. queued = task_queue->enqueue([] {});
  16390. EXPECT_FALSE(queued);
  16391. }
  16392. /* Give the credits to allow the previous tasks to complete. */
  16393. {
  16394. std::unique_lock<std::mutex> lock(sem_mtx);
  16395. credits += qlimit + 1;
  16396. }
  16397. sem_cv.notify_all();
  16398. /* Wait for all the credits to be consumed. */
  16399. {
  16400. std::unique_lock<std::mutex> lock(sem_mtx);
  16401. while (credits > 0) {
  16402. sem_cv.wait(lock);
  16403. }
  16404. }
  16405. /* Check that we are able again to enqueue at least qlimit tasks. */
  16406. for (unsigned int i = 0; i < qlimit; i++) {
  16407. queued = task_queue->enqueue([] {});
  16408. EXPECT_TRUE(queued);
  16409. }
  16410. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16411. task_queue->shutdown();
  16412. #else
  16413. EXPECT_NO_THROW(task_queue->shutdown());
  16414. #endif
  16415. }
  16416. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16417. Server svr;
  16418. std::string method;
  16419. std::string body;
  16420. auto has_content_length = false;
  16421. auto has_transfer_encoding = false;
  16422. std::atomic<int> bad_requests{0};
  16423. // Leftover body bytes get parsed as a malformed request and answered with
  16424. // 400
  16425. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16426. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16427. });
  16428. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16429. res.set_redirect("/down", StatusCode::SeeOther_303);
  16430. });
  16431. svr.Get("/down", [&](const Request &req, Response &res) {
  16432. method = req.method;
  16433. body = req.body;
  16434. has_content_length = req.has_header("Content-Length");
  16435. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16436. res.set_content("ok", "text/plain");
  16437. });
  16438. auto port = svr.bind_to_any_port(HOST);
  16439. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16440. auto se = detail::scope_exit([&] {
  16441. svr.stop();
  16442. thread.join();
  16443. ASSERT_FALSE(svr.is_running());
  16444. });
  16445. svr.wait_until_ready();
  16446. const std::string payload = "SECRET-BODY";
  16447. auto check = [&](Client &cli, const Result &res) {
  16448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16449. EXPECT_EQ(StatusCode::OK_200, res->status);
  16450. EXPECT_EQ("ok", res->body);
  16451. EXPECT_EQ("GET", method);
  16452. EXPECT_TRUE(body.empty());
  16453. EXPECT_FALSE(has_content_length);
  16454. EXPECT_FALSE(has_transfer_encoding);
  16455. // Nothing of the original body may be left on the connection
  16456. auto res2 = cli.Get("/down");
  16457. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16458. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16459. EXPECT_EQ("ok", res2->body);
  16460. EXPECT_EQ(0, bad_requests);
  16461. };
  16462. // With content length
  16463. {
  16464. Client cli(HOST, port);
  16465. cli.set_keep_alive(true);
  16466. cli.set_follow_location(true);
  16467. auto res = cli.Post(
  16468. "/up", payload.size(),
  16469. [&](size_t offset, size_t length, DataSink &sink) {
  16470. return sink.write(payload.data() + offset, length);
  16471. },
  16472. "text/plain");
  16473. check(cli, res);
  16474. }
  16475. // Without content length (chunked)
  16476. {
  16477. Client cli(HOST, port);
  16478. cli.set_keep_alive(true);
  16479. cli.set_follow_location(true);
  16480. auto res = cli.Post(
  16481. "/up",
  16482. [&](size_t /*offset*/, DataSink &sink) {
  16483. sink.write(payload.data(), payload.size());
  16484. sink.done();
  16485. return true;
  16486. },
  16487. "text/plain");
  16488. check(cli, res);
  16489. }
  16490. }
  16491. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16492. Server svr;
  16493. std::string target;
  16494. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16495. // Echo the still-encoded name back in the Location
  16496. const std::string prefix = "/start/";
  16497. res.status = StatusCode::Found_302;
  16498. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16499. });
  16500. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16501. target = req.target;
  16502. res.set_content("ok", "text/plain");
  16503. });
  16504. auto port = svr.bind_to_any_port(HOST);
  16505. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16506. auto se = detail::scope_exit([&] {
  16507. svr.stop();
  16508. thread.join();
  16509. ASSERT_FALSE(svr.is_running());
  16510. });
  16511. svr.wait_until_ready();
  16512. // Decoding the Location path would turn the first four into a path
  16513. // separator, a query delimiter, a fragment delimiter and a different
  16514. // percent-encoded octet. The rest must keep reaching the server as they are.
  16515. const std::vector<std::string> names = {
  16516. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16517. };
  16518. for (auto path_encode : {true, false}) {
  16519. Client cli(HOST, port);
  16520. cli.set_follow_location(true);
  16521. cli.set_path_encode(path_encode);
  16522. for (const auto &name : names) {
  16523. target.clear();
  16524. auto res = cli.Get("/start/" + name);
  16525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16526. EXPECT_EQ(StatusCode::OK_200, res->status);
  16527. EXPECT_EQ("/dest/" + name, target);
  16528. }
  16529. }
  16530. }
  16531. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16532. Server svr;
  16533. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16534. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16535. });
  16536. svr.Get("/hello", [](const Request &req, Response &res) {
  16537. res.set_content(req.get_param_value("key"), "text/plain");
  16538. });
  16539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16540. auto se = detail::scope_exit([&] {
  16541. svr.stop();
  16542. thread.join();
  16543. ASSERT_FALSE(svr.is_running());
  16544. });
  16545. svr.wait_until_ready();
  16546. {
  16547. Client cli(HOST, PORT);
  16548. cli.set_follow_location(true);
  16549. auto res = cli.Get("/");
  16550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16551. EXPECT_EQ(StatusCode::OK_200, res->status);
  16552. EXPECT_EQ("val&key2=val2", res->body);
  16553. }
  16554. }
  16555. #endif
  16556. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16557. Server svr;
  16558. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16559. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16560. });
  16561. svr.Get("/hello", [](const Request &req, Response &res) {
  16562. res.set_content(req.get_param_value("key"), "text/plain");
  16563. });
  16564. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16565. auto se = detail::scope_exit([&] {
  16566. svr.stop();
  16567. thread.join();
  16568. ASSERT_FALSE(svr.is_running());
  16569. });
  16570. svr.wait_until_ready();
  16571. {
  16572. Client cli(HOST, PORT);
  16573. cli.set_follow_location(true);
  16574. auto res = cli.Get("/");
  16575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16576. EXPECT_EQ(StatusCode::OK_200, res->status);
  16577. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16578. }
  16579. }
  16580. TEST(RedirectTest, RedirectWithPlusInPath) {
  16581. Server svr;
  16582. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16583. res.set_redirect("/a+b");
  16584. });
  16585. // Route pattern uses regex; escape + as \\+
  16586. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16587. res.set_content(req.path, "text/plain");
  16588. });
  16589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16590. auto se = detail::scope_exit([&] {
  16591. svr.stop();
  16592. thread.join();
  16593. ASSERT_FALSE(svr.is_running());
  16594. });
  16595. svr.wait_until_ready();
  16596. {
  16597. Client cli(HOST, PORT);
  16598. cli.set_follow_location(true);
  16599. auto res = cli.Get("/");
  16600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16601. EXPECT_EQ(StatusCode::OK_200, res->status);
  16602. EXPECT_EQ("/a+b", res->body);
  16603. }
  16604. }
  16605. TEST(RedirectTest, ResolveRelativeLocation) {
  16606. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16607. const std::vector<std::pair<std::string, std::string>> cases = {
  16608. {"g", "/b/c/g"},
  16609. {"./g", "/b/c/g"},
  16610. {"g/", "/b/c/g/"},
  16611. {"?y", "/b/c/d;p?y"},
  16612. {"g?y", "/b/c/g?y"},
  16613. {"#s", "/b/c/d;p?q#s"},
  16614. {"g#s", "/b/c/g#s"},
  16615. {"g?y#s", "/b/c/g?y#s"},
  16616. {";x", "/b/c/;x"},
  16617. {"g;x", "/b/c/g;x"},
  16618. {".", "/b/c/"},
  16619. {"./", "/b/c/"},
  16620. {"..", "/b/"},
  16621. {"../", "/b/"},
  16622. {"../g", "/b/g"},
  16623. {"../..", "/"},
  16624. {"../../", "/"},
  16625. {"../../g", "/g"},
  16626. {"../../../g", "/g"},
  16627. {"g.", "/b/c/g."},
  16628. {".g", "/b/c/.g"},
  16629. {"g..", "/b/c/g.."},
  16630. {"..g", "/b/c/..g"},
  16631. {"./../g", "/b/g"},
  16632. {"./g/.", "/b/c/g/"},
  16633. {"g/./h", "/b/c/g/h"},
  16634. {"g/../h", "/b/c/h"},
  16635. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16636. {"g;x=1/../y", "/b/c/y"},
  16637. {"g?y/./x", "/b/c/g?y/./x"},
  16638. {"g#s/../x", "/b/c/g#s/../x"},
  16639. // Not relative-path references, so left for parse_url.
  16640. {"/g", "/g"},
  16641. {"//g", "//g"},
  16642. {"http://g/x", "http://g/x"},
  16643. {"g:h", "g:h"},
  16644. };
  16645. for (const auto &c : cases) {
  16646. EXPECT_EQ(c.second,
  16647. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16648. << c.first;
  16649. }
  16650. }
  16651. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16652. Server svr;
  16653. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16654. res.set_redirect(req.get_param_value("to"));
  16655. });
  16656. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16657. res.set_content(req.target, "text/plain");
  16658. });
  16659. svr.Get("/other", [](const Request &req, Response &res) {
  16660. res.set_content(req.target, "text/plain");
  16661. });
  16662. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16663. auto se = detail::scope_exit([&] {
  16664. svr.stop();
  16665. thread.join();
  16666. ASSERT_FALSE(svr.is_running());
  16667. });
  16668. svr.wait_until_ready();
  16669. const std::vector<std::pair<std::string, std::string>> cases = {
  16670. {"next", "/dir/next"},
  16671. {"./next?x=1", "/dir/next?x=1"},
  16672. {"../other", "/other"},
  16673. };
  16674. for (const auto &c : cases) {
  16675. Client cli(HOST, PORT);
  16676. cli.set_follow_location(true);
  16677. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16678. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16679. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16680. EXPECT_EQ(c.second, res->body) << c.first;
  16681. }
  16682. }
  16683. #ifdef CPPHTTPLIB_SSL_ENABLED
  16684. TEST(RedirectTest, Issue2185_Online) {
  16685. SSLClient client("github.com");
  16686. client.set_follow_location(true);
  16687. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16688. "Coollab-Windows.zip");
  16689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16690. EXPECT_EQ(StatusCode::OK_200, res->status);
  16691. EXPECT_EQ(9920427U, res->body.size());
  16692. }
  16693. #endif
  16694. TEST(VulnerabilityTest, CRLFInjection) {
  16695. Server svr;
  16696. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16697. res.set_content("Hello 1", "text/plain");
  16698. });
  16699. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16700. res.set_content("Hello 2", "text/plain");
  16701. });
  16702. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16703. res.set_content("Hello 3", "text/plain");
  16704. });
  16705. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16706. res.set_content("Hello 4", "text/plain");
  16707. });
  16708. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16709. for (const auto &x : req.headers) {
  16710. auto key = x.first;
  16711. EXPECT_STRNE("evil", key.c_str());
  16712. }
  16713. });
  16714. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16715. auto se = detail::scope_exit([&] {
  16716. svr.stop();
  16717. thread.join();
  16718. ASSERT_FALSE(svr.is_running());
  16719. });
  16720. svr.wait_until_ready();
  16721. {
  16722. Client cli(HOST, PORT);
  16723. cli.Post("/test1", "A=B",
  16724. "application/x-www-form-urlencoded\r\nevil: hello1");
  16725. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16726. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16727. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16728. }
  16729. }
  16730. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16731. auto server_thread = std::thread([] {
  16732. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16733. default_socket_options(srv);
  16734. sockaddr_in addr{};
  16735. addr.sin_family = AF_INET;
  16736. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16737. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16738. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16739. ::listen(srv, 1);
  16740. sockaddr_in cli_addr{};
  16741. socklen_t cli_len = sizeof(cli_addr);
  16742. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16743. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16744. std::string buf_all;
  16745. char buf[2048];
  16746. ssize_t n;
  16747. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16748. buf_all.append(buf, static_cast<size_t>(n));
  16749. size_t pos;
  16750. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16751. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16752. auto e = request_block.find("\r\n");
  16753. if (e != std::string::npos) {
  16754. auto request_line = request_block.substr(0, e);
  16755. std::string msg =
  16756. "CRLF injection detected in request line: '" + request_line + "'";
  16757. EXPECT_FALSE(true) << msg;
  16758. }
  16759. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16760. ::send(cli,
  16761. #ifdef _WIN32
  16762. static_cast<const char *>(resp.c_str()),
  16763. static_cast<int>(resp.size()),
  16764. #else
  16765. resp.c_str(), resp.size(),
  16766. #endif
  16767. 0);
  16768. buf_all.erase(0, pos + 4);
  16769. }
  16770. }
  16771. detail::close_socket(cli);
  16772. detail::close_socket(srv);
  16773. });
  16774. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16775. auto cli = Client("127.0.0.1", PORT + 1);
  16776. auto headers = Headers{
  16777. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16778. {"Connection", "keep-alive"}};
  16779. auto res = cli.Get("/hi", headers);
  16780. EXPECT_FALSE(res);
  16781. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16782. server_thread.join();
  16783. }
  16784. // A request rejected before any byte reaches the socket must fail right away
  16785. // instead of waiting for a response the server will never send.
  16786. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16787. // The kernel completes the TCP handshake from the listen backlog, so the
  16788. // client connects, but nothing ever reads, responds or closes.
  16789. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16790. default_socket_options(srv);
  16791. sockaddr_in addr{};
  16792. addr.sin_family = AF_INET;
  16793. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16794. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16795. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16796. ASSERT_EQ(0, ::listen(srv, 8));
  16797. auto cli = Client("127.0.0.1", PORT + 1);
  16798. cli.set_read_timeout(10, 0);
  16799. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16800. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16801. std::chrono::steady_clock::now() - start)
  16802. .count();
  16803. };
  16804. {
  16805. Request req;
  16806. req.method = "GE T";
  16807. req.path = "/";
  16808. auto start = std::chrono::steady_clock::now();
  16809. auto res = cli.send(req);
  16810. EXPECT_FALSE(res);
  16811. EXPECT_EQ(Error::Write, res.error());
  16812. EXPECT_LT(elapsed_ms(start), 1000);
  16813. }
  16814. {
  16815. auto start = std::chrono::steady_clock::now();
  16816. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16817. EXPECT_FALSE(res);
  16818. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16819. EXPECT_LT(elapsed_ms(start), 1000);
  16820. }
  16821. EXPECT_FALSE(cli.is_socket_open());
  16822. detail::close_socket(srv);
  16823. }
  16824. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16825. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16826. default_socket_options(srv);
  16827. sockaddr_in addr{};
  16828. addr.sin_family = AF_INET;
  16829. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16830. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16831. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16832. ASSERT_EQ(0, ::listen(srv, 1));
  16833. std::string received;
  16834. auto server_thread = std::thread([&] {
  16835. auto sock = ::accept(srv, nullptr, nullptr);
  16836. if (sock == INVALID_SOCKET) { return; }
  16837. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16838. char buf[2048];
  16839. ssize_t n;
  16840. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16841. received.append(buf, static_cast<size_t>(n));
  16842. }
  16843. detail::close_socket(sock);
  16844. });
  16845. {
  16846. auto cli = Client("127.0.0.1", PORT + 1);
  16847. // "Z" sorts after the default headers, so writing straight to the socket
  16848. // would have sent the request line and those headers before the rejection.
  16849. auto handle =
  16850. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16851. EXPECT_FALSE(handle.is_valid());
  16852. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16853. }
  16854. server_thread.join();
  16855. detail::close_socket(srv);
  16856. EXPECT_TRUE(received.empty()) << received;
  16857. }
  16858. TEST(PathParamsTest, StaticMatch) {
  16859. const auto pattern = "/users/all";
  16860. detail::PathParamsMatcher matcher(pattern);
  16861. Request request;
  16862. request.path = "/users/all";
  16863. ASSERT_TRUE(matcher.match(request));
  16864. std::unordered_map<std::string, std::string> expected_params = {};
  16865. EXPECT_EQ(request.path_params, expected_params);
  16866. }
  16867. TEST(PathParamsTest, StaticMismatch) {
  16868. const auto pattern = "/users/all";
  16869. detail::PathParamsMatcher matcher(pattern);
  16870. Request request;
  16871. request.path = "/users/1";
  16872. ASSERT_FALSE(matcher.match(request));
  16873. }
  16874. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16875. const auto pattern = "/users/:id/subscriptions";
  16876. detail::PathParamsMatcher matcher(pattern);
  16877. Request request;
  16878. request.path = "/users/42/subscriptions";
  16879. ASSERT_TRUE(matcher.match(request));
  16880. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16881. EXPECT_EQ(request.path_params, expected_params);
  16882. }
  16883. TEST(PathParamsTest, SingleParamInTheEnd) {
  16884. const auto pattern = "/users/:id";
  16885. detail::PathParamsMatcher matcher(pattern);
  16886. Request request;
  16887. request.path = "/users/24";
  16888. ASSERT_TRUE(matcher.match(request));
  16889. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16890. EXPECT_EQ(request.path_params, expected_params);
  16891. }
  16892. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16893. const auto pattern = "/users/:id/";
  16894. detail::PathParamsMatcher matcher(pattern);
  16895. Request request;
  16896. request.path = "/users/42/";
  16897. ASSERT_TRUE(matcher.match(request));
  16898. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16899. EXPECT_EQ(request.path_params, expected_params);
  16900. }
  16901. TEST(PathParamsTest, EmptyParam) {
  16902. const auto pattern = "/users/:id/";
  16903. detail::PathParamsMatcher matcher(pattern);
  16904. Request request;
  16905. request.path = "/users//";
  16906. ASSERT_TRUE(matcher.match(request));
  16907. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16908. EXPECT_EQ(request.path_params, expected_params);
  16909. }
  16910. TEST(PathParamsTest, FragmentMismatch) {
  16911. const auto pattern = "/users/:id/";
  16912. detail::PathParamsMatcher matcher(pattern);
  16913. Request request;
  16914. request.path = "/admins/24/";
  16915. ASSERT_FALSE(matcher.match(request));
  16916. }
  16917. TEST(PathParamsTest, ExtraFragments) {
  16918. const auto pattern = "/users/:id";
  16919. detail::PathParamsMatcher matcher(pattern);
  16920. Request request;
  16921. request.path = "/users/42/subscriptions";
  16922. ASSERT_FALSE(matcher.match(request));
  16923. }
  16924. TEST(PathParamsTest, MissingTrailingParam) {
  16925. const auto pattern = "/users/:id";
  16926. detail::PathParamsMatcher matcher(pattern);
  16927. Request request;
  16928. request.path = "/users";
  16929. ASSERT_FALSE(matcher.match(request));
  16930. }
  16931. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16932. const auto pattern = "/users/:id/subscriptions";
  16933. detail::PathParamsMatcher matcher(pattern);
  16934. Request request;
  16935. request.path = "/users/subscriptions";
  16936. ASSERT_FALSE(matcher.match(request));
  16937. }
  16938. TEST(PathParamsTest, MultipleParams) {
  16939. const auto pattern = "/users/:userid/subscriptions/:subid";
  16940. detail::PathParamsMatcher matcher(pattern);
  16941. Request request;
  16942. request.path = "/users/42/subscriptions/2";
  16943. ASSERT_TRUE(matcher.match(request));
  16944. std::unordered_map<std::string, std::string> expected_params = {
  16945. {"userid", "42"}, {"subid", "2"}};
  16946. EXPECT_EQ(request.path_params, expected_params);
  16947. }
  16948. TEST(PathParamsTest, SequenceOfParams) {
  16949. const auto pattern = "/values/:x/:y/:z";
  16950. detail::PathParamsMatcher matcher(pattern);
  16951. Request request;
  16952. request.path = "/values/1/2/3";
  16953. ASSERT_TRUE(matcher.match(request));
  16954. std::unordered_map<std::string, std::string> expected_params = {
  16955. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16956. EXPECT_EQ(request.path_params, expected_params);
  16957. }
  16958. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16959. const auto pattern = "/prefix:suffix";
  16960. detail::PathParamsMatcher matcher(pattern);
  16961. Request request;
  16962. request.path = "/prefix:suffix";
  16963. ASSERT_TRUE(matcher.match(request));
  16964. const std::unordered_map<std::string, std::string> expected_params = {};
  16965. EXPECT_EQ(request.path_params, expected_params);
  16966. }
  16967. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16968. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16969. // calling thread's stack on a long enough path for a quantified pattern;
  16970. // RegexMatcher must refuse to run regex matching on paths beyond
  16971. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16972. detail::RegexMatcher matcher("/files/(.*)");
  16973. Request within_limit;
  16974. within_limit.path = "/files/" + std::string(10, 'A');
  16975. EXPECT_TRUE(matcher.match(within_limit));
  16976. Request over_limit;
  16977. over_limit.path =
  16978. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16979. EXPECT_FALSE(matcher.match(over_limit));
  16980. }
  16981. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16982. Server svr;
  16983. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16984. res.set_content("ok", "text/plain");
  16985. });
  16986. auto port = svr.bind_to_any_port(HOST);
  16987. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16988. auto se = detail::scope_exit([&] {
  16989. svr.stop();
  16990. thread.join();
  16991. ASSERT_FALSE(svr.is_running());
  16992. });
  16993. svr.wait_until_ready();
  16994. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16995. // request URI limit; this used to be able to crash the process.
  16996. std::string path =
  16997. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16998. std::string req = "GET " + path +
  16999. " HTTP/1.1\r\n"
  17000. "Host: " +
  17001. std::string(HOST) + ":" + std::to_string(port) +
  17002. "\r\n"
  17003. "Connection: close\r\n"
  17004. "\r\n";
  17005. std::string response;
  17006. ASSERT_TRUE(send_request(5, req, &response, port));
  17007. EXPECT_NE(std::string::npos, response.find("404"));
  17008. }
  17009. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17010. Server svr;
  17011. auto handler = [](const Request & /*req*/, Response &res) {
  17012. res.set_content("hit", "text/plain");
  17013. };
  17014. // No regex metacharacter, so this one is compared literally
  17015. svr.Get("/literal/route", handler);
  17016. // '.' is a regex metacharacter, so this one must keep regex semantics
  17017. svr.Get("/a.c", handler);
  17018. auto port = svr.bind_to_any_port(HOST);
  17019. std::thread t([&]() { svr.listen_after_bind(); });
  17020. auto se = detail::scope_exit([&] {
  17021. svr.stop();
  17022. t.join();
  17023. ASSERT_FALSE(svr.is_running());
  17024. });
  17025. svr.wait_until_ready();
  17026. Client cli(HOST, port);
  17027. struct {
  17028. const char *path;
  17029. int status;
  17030. } cases[] = {
  17031. {"/literal/route", StatusCode::OK_200},
  17032. {"/literal/routes", StatusCode::NotFound_404},
  17033. {"/literal/rout", StatusCode::NotFound_404},
  17034. {"/abc", StatusCode::OK_200},
  17035. {"/a.c", StatusCode::OK_200},
  17036. };
  17037. for (const auto &x : cases) {
  17038. auto res = cli.Get(x.path);
  17039. ASSERT_TRUE(res) << x.path;
  17040. EXPECT_EQ(x.status, res->status) << x.path;
  17041. }
  17042. }
  17043. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17044. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17045. // from exhausting the stack, so it must only constrain routes that actually
  17046. // run a regular expression. A literal route is matched by comparison and
  17047. // stays usable at any length.
  17048. Server svr;
  17049. const std::string pattern =
  17050. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17051. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17052. res.set_content("hit", "text/plain");
  17053. });
  17054. auto port = svr.bind_to_any_port(HOST);
  17055. std::thread t([&]() { svr.listen_after_bind(); });
  17056. auto se = detail::scope_exit([&] {
  17057. svr.stop();
  17058. t.join();
  17059. ASSERT_FALSE(svr.is_running());
  17060. });
  17061. svr.wait_until_ready();
  17062. Client cli(HOST, port);
  17063. auto res = cli.Get(pattern);
  17064. ASSERT_TRUE(res);
  17065. EXPECT_EQ(StatusCode::OK_200, res->status);
  17066. }
  17067. TEST(ParseUrlTest, VariousPatterns) {
  17068. {
  17069. detail::UrlComponents uc;
  17070. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17071. EXPECT_EQ("http", uc.scheme);
  17072. EXPECT_EQ("example.com", uc.host);
  17073. EXPECT_EQ("8080", uc.port);
  17074. EXPECT_EQ("/path", uc.path);
  17075. EXPECT_EQ("?q=1", uc.query);
  17076. }
  17077. {
  17078. detail::UrlComponents uc;
  17079. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17080. EXPECT_EQ("https", uc.scheme);
  17081. EXPECT_EQ("example.com", uc.host);
  17082. EXPECT_TRUE(uc.port.empty());
  17083. EXPECT_EQ("/path", uc.path);
  17084. }
  17085. {
  17086. detail::UrlComponents uc;
  17087. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17088. EXPECT_EQ("::1", uc.host);
  17089. EXPECT_EQ("8080", uc.port);
  17090. EXPECT_EQ("/path", uc.path);
  17091. }
  17092. {
  17093. detail::UrlComponents uc;
  17094. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17095. }
  17096. {
  17097. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17098. // the path while the connection still targets the bracketed host.
  17099. detail::UrlComponents uc;
  17100. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17101. }
  17102. {
  17103. detail::UrlComponents uc;
  17104. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17105. }
  17106. {
  17107. detail::UrlComponents uc;
  17108. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17109. EXPECT_EQ("::1", uc.host);
  17110. EXPECT_TRUE(uc.port.empty());
  17111. EXPECT_EQ("/path", uc.path);
  17112. }
  17113. {
  17114. detail::UrlComponents uc;
  17115. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17116. EXPECT_TRUE(uc.scheme.empty());
  17117. EXPECT_EQ("example.com", uc.host);
  17118. EXPECT_EQ("/path", uc.path);
  17119. EXPECT_EQ("?q=1", uc.query);
  17120. }
  17121. {
  17122. detail::UrlComponents uc;
  17123. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17124. EXPECT_TRUE(uc.host.empty());
  17125. EXPECT_EQ("/path", uc.path);
  17126. EXPECT_EQ("?q=1", uc.query);
  17127. }
  17128. {
  17129. detail::UrlComponents uc;
  17130. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17131. EXPECT_EQ("example.com", uc.host);
  17132. EXPECT_EQ("8080", uc.port);
  17133. }
  17134. {
  17135. // Unix socket path — must not be parsed as host
  17136. detail::UrlComponents uc;
  17137. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17138. EXPECT_TRUE(uc.host.empty());
  17139. }
  17140. {
  17141. detail::UrlComponents uc;
  17142. ASSERT_TRUE(detail::parse_url("", uc));
  17143. EXPECT_TRUE(uc.host.empty());
  17144. EXPECT_TRUE(uc.path.empty());
  17145. }
  17146. {
  17147. detail::UrlComponents uc;
  17148. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17149. }
  17150. {
  17151. detail::UrlComponents uc;
  17152. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17153. }
  17154. {
  17155. // Accepted by parse_url; callers restrict to http/https
  17156. detail::UrlComponents uc;
  17157. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17158. EXPECT_EQ("ftp", uc.scheme);
  17159. }
  17160. {
  17161. detail::UrlComponents uc;
  17162. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17163. }
  17164. {
  17165. detail::UrlComponents uc;
  17166. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17167. }
  17168. }
  17169. TEST(ParseUrlTest, FragmentHandling) {
  17170. {
  17171. detail::UrlComponents uc;
  17172. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17173. EXPECT_EQ("/path", uc.path);
  17174. EXPECT_TRUE(uc.query.empty());
  17175. }
  17176. {
  17177. detail::UrlComponents uc;
  17178. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17179. EXPECT_TRUE(uc.path.empty());
  17180. EXPECT_TRUE(uc.query.empty());
  17181. }
  17182. }
  17183. TEST(ParseUrlTest, UserinfoHandling) {
  17184. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17185. // parsers would see evil.com as the host.
  17186. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17187. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17188. for (auto url : urls) {
  17189. detail::UrlComponents uc;
  17190. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17191. }
  17192. }
  17193. TEST(ParseUrlTest, IPv6EdgeCases) {
  17194. {
  17195. detail::UrlComponents uc;
  17196. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17197. EXPECT_TRUE(uc.scheme.empty());
  17198. EXPECT_EQ("::1", uc.host);
  17199. EXPECT_EQ("8080", uc.port);
  17200. }
  17201. {
  17202. // Zone ID '%25' is not in [a-fA-F0-9:]
  17203. detail::UrlComponents uc;
  17204. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17205. }
  17206. }
  17207. TEST(ParseUrlTest, SchemeEdgeCases) {
  17208. {
  17209. detail::UrlComponents uc;
  17210. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17211. }
  17212. {
  17213. detail::UrlComponents uc;
  17214. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17215. }
  17216. {
  17217. detail::UrlComponents uc;
  17218. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17219. }
  17220. }
  17221. TEST(ParseUrlTest, PortEdgeCases) {
  17222. {
  17223. detail::UrlComponents uc;
  17224. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17225. EXPECT_TRUE(uc.port.empty());
  17226. EXPECT_EQ("/path", uc.path);
  17227. }
  17228. {
  17229. // parse_url accepts any port string; validation is done by parse_port
  17230. detail::UrlComponents uc;
  17231. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17232. EXPECT_EQ("abc", uc.port);
  17233. }
  17234. }
  17235. TEST(ParseUrlTest, WebSocketPatterns) {
  17236. {
  17237. detail::UrlComponents uc;
  17238. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17239. EXPECT_EQ("ws", uc.scheme);
  17240. EXPECT_EQ("echo.example.com", uc.host);
  17241. EXPECT_EQ("8080", uc.port);
  17242. EXPECT_EQ("/ws", uc.path);
  17243. }
  17244. {
  17245. detail::UrlComponents uc;
  17246. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17247. EXPECT_EQ("wss", uc.scheme);
  17248. EXPECT_EQ("echo.example.com", uc.host);
  17249. EXPECT_TRUE(uc.port.empty());
  17250. EXPECT_EQ("/ws", uc.path);
  17251. }
  17252. }
  17253. TEST(ParseUrlTest, QueryOnly) {
  17254. detail::UrlComponents uc;
  17255. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17256. EXPECT_TRUE(uc.host.empty());
  17257. EXPECT_TRUE(uc.path.empty());
  17258. EXPECT_EQ("?q=1&r=2", uc.query);
  17259. }
  17260. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17261. detail::UrlComponents uc;
  17262. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17263. EXPECT_TRUE(uc.scheme.empty());
  17264. EXPECT_EQ("example.com", uc.host);
  17265. EXPECT_EQ("443", uc.port);
  17266. EXPECT_EQ("/path", uc.path);
  17267. }
  17268. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17269. // If ipv6 regex working, regex match codepath is taken.
  17270. // else port will default to 80 in Client impl
  17271. int clientImplMagicPort = 80;
  17272. int port = 4321;
  17273. // above ports must be different to avoid false negative
  17274. EXPECT_NE(clientImplMagicPort, port);
  17275. std::string ipV6TestURL = "http://[ff06::c3]";
  17276. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17277. CLIENT_PRIVATE_KEY_FILE);
  17278. EXPECT_EQ(cli.port(), port);
  17279. }
  17280. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17281. auto file_path = "./www/dir/index.html";
  17282. auto dir_path = "./www/dir";
  17283. detail::FileStat stat_file(file_path);
  17284. EXPECT_TRUE(stat_file.is_file());
  17285. EXPECT_FALSE(stat_file.is_dir());
  17286. detail::FileStat stat_dir(dir_path);
  17287. EXPECT_FALSE(stat_dir.is_file());
  17288. EXPECT_TRUE(stat_dir.is_dir());
  17289. }
  17290. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17291. // IPv4 with default HTTP port (80)
  17292. EXPECT_EQ("example.com",
  17293. detail::make_host_and_port_string("example.com", 80, false));
  17294. // IPv4 with default HTTPS port (443)
  17295. EXPECT_EQ("example.com",
  17296. detail::make_host_and_port_string("example.com", 443, true));
  17297. // IPv4 with non-default HTTP port
  17298. EXPECT_EQ("example.com:8080",
  17299. detail::make_host_and_port_string("example.com", 8080, false));
  17300. // IPv4 with non-default HTTPS port
  17301. EXPECT_EQ("example.com:8443",
  17302. detail::make_host_and_port_string("example.com", 8443, true));
  17303. // IPv6 with default HTTP port (80)
  17304. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17305. // IPv6 with default HTTPS port (443)
  17306. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17307. // IPv6 with non-default HTTP port
  17308. EXPECT_EQ("[::1]:8080",
  17309. detail::make_host_and_port_string("::1", 8080, false));
  17310. // IPv6 with non-default HTTPS port
  17311. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17312. // IPv6 full address with default port
  17313. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17314. detail::make_host_and_port_string(
  17315. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17316. // IPv6 full address with non-default port
  17317. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17318. detail::make_host_and_port_string(
  17319. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17320. // IPv6 localhost with non-default port
  17321. EXPECT_EQ("[::1]:3000",
  17322. detail::make_host_and_port_string("::1", 3000, false));
  17323. // IPv6 with zone ID (link-local address) with default port
  17324. EXPECT_EQ("[fe80::1%eth0]",
  17325. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17326. // IPv6 with zone ID (link-local address) with non-default port
  17327. EXPECT_EQ("[fe80::1%eth0]:8080",
  17328. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17329. // Edge case: Port 443 with is_ssl=false (should add port)
  17330. EXPECT_EQ("example.com:443",
  17331. detail::make_host_and_port_string("example.com", 443, false));
  17332. // Edge case: Port 80 with is_ssl=true (should add port)
  17333. EXPECT_EQ("example.com:80",
  17334. detail::make_host_and_port_string("example.com", 80, true));
  17335. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17336. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17337. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17338. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17339. // Security fix: Already bracketed IPv6 should not get double brackets
  17340. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17341. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17342. EXPECT_EQ("[::1]:8080",
  17343. detail::make_host_and_port_string("[::1]", 8080, false));
  17344. EXPECT_EQ("[2001:db8::1]:8080",
  17345. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17346. EXPECT_EQ("[fe80::1%eth0]",
  17347. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17348. EXPECT_EQ("[fe80::1%eth0]:8080",
  17349. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17350. // Edge case: Empty host (should return as-is)
  17351. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17352. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17353. // This is a known limitation but shouldn't crash
  17354. EXPECT_EQ("[host:name]",
  17355. detail::make_host_and_port_string("host:name", 80, false));
  17356. // Port number edge cases (no validation, but should not crash)
  17357. EXPECT_EQ("example.com:0",
  17358. detail::make_host_and_port_string("example.com", 0, false));
  17359. EXPECT_EQ("example.com:-1",
  17360. detail::make_host_and_port_string("example.com", -1, false));
  17361. EXPECT_EQ("example.com:65535",
  17362. detail::make_host_and_port_string("example.com", 65535, false));
  17363. EXPECT_EQ("example.com:65536",
  17364. detail::make_host_and_port_string("example.com", 65536, false));
  17365. }
  17366. #ifdef CPPHTTPLIB_SSL_ENABLED
  17367. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17368. httplib::SSLClient cli("roblox.com", 443);
  17369. cli.set_follow_location(true);
  17370. auto res = cli.Get("/");
  17371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17372. EXPECT_EQ(StatusCode::OK_200, res->status);
  17373. }
  17374. #endif
  17375. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17376. Server svr;
  17377. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17378. EXPECT_EQ(res.status, 400);
  17379. });
  17380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17381. auto se = detail::scope_exit([&] {
  17382. svr.stop();
  17383. thread.join();
  17384. ASSERT_FALSE(svr.is_running());
  17385. });
  17386. svr.wait_until_ready();
  17387. Client cli(HOST, PORT);
  17388. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17389. }
  17390. TEST(InvalidHeaderCharsTest, is_field_name) {
  17391. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17392. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17393. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17394. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17395. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17396. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17397. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17398. EXPECT_FALSE(detail::fields::is_field_name(""));
  17399. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17400. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17401. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17402. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17403. }
  17404. TEST(InvalidHeaderCharsTest, is_field_value) {
  17405. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17406. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17407. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17408. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17409. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17410. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17411. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17412. EXPECT_TRUE(detail::fields::is_field_value(""));
  17413. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17414. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17415. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17416. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17417. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17418. }
  17419. TEST(InvalidHeaderCharsTest, OnServer) {
  17420. Server svr;
  17421. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17422. std::string header = "Not Set";
  17423. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17424. res.set_header(header, "value");
  17425. res.set_content("Page Content Page Content", "text/plain");
  17426. });
  17427. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17428. std::string header = "Not Set";
  17429. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17430. res.set_header("X-Test", header);
  17431. res.set_content("Page Content Page Content", "text/plain");
  17432. });
  17433. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17434. auto se = detail::scope_exit([&] {
  17435. svr.stop();
  17436. thread.join();
  17437. ASSERT_FALSE(svr.is_running());
  17438. });
  17439. svr.wait_until_ready();
  17440. Client cli(HOST, PORT);
  17441. {
  17442. auto res = cli.Get(
  17443. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17445. EXPECT_EQ("Page Content Page Content", res->body);
  17446. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17447. }
  17448. {
  17449. auto res = cli.Get(
  17450. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17452. EXPECT_EQ("Page Content Page Content", res->body);
  17453. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17454. }
  17455. }
  17456. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17457. auto handled = false;
  17458. Server svr;
  17459. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17460. thread t = thread([&] { svr.listen(HOST, PORT); });
  17461. auto se = detail::scope_exit([&] {
  17462. svr.stop();
  17463. t.join();
  17464. ASSERT_FALSE(svr.is_running());
  17465. ASSERT_FALSE(handled);
  17466. });
  17467. svr.wait_until_ready();
  17468. auto req = "POST /test HTTP/1.1\r\n"
  17469. "Content-Length: x\r\n"
  17470. "\r\n";
  17471. std::string response;
  17472. ASSERT_TRUE(send_request(1, req, &response));
  17473. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17474. response.substr(0, response.find("\r\n")));
  17475. }
  17476. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17477. // case-insensitive, and a server that receives a 100-continue expectation in
  17478. // an HTTP/1.0 request MUST ignore it.
  17479. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17480. std::string response;
  17481. ASSERT_TRUE(send_request(1, req, &response, port));
  17482. *got_100 = response.find("100 Continue") != std::string::npos;
  17483. }
  17484. class ExpectTokenTest : public ::testing::Test {
  17485. protected:
  17486. void SetUp() override {
  17487. svr_.Post("/p", [](const Request &, Response &res) {
  17488. res.set_content("ok", "text/plain");
  17489. });
  17490. port_ = svr_.bind_to_any_port(HOST);
  17491. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17492. svr_.wait_until_ready();
  17493. }
  17494. void TearDown() override {
  17495. svr_.stop();
  17496. if (thread_.joinable()) { thread_.join(); }
  17497. }
  17498. std::string request(const char *version, const char *expect_value) const {
  17499. return std::string("POST /p ") + version +
  17500. "\r\n"
  17501. "Host: localhost\r\n"
  17502. "Content-Length: 2\r\n"
  17503. "Connection: close\r\n"
  17504. "Expect: " +
  17505. expect_value +
  17506. "\r\n"
  17507. "\r\n"
  17508. "hi";
  17509. }
  17510. Server svr_;
  17511. int port_ = 0;
  17512. thread thread_;
  17513. };
  17514. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17515. bool got_100 = false;
  17516. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17517. EXPECT_TRUE(got_100);
  17518. }
  17519. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17520. bool got_100 = true;
  17521. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17522. EXPECT_FALSE(got_100);
  17523. }
  17524. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17525. bool got_100 = false;
  17526. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17527. EXPECT_TRUE(got_100);
  17528. }
  17529. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17530. bool got_100 = false;
  17531. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17532. EXPECT_TRUE(got_100);
  17533. }
  17534. // `100 Continue` is sent only when the server starts reading the body, so a
  17535. // request rejected before that never invites the client to send it. The
  17536. // requests below carry the expectation but withhold the body, as a client
  17537. // waiting for `100 Continue` would.
  17538. // A POST that expects `100 Continue` and withholds its two-byte body.
  17539. static std::string expect_headers_only(const std::string &path) {
  17540. return "POST " + path +
  17541. " HTTP/1.1\r\n"
  17542. "Host: localhost\r\n"
  17543. "Content-Length: 2\r\n"
  17544. "Expect: 100-continue\r\n"
  17545. "\r\n";
  17546. }
  17547. class ExpectLazyContinueTest : public ::testing::Test {
  17548. protected:
  17549. void SetUp() override {
  17550. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17551. if (req.path == "/pre-routing") {
  17552. res.status = StatusCode::Unauthorized_401;
  17553. return Server::HandlerResponse::Handled;
  17554. }
  17555. return Server::HandlerResponse::Unhandled;
  17556. });
  17557. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17558. if (req.matched_route == "/pre-request") {
  17559. res.status = StatusCode::Forbidden_403;
  17560. return Server::HandlerResponse::Handled;
  17561. }
  17562. return Server::HandlerResponse::Unhandled;
  17563. });
  17564. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17565. res.set_content("ok", "text/plain");
  17566. });
  17567. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17568. res.set_content("ok", "text/plain");
  17569. });
  17570. svr_.Post("/reader-used", [](const Request &, Response &res,
  17571. const ContentReader &content_reader) {
  17572. std::string body;
  17573. content_reader([&](const char *data, size_t len) {
  17574. body.append(data, len);
  17575. return true;
  17576. });
  17577. res.set_content(body, "text/plain");
  17578. });
  17579. svr_.Post("/reader-unused",
  17580. [](const Request &, Response &res, const ContentReader &) {
  17581. res.set_content("ignored", "text/plain");
  17582. });
  17583. port_ = svr_.bind_to_any_port(HOST);
  17584. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17585. svr_.wait_until_ready();
  17586. }
  17587. void TearDown() override {
  17588. svr_.stop();
  17589. if (thread_.joinable()) { thread_.join(); }
  17590. }
  17591. // Sends `req` and reads until the server closes the connection. Returns
  17592. // false if the read had to wait for the client-side timeout instead.
  17593. bool send_until_closed(const std::string &req, std::string *resp) const {
  17594. auto start = std::chrono::steady_clock::now();
  17595. if (!send_request(3, req, resp, port_)) { return false; }
  17596. auto elapsed = std::chrono::steady_clock::now() - start;
  17597. return elapsed < std::chrono::seconds(2);
  17598. }
  17599. // The final response comes without `100 Continue`, and the server closes
  17600. // the connection since the body may or may not follow.
  17601. void expect_final_without_interim(const std::string &path,
  17602. const char *status_line) const {
  17603. std::string resp;
  17604. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17605. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17606. EXPECT_EQ(0u, resp.find(status_line));
  17607. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17608. }
  17609. Server svr_;
  17610. int port_ = 0;
  17611. thread thread_;
  17612. };
  17613. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17614. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17615. }
  17616. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17617. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17618. }
  17619. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17620. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17621. }
  17622. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17623. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17624. }
  17625. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17626. // The body follows once `100 Continue` has had time to arrive.
  17627. auto req = expect_headers_only("/reader-used");
  17628. req.insert(req.size() - 2, "Connection: close\r\n");
  17629. std::string resp;
  17630. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17631. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17632. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17633. EXPECT_NE(std::string::npos, resp.find("hi"));
  17634. }
  17635. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17636. // Large enough for the client to add `Expect: 100-continue` itself.
  17637. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17638. std::atomic<bool> body_sent{false};
  17639. Client cli(HOST, port_);
  17640. auto res = cli.Post(
  17641. "/pre-request", length,
  17642. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17643. body_sent = true;
  17644. std::string chunk(len, 'x');
  17645. sink.write(chunk.data(), chunk.size());
  17646. return true;
  17647. },
  17648. "application/octet-stream");
  17649. ASSERT_TRUE(res);
  17650. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17651. EXPECT_FALSE(body_sent);
  17652. }
  17653. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17654. Server svr;
  17655. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17656. return StatusCode::ExpectationFailed_417;
  17657. });
  17658. svr.Post("/p", [](const Request &, Response &res) {
  17659. res.set_content("ok", "text/plain");
  17660. });
  17661. auto port = svr.bind_to_any_port(HOST);
  17662. thread t = thread([&] { svr.listen_after_bind(); });
  17663. auto se = detail::scope_exit([&] {
  17664. svr.stop();
  17665. t.join();
  17666. });
  17667. svr.wait_until_ready();
  17668. std::string resp;
  17669. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17670. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17671. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17672. // Exactly one response: the route handler must not run after the 417.
  17673. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17674. }
  17675. #ifndef _WIN32
  17676. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17677. static constexpr char reject[] = "Unauthorized";
  17678. static constexpr char accept[] = "Upload accepted";
  17679. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17680. Server svr;
  17681. svr.set_expect_100_continue_handler(
  17682. [](const Request & /*req*/, Response &res) {
  17683. res.status = StatusCode::Unauthorized_401;
  17684. res.set_content(reject, "text/plain");
  17685. return res.status;
  17686. });
  17687. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17688. res.set_content(accept, "text/plain");
  17689. });
  17690. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17691. auto se = detail::scope_exit([&] {
  17692. svr.stop();
  17693. thread.join();
  17694. ASSERT_FALSE(svr.is_running());
  17695. });
  17696. svr.wait_until_ready();
  17697. {
  17698. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17699. curl_easy_init(), &curl_easy_cleanup};
  17700. ASSERT_NE(curl, nullptr);
  17701. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17702. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17703. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17704. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17705. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17706. &curl_slist_free_all};
  17707. ASSERT_NE(list, nullptr);
  17708. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17709. struct read_data {
  17710. size_t read_size;
  17711. size_t total_size;
  17712. } data = {0, total_size};
  17713. using read_callback_t =
  17714. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17715. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17716. void *userdata) -> size_t {
  17717. read_data *d = (read_data *)userdata;
  17718. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17719. std::fill_n(ptr, size * nmemb, 'A');
  17720. d->read_size += size * nmemb;
  17721. return size * nmemb;
  17722. };
  17723. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17724. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17725. std::vector<char> buffer;
  17726. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17727. using write_callback_t =
  17728. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17729. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17730. void *userdata) -> size_t {
  17731. std::vector<char> *buf = (std::vector<char> *)userdata;
  17732. buf->reserve(buf->size() + size * nmemb + 1);
  17733. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17734. return size * nmemb;
  17735. };
  17736. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17737. {
  17738. const auto res = curl_easy_perform(curl.get());
  17739. ASSERT_EQ(res, CURLE_OK);
  17740. }
  17741. {
  17742. auto response_code = long{};
  17743. const auto res =
  17744. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17745. ASSERT_EQ(res, CURLE_OK);
  17746. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17747. }
  17748. {
  17749. auto dl = curl_off_t{};
  17750. const auto res =
  17751. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17752. ASSERT_EQ(res, CURLE_OK);
  17753. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17754. }
  17755. {
  17756. buffer.push_back('\0');
  17757. ASSERT_STRCASEEQ(buffer.data(), reject);
  17758. }
  17759. }
  17760. }
  17761. #endif
  17762. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17763. // Regression test for #2458.
  17764. //
  17765. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17766. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17767. // ticket can make the client socket spuriously readable during the
  17768. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17769. // the client withholds the body and then blocks reading a response that never
  17770. // comes, failing with `Failed to read connection`.
  17771. //
  17772. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17773. // within the timeout. This raw OpenSSL server deliberately never sends
  17774. // `100 Continue`; the client must still deliver the body and receive 200.
  17775. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17776. signal(SIGPIPE, SIG_IGN);
  17777. const auto port = PORT + 4;
  17778. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17779. ASSERT_NE(srv, INVALID_SOCKET);
  17780. int opt = 1;
  17781. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17782. sockaddr_in addr{};
  17783. addr.sin_family = AF_INET;
  17784. addr.sin_port = htons(static_cast<uint16_t>(port));
  17785. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17786. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17787. ASSERT_EQ(0, ::listen(srv, 1));
  17788. std::atomic<size_t> server_body_bytes{0};
  17789. auto server_thread = std::thread([&] {
  17790. sockaddr_in cli_addr{};
  17791. socklen_t cli_len = sizeof(cli_addr);
  17792. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17793. if (cli == INVALID_SOCKET) { return; }
  17794. // Bound the lifetime of the server side so a buggy client (which never
  17795. // sends the body) cannot make this thread block forever on join.
  17796. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17797. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17798. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17799. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17800. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17801. SSL *ssl = SSL_new(ctx);
  17802. SSL_set_fd(ssl, static_cast<int>(cli));
  17803. if (SSL_accept(ssl) > 0) {
  17804. // Read the request headers. Reading here also flushes the TLS 1.3
  17805. // session tickets to the client. Deliberately do NOT send
  17806. // `100 Continue`.
  17807. std::string buf;
  17808. char tmp[1024];
  17809. while (buf.find("\r\n\r\n") == std::string::npos) {
  17810. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17811. if (n <= 0) { break; }
  17812. buf.append(tmp, static_cast<size_t>(n));
  17813. }
  17814. // A correct client sends the body now; count what arrives.
  17815. auto pos = buf.find("\r\n\r\n");
  17816. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17817. while (body < 4096) {
  17818. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17819. if (n <= 0) { break; }
  17820. body += static_cast<size_t>(n);
  17821. }
  17822. server_body_bytes = body;
  17823. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17824. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17825. SSL_shutdown(ssl);
  17826. }
  17827. SSL_free(ssl);
  17828. detail::close_socket(cli);
  17829. SSL_CTX_free(ctx);
  17830. });
  17831. auto se = detail::scope_exit([&] {
  17832. server_thread.join();
  17833. detail::close_socket(srv);
  17834. });
  17835. SSLClient cli("127.0.0.1", port);
  17836. cli.enable_server_certificate_verification(false);
  17837. cli.set_connection_timeout(5, 0);
  17838. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17839. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17840. std::string body(4096, 'A');
  17841. auto res = cli.Put("/api/test", body, "application/json");
  17842. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17843. EXPECT_EQ(StatusCode::OK_200, res->status);
  17844. EXPECT_EQ(body.size(), server_body_bytes.load());
  17845. }
  17846. #endif
  17847. template <typename S, typename C>
  17848. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17849. svr.Get("/stream", [&](const Request &, Response &res) {
  17850. auto data = new std::string("01234567890123456789");
  17851. res.set_content_provider(
  17852. data->size(), "text/plain",
  17853. [&, data](size_t offset, size_t length, DataSink &sink) {
  17854. const size_t DATA_CHUNK_SIZE = 4;
  17855. const auto &d = *data;
  17856. std::this_thread::sleep_for(std::chrono::seconds(1));
  17857. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17858. return true;
  17859. },
  17860. [data](bool success) {
  17861. EXPECT_FALSE(success);
  17862. delete data;
  17863. });
  17864. });
  17865. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17866. auto i = new size_t(0);
  17867. res.set_content_provider(
  17868. "text/plain",
  17869. [i](size_t, DataSink &sink) {
  17870. if (*i < 5) {
  17871. std::this_thread::sleep_for(std::chrono::seconds(1));
  17872. sink.write("abcd", 4);
  17873. (*i)++;
  17874. } else {
  17875. sink.done();
  17876. }
  17877. return true;
  17878. },
  17879. [i](bool success) {
  17880. EXPECT_FALSE(success);
  17881. delete i;
  17882. });
  17883. });
  17884. svr.Get("/chunked", [&](const Request &, Response &res) {
  17885. auto i = new size_t(0);
  17886. res.set_chunked_content_provider(
  17887. "text/plain",
  17888. [i](size_t, DataSink &sink) {
  17889. if (*i < 5) {
  17890. std::this_thread::sleep_for(std::chrono::seconds(1));
  17891. sink.os << "abcd";
  17892. (*i)++;
  17893. } else {
  17894. sink.done();
  17895. }
  17896. return true;
  17897. },
  17898. [i](bool success) {
  17899. EXPECT_FALSE(success);
  17900. delete i;
  17901. });
  17902. });
  17903. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17904. auto se = detail::scope_exit([&] {
  17905. svr.stop();
  17906. listen_thread.join();
  17907. ASSERT_FALSE(svr.is_running());
  17908. });
  17909. svr.wait_until_ready();
  17910. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17911. {
  17912. auto start = std::chrono::steady_clock::now();
  17913. auto res = cli.Get("/stream");
  17914. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17915. std::chrono::steady_clock::now() - start)
  17916. .count();
  17917. ASSERT_FALSE(res);
  17918. EXPECT_EQ(Error::Read, res.error());
  17919. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17920. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17921. }
  17922. {
  17923. auto start = std::chrono::steady_clock::now();
  17924. auto res = cli.Get("/stream_without_length");
  17925. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17926. std::chrono::steady_clock::now() - start)
  17927. .count();
  17928. ASSERT_FALSE(res);
  17929. EXPECT_EQ(Error::Read, res.error());
  17930. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17931. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17932. }
  17933. {
  17934. auto start = std::chrono::steady_clock::now();
  17935. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17936. EXPECT_EQ("abcd", string(data, data_length));
  17937. return true;
  17938. });
  17939. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17940. std::chrono::steady_clock::now() - start)
  17941. .count();
  17942. ASSERT_FALSE(res);
  17943. EXPECT_EQ(Error::Read, res.error());
  17944. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17945. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17946. }
  17947. }
  17948. TEST(MaxTimeoutTest, ContentStream) {
  17949. time_t timeout = 2000;
  17950. time_t threshold = 200;
  17951. Server svr;
  17952. Client cli("localhost", PORT);
  17953. max_timeout_test(svr, cli, timeout, threshold);
  17954. }
  17955. #ifdef CPPHTTPLIB_SSL_ENABLED
  17956. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17957. time_t timeout = 2000;
  17958. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17960. SSLClient cli("localhost", PORT);
  17961. cli.enable_server_certificate_verification(false);
  17962. max_timeout_test(svr, cli, timeout, threshold);
  17963. }
  17964. #endif
  17965. class EventDispatcher {
  17966. public:
  17967. EventDispatcher() {}
  17968. bool wait_event(DataSink *sink) {
  17969. unique_lock<mutex> lk(m_);
  17970. int id = id_;
  17971. // Wait with timeout to prevent hanging if client disconnects
  17972. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17973. [&] { return cid_ == id; })) {
  17974. return false; // Timeout occurred
  17975. }
  17976. sink->write(message_.data(), message_.size());
  17977. return true;
  17978. }
  17979. void send_event(const string &message) {
  17980. lock_guard<mutex> lk(m_);
  17981. cid_ = id_++;
  17982. message_ = message;
  17983. cv_.notify_all();
  17984. }
  17985. private:
  17986. mutex m_;
  17987. condition_variable cv_;
  17988. atomic_int id_{0};
  17989. atomic_int cid_{-1};
  17990. string message_;
  17991. };
  17992. TEST(ClientInThreadTest, Issue2068) {
  17993. EventDispatcher ed;
  17994. Server svr;
  17995. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17996. res.set_chunked_content_provider("text/event-stream",
  17997. [&](size_t /*offset*/, DataSink &sink) {
  17998. return ed.wait_event(&sink);
  17999. });
  18000. });
  18001. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18002. svr.wait_until_ready();
  18003. thread event_thread([&] {
  18004. int id = 0;
  18005. while (svr.is_running()) {
  18006. this_thread::sleep_for(chrono::milliseconds(500));
  18007. std::stringstream ss;
  18008. ss << "data: " << id << "\n\n";
  18009. ed.send_event(ss.str());
  18010. id++;
  18011. }
  18012. });
  18013. auto se = detail::scope_exit([&] {
  18014. svr.stop();
  18015. listen_thread.join();
  18016. event_thread.join();
  18017. ASSERT_FALSE(svr.is_running());
  18018. });
  18019. {
  18020. auto client = detail::make_unique<Client>(HOST, PORT);
  18021. client->set_read_timeout(std::chrono::minutes(10));
  18022. std::atomic<bool> stop{false};
  18023. std::thread t([&] {
  18024. client->Get("/event1",
  18025. [&](const char *, size_t) -> bool { return !stop; });
  18026. });
  18027. std::this_thread::sleep_for(std::chrono::seconds(2));
  18028. stop = true;
  18029. client->stop();
  18030. t.join();
  18031. // Reset client after thread has finished
  18032. client.reset();
  18033. }
  18034. }
  18035. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18036. auto handled = false;
  18037. Server svr;
  18038. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18039. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18040. auto se = detail::scope_exit([&] {
  18041. svr.stop();
  18042. t.join();
  18043. ASSERT_FALSE(svr.is_running());
  18044. ASSERT_FALSE(handled);
  18045. });
  18046. svr.wait_until_ready();
  18047. // Two Content-Length headers with different values — must be rejected
  18048. auto req = "POST /test HTTP/1.1\r\n"
  18049. "Content-Length: 5\r\n"
  18050. "Content-Length: 10\r\n"
  18051. "\r\n"
  18052. "hello";
  18053. std::string response;
  18054. ASSERT_TRUE(send_request(1, req, &response));
  18055. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18056. response.substr(0, response.find("\r\n")));
  18057. }
  18058. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18059. auto handled = false;
  18060. Server svr;
  18061. svr.Post("/test", [&](const Request &, Response &res) {
  18062. handled = true;
  18063. res.set_content("ok", "text/plain");
  18064. });
  18065. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18066. auto se = detail::scope_exit([&] {
  18067. svr.stop();
  18068. t.join();
  18069. ASSERT_FALSE(svr.is_running());
  18070. ASSERT_TRUE(handled);
  18071. });
  18072. svr.wait_until_ready();
  18073. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18074. auto req = "POST /test HTTP/1.1\r\n"
  18075. "Host: localhost\r\n"
  18076. "Content-Length: 5\r\n"
  18077. "Content-Length: 5\r\n"
  18078. "\r\n"
  18079. "hello";
  18080. std::string response;
  18081. ASSERT_TRUE(send_request(1, req, &response));
  18082. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18083. }
  18084. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18085. Server svr;
  18086. svr.Get("/test", [](const Request &, Response &res) {
  18087. res.set_content("ok", "text/plain");
  18088. });
  18089. auto port = svr.bind_to_any_port(HOST);
  18090. thread t = thread([&] { svr.listen_after_bind(); });
  18091. auto se = detail::scope_exit([&] {
  18092. svr.stop();
  18093. t.join();
  18094. ASSERT_FALSE(svr.is_running());
  18095. });
  18096. svr.wait_until_ready();
  18097. auto status_line = [&](const std::string &host_lines) {
  18098. std::string res;
  18099. send_request(
  18100. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18101. &res, port);
  18102. return res.substr(0, res.find("\r\n"));
  18103. };
  18104. const char *accepted[] = {
  18105. "Host: localhost\r\n",
  18106. "Host: a.example:8080\r\n",
  18107. "Host: my_service\r\n",
  18108. "Host: [::1]:8080\r\n",
  18109. "Host: [fe80::1%25eth0]\r\n",
  18110. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18111. };
  18112. for (auto host_lines : accepted) {
  18113. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18114. }
  18115. const char *rejected[] = {
  18116. "Host: a.example\r\nHost: b.example\r\n",
  18117. "Host: a.example\r\nHost: a.example\r\n",
  18118. "Host: a@b.example\r\n",
  18119. "Host: a.example/b\r\n",
  18120. "Host: a.example\\b\r\n",
  18121. "Host: a.example?b\r\n",
  18122. "Host: a.example#b\r\n",
  18123. "Host: a.example b.example\r\n",
  18124. };
  18125. for (auto host_lines : rejected) {
  18126. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18127. << host_lines;
  18128. }
  18129. }
  18130. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18131. Server svr;
  18132. svr.Get("/", [](const Request &req, Response &res) {
  18133. EXPECT_EQ(2U, req.trailers.size());
  18134. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18135. // Denied
  18136. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18137. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18138. // Accepted
  18139. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18140. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18141. EXPECT_TRUE(req.has_trailer("X-World"));
  18142. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18143. res.set_content("ok", "text/plain");
  18144. });
  18145. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18146. auto se = detail::scope_exit([&] {
  18147. svr.stop();
  18148. t.join();
  18149. ASSERT_FALSE(svr.is_running());
  18150. });
  18151. svr.wait_until_ready();
  18152. const std::string req = "GET / HTTP/1.1\r\n"
  18153. "Transfer-Encoding: chunked\r\n"
  18154. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18155. "\r\n"
  18156. "0\r\n"
  18157. "Content-Length: 10\r\n"
  18158. "Host: internal.local\r\n"
  18159. "Content-Type: malicious/content\r\n"
  18160. "Cookie: any\r\n"
  18161. "Set-Cookie: any\r\n"
  18162. "X-Forwarded-For: attacker.com\r\n"
  18163. "X-Real-Ip: 1.1.1.1\r\n"
  18164. "X-Hello: hello\r\n"
  18165. "X-World: world\r\n"
  18166. "\r\n";
  18167. std::string res;
  18168. ASSERT_TRUE(send_request(1, req, &res));
  18169. }
  18170. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18171. // several field lines, and the combined value is what has to be parsed. A
  18172. // Trailer field split across lines therefore declares every name it lists;
  18173. // reading only the first line silently drops the trailers the later lines
  18174. // declare. The prohibited-trailer filter still applies to every line.
  18175. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18176. Server svr;
  18177. size_t observed_trailer_count = 0;
  18178. std::string observed_hello;
  18179. std::string observed_world;
  18180. bool observed_content_length = true;
  18181. svr.Get("/", [&](const Request &req, Response &res) {
  18182. observed_trailer_count = req.trailers.size();
  18183. observed_hello = req.get_trailer_value("X-Hello");
  18184. observed_world = req.get_trailer_value("X-World");
  18185. observed_content_length = req.has_trailer("Content-Length");
  18186. res.set_content("ok", "text/plain");
  18187. });
  18188. auto port = svr.bind_to_any_port(HOST);
  18189. thread t = thread([&]() { svr.listen_after_bind(); });
  18190. auto se = detail::scope_exit([&] {
  18191. svr.stop();
  18192. t.join();
  18193. ASSERT_FALSE(svr.is_running());
  18194. });
  18195. svr.wait_until_ready();
  18196. const std::string req = "GET / HTTP/1.1\r\n"
  18197. "Host: localhost\r\n"
  18198. "Transfer-Encoding: chunked\r\n"
  18199. "Trailer: X-Hello\r\n"
  18200. "Trailer: X-World, Content-Length\r\n"
  18201. "\r\n"
  18202. "0\r\n"
  18203. "X-Hello: hello\r\n"
  18204. "X-World: world\r\n"
  18205. "Content-Length: 10\r\n"
  18206. "\r\n";
  18207. std::string res;
  18208. ASSERT_TRUE(send_request(1, req, &res, port));
  18209. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18210. // Accepted: both field lines contribute to the declared set
  18211. EXPECT_EQ(2U, observed_trailer_count);
  18212. EXPECT_EQ(observed_hello, "hello");
  18213. EXPECT_EQ(observed_world, "world");
  18214. // Denied: a prohibited name stays prohibited on a later field line
  18215. EXPECT_FALSE(observed_content_length);
  18216. }
  18217. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18218. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18219. // unbounded run of fields that are never declared, because the counter would
  18220. // only advance for declared fields.
  18221. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18222. Server svr;
  18223. bool handler_called = false;
  18224. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18225. handler_called = true;
  18226. res.set_content("ok", "text/plain");
  18227. });
  18228. auto port = svr.bind_to_any_port(HOST);
  18229. thread t = thread([&]() { svr.listen_after_bind(); });
  18230. auto se = detail::scope_exit([&] {
  18231. svr.stop();
  18232. t.join();
  18233. ASSERT_FALSE(svr.is_running());
  18234. });
  18235. svr.wait_until_ready();
  18236. // Declare nothing, then send far more undeclared trailer fields than the
  18237. // header-count limit. Parsing must stop and reject the request rather than
  18238. // read every line.
  18239. std::string req = "GET / HTTP/1.1\r\n"
  18240. "Transfer-Encoding: chunked\r\n"
  18241. "\r\n"
  18242. "0\r\n";
  18243. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18244. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18245. }
  18246. req += "\r\n";
  18247. std::string res;
  18248. ASSERT_TRUE(send_request(1, req, &res, port));
  18249. // The request is rejected before the handler runs.
  18250. EXPECT_FALSE(handler_called);
  18251. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18252. }
  18253. // The set of declared trailer names is capped so a peer cannot grow it without
  18254. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18255. // declared past the cap is not honored, even if the field is actually sent.
  18256. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18257. Server svr;
  18258. // One name inside the cap and one past it, so the test tracks the cap rather
  18259. // than a fixed count.
  18260. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18261. const std::string within_cap_name = "X-T-0";
  18262. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18263. bool observed_within_cap = false;
  18264. bool observed_past_cap = false;
  18265. svr.Get("/", [&](const Request &req, Response &res) {
  18266. observed_within_cap = req.has_trailer(within_cap_name);
  18267. observed_past_cap = req.has_trailer(past_cap_name);
  18268. res.set_content("ok", "text/plain");
  18269. });
  18270. auto port = svr.bind_to_any_port(HOST);
  18271. thread t = thread([&]() { svr.listen_after_bind(); });
  18272. auto se = detail::scope_exit([&] {
  18273. svr.stop();
  18274. t.join();
  18275. ASSERT_FALSE(svr.is_running());
  18276. });
  18277. svr.wait_until_ready();
  18278. // Declare more trailer names than the cap in a single Trailer field, then
  18279. // actually send the first (within the cap) and the last (past it).
  18280. std::string trailer_decl = "Trailer: ";
  18281. for (int i = 0; i < declared_count; i++) {
  18282. if (i != 0) { trailer_decl += ", "; }
  18283. trailer_decl += "X-T-" + std::to_string(i);
  18284. }
  18285. trailer_decl += "\r\n";
  18286. const std::string req = "GET / HTTP/1.1\r\n"
  18287. "Host: localhost\r\n"
  18288. "Transfer-Encoding: chunked\r\n" +
  18289. trailer_decl +
  18290. "\r\n"
  18291. "0\r\n" +
  18292. within_cap_name + ": a\r\n" + past_cap_name +
  18293. ": b\r\n"
  18294. "\r\n";
  18295. std::string res;
  18296. ASSERT_TRUE(send_request(1, req, &res, port));
  18297. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18298. // A name within the cap is honored; one declared past the cap is dropped.
  18299. EXPECT_TRUE(observed_within_cap);
  18300. EXPECT_FALSE(observed_past_cap);
  18301. }
  18302. // A direct client that is not listed in trusted_proxies must not be able to
  18303. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18304. // the peer address on the actual TCP connection determines whether the
  18305. // header is honored.
  18306. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18307. Server svr;
  18308. // Deliberately does NOT include the loopback address the test client
  18309. // actually connects from, so the direct connection is not a trusted proxy.
  18310. svr.set_trusted_proxies({"203.0.113.66"});
  18311. std::string observed_remote_addr;
  18312. svr.Get("/ip", [&](const Request &req, Response &res) {
  18313. observed_remote_addr = req.remote_addr;
  18314. res.set_content("ok", "text/plain");
  18315. });
  18316. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18317. auto se = detail::scope_exit([&] {
  18318. svr.stop();
  18319. t.join();
  18320. ASSERT_FALSE(svr.is_running());
  18321. });
  18322. svr.wait_until_ready();
  18323. Client cli(HOST, PORT);
  18324. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18326. EXPECT_EQ(StatusCode::OK_200, res->status);
  18327. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18328. // ignored entirely and the real connection-level address retained.
  18329. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18330. observed_remote_addr == "127.0.0.1");
  18331. }
  18332. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18333. Server svr;
  18334. std::string observed_remote_addr;
  18335. std::string observed_xff;
  18336. svr.Get("/ip", [&](const Request &req, Response &res) {
  18337. observed_remote_addr = req.remote_addr;
  18338. observed_xff = req.get_header_value("X-Forwarded-For");
  18339. res.set_content("ok", "text/plain");
  18340. });
  18341. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18342. auto se = detail::scope_exit([&] {
  18343. svr.stop();
  18344. t.join();
  18345. ASSERT_FALSE(svr.is_running());
  18346. });
  18347. svr.wait_until_ready();
  18348. Client cli(HOST, PORT);
  18349. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18351. EXPECT_EQ(StatusCode::OK_200, res->status);
  18352. EXPECT_EQ(observed_xff, "203.0.113.66");
  18353. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18354. observed_remote_addr == "127.0.0.1");
  18355. }
  18356. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18357. Server svr;
  18358. svr.set_trusted_proxies({"203.0.113.66"});
  18359. std::string observed_remote_addr;
  18360. std::string observed_xff;
  18361. svr.Get("/ip", [&](const Request &req, Response &res) {
  18362. observed_remote_addr = req.remote_addr;
  18363. observed_xff = req.get_header_value("X-Forwarded-For");
  18364. res.set_content("ok", "text/plain");
  18365. });
  18366. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18367. auto se = detail::scope_exit([&] {
  18368. svr.stop();
  18369. t.join();
  18370. ASSERT_FALSE(svr.is_running());
  18371. });
  18372. svr.wait_until_ready();
  18373. Client cli(HOST, PORT);
  18374. auto res = cli.Get("/ip");
  18375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18376. EXPECT_EQ(StatusCode::OK_200, res->status);
  18377. EXPECT_EQ(observed_xff, "");
  18378. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18379. observed_remote_addr == "127.0.0.1");
  18380. }
  18381. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18382. Server svr;
  18383. // Include the loopback address the test client actually connects from, so
  18384. // the direct connection itself is recognized as the trusted proxy hop.
  18385. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18386. std::string observed_remote_addr;
  18387. std::string observed_xff;
  18388. svr.Get("/ip", [&](const Request &req, Response &res) {
  18389. observed_remote_addr = req.remote_addr;
  18390. observed_xff = req.get_header_value("X-Forwarded-For");
  18391. res.set_content("ok", "text/plain");
  18392. });
  18393. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18394. auto se = detail::scope_exit([&] {
  18395. svr.stop();
  18396. t.join();
  18397. ASSERT_FALSE(svr.is_running());
  18398. });
  18399. svr.wait_until_ready();
  18400. Client cli(HOST, PORT);
  18401. auto res = cli.Get(
  18402. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18404. EXPECT_EQ(StatusCode::OK_200, res->status);
  18405. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18406. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18407. }
  18408. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18409. Server svr;
  18410. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18411. std::string observed_remote_addr;
  18412. std::string observed_xff;
  18413. svr.Get("/ip", [&](const Request &req, Response &res) {
  18414. observed_remote_addr = req.remote_addr;
  18415. observed_xff = req.get_header_value("X-Forwarded-For");
  18416. res.set_content("ok", "text/plain");
  18417. });
  18418. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18419. auto se = detail::scope_exit([&] {
  18420. svr.stop();
  18421. t.join();
  18422. ASSERT_FALSE(svr.is_running());
  18423. });
  18424. svr.wait_until_ready();
  18425. Client cli(HOST, PORT);
  18426. auto res = cli.Get(
  18427. "/ip",
  18428. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18430. EXPECT_EQ(StatusCode::OK_200, res->status);
  18431. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18432. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18433. }
  18434. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18435. Server svr;
  18436. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18437. std::string observed_remote_addr;
  18438. std::string observed_xff;
  18439. svr.Get("/ip", [&](const Request &req, Response &res) {
  18440. observed_remote_addr = req.remote_addr;
  18441. observed_xff = req.get_header_value("X-Forwarded-For");
  18442. res.set_content("ok", "text/plain");
  18443. });
  18444. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18445. auto se = detail::scope_exit([&] {
  18446. svr.stop();
  18447. t.join();
  18448. ASSERT_FALSE(svr.is_running());
  18449. });
  18450. svr.wait_until_ready();
  18451. Client cli(HOST, PORT);
  18452. auto res = cli.Get(
  18453. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18455. EXPECT_EQ(StatusCode::OK_200, res->status);
  18456. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18457. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18458. // and must not be selected.
  18459. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18460. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18461. }
  18462. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18463. Server svr;
  18464. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18465. std::string observed_remote_addr;
  18466. svr.Get("/ip", [&](const Request &req, Response &res) {
  18467. observed_remote_addr = req.remote_addr;
  18468. res.set_content("ok", "text/plain");
  18469. });
  18470. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18471. auto se = detail::scope_exit([&] {
  18472. svr.stop();
  18473. t.join();
  18474. ASSERT_FALSE(svr.is_running());
  18475. });
  18476. svr.wait_until_ready();
  18477. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18478. // a forged address and the trusted proxy's own address; the forged value must
  18479. // not win over the address the trusted proxy actually recorded.
  18480. Client cli(HOST, PORT);
  18481. auto res = cli.Get(
  18482. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18484. EXPECT_EQ(StatusCode::OK_200, res->status);
  18485. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18486. }
  18487. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18488. Server svr;
  18489. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18490. std::string observed_remote_addr;
  18491. std::string observed_xff;
  18492. svr.Get("/ip", [&](const Request &req, Response &res) {
  18493. observed_remote_addr = req.remote_addr;
  18494. observed_xff = req.get_header_value("X-Forwarded-For");
  18495. res.set_content("ok", "text/plain");
  18496. });
  18497. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18498. auto se = detail::scope_exit([&] {
  18499. svr.stop();
  18500. t.join();
  18501. ASSERT_FALSE(svr.is_running());
  18502. });
  18503. svr.wait_until_ready();
  18504. Client cli(HOST, PORT);
  18505. auto res = cli.Get(
  18506. "/ip",
  18507. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18509. EXPECT_EQ(StatusCode::OK_200, res->status);
  18510. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18511. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18512. }
  18513. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18514. Server svr;
  18515. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18516. std::string observed_remote_addr;
  18517. std::string observed_xff;
  18518. svr.Get("/ip", [&](const Request &req, Response &res) {
  18519. observed_remote_addr = req.remote_addr;
  18520. observed_xff = req.get_header_value("X-Forwarded-For");
  18521. res.set_content("ok", "text/plain");
  18522. });
  18523. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18524. auto se = detail::scope_exit([&] {
  18525. svr.stop();
  18526. t.join();
  18527. ASSERT_FALSE(svr.is_running());
  18528. });
  18529. svr.wait_until_ready();
  18530. std::string raw_req =
  18531. "GET /ip HTTP/1.1\r\n"
  18532. "Host: localhost\r\n"
  18533. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18534. "Connection: close\r\n"
  18535. "\r\n";
  18536. std::string out;
  18537. ASSERT_TRUE(send_request(5, raw_req, &out));
  18538. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18539. // Header parser trims surrounding whitespace of the header value
  18540. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18541. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18542. }
  18543. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18544. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18545. // their own X-Forwarded-For as a separate field line rather than extending the
  18546. // one the client sent, so every occurrence has to be taken into account.
  18547. // Reading only the first one hands back the address the client chose.
  18548. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18549. Server svr;
  18550. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18551. std::string observed_remote_addr;
  18552. size_t observed_xff_count = 0;
  18553. svr.Get("/ip", [&](const Request &req, Response &res) {
  18554. observed_remote_addr = req.remote_addr;
  18555. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18556. res.set_content("ok", "text/plain");
  18557. });
  18558. auto port = svr.bind_to_any_port(HOST);
  18559. thread t = thread([&]() { svr.listen_after_bind(); });
  18560. auto se = detail::scope_exit([&] {
  18561. svr.stop();
  18562. t.join();
  18563. ASSERT_FALSE(svr.is_running());
  18564. });
  18565. svr.wait_until_ready();
  18566. // The client supplies the first field line; the trusted proxy appends the
  18567. // address it observed as a second one.
  18568. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18569. "Host: localhost\r\n"
  18570. "X-Forwarded-For: 1.2.3.4\r\n"
  18571. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18572. "Connection: close\r\n"
  18573. "\r\n";
  18574. std::string out;
  18575. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18576. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18577. EXPECT_EQ(observed_xff_count, 2U);
  18578. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18579. // The same chain spread over one field line per hop derives the same client
  18580. // address, i.e. the split and the comma-joined representations agree.
  18581. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18582. "Host: localhost\r\n"
  18583. "X-Forwarded-For: 1.2.3.4\r\n"
  18584. "X-Forwarded-For: 198.51.100.23\r\n"
  18585. "X-Forwarded-For: 192.0.2.45\r\n"
  18586. "Connection: close\r\n"
  18587. "\r\n";
  18588. out.clear();
  18589. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18590. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18591. EXPECT_EQ(observed_xff_count, 3U);
  18592. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18593. }
  18594. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18595. // crash the server (it used to call front() on an empty vector inside
  18596. // get_client_ip). The connection-level remote address must be retained instead.
  18597. static void run_malformed_xff_test(const std::string &xff_value) {
  18598. Server svr;
  18599. svr.set_trusted_proxies({"192.0.2.45"});
  18600. std::string observed_remote_addr;
  18601. svr.Get("/ip", [&](const Request &req, Response &res) {
  18602. observed_remote_addr = req.remote_addr;
  18603. res.set_content("ok", "text/plain");
  18604. });
  18605. int port = 0;
  18606. thread t = thread([&]() {
  18607. port = svr.bind_to_any_port(HOST);
  18608. svr.listen_after_bind();
  18609. });
  18610. auto se = detail::scope_exit([&] {
  18611. svr.stop();
  18612. t.join();
  18613. ASSERT_FALSE(svr.is_running());
  18614. });
  18615. svr.wait_until_ready();
  18616. Client cli(HOST, port);
  18617. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18619. EXPECT_EQ(StatusCode::OK_200, res->status);
  18620. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18621. observed_remote_addr == "127.0.0.1");
  18622. }
  18623. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18624. run_malformed_xff_test("");
  18625. }
  18626. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18627. run_malformed_xff_test(",");
  18628. }
  18629. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18630. run_malformed_xff_test(", , ,");
  18631. }
  18632. // The same rule applies to Accept: a request whose acceptable types are spread
  18633. // over several field lines must be negotiated against all of them.
  18634. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18635. // case-insensitive connection options. Comparing the whole field value against
  18636. // one option misses a client that sends several of them, and misses every
  18637. // casing but the one written in the comparison.
  18638. //
  18639. // Sends req, reads the response, then reuses the same socket for a second
  18640. // request to find out whether the server kept the connection.
  18641. static void probe_connection_reuse(int port, const std::string &req,
  18642. bool *announced_close, bool *reusable) {
  18643. auto error = Error::Success;
  18644. auto sock = detail::create_client_socket(
  18645. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18646. /*connection_timeout_sec=*/5, 0,
  18647. /*read_timeout_sec=*/1, 0,
  18648. /*write_timeout_sec=*/5, 0, std::string(), error);
  18649. ASSERT_NE(sock, INVALID_SOCKET);
  18650. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18651. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18652. "Host: localhost\r\n"
  18653. "Connection: close\r\n"
  18654. "\r\n";
  18655. std::string first_response;
  18656. std::string second_response;
  18657. detail::process_client_socket(
  18658. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18659. [&](Stream &strm) {
  18660. if (strm.write(req.data(), req.size()) !=
  18661. static_cast<ssize_t>(req.size())) {
  18662. return false;
  18663. }
  18664. char buf[512];
  18665. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18666. // Headers plus the two-byte body of the handler below
  18667. while (reader.getline()) {
  18668. first_response += reader.ptr();
  18669. if (first_response.find("ok") != std::string::npos) { break; }
  18670. }
  18671. if (strm.write(second.data(), second.size()) !=
  18672. static_cast<ssize_t>(second.size())) {
  18673. return true;
  18674. }
  18675. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18676. while (reader2.getline()) {
  18677. second_response += reader2.ptr();
  18678. if (second_response.find("ok") != std::string::npos) { break; }
  18679. }
  18680. return true;
  18681. });
  18682. *announced_close =
  18683. first_response.find("Connection: close") != std::string::npos;
  18684. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18685. }
  18686. class ConnectionTokenTest : public ::testing::Test {
  18687. protected:
  18688. void SetUp() override {
  18689. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18690. res.set_content("ok", "text/plain");
  18691. });
  18692. port_ = svr_.bind_to_any_port(HOST);
  18693. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18694. svr_.wait_until_ready();
  18695. }
  18696. void TearDown() override {
  18697. svr_.stop();
  18698. if (thread_.joinable()) { thread_.join(); }
  18699. }
  18700. Server svr_;
  18701. int port_ = 0;
  18702. thread thread_;
  18703. };
  18704. // "close" alongside another option still closes the connection, and the
  18705. // response says so rather than leaving the peer to discover it.
  18706. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18707. bool announced_close = false;
  18708. bool reusable = true;
  18709. probe_connection_reuse(port_,
  18710. "GET /keepalive HTTP/1.1\r\n"
  18711. "Host: localhost\r\n"
  18712. "Connection: keep-alive, close\r\n"
  18713. "\r\n",
  18714. &announced_close, &reusable);
  18715. EXPECT_TRUE(announced_close);
  18716. EXPECT_FALSE(reusable);
  18717. }
  18718. // "close" split over two field lines is the same list, so it is honored too.
  18719. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18720. bool announced_close = false;
  18721. bool reusable = true;
  18722. probe_connection_reuse(port_,
  18723. "GET /keepalive HTTP/1.1\r\n"
  18724. "Host: localhost\r\n"
  18725. "Connection: keep-alive\r\n"
  18726. "Connection: close\r\n"
  18727. "\r\n",
  18728. &announced_close, &reusable);
  18729. EXPECT_TRUE(announced_close);
  18730. EXPECT_FALSE(reusable);
  18731. }
  18732. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18733. // keep-alive in the spelling everyone actually sends keeps its connection.
  18734. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18735. bool announced_close = false;
  18736. bool reusable = false;
  18737. probe_connection_reuse(port_,
  18738. "GET /keepalive HTTP/1.0\r\n"
  18739. "Host: localhost\r\n"
  18740. "Connection: keep-alive\r\n"
  18741. "\r\n",
  18742. &announced_close, &reusable);
  18743. EXPECT_FALSE(announced_close);
  18744. EXPECT_TRUE(reusable);
  18745. }
  18746. // A token the value merely contains is not the token itself.
  18747. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18748. bool announced_close = false;
  18749. bool reusable = false;
  18750. probe_connection_reuse(port_,
  18751. "GET /keepalive HTTP/1.1\r\n"
  18752. "Host: localhost\r\n"
  18753. "Connection: notclose\r\n"
  18754. "\r\n",
  18755. &announced_close, &reusable);
  18756. EXPECT_FALSE(announced_close);
  18757. EXPECT_TRUE(reusable);
  18758. }
  18759. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18760. Server svr;
  18761. std::vector<std::string> observed_types;
  18762. svr.Get("/", [&](const Request &req, Response &res) {
  18763. observed_types = req.accept_content_types;
  18764. res.set_content("ok", "text/plain");
  18765. });
  18766. auto port = svr.bind_to_any_port(HOST);
  18767. thread t = thread([&]() { svr.listen_after_bind(); });
  18768. auto se = detail::scope_exit([&] {
  18769. svr.stop();
  18770. t.join();
  18771. ASSERT_FALSE(svr.is_running());
  18772. });
  18773. svr.wait_until_ready();
  18774. Client cli(HOST, port);
  18775. Headers headers;
  18776. headers.emplace("Accept", "text/plain;q=0.5");
  18777. headers.emplace("Accept", "application/json");
  18778. auto res = cli.Get("/", headers);
  18779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18780. EXPECT_EQ(StatusCode::OK_200, res->status);
  18781. // Sorted by q-value, so the second field line's type comes first
  18782. ASSERT_EQ(2U, observed_types.size());
  18783. EXPECT_EQ("application/json", observed_types[0]);
  18784. EXPECT_EQ("text/plain", observed_types[1]);
  18785. }
  18786. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18787. // empty field line must not contribute a bare comma to the combined value.
  18788. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18789. Server svr;
  18790. std::vector<std::string> observed_types;
  18791. svr.Get("/", [&](const Request &req, Response &res) {
  18792. observed_types = req.accept_content_types;
  18793. res.set_content("ok", "text/plain");
  18794. });
  18795. auto port = svr.bind_to_any_port(HOST);
  18796. thread t = thread([&]() { svr.listen_after_bind(); });
  18797. auto se = detail::scope_exit([&] {
  18798. svr.stop();
  18799. t.join();
  18800. ASSERT_FALSE(svr.is_running());
  18801. });
  18802. svr.wait_until_ready();
  18803. // Empty first field line, then a real one
  18804. std::string raw_req = "GET / HTTP/1.1\r\n"
  18805. "Host: localhost\r\n"
  18806. "Accept:\r\n"
  18807. "Accept: application/json\r\n"
  18808. "Connection: close\r\n"
  18809. "\r\n";
  18810. std::string out;
  18811. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18812. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18813. ASSERT_EQ(1U, observed_types.size());
  18814. EXPECT_EQ("application/json", observed_types[0]);
  18815. }
  18816. // The skip in get_combined_header_value() is what keeps an empty field line
  18817. // from contributing a bare comma. Only a trailing empty field line exercises
  18818. // it: a leading one is already covered by the "combined is still empty" check,
  18819. // and parse_accept_header() now ignores the empty element either way, so the
  18820. // request-level test above can no longer tell the two apart.
  18821. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18822. Headers headers;
  18823. headers.emplace("Accept", "text/html");
  18824. headers.emplace("Accept", "");
  18825. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18826. headers.clear();
  18827. headers.emplace("Accept", "");
  18828. headers.emplace("Accept", "application/json");
  18829. EXPECT_EQ("application/json",
  18830. detail::get_combined_header_value(headers, "Accept"));
  18831. }
  18832. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18833. // An encoding offered on a later Accept-Encoding field line is still offered.
  18834. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18835. Server svr;
  18836. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18837. res.set_content(std::string(1024, 'x'), "text/plain");
  18838. });
  18839. auto port = svr.bind_to_any_port(HOST);
  18840. thread t = thread([&]() { svr.listen_after_bind(); });
  18841. auto se = detail::scope_exit([&] {
  18842. svr.stop();
  18843. t.join();
  18844. ASSERT_FALSE(svr.is_running());
  18845. });
  18846. svr.wait_until_ready();
  18847. Client cli(HOST, port);
  18848. cli.set_decompress(false);
  18849. Headers headers;
  18850. headers.emplace("Accept-Encoding", "identity");
  18851. headers.emplace("Accept-Encoding", "gzip");
  18852. auto res = cli.Get("/", headers);
  18853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18854. EXPECT_EQ(StatusCode::OK_200, res->status);
  18855. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18856. }
  18857. #endif
  18858. #ifndef _WIN32
  18859. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18860. Server svr;
  18861. svr.Post("/post", [&](const Request &req, Response &res) {
  18862. res.set_content(req.body, "text/plain");
  18863. });
  18864. svr.Put("/put", [&](const Request &req, Response &res) {
  18865. res.set_content(req.body, "text/plain");
  18866. });
  18867. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18868. res.set_content(req.body, "text/plain");
  18869. });
  18870. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18871. res.set_content(req.body, "text/plain");
  18872. });
  18873. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18874. auto se = detail::scope_exit([&] {
  18875. svr.stop();
  18876. t.join();
  18877. ASSERT_FALSE(svr.is_running());
  18878. });
  18879. svr.wait_until_ready();
  18880. std::string resp;
  18881. // POST without Content-Length
  18882. ASSERT_TRUE(send_request(5,
  18883. "POST /post HTTP/1.1\r\n"
  18884. "Host: localhost\r\n"
  18885. "Connection: close\r\n"
  18886. "\r\n",
  18887. &resp));
  18888. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18889. // PUT without Content-Length
  18890. resp.clear();
  18891. ASSERT_TRUE(send_request(5,
  18892. "PUT /put HTTP/1.1\r\n"
  18893. "Host: localhost\r\n"
  18894. "Connection: close\r\n"
  18895. "\r\n",
  18896. &resp));
  18897. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18898. // PATCH without Content-Length
  18899. resp.clear();
  18900. ASSERT_TRUE(send_request(5,
  18901. "PATCH /patch HTTP/1.1\r\n"
  18902. "Host: localhost\r\n"
  18903. "Connection: close\r\n"
  18904. "\r\n",
  18905. &resp));
  18906. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18907. // DELETE without Content-Length
  18908. resp.clear();
  18909. ASSERT_TRUE(send_request(5,
  18910. "DELETE /delete HTTP/1.1\r\n"
  18911. "Host: localhost\r\n"
  18912. "Connection: close\r\n"
  18913. "\r\n",
  18914. &resp));
  18915. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18916. }
  18917. #endif
  18918. //==============================================================================
  18919. // open_stream() Tests
  18920. //==============================================================================
  18921. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18922. std::string result;
  18923. char buf[8192];
  18924. ssize_t n;
  18925. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18926. result.append(buf, static_cast<size_t>(n));
  18927. }
  18928. return result;
  18929. }
  18930. // Mock stream for unit tests
  18931. class MockStream : public Stream {
  18932. public:
  18933. std::string data;
  18934. size_t pos = 0;
  18935. ssize_t error_after = -1; // -1 = no error
  18936. explicit MockStream(const std::string &d, ssize_t err = -1)
  18937. : data(d), error_after(err) {}
  18938. bool is_readable() const override { return true; }
  18939. bool wait_readable() const override { return true; }
  18940. bool wait_writable() const override { return true; }
  18941. ssize_t read(char *ptr, size_t size) override {
  18942. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18943. if (pos >= data.size()) return 0;
  18944. size_t limit =
  18945. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18946. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18947. std::memcpy(ptr, data.data() + pos, to_read);
  18948. pos += to_read;
  18949. return static_cast<ssize_t>(to_read);
  18950. }
  18951. ssize_t write(const char *, size_t) override { return -1; }
  18952. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18953. ip = "127.0.0.1";
  18954. port = 0;
  18955. }
  18956. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18957. ip = "127.0.0.1";
  18958. port = 0;
  18959. }
  18960. socket_t socket() const override { return INVALID_SOCKET; }
  18961. time_t duration() const override { return 0; }
  18962. };
  18963. TEST(StreamHandleTest, Basic) {
  18964. ClientImpl::StreamHandle handle;
  18965. EXPECT_FALSE(handle.is_valid());
  18966. handle.response = detail::make_unique<Response>();
  18967. handle.error = Error::Connection;
  18968. EXPECT_FALSE(handle.is_valid());
  18969. handle.error = Error::Success;
  18970. EXPECT_TRUE(handle.is_valid());
  18971. }
  18972. TEST(BodyReaderTest, Basic) {
  18973. MockStream stream("Hello, World!");
  18974. detail::BodyReader reader;
  18975. reader.stream = &stream;
  18976. reader.content_length = 13;
  18977. char buf[32];
  18978. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18979. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18980. EXPECT_TRUE(reader.eof);
  18981. }
  18982. TEST(BodyReaderTest, NoStream) {
  18983. detail::BodyReader reader;
  18984. char buf[32];
  18985. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18986. EXPECT_EQ(Error::Connection, reader.last_error);
  18987. }
  18988. TEST(BodyReaderTest, Error) {
  18989. MockStream stream("Hello, World!", 5);
  18990. detail::BodyReader reader;
  18991. reader.stream = &stream;
  18992. reader.content_length = 13;
  18993. char buf[32];
  18994. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18995. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18996. EXPECT_EQ(Error::Read, reader.last_error);
  18997. }
  18998. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18999. // Mock-based StreamHandle tests relying on private internals are removed.
  19000. class OpenStreamTest : public ::testing::Test {
  19001. protected:
  19002. void SetUp() override {
  19003. svr_.Get("/hello", [](const Request &, Response &res) {
  19004. res.set_content("Hello World!", "text/plain");
  19005. });
  19006. svr_.Get("/large", [](const Request &, Response &res) {
  19007. res.set_content(std::string(10000, 'X'), "text/plain");
  19008. });
  19009. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19010. res.set_content("Hello World!", "image/jpeg");
  19011. res.set_header("Content-Encoding", "UTF-8");
  19012. });
  19013. svr_.Get("/chunked", [](const Request &, Response &res) {
  19014. res.set_chunked_content_provider("text/plain",
  19015. [](size_t offset, DataSink &sink) {
  19016. if (offset < 15) {
  19017. sink.write("chunk", 5);
  19018. return true;
  19019. }
  19020. sink.done();
  19021. return true;
  19022. });
  19023. });
  19024. svr_.Get("/compressible", [](const Request &, Response &res) {
  19025. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19026. DataSink &sink) {
  19027. if (offset < 100 * 1024) {
  19028. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19029. sink.write(chunk.data(), chunk.size());
  19030. return true;
  19031. }
  19032. sink.done();
  19033. return true;
  19034. });
  19035. });
  19036. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19037. [](const Request & /*req*/, Response &res) {
  19038. auto i = new int(0);
  19039. res.set_header("Trailer", "Content-Length, X-Allowed");
  19040. res.set_chunked_content_provider(
  19041. "text/plain",
  19042. [i](size_t /*offset*/, DataSink &sink) {
  19043. switch (*i) {
  19044. case 0: sink.os << "123"; break;
  19045. case 1: sink.os << "456"; break;
  19046. case 2: sink.os << "789"; break;
  19047. case 3: {
  19048. sink.done_with_trailer(
  19049. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19050. } break;
  19051. }
  19052. (*i)++;
  19053. return true;
  19054. },
  19055. [i](bool success) {
  19056. EXPECT_TRUE(success);
  19057. delete i;
  19058. });
  19059. });
  19060. // Echo headers endpoint for header-related tests
  19061. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19062. std::string body;
  19063. for (const auto &h : req.headers) {
  19064. body.append(h.first);
  19065. body.push_back(':');
  19066. body.append(h.second);
  19067. body.push_back('\n');
  19068. }
  19069. res.set_content(body, "text/plain");
  19070. });
  19071. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19072. std::string body;
  19073. for (const auto &h : req.headers) {
  19074. body.append(h.first);
  19075. body.push_back(':');
  19076. body.append(h.second);
  19077. body.push_back('\n');
  19078. }
  19079. res.set_content(body, "text/plain");
  19080. });
  19081. port_ = svr_.bind_to_any_port("127.0.0.1");
  19082. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19083. svr_.wait_until_ready();
  19084. }
  19085. void TearDown() override {
  19086. svr_.stop();
  19087. if (thread_.joinable()) thread_.join();
  19088. }
  19089. Server svr_;
  19090. std::thread thread_;
  19091. int port_ = 0;
  19092. };
  19093. TEST_F(OpenStreamTest, Basic) {
  19094. Client cli("127.0.0.1", port_);
  19095. auto handle = cli.open_stream("GET", "/hello");
  19096. EXPECT_TRUE(handle.is_valid());
  19097. EXPECT_EQ("Hello World!", read_all(handle));
  19098. }
  19099. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19100. Client cli("127.0.0.1", port_);
  19101. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19102. ASSERT_TRUE(handle.is_valid());
  19103. EXPECT_EQ("Hello World!", read_all(handle));
  19104. }
  19105. TEST_F(OpenStreamTest, SmallBuffer) {
  19106. Client cli("127.0.0.1", port_);
  19107. auto handle = cli.open_stream("GET", "/hello");
  19108. std::string result;
  19109. char buf[4];
  19110. ssize_t n;
  19111. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19112. result.append(buf, static_cast<size_t>(n));
  19113. EXPECT_EQ("Hello World!", result);
  19114. }
  19115. TEST_F(OpenStreamTest, DefaultHeaders) {
  19116. Client cli("127.0.0.1", port_);
  19117. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19118. {
  19119. auto handle = cli.open_stream("GET", "/echo-headers");
  19120. ASSERT_TRUE(handle.is_valid());
  19121. auto body = read_all(handle);
  19122. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19123. std::string::npos);
  19124. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19125. std::string::npos);
  19126. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19127. }
  19128. // open_stream POST with body and no explicit content_type should NOT add
  19129. // text/plain Content-Type (behavior differs from non-streaming path), but
  19130. // should include Content-Length
  19131. {
  19132. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19133. ASSERT_TRUE(handle.is_valid());
  19134. auto body = read_all(handle);
  19135. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19136. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19137. }
  19138. // open_stream POST with explicit Content-Type should preserve it
  19139. {
  19140. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19141. {{"Content-Type", "application/custom"}},
  19142. "{}", "application/custom");
  19143. ASSERT_TRUE(handle.is_valid());
  19144. auto body = read_all(handle);
  19145. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19146. }
  19147. // User-specified User-Agent must not be overwritten for stream API
  19148. {
  19149. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19150. {{"User-Agent", "MyAgent/1.2"}});
  19151. ASSERT_TRUE(handle.is_valid());
  19152. auto body = read_all(handle);
  19153. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19154. }
  19155. }
  19156. TEST_F(OpenStreamTest, Large) {
  19157. Client cli("127.0.0.1", port_);
  19158. auto handle = cli.open_stream("GET", "/large");
  19159. EXPECT_EQ(10000u, read_all(handle).size());
  19160. }
  19161. TEST_F(OpenStreamTest, ConnectionError) {
  19162. Client cli("127.0.0.1", 9999);
  19163. auto handle = cli.open_stream("GET", "/hello");
  19164. EXPECT_FALSE(handle.is_valid());
  19165. }
  19166. TEST_F(OpenStreamTest, Chunked) {
  19167. Client cli("127.0.0.1", port_);
  19168. auto handle = cli.open_stream("GET", "/chunked");
  19169. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19170. "Transfer-Encoding") == "chunked");
  19171. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19172. }
  19173. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19174. Client cli("127.0.0.1", port_);
  19175. auto handle =
  19176. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19177. ASSERT_TRUE(handle.is_valid());
  19178. // Consume body to allow trailers to be received/parsed
  19179. auto body = read_all(handle);
  19180. // Explicitly parse trailers (ensure trailers are available for assertion)
  19181. handle.parse_trailers_if_needed();
  19182. EXPECT_EQ(std::string("123456789"), body);
  19183. // The response should include a Trailer header declaring both names
  19184. ASSERT_TRUE(handle.response);
  19185. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19186. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19187. handle.response->get_header_value("Trailer"));
  19188. // Prohibited trailer must not be present
  19189. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19190. // Allowed trailer should be present
  19191. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19192. EXPECT_EQ(std::string("yes"),
  19193. handle.response->get_trailer_value("X-Allowed"));
  19194. // Verify trailers are NOT present as regular headers
  19195. EXPECT_EQ(std::string(""),
  19196. handle.response->get_header_value("Content-Length"));
  19197. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19198. }
  19199. // Accepts one connection on an OS-assigned port, which it hands over through
  19200. // port_promise, reads the request head and sends back response. after_send,
  19201. // if given, runs on the connection before it is closed.
  19202. static std::thread
  19203. serve_single_response(std::promise<int> &port_promise,
  19204. const std::string &response,
  19205. std::function<void(socket_t)> after_send = nullptr) {
  19206. return std::thread([&port_promise, response, after_send] {
  19207. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19208. default_socket_options(srv);
  19209. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19210. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19211. sockaddr_in addr{};
  19212. addr.sin_family = AF_INET;
  19213. addr.sin_port = htons(0); // Let OS assign a free port
  19214. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19215. int opt = 1;
  19216. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19217. #ifdef _WIN32
  19218. reinterpret_cast<const char *>(&opt),
  19219. #else
  19220. &opt,
  19221. #endif
  19222. sizeof(opt));
  19223. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19224. ::listen(srv, 1) != 0) {
  19225. port_promise.set_value(-1);
  19226. detail::close_socket(srv);
  19227. return;
  19228. }
  19229. socklen_t addr_len = sizeof(addr);
  19230. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19231. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19232. sockaddr_in cli_addr{};
  19233. socklen_t cli_len = sizeof(cli_addr);
  19234. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19235. if (cli != INVALID_SOCKET) {
  19236. // Read the complete HTTP request (until the blank line that terminates
  19237. // headers) before sending the response. If the server closes the socket
  19238. // while the client's request data is still unread in the kernel receive
  19239. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19240. // connection on both sides: it discards the client's receive buffer
  19241. // (which already holds our response) and causes any in-progress write on
  19242. // the client to fail with ECONNRESET. Reading all request data first
  19243. // ensures close() emits a graceful FIN.
  19244. {
  19245. char rbuf[256];
  19246. std::string req;
  19247. while (req.find("\r\n\r\n") == std::string::npos) {
  19248. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19249. if (n <= 0) { break; }
  19250. req.append(rbuf, static_cast<size_t>(n));
  19251. }
  19252. }
  19253. ::send(cli,
  19254. #ifdef _WIN32
  19255. static_cast<const char *>(response.c_str()),
  19256. static_cast<int>(response.size()),
  19257. #else
  19258. response.c_str(), response.size(),
  19259. #endif
  19260. 0);
  19261. if (after_send) { after_send(cli); }
  19262. detail::close_socket(cli);
  19263. }
  19264. detail::close_socket(srv);
  19265. });
  19266. }
  19267. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19268. #ifndef _WIN32
  19269. signal(SIGPIPE, SIG_IGN);
  19270. #endif
  19271. std::promise<int> port_promise;
  19272. auto port_future = port_promise.get_future();
  19273. auto server_thread =
  19274. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19275. "Content-Type: text/plain\r\n"
  19276. "Content-Length: not-a-number\r\n"
  19277. "Connection: close\r\n"
  19278. "\r\n"
  19279. "hello");
  19280. auto port = port_future.get();
  19281. ASSERT_GT(port, 0);
  19282. Client cli("127.0.0.1", port);
  19283. auto handle = cli.open_stream("GET", "/");
  19284. EXPECT_FALSE(handle.is_valid());
  19285. server_thread.join();
  19286. }
  19287. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19288. #ifndef _WIN32
  19289. signal(SIGPIPE, SIG_IGN);
  19290. #endif
  19291. std::promise<int> port_promise;
  19292. auto port_future = port_promise.get_future();
  19293. auto server_thread = serve_single_response(
  19294. port_promise, "HTTP/1.1 200 OK\r\n"
  19295. "Content-Type: text/plain\r\n"
  19296. "Content-Length: 99999999999999999999999999\r\n"
  19297. "Connection: close\r\n"
  19298. "\r\n"
  19299. "hello");
  19300. auto port = port_future.get();
  19301. ASSERT_GT(port, 0);
  19302. // Historically std::stoull would throw std::out_of_range here and crash
  19303. // the process, then parsing silently clamped to a bogus framing length and
  19304. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19305. // so the stream fails to open, matching the not-a-number case above. The
  19306. // process still must NOT terminate.
  19307. Client cli("127.0.0.1", port);
  19308. auto handle = cli.open_stream("GET", "/");
  19309. EXPECT_FALSE(handle.is_valid());
  19310. server_thread.join();
  19311. }
  19312. // Serves `response` to the single request `fn` makes with a fresh client.
  19313. template <typename Fn>
  19314. static void with_single_response(const std::string &response, Fn fn) {
  19315. #ifndef _WIN32
  19316. signal(SIGPIPE, SIG_IGN);
  19317. #endif
  19318. std::promise<int> port_promise;
  19319. auto port_future = port_promise.get_future();
  19320. auto server_thread = serve_single_response(port_promise, response);
  19321. auto se = detail::scope_exit([&] { server_thread.join(); });
  19322. auto port = port_future.get();
  19323. ASSERT_GT(port, 0);
  19324. Client cli("127.0.0.1", port);
  19325. fn(cli);
  19326. }
  19327. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19328. const char *responses[] = {
  19329. "HTTP/1.1 103 Early Hints\r\n"
  19330. "Link: </style.css>; rel=preload\r\n"
  19331. "\r\n"
  19332. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19333. "HTTP/1.1 100 Continue\r\n"
  19334. "X-Note: interim\r\n"
  19335. "\r\n"
  19336. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19337. };
  19338. for (auto response : responses) {
  19339. with_single_response(response, [](Client &cli) {
  19340. auto res = cli.Get("/");
  19341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19342. EXPECT_EQ(StatusCode::OK_200, res->status);
  19343. EXPECT_EQ("ok", res->body);
  19344. });
  19345. }
  19346. }
  19347. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19348. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19349. const std::string final_response =
  19350. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19351. std::string interims;
  19352. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19353. interims += interim;
  19354. }
  19355. with_single_response(interims + final_response, [](Client &cli) {
  19356. auto res = cli.Get("/");
  19357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19358. EXPECT_EQ("ok", res->body);
  19359. });
  19360. with_single_response(interims + interim + final_response, [](Client &cli) {
  19361. auto res = cli.Get("/");
  19362. ASSERT_FALSE(res);
  19363. EXPECT_EQ(Error::Read, res.error());
  19364. });
  19365. }
  19366. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19367. #ifndef _WIN32
  19368. signal(SIGPIPE, SIG_IGN);
  19369. #endif
  19370. // The server answers the head without asking for the body. Bytes it then
  19371. // reads on the connection would be taken for the body the request declared.
  19372. auto closed_by_client = false;
  19373. std::promise<int> port_promise;
  19374. auto server_thread = serve_single_response(
  19375. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19376. [&](socket_t sock) {
  19377. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19378. char buf[256];
  19379. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19380. });
  19381. Client cli("127.0.0.1", port_promise.get_future().get());
  19382. cli.set_keep_alive(true);
  19383. cli.set_read_timeout(1, 0);
  19384. // Long enough for the client to send Expect: 100-continue.
  19385. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19387. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19388. cli.Get("/second");
  19389. server_thread.join();
  19390. EXPECT_TRUE(closed_by_client);
  19391. }
  19392. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19393. // Long enough for the client to send Expect: 100-continue
  19394. with_single_response(
  19395. "HTTP/1.1 103 Early Hints\r\n"
  19396. "Link: </style.css>; rel=preload\r\n"
  19397. "\r\n"
  19398. "HTTP/1.1 401 Unauthorized\r\n"
  19399. "Content-Length: 0\r\n\r\n",
  19400. [](Client &cli) {
  19401. cli.set_read_timeout(2, 0);
  19402. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19404. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19405. });
  19406. }
  19407. #ifdef CPPHTTPLIB_SSL_ENABLED
  19408. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19409. #ifndef _WIN32
  19410. signal(SIGPIPE, SIG_IGN);
  19411. #endif
  19412. auto reused = false;
  19413. std::promise<int> port_promise;
  19414. auto server_thread = serve_single_response(
  19415. port_promise,
  19416. "HTTP/1.1 401 Unauthorized\r\n"
  19417. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19418. "Content-Length: 0\r\n\r\n",
  19419. [&](socket_t sock) {
  19420. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19421. char buf[256];
  19422. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19423. });
  19424. Client cli("127.0.0.1", port_promise.get_future().get());
  19425. cli.set_keep_alive(true);
  19426. cli.set_digest_auth("user", "pass");
  19427. cli.set_read_timeout(1, 0);
  19428. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19429. server_thread.join();
  19430. EXPECT_FALSE(reused);
  19431. }
  19432. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19433. // Any other answer to CONNECT would read as the origin's response.
  19434. struct {
  19435. const char *response;
  19436. bool passed_on;
  19437. } cases[] = {
  19438. {"HTTP/1.1 201 Created\r\n"
  19439. "Set-Cookie: session=from-proxy\r\n"
  19440. "Content-Length: 0\r\n\r\n",
  19441. false},
  19442. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19443. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19444. "Content-Length: 0\r\n\r\n",
  19445. true},
  19446. };
  19447. for (const auto &c : cases) {
  19448. std::promise<int> port_promise;
  19449. auto server_thread = serve_single_response(port_promise, c.response);
  19450. SSLClient cli("example.com", 443);
  19451. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19452. auto res = cli.Get("/");
  19453. server_thread.join();
  19454. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19455. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19456. if (res) {
  19457. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19458. }
  19459. }
  19460. }
  19461. #endif
  19462. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19463. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19464. // the chunked coding and drop Content-Length, so a front-end that trusts
  19465. // Content-Length would disagree about where the body ends (response
  19466. // smuggling). The client must reject such a response.
  19467. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19468. for (const char *te : {"chunked", "gzip, chunked"}) {
  19469. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19470. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19471. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19472. "5\r\nhello\r\n0\r\n\r\n";
  19473. with_single_response(response, [&](Client &cli) {
  19474. auto res = cli.Get("/");
  19475. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19476. EXPECT_EQ(Error::Read, res.error()) << te;
  19477. });
  19478. with_single_response(response, [&](Client &cli) {
  19479. auto handle = cli.open_stream("GET", "/");
  19480. EXPECT_FALSE(handle.is_valid()) << te;
  19481. EXPECT_EQ(Error::Read, handle.error) << te;
  19482. });
  19483. }
  19484. }
  19485. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19486. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19487. // closing the connection (unlike a request, which must be rejected).
  19488. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19489. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19490. "Transfer-Encoding: chunked\r\n"
  19491. "Connection: close\r\n"
  19492. "\r\n"
  19493. "5\r\nhello\r\n0\r\n\r\n",
  19494. "HTTP/1.1 200 OK\r\n"
  19495. "Transfer-Encoding: gzip\r\n"
  19496. "Connection: close\r\n"
  19497. "\r\n"
  19498. "hello"}) {
  19499. with_single_response(response, [&](Client &cli) {
  19500. auto res = cli.Get("/");
  19501. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19502. EXPECT_EQ("hello", res->body);
  19503. });
  19504. with_single_response(response, [&](Client &cli) {
  19505. auto handle = cli.open_stream("GET", "/");
  19506. ASSERT_TRUE(handle.is_valid()) << response;
  19507. EXPECT_EQ("hello", read_all(handle));
  19508. });
  19509. }
  19510. }
  19511. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19512. // framing headers describe nothing to read and must not be rejected.
  19513. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19514. const std::string framing = "Content-Length: 5\r\n"
  19515. "Transfer-Encoding: chunked\r\n"
  19516. "Connection: close\r\n"
  19517. "\r\n";
  19518. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19519. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19520. });
  19521. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19522. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19523. });
  19524. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19525. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19526. with_single_response(response, [&](Client &cli) {
  19527. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19528. });
  19529. with_single_response(response, [&](Client &cli) {
  19530. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19531. });
  19532. }
  19533. }
  19534. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19535. // response, is faulty framing, so the connection is not reused after it.
  19536. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19537. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19538. "Content-Length: 0\r\n"
  19539. "Transfer-Encoding: chunked\r\n"
  19540. "\r\n"
  19541. "5\r\nhello\r\n0\r\n\r\n",
  19542. "HTTP/1.0 200 Connection established\r\n"
  19543. "Connection: keep-alive\r\n"
  19544. "Transfer-Encoding: chunked\r\n"
  19545. "\r\n"
  19546. "5\r\nhello\r\n0\r\n\r\n"}) {
  19547. with_single_response(response, [&](Client &cli) {
  19548. cli.set_keep_alive(true);
  19549. auto res = cli.Get("/");
  19550. ASSERT_TRUE(res) << response;
  19551. EXPECT_EQ("hello", res->body);
  19552. EXPECT_FALSE(cli.is_socket_open()) << response;
  19553. });
  19554. }
  19555. }
  19556. // A payload max length of 0 means no limit, however the body is framed.
  19557. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19558. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19559. "Transfer-Encoding: chunked\r\n"
  19560. "\r\n"
  19561. "5\r\nhello\r\n0\r\n\r\n",
  19562. "HTTP/1.1 200 OK\r\n"
  19563. "Connection: close\r\n"
  19564. "\r\n"
  19565. "hello"}) {
  19566. with_single_response(response, [&](Client &cli) {
  19567. cli.set_payload_max_length(0);
  19568. auto res = cli.Get("/");
  19569. ASSERT_TRUE(res) << response;
  19570. EXPECT_EQ("hello", res->body) << response;
  19571. });
  19572. }
  19573. }
  19574. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19575. Server svr;
  19576. svr.set_payload_max_length(0);
  19577. svr.Post("/echo", [](const Request &req, Response &res) {
  19578. res.set_content(req.body, "text/plain");
  19579. });
  19580. auto port = svr.bind_to_any_port(HOST);
  19581. thread t = thread([&] { svr.listen_after_bind(); });
  19582. auto se = detail::scope_exit([&] {
  19583. svr.stop();
  19584. t.join();
  19585. ASSERT_FALSE(svr.is_running());
  19586. });
  19587. svr.wait_until_ready();
  19588. Client cli(HOST, port);
  19589. auto res = cli.Post(
  19590. "/echo",
  19591. [](size_t /*offset*/, DataSink &sink) {
  19592. sink.write("hello", 5);
  19593. sink.done();
  19594. return true;
  19595. },
  19596. "text/plain");
  19597. ASSERT_TRUE(res);
  19598. EXPECT_EQ(StatusCode::OK_200, res->status);
  19599. EXPECT_EQ("hello", res->body);
  19600. }
  19601. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19602. TEST_F(OpenStreamTest, Gzip) {
  19603. Client cli("127.0.0.1", port_);
  19604. auto handle = cli.open_stream("GET", "/compressible", {},
  19605. {{"Accept-Encoding", "gzip"}});
  19606. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19607. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19608. }
  19609. #endif
  19610. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19611. TEST_F(OpenStreamTest, Brotli) {
  19612. Client cli("127.0.0.1", port_);
  19613. auto handle =
  19614. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19615. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19616. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19617. }
  19618. #endif
  19619. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19620. TEST_F(OpenStreamTest, Zstd) {
  19621. Client cli("127.0.0.1", port_);
  19622. auto handle = cli.open_stream("GET", "/compressible", {},
  19623. {{"Accept-Encoding", "zstd"}});
  19624. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19625. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19626. }
  19627. #endif
  19628. #ifdef CPPHTTPLIB_SSL_ENABLED
  19629. class SSLOpenStreamTest : public ::testing::Test {
  19630. protected:
  19631. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19632. void SetUp() override {
  19633. svr_.Get("/hello", [](const Request &, Response &res) {
  19634. res.set_content("Hello SSL World!", "text/plain");
  19635. });
  19636. svr_.Get("/chunked", [](const Request &, Response &res) {
  19637. res.set_chunked_content_provider("text/plain",
  19638. [](size_t offset, DataSink &sink) {
  19639. if (offset < 15) {
  19640. sink.write("chunk", 5);
  19641. return true;
  19642. }
  19643. sink.done();
  19644. return true;
  19645. });
  19646. });
  19647. svr_.Post("/echo", [](const Request &req, Response &res) {
  19648. res.set_content(req.body, req.get_header_value("Content-Type"));
  19649. });
  19650. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19651. std::string body = req.body;
  19652. res.set_chunked_content_provider(
  19653. "text/plain", [body](size_t offset, DataSink &sink) {
  19654. if (offset < body.size()) {
  19655. sink.write(body.data() + offset, body.size() - offset);
  19656. }
  19657. sink.done();
  19658. return true;
  19659. });
  19660. });
  19661. port_ = svr_.bind_to_any_port("127.0.0.1");
  19662. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19663. svr_.wait_until_ready();
  19664. }
  19665. void TearDown() override {
  19666. svr_.stop();
  19667. if (thread_.joinable()) thread_.join();
  19668. }
  19669. SSLServer svr_;
  19670. std::thread thread_;
  19671. int port_ = 0;
  19672. };
  19673. TEST_F(SSLOpenStreamTest, Basic) {
  19674. SSLClient cli("127.0.0.1", port_);
  19675. cli.enable_server_certificate_verification(false);
  19676. auto handle = cli.open_stream("GET", "/hello");
  19677. ASSERT_TRUE(handle.is_valid());
  19678. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19679. }
  19680. TEST_F(SSLOpenStreamTest, Chunked) {
  19681. SSLClient cli("127.0.0.1", port_);
  19682. cli.enable_server_certificate_verification(false);
  19683. auto handle = cli.open_stream("GET", "/chunked");
  19684. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19685. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19686. "Transfer-Encoding") == "chunked");
  19687. auto body = read_all(handle);
  19688. EXPECT_EQ("chunkchunkchunk", body);
  19689. }
  19690. TEST_F(SSLOpenStreamTest, Post) {
  19691. SSLClient cli("127.0.0.1", port_);
  19692. cli.enable_server_certificate_verification(false);
  19693. auto handle =
  19694. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19695. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19696. EXPECT_EQ(200, handle.response->status);
  19697. auto body = read_all(handle);
  19698. EXPECT_EQ("Hello SSL POST", body);
  19699. }
  19700. TEST_F(SSLOpenStreamTest, PostChunked) {
  19701. SSLClient cli("127.0.0.1", port_);
  19702. cli.enable_server_certificate_verification(false);
  19703. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19704. "Chunked SSL Data", "text/plain");
  19705. ASSERT_TRUE(handle.is_valid());
  19706. EXPECT_EQ(200, handle.response->status);
  19707. auto body = read_all(handle);
  19708. EXPECT_EQ("Chunked SSL Data", body);
  19709. }
  19710. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19711. // Content-Length is terminated by the server closing the connection. When the
  19712. // SSL peer sends a close_notify after the body, the client must treat it as a
  19713. // clean EOF and return a successful response rather than an error.
  19714. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19716. ASSERT_TRUE(svr.is_valid());
  19717. svr.set_keep_alive_max_count(1);
  19718. const std::string expected_body = "Hello from connection-close response!";
  19719. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19720. res.set_content_provider("text/plain",
  19721. [&](size_t offset, DataSink &sink) -> bool {
  19722. if (offset < expected_body.size()) {
  19723. sink.write(expected_body.data() + offset,
  19724. expected_body.size() - offset);
  19725. }
  19726. sink.done();
  19727. return true;
  19728. });
  19729. });
  19730. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19731. auto se = detail::scope_exit([&] {
  19732. svr.stop();
  19733. listen_thread.join();
  19734. ASSERT_FALSE(svr.is_running());
  19735. });
  19736. svr.wait_until_ready();
  19737. SSLClient cli(HOST, PORT);
  19738. cli.enable_server_certificate_verification(false);
  19739. auto res = cli.Get("/no-content-length");
  19740. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19741. EXPECT_EQ(StatusCode::OK_200, res->status);
  19742. EXPECT_EQ(expected_body, res->body);
  19743. }
  19744. #endif // CPPHTTPLIB_SSL_ENABLED
  19745. //==============================================================================
  19746. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19747. // results for various scenarios.
  19748. //==============================================================================
  19749. TEST(ParityTest, GetVsOpenStream) {
  19750. Server svr;
  19751. const std::string path = "/parity";
  19752. const std::string content = "Parity test content: hello world";
  19753. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19754. res.set_content(content, "text/plain");
  19755. });
  19756. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19757. auto se = detail::scope_exit([&] {
  19758. svr.stop();
  19759. t.join();
  19760. ASSERT_FALSE(svr.is_running());
  19761. });
  19762. svr.wait_until_ready();
  19763. Client cli(HOST, PORT);
  19764. // Non-stream path
  19765. auto r1 = cli.Get(path);
  19766. ASSERT_TRUE(r1);
  19767. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19768. // Stream path
  19769. auto h = cli.open_stream("GET", path);
  19770. ASSERT_TRUE(h.is_valid());
  19771. EXPECT_EQ(r1->body, read_all(h));
  19772. }
  19773. // Helper to compress data with provided compressor type T
  19774. template <typename Compressor>
  19775. static std::string compress_payload_for_parity(const std::string &in) {
  19776. std::string out;
  19777. Compressor compressor;
  19778. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19779. [&](const char *data, size_t n) {
  19780. out.append(data, n);
  19781. return true;
  19782. });
  19783. EXPECT_TRUE(ok);
  19784. return out;
  19785. }
  19786. // Helper function for compression parity tests
  19787. template <typename Compressor>
  19788. static void test_compression_parity(const std::string &original,
  19789. const std::string &path,
  19790. const std::string &encoding) {
  19791. const std::string compressed =
  19792. compress_payload_for_parity<Compressor>(original);
  19793. Server svr;
  19794. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19795. res.set_content(compressed, "application/octet-stream");
  19796. res.set_header("Content-Encoding", encoding);
  19797. });
  19798. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19799. auto se = detail::scope_exit([&] {
  19800. svr.stop();
  19801. t.join();
  19802. ASSERT_FALSE(svr.is_running());
  19803. });
  19804. svr.wait_until_ready();
  19805. Client cli(HOST, PORT);
  19806. // Non-streaming
  19807. {
  19808. auto res = cli.Get(path);
  19809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19810. EXPECT_EQ(StatusCode::OK_200, res->status);
  19811. EXPECT_EQ(original, res->body);
  19812. }
  19813. // Streaming
  19814. {
  19815. auto h = cli.open_stream("GET", path);
  19816. ASSERT_TRUE(h.is_valid());
  19817. EXPECT_EQ(original, read_all(h));
  19818. }
  19819. }
  19820. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19821. TEST(ParityTest, Gzip) {
  19822. test_compression_parity<detail::gzip_compressor>(
  19823. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19824. }
  19825. #endif
  19826. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19827. TEST(ParityTest, Brotli) {
  19828. test_compression_parity<detail::brotli_compressor>(
  19829. "Hello, brotli parity test payload", "/parity-br", "br");
  19830. }
  19831. #endif
  19832. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19833. TEST(ParityTest, Zstd) {
  19834. test_compression_parity<detail::zstd_compressor>(
  19835. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19836. }
  19837. #endif
  19838. //==============================================================================
  19839. // New Stream API Tests
  19840. //==============================================================================
  19841. inline std::string read_body(httplib::stream::Result &result) {
  19842. std::string body;
  19843. while (result.next()) {
  19844. body.append(result.data(), result.size());
  19845. }
  19846. return body;
  19847. }
  19848. TEST(ClientConnectionTest, Basic) {
  19849. httplib::ClientConnection conn;
  19850. EXPECT_FALSE(conn.is_open());
  19851. conn.sock = 1;
  19852. EXPECT_TRUE(conn.is_open());
  19853. httplib::ClientConnection conn2(std::move(conn));
  19854. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19855. conn2.sock = INVALID_SOCKET;
  19856. }
  19857. // Unified test server for all stream::* tests
  19858. class StreamApiTest : public ::testing::Test {
  19859. protected:
  19860. void SetUp() override {
  19861. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19862. res.set_content("Hello World!", "text/plain");
  19863. });
  19864. svr_.Get("/echo-params",
  19865. [](const httplib::Request &req, httplib::Response &res) {
  19866. std::string r;
  19867. for (const auto &p : req.params) {
  19868. if (!r.empty()) r += "&";
  19869. r += p.first + "=" + p.second;
  19870. }
  19871. res.set_content(r, "text/plain");
  19872. });
  19873. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19874. res.set_content(req.body, req.get_header_value("Content-Type"));
  19875. });
  19876. svr_.Post("/echo-headers",
  19877. [](const httplib::Request &req, httplib::Response &res) {
  19878. std::string r;
  19879. for (const auto &h : req.headers)
  19880. r += h.first + ": " + h.second + "\n";
  19881. res.set_content(r, "text/plain");
  19882. });
  19883. svr_.Post("/echo-params",
  19884. [](const httplib::Request &req, httplib::Response &res) {
  19885. std::string r = "params:";
  19886. for (const auto &p : req.params)
  19887. r += p.first + "=" + p.second + ";";
  19888. res.set_content(r + " body:" + req.body, "text/plain");
  19889. });
  19890. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19891. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19892. });
  19893. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19894. res.set_content("PUT:" + req.body, "text/plain");
  19895. });
  19896. svr_.Patch("/echo",
  19897. [](const httplib::Request &req, httplib::Response &res) {
  19898. res.set_content("PATCH:" + req.body, "text/plain");
  19899. });
  19900. svr_.Delete(
  19901. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19902. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19903. "text/plain");
  19904. });
  19905. svr_.Get("/head-test",
  19906. [](const httplib::Request &, httplib::Response &res) {
  19907. res.set_content("body for HEAD", "text/plain");
  19908. });
  19909. svr_.Options("/options",
  19910. [](const httplib::Request &, httplib::Response &res) {
  19911. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19912. });
  19913. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19914. svr_.wait_until_ready();
  19915. }
  19916. void TearDown() override {
  19917. svr_.stop();
  19918. if (thread_.joinable()) thread_.join();
  19919. }
  19920. httplib::Server svr_;
  19921. std::thread thread_;
  19922. };
  19923. // stream::Get tests
  19924. TEST_F(StreamApiTest, GetBasic) {
  19925. httplib::Client cli(HOST, PORT);
  19926. auto result = httplib::stream::Get(cli, "/hello");
  19927. ASSERT_TRUE(result.is_valid());
  19928. EXPECT_EQ(200, result.status());
  19929. EXPECT_EQ("Hello World!", read_body(result));
  19930. }
  19931. TEST_F(StreamApiTest, GetWithParams) {
  19932. httplib::Client cli(HOST, PORT);
  19933. httplib::Params params{{"foo", "bar"}};
  19934. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19935. ASSERT_TRUE(result.is_valid());
  19936. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19937. }
  19938. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19939. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19940. httplib::Client cli(HOST, PORT);
  19941. cli.set_payload_max_length(0);
  19942. auto result = httplib::stream::Get(cli, "/hello");
  19943. ASSERT_TRUE(result.is_valid());
  19944. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19945. EXPECT_EQ("Hello World!", read_body(result));
  19946. }
  19947. #endif
  19948. TEST_F(StreamApiTest, GetConnectionError) {
  19949. httplib::Client cli(HOST, 9999);
  19950. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19951. }
  19952. TEST_F(StreamApiTest, Get404) {
  19953. httplib::Client cli(HOST, PORT);
  19954. auto result = httplib::stream::Get(cli, "/nonexistent");
  19955. EXPECT_TRUE(result.is_valid());
  19956. EXPECT_EQ(404, result.status());
  19957. }
  19958. // stream::Post tests
  19959. TEST_F(StreamApiTest, PostBasic) {
  19960. httplib::Client cli(HOST, PORT);
  19961. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19962. "application/json");
  19963. ASSERT_TRUE(result.is_valid());
  19964. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19965. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19966. }
  19967. TEST_F(StreamApiTest, PostWithHeaders) {
  19968. httplib::Client cli(HOST, PORT);
  19969. httplib::Headers headers{{"X-Custom", "value"}};
  19970. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19971. "text/plain");
  19972. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19973. }
  19974. TEST_F(StreamApiTest, PostWithParams) {
  19975. httplib::Client cli(HOST, PORT);
  19976. httplib::Params params{{"k", "v"}};
  19977. auto result =
  19978. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19979. auto body = read_body(result);
  19980. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19981. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19982. }
  19983. TEST_F(StreamApiTest, PostLarge) {
  19984. httplib::Client cli(HOST, PORT);
  19985. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19986. size_t total = 0;
  19987. while (result.next()) {
  19988. total += result.size();
  19989. }
  19990. EXPECT_EQ(100u * 1024u, total);
  19991. }
  19992. // stream::Put/Patch tests
  19993. TEST_F(StreamApiTest, PutAndPatch) {
  19994. httplib::Client cli(HOST, PORT);
  19995. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19996. EXPECT_EQ("PUT:test", read_body(put));
  19997. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19998. EXPECT_EQ("PATCH:test", read_body(patch));
  19999. }
  20000. // stream::Delete tests
  20001. TEST_F(StreamApiTest, Delete) {
  20002. httplib::Client cli(HOST, PORT);
  20003. auto del1 = httplib::stream::Delete(cli, "/resource");
  20004. EXPECT_EQ("Deleted", read_body(del1));
  20005. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20006. EXPECT_EQ("Deleted:data", read_body(del2));
  20007. }
  20008. // stream::Head/Options tests
  20009. TEST_F(StreamApiTest, HeadAndOptions) {
  20010. httplib::Client cli(HOST, PORT);
  20011. auto head = httplib::stream::Head(cli, "/head-test");
  20012. EXPECT_TRUE(head.is_valid());
  20013. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20014. auto opts = httplib::stream::Options(cli, "/options");
  20015. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20016. }
  20017. // SSL stream::* tests
  20018. #ifdef CPPHTTPLIB_SSL_ENABLED
  20019. class SSLStreamApiTest : public ::testing::Test {
  20020. protected:
  20021. void SetUp() override {
  20022. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20023. res.set_content("Hello SSL!", "text/plain");
  20024. });
  20025. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20026. res.set_content(req.body, "text/plain");
  20027. });
  20028. port_ = svr_.bind_to_any_port("127.0.0.1");
  20029. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20030. svr_.wait_until_ready();
  20031. }
  20032. void TearDown() override {
  20033. svr_.stop();
  20034. if (thread_.joinable()) thread_.join();
  20035. }
  20036. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20037. std::thread thread_;
  20038. int port_ = 0;
  20039. };
  20040. TEST_F(SSLStreamApiTest, GetAndPost) {
  20041. httplib::SSLClient cli("127.0.0.1", port_);
  20042. cli.enable_server_certificate_verification(false);
  20043. auto get = httplib::stream::Get(cli, "/hello");
  20044. EXPECT_EQ("Hello SSL!", read_body(get));
  20045. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20046. EXPECT_EQ("test", read_body(post));
  20047. }
  20048. #endif
  20049. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20050. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20051. // BodyReader
  20052. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20053. // Test that read timeout during streaming is detected
  20054. // Use a large content-length response where server delays mid-stream
  20055. Server svr;
  20056. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20057. // Send a large response with delay in the middle
  20058. res.set_content_provider(
  20059. 1000, // content_length
  20060. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20061. if (offset < 100) {
  20062. // Send first 100 bytes immediately
  20063. std::string data(100, 'A');
  20064. sink.write(data.c_str(), data.size());
  20065. return true;
  20066. }
  20067. // Then delay longer than client timeout
  20068. std::this_thread::sleep_for(std::chrono::seconds(3));
  20069. std::string data(900, 'B');
  20070. sink.write(data.c_str(), data.size());
  20071. return true;
  20072. });
  20073. });
  20074. auto port = 8091;
  20075. std::thread t([&]() { svr.listen("localhost", port); });
  20076. svr.wait_until_ready();
  20077. Client cli("localhost", port);
  20078. cli.set_read_timeout(1, 0); // 1 second timeout
  20079. auto handle = cli.open_stream("GET", "/slow-stream");
  20080. ASSERT_TRUE(handle.is_valid());
  20081. char buf[256];
  20082. ssize_t total = 0;
  20083. ssize_t n;
  20084. bool got_error = false;
  20085. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20086. total += n;
  20087. }
  20088. if (n < 0) {
  20089. got_error = true;
  20090. // Should be timeout or read error
  20091. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20092. handle.get_read_error() == Error::Read)
  20093. << "Actual error: " << to_string(handle.get_read_error());
  20094. }
  20095. // Either we got an error, or we got less data than expected
  20096. EXPECT_TRUE(got_error || total < 1000)
  20097. << "Expected timeout but got all " << total << " bytes";
  20098. svr.stop();
  20099. t.join();
  20100. }
  20101. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20102. // Test connection closed detection via BodyReader
  20103. Server svr;
  20104. std::atomic<bool> close_now{false};
  20105. svr.Get("/will-close", [&](const Request &, Response &res) {
  20106. res.set_content_provider(
  20107. 10000, // Large content_length that we won't fully send
  20108. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20109. if (offset < 100) {
  20110. std::string data(100, 'X');
  20111. sink.write(data.c_str(), data.size());
  20112. return true;
  20113. }
  20114. // Wait for signal then abort
  20115. while (!close_now) {
  20116. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20117. }
  20118. return false; // Abort - server will close connection
  20119. });
  20120. });
  20121. auto port = 8092;
  20122. std::thread t([&]() { svr.listen("localhost", port); });
  20123. svr.wait_until_ready();
  20124. Client cli("localhost", port);
  20125. auto handle = cli.open_stream("GET", "/will-close");
  20126. ASSERT_TRUE(handle.is_valid());
  20127. char buf[256];
  20128. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20129. EXPECT_GT(n, 0) << "First read should succeed";
  20130. // Signal server to close
  20131. close_now = true;
  20132. // Keep reading until error or EOF
  20133. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20134. // Keep reading
  20135. }
  20136. // Should get an error since content_length wasn't satisfied
  20137. if (n < 0) {
  20138. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20139. handle.get_read_error() == Error::Read)
  20140. << "Actual error: " << to_string(handle.get_read_error());
  20141. }
  20142. svr.stop();
  20143. t.join();
  20144. }
  20145. #ifdef CPPHTTPLIB_SSL_ENABLED
  20146. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20147. // Test that read timeout during SSL streaming is detected
  20148. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20149. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20150. res.set_content_provider(
  20151. 1000, "text/plain",
  20152. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20153. if (offset < 100) {
  20154. std::string data(100, 'A');
  20155. sink.write(data.c_str(), data.size());
  20156. return true;
  20157. }
  20158. std::this_thread::sleep_for(std::chrono::seconds(3));
  20159. std::string data(900, 'B');
  20160. sink.write(data.c_str(), data.size());
  20161. return true;
  20162. });
  20163. });
  20164. auto port = 8093;
  20165. std::thread t([&]() { svr.listen("localhost", port); });
  20166. svr.wait_until_ready();
  20167. SSLClient cli("localhost", port);
  20168. cli.enable_server_certificate_verification(false);
  20169. cli.set_read_timeout(1, 0); // 1 second timeout
  20170. auto handle = cli.open_stream("GET", "/slow-stream");
  20171. ASSERT_TRUE(handle.is_valid());
  20172. char buf[256];
  20173. ssize_t total = 0;
  20174. ssize_t n;
  20175. bool got_error = false;
  20176. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20177. total += n;
  20178. }
  20179. if (n < 0) {
  20180. got_error = true;
  20181. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20182. handle.get_read_error() == Error::Read)
  20183. << "Actual error: " << to_string(handle.get_read_error());
  20184. }
  20185. EXPECT_TRUE(got_error || total < 1000)
  20186. << "Expected timeout but got all " << total << " bytes";
  20187. svr.stop();
  20188. t.join();
  20189. }
  20190. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20191. // Test SSL connection closed detection
  20192. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20193. std::atomic<bool> close_now{false};
  20194. svr.Get("/will-close", [&](const Request &, Response &res) {
  20195. res.set_content_provider(
  20196. 10000, "text/plain",
  20197. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20198. if (offset < 100) {
  20199. std::string data(100, 'X');
  20200. sink.write(data.c_str(), data.size());
  20201. return true;
  20202. }
  20203. while (!close_now) {
  20204. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20205. }
  20206. return false;
  20207. });
  20208. });
  20209. auto port = 8094;
  20210. std::thread t([&]() { svr.listen("localhost", port); });
  20211. svr.wait_until_ready();
  20212. SSLClient cli("localhost", port);
  20213. cli.enable_server_certificate_verification(false);
  20214. auto handle = cli.open_stream("GET", "/will-close");
  20215. ASSERT_TRUE(handle.is_valid());
  20216. char buf[256];
  20217. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20218. EXPECT_GT(n, 0);
  20219. // Signal server to close
  20220. close_now = true;
  20221. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20222. // Keep reading
  20223. }
  20224. if (n < 0) {
  20225. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20226. handle.get_read_error() == Error::Read)
  20227. << "Actual error: " << to_string(handle.get_read_error());
  20228. }
  20229. svr.stop();
  20230. t.join();
  20231. }
  20232. #endif
  20233. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20234. using namespace httplib;
  20235. // Create a test file
  20236. const char *fname = "etag_testfile.txt";
  20237. const char *content = "etag-content";
  20238. {
  20239. std::ofstream ofs(fname);
  20240. ofs << content;
  20241. ASSERT_TRUE(ofs.good());
  20242. }
  20243. Server svr;
  20244. svr.set_mount_point("/static", ".");
  20245. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20246. svr.wait_until_ready();
  20247. Client cli(HOST, PORT);
  20248. // First request: should get 200 with ETag header
  20249. auto res1 = cli.Get("/static/etag_testfile.txt");
  20250. ASSERT_TRUE(res1);
  20251. ASSERT_EQ(200, res1->status);
  20252. ASSERT_TRUE(res1->has_header("ETag"));
  20253. std::string etag = res1->get_header_value("ETag");
  20254. EXPECT_FALSE(etag.empty());
  20255. // Verify ETag format: W/"hex-hex"
  20256. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20257. EXPECT_EQ('W', etag[0]);
  20258. EXPECT_EQ('/', etag[1]);
  20259. EXPECT_EQ('"', etag[2]);
  20260. EXPECT_EQ('"', etag.back());
  20261. // Exact match: expect 304 Not Modified
  20262. Headers h2 = {{"If-None-Match", etag}};
  20263. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20264. ASSERT_TRUE(res2);
  20265. EXPECT_EQ(304, res2->status);
  20266. // Wildcard match: expect 304 Not Modified
  20267. Headers h3 = {{"If-None-Match", "*"}};
  20268. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20269. ASSERT_TRUE(res3);
  20270. EXPECT_EQ(304, res3->status);
  20271. // Non-matching ETag: expect 200
  20272. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20273. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20274. ASSERT_TRUE(res4);
  20275. EXPECT_EQ(200, res4->status);
  20276. // Multiple ETags with one matching: expect 304
  20277. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20278. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20279. ASSERT_TRUE(res5);
  20280. EXPECT_EQ(304, res5->status);
  20281. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20282. // that equivalent to the single comma-separated list above, so the match on
  20283. // the second line must still be found.
  20284. Headers h6;
  20285. h6.emplace("If-None-Match", "W/\"other\"");
  20286. h6.emplace("If-None-Match", etag);
  20287. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20288. ASSERT_TRUE(res6);
  20289. EXPECT_EQ(304, res6->status);
  20290. svr.stop();
  20291. t.join();
  20292. std::remove(fname);
  20293. }
  20294. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20295. using namespace httplib;
  20296. Server svr;
  20297. svr.set_mount_point("/static", ".");
  20298. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20299. svr.wait_until_ready();
  20300. Client cli(HOST, PORT);
  20301. // Send If-None-Match: * to a non-existent file
  20302. Headers h = {{"If-None-Match", "*"}};
  20303. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20305. EXPECT_EQ(404, res->status);
  20306. svr.stop();
  20307. t.join();
  20308. }
  20309. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20310. using namespace httplib;
  20311. // Create a test file
  20312. const char *fname = "etag_boundary_testfile.txt";
  20313. const char *content = "boundary-test";
  20314. {
  20315. std::ofstream ofs(fname);
  20316. ofs << content;
  20317. ASSERT_TRUE(ofs.good());
  20318. }
  20319. Server svr;
  20320. svr.set_mount_point("/static", ".");
  20321. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20322. svr.wait_until_ready();
  20323. Client cli(HOST, PORT);
  20324. // Get the actual ETag
  20325. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20326. ASSERT_TRUE(res1);
  20327. ASSERT_EQ(200, res1->status);
  20328. ASSERT_TRUE(res1->has_header("ETag"));
  20329. std::string etag = res1->get_header_value("ETag");
  20330. // Test 1: Very long ETag value (longer than actual ETag)
  20331. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20332. Headers h1 = {{"If-None-Match", "W/"
  20333. "\"very-long-etag-value-that-is-much-longer-"
  20334. "than-the-actual-etag-value\""}};
  20335. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20336. ASSERT_TRUE(res2);
  20337. EXPECT_EQ(200, res2->status); // Should not match
  20338. // Test 2: Long string followed by wildcard
  20339. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20340. // string)
  20341. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20342. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20343. ASSERT_TRUE(res3);
  20344. EXPECT_EQ(304, res3->status); // Should match on "*"
  20345. // Test 3: Wildcard followed by long string
  20346. // Should match on "*" immediately and return 304
  20347. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20348. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20349. ASSERT_TRUE(res4);
  20350. EXPECT_EQ(304, res4->status); // Should match on "*"
  20351. // Test 4: Multiple long non-matching values
  20352. // Should NOT match and return 200 (test that all comparisons are safe)
  20353. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20354. "W/\"second-long-non-matching-value\", "
  20355. "W/\"third-long-non-matching-value\""}};
  20356. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20357. ASSERT_TRUE(res5);
  20358. EXPECT_EQ(200, res5->status); // Should not match
  20359. // Test 5: Single character that is not "*" (edge case)
  20360. Headers h5 = {{"If-None-Match", "X"}};
  20361. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20362. ASSERT_TRUE(res6);
  20363. EXPECT_EQ(200, res6->status); // Should not match
  20364. svr.stop();
  20365. t.join();
  20366. std::remove(fname);
  20367. }
  20368. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20369. using namespace httplib;
  20370. // Create a test file
  20371. const char *fname = "ims_testfile.txt";
  20372. const char *content = "if-modified-since-test";
  20373. {
  20374. std::ofstream ofs(fname);
  20375. ofs << content;
  20376. ASSERT_TRUE(ofs.good());
  20377. }
  20378. Server svr;
  20379. svr.set_mount_point("/static", ".");
  20380. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20381. svr.wait_until_ready();
  20382. Client cli(HOST, PORT);
  20383. // First request: should get 200 with Last-Modified header
  20384. auto res1 = cli.Get("/static/ims_testfile.txt");
  20385. ASSERT_TRUE(res1);
  20386. ASSERT_EQ(200, res1->status);
  20387. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20388. std::string last_modified = res1->get_header_value("Last-Modified");
  20389. EXPECT_FALSE(last_modified.empty());
  20390. // If-Modified-Since with same time: expect 304
  20391. Headers h2 = {{"If-Modified-Since", last_modified}};
  20392. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20393. ASSERT_TRUE(res2);
  20394. EXPECT_EQ(304, res2->status);
  20395. // If-Modified-Since with future time: expect 304
  20396. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20397. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20398. ASSERT_TRUE(res3);
  20399. EXPECT_EQ(304, res3->status);
  20400. // If-Modified-Since with past time: expect 200
  20401. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20402. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20403. ASSERT_TRUE(res4);
  20404. EXPECT_EQ(200, res4->status);
  20405. // If-None-Match takes precedence over If-Modified-Since
  20406. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20407. ASSERT_TRUE(res1->has_header("ETag"));
  20408. std::string etag = res1->get_header_value("ETag");
  20409. Headers h5 = {{"If-None-Match", etag},
  20410. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20411. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20412. ASSERT_TRUE(res5);
  20413. EXPECT_EQ(304, res5->status);
  20414. svr.stop();
  20415. t.join();
  20416. std::remove(fname);
  20417. }
  20418. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20419. using namespace httplib;
  20420. Server svr;
  20421. // Endpoint that returns compressible content
  20422. svr.Get("/compressible", [](const Request &, Response &res) {
  20423. // Return a large enough body to trigger compression
  20424. std::string body(1000, 'a');
  20425. res.set_content(body, "text/plain");
  20426. });
  20427. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20428. svr.wait_until_ready();
  20429. Client cli(HOST, PORT);
  20430. // Request with gzip support: should get Vary header when compressed
  20431. cli.set_compress(true);
  20432. auto res1 = cli.Get("/compressible");
  20433. ASSERT_TRUE(res1);
  20434. EXPECT_EQ(200, res1->status);
  20435. // If Content-Encoding is set, Vary should also be set
  20436. if (res1->has_header("Content-Encoding")) {
  20437. EXPECT_TRUE(res1->has_header("Vary"));
  20438. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20439. }
  20440. // Request without Accept-Encoding header: should not have compression
  20441. Headers h_no_compress;
  20442. auto res2 = cli.Get("/compressible", h_no_compress);
  20443. ASSERT_TRUE(res2);
  20444. EXPECT_EQ(200, res2->status);
  20445. // Verify Vary header is present when compression is applied
  20446. // (the exact behavior depends on server configuration)
  20447. svr.stop();
  20448. t.join();
  20449. }
  20450. TEST(ETagTest, IfRangeWithETag) {
  20451. using namespace httplib;
  20452. // Create a test file with known content
  20453. const char *fname = "if_range_testfile.txt";
  20454. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20455. {
  20456. std::ofstream ofs(fname);
  20457. ofs << content;
  20458. ASSERT_TRUE(ofs.good());
  20459. }
  20460. Server svr;
  20461. svr.set_mount_point("/static", ".");
  20462. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20463. svr.wait_until_ready();
  20464. Client cli(HOST, PORT);
  20465. // First request: get ETag
  20466. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20467. ASSERT_TRUE(res1);
  20468. ASSERT_EQ(200, res1->status);
  20469. ASSERT_TRUE(res1->has_header("ETag"));
  20470. std::string etag = res1->get_header_value("ETag");
  20471. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20472. // Since our server generates weak ETags (W/"..."), If-Range with our
  20473. // ETag should NOT result in partial content - it should return full content.
  20474. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20475. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20476. ASSERT_TRUE(res2);
  20477. // Weak ETag in If-Range -> full content (200), not partial (206)
  20478. EXPECT_EQ(200, res2->status);
  20479. EXPECT_EQ(content, res2->body);
  20480. EXPECT_FALSE(res2->has_header("Content-Range"));
  20481. // Range request with non-matching If-Range (ETag): should get 200 (full
  20482. // content)
  20483. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20484. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20485. ASSERT_TRUE(res3);
  20486. EXPECT_EQ(200, res3->status);
  20487. EXPECT_EQ(content, res3->body);
  20488. EXPECT_FALSE(res3->has_header("Content-Range"));
  20489. // Range request with strong ETag (hypothetical - our server doesn't generate
  20490. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20491. // should return full content)
  20492. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20493. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20494. ASSERT_TRUE(res4);
  20495. EXPECT_EQ(200, res4->status);
  20496. EXPECT_EQ(content, res4->body);
  20497. EXPECT_FALSE(res4->has_header("Content-Range"));
  20498. svr.stop();
  20499. t.join();
  20500. std::remove(fname);
  20501. }
  20502. TEST(ETagTest, IfRangeWithDate) {
  20503. using namespace httplib;
  20504. // Create a test file
  20505. const char *fname = "if_range_date_testfile.txt";
  20506. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20507. {
  20508. std::ofstream ofs(fname);
  20509. ofs << content;
  20510. ASSERT_TRUE(ofs.good());
  20511. }
  20512. Server svr;
  20513. svr.set_mount_point("/static", ".");
  20514. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20515. svr.wait_until_ready();
  20516. Client cli(HOST, PORT);
  20517. // First request: get Last-Modified
  20518. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20519. ASSERT_TRUE(res1);
  20520. ASSERT_EQ(200, res1->status);
  20521. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20522. std::string last_modified = res1->get_header_value("Last-Modified");
  20523. // Range request with matching If-Range (date): should get 206
  20524. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20525. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20526. ASSERT_TRUE(res2);
  20527. EXPECT_EQ(206, res2->status);
  20528. EXPECT_EQ("FGHIJ", res2->body);
  20529. // Range request with old If-Range date: should get 200 (full content)
  20530. Headers h3 = {{"Range", "bytes=5-9"},
  20531. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20532. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20533. ASSERT_TRUE(res3);
  20534. EXPECT_EQ(200, res3->status);
  20535. EXPECT_EQ(content, res3->body);
  20536. // Range request with future If-Range date: should get 206
  20537. Headers h4 = {{"Range", "bytes=0-4"},
  20538. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20539. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20540. ASSERT_TRUE(res4);
  20541. EXPECT_EQ(206, res4->status);
  20542. EXPECT_EQ("ABCDE", res4->body);
  20543. svr.stop();
  20544. t.join();
  20545. std::remove(fname);
  20546. }
  20547. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20548. using namespace httplib;
  20549. const char *fname = "etag_malformed.txt";
  20550. const char *content = "malformed-etag";
  20551. {
  20552. std::ofstream ofs(fname);
  20553. ofs << content;
  20554. ASSERT_TRUE(ofs.good());
  20555. }
  20556. Server svr;
  20557. svr.set_mount_point("/static", ".");
  20558. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20559. svr.wait_until_ready();
  20560. Client cli(HOST, PORT);
  20561. // baseline: should get 200 and an ETag
  20562. auto res1 = cli.Get("/static/etag_malformed.txt");
  20563. ASSERT_TRUE(res1);
  20564. ASSERT_EQ(200, res1->status);
  20565. ASSERT_TRUE(res1->has_header("ETag"));
  20566. // Malformed ETag value (missing quotes) should be treated as non-matching
  20567. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20568. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20569. ASSERT_TRUE(res_bad);
  20570. EXPECT_EQ(200, res_bad->status);
  20571. // Whitespace-only header value should be considered invalid / non-matching
  20572. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20573. "Host: localhost\r\n"
  20574. "If-None-Match: \r\n"
  20575. "Connection: close\r\n"
  20576. "\r\n";
  20577. std::string out;
  20578. ASSERT_TRUE(send_request(5, raw_req, &out));
  20579. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20580. svr.stop();
  20581. t.join();
  20582. std::remove(fname);
  20583. }
  20584. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20585. using namespace httplib;
  20586. const char *fname = "ims_invalid_format.txt";
  20587. const char *content = "ims-bad-format";
  20588. {
  20589. std::ofstream ofs(fname);
  20590. ofs << content;
  20591. ASSERT_TRUE(ofs.good());
  20592. }
  20593. Server svr;
  20594. svr.set_mount_point("/static", ".");
  20595. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20596. svr.wait_until_ready();
  20597. Client cli(HOST, PORT);
  20598. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20599. ASSERT_TRUE(res1);
  20600. ASSERT_EQ(200, res1->status);
  20601. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20602. // If-Modified-Since with invalid format should not result in 304
  20603. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20604. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20605. ASSERT_TRUE(res_bad);
  20606. EXPECT_EQ(200, res_bad->status);
  20607. // If-Range with invalid date format should be treated as mismatch -> full
  20608. // content (200)
  20609. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20610. {"If-Range", "invalid-date"}};
  20611. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20612. ASSERT_TRUE(res_ifrange);
  20613. EXPECT_EQ(200, res_ifrange->status);
  20614. svr.stop();
  20615. t.join();
  20616. std::remove(fname);
  20617. }
  20618. TEST(ETagTest, IfRangeWithMalformedETag) {
  20619. using namespace httplib;
  20620. const char *fname = "ifrange_malformed.txt";
  20621. const std::string content = "0123456789";
  20622. {
  20623. std::ofstream ofs(fname);
  20624. ofs << content;
  20625. ASSERT_TRUE(ofs.good());
  20626. }
  20627. Server svr;
  20628. svr.set_mount_point("/static", ".");
  20629. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20630. svr.wait_until_ready();
  20631. Client cli(HOST, PORT);
  20632. // First request: get ETag
  20633. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20634. ASSERT_TRUE(res1);
  20635. ASSERT_EQ(200, res1->status);
  20636. ASSERT_TRUE(res1->has_header("ETag"));
  20637. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20638. // full content (200)
  20639. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20640. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20641. ASSERT_TRUE(res2);
  20642. EXPECT_EQ(200, res2->status);
  20643. EXPECT_EQ(content, res2->body);
  20644. svr.stop();
  20645. t.join();
  20646. std::remove(fname);
  20647. }
  20648. TEST(ETagTest, ExtremeLargeDateValues) {
  20649. using namespace httplib;
  20650. const char *fname = "ims_extreme_date.txt";
  20651. const char *content = "ims-extreme-date";
  20652. {
  20653. std::ofstream ofs(fname);
  20654. ofs << content;
  20655. ASSERT_TRUE(ofs.good());
  20656. }
  20657. Server svr;
  20658. svr.set_mount_point("/static", ".");
  20659. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20660. svr.wait_until_ready();
  20661. Client cli(HOST, PORT);
  20662. auto res1 = cli.Get(std::string("/static/") + fname);
  20663. ASSERT_TRUE(res1);
  20664. ASSERT_EQ(200, res1->status);
  20665. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20666. // Extremely large year that may overflow date parsing routines.
  20667. Headers h_large_date = {
  20668. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20669. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20670. ASSERT_TRUE(res_bad);
  20671. // Expect server to treat this as invalid/mismatch and return full content
  20672. EXPECT_EQ(200, res_bad->status);
  20673. // If-Range with extremely large date should be treated as mismatch -> full
  20674. // content (200)
  20675. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20676. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20677. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20678. ASSERT_TRUE(res_ifrange);
  20679. EXPECT_EQ(200, res_ifrange->status);
  20680. svr.stop();
  20681. t.join();
  20682. std::remove(fname);
  20683. }
  20684. TEST(ETagTest, NegativeFileModificationTime) {
  20685. using namespace httplib;
  20686. const char *fname = "ims_negative_mtime.txt";
  20687. const std::string content = "negative-mtime";
  20688. {
  20689. std::ofstream ofs(fname);
  20690. ofs << content;
  20691. ASSERT_TRUE(ofs.good());
  20692. }
  20693. // Try to set file mtime to a negative value. This may fail on some
  20694. // platforms/filesystems; if it fails, the test will still verify server
  20695. // behaves safely by performing a regular conditional request.
  20696. #if defined(__APPLE__) || defined(__linux__)
  20697. bool set_negative = false;
  20698. do {
  20699. struct timeval times[2];
  20700. // access time: now
  20701. times[0].tv_sec = time(nullptr);
  20702. times[0].tv_usec = 0;
  20703. // modification time: negative (e.g., -1)
  20704. times[1].tv_sec = -1;
  20705. times[1].tv_usec = 0;
  20706. if (utimes(fname, times) == 0) { set_negative = true; }
  20707. } while (0);
  20708. #else
  20709. bool set_negative = false;
  20710. #endif
  20711. Server svr;
  20712. svr.set_mount_point("/static", ".");
  20713. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20714. svr.wait_until_ready();
  20715. Client cli(HOST, PORT);
  20716. auto res1 = cli.Get(std::string("/static/") + fname);
  20717. ASSERT_TRUE(res1);
  20718. ASSERT_EQ(200, res1->status);
  20719. bool has_last_modified = res1->has_header("Last-Modified");
  20720. std::string last_modified;
  20721. if (has_last_modified) {
  20722. last_modified = res1->get_header_value("Last-Modified");
  20723. }
  20724. if (set_negative) {
  20725. // If we successfully set a negative mtime, ensure server returns a
  20726. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20727. // with an old date and ensure server handles it without crash.
  20728. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20729. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20730. ASSERT_TRUE(res2);
  20731. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20732. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20733. } else {
  20734. // Could not set negative mtime on this platform; fall back to verifying
  20735. // that normal invalid/malformed dates are treated safely (non-304).
  20736. Headers h_bad_date = {
  20737. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20738. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20739. ASSERT_TRUE(res_bad);
  20740. EXPECT_EQ(200, res_bad->status);
  20741. }
  20742. svr.stop();
  20743. t.join();
  20744. std::remove(fname);
  20745. }
  20746. //==============================================================================
  20747. // Integration Tests with Server
  20748. //==============================================================================
  20749. class SSEIntegrationTest : public ::testing::Test {
  20750. protected:
  20751. void SetUp() override {
  20752. stop_server_.store(false);
  20753. events_.clear();
  20754. server_ = httplib::detail::make_unique<Server>();
  20755. setup_server();
  20756. start_server();
  20757. }
  20758. void TearDown() override {
  20759. stop_server_.store(true);
  20760. event_cv_.notify_all();
  20761. server_->stop();
  20762. if (server_thread_.joinable()) { server_thread_.join(); }
  20763. }
  20764. void setup_server() {
  20765. // Simple SSE endpoint
  20766. server_->Get("/events", [this](const Request &req, Response &res) {
  20767. auto last_id = req.get_header_value("Last-Event-ID");
  20768. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20769. res.set_chunked_content_provider(
  20770. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20771. std::unique_lock<std::mutex> lock(event_mutex_);
  20772. if (event_cv_.wait_for(
  20773. lock, std::chrono::milliseconds(200), [this] {
  20774. return !events_.empty() || stop_server_.load();
  20775. })) {
  20776. if (stop_server_.load()) { return false; }
  20777. if (!events_.empty()) {
  20778. std::string event = events_.front();
  20779. events_.erase(events_.begin());
  20780. sink.write(event.data(), event.size());
  20781. return true;
  20782. }
  20783. }
  20784. return !stop_server_.load();
  20785. });
  20786. });
  20787. // Endpoint that returns error
  20788. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20789. res.status = 500;
  20790. res.set_content("Internal Server Error", "text/plain");
  20791. });
  20792. // Endpoint for custom event types
  20793. server_->Get("/custom-events", [](const Request &, Response &res) {
  20794. res.set_chunked_content_provider(
  20795. "text/event-stream", [](size_t offset, DataSink &sink) {
  20796. if (offset == 0) {
  20797. std::string event = "event: update\ndata: updated\n\n"
  20798. "event: delete\ndata: deleted\n\n";
  20799. sink.write(event.data(), event.size());
  20800. }
  20801. return false; // End stream after sending
  20802. });
  20803. });
  20804. }
  20805. void start_server() {
  20806. port_ = server_->bind_to_any_port(HOST);
  20807. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20808. // Wait for server to start
  20809. while (!server_->is_running()) {
  20810. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20811. }
  20812. }
  20813. int get_port() const { return port_; }
  20814. void send_event(const std::string &event) {
  20815. std::lock_guard<std::mutex> lock(event_mutex_);
  20816. events_.push_back(event);
  20817. event_cv_.notify_all();
  20818. }
  20819. std::unique_ptr<Server> server_;
  20820. std::thread server_thread_;
  20821. std::mutex event_mutex_;
  20822. std::condition_variable event_cv_;
  20823. std::vector<std::string> events_;
  20824. std::atomic<bool> stop_server_{false};
  20825. std::string last_received_event_id_;
  20826. int port_ = 0;
  20827. };
  20828. //==============================================================================
  20829. // SSE Parsing Tests
  20830. //==============================================================================
  20831. class SSEParsingTest : public SSEIntegrationTest {
  20832. protected:
  20833. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20834. // A trailing sentinel event tells when the whole stream has been parsed.
  20835. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20836. auto body = stream + "event: end\ndata: end\n\n";
  20837. server_->Get("/parse", [body](const Request &, Response &res) {
  20838. res.set_content(body, "text/event-stream");
  20839. });
  20840. return collect("/parse");
  20841. }
  20842. // Runs SSEClient against path until an "end" event arrives and returns the
  20843. // messages dispatched before it
  20844. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20845. Client client(HOST, get_port());
  20846. sse::SSEClient sse(client, path);
  20847. std::mutex mutex;
  20848. std::condition_variable cv;
  20849. std::vector<sse::SSEMessage> messages;
  20850. auto done = false;
  20851. sse.on_message([&](const sse::SSEMessage &msg) {
  20852. std::lock_guard<std::mutex> lock(mutex);
  20853. // Ignore a replay from a reconnect that races with stop()
  20854. if (!done) { messages.push_back(msg); }
  20855. });
  20856. sse.on_event("end", [&](const sse::SSEMessage &) {
  20857. std::lock_guard<std::mutex> lock(mutex);
  20858. done = true;
  20859. cv.notify_all();
  20860. });
  20861. sse.set_reconnect_interval(100);
  20862. sse.start_async();
  20863. {
  20864. std::unique_lock<std::mutex> lock(mutex);
  20865. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20866. }
  20867. sse.stop();
  20868. EXPECT_TRUE(done);
  20869. return messages;
  20870. }
  20871. };
  20872. TEST_F(SSEParsingTest, SingleLineData) {
  20873. auto msgs = parse("data: hello\n\n");
  20874. ASSERT_EQ(msgs.size(), 1u);
  20875. EXPECT_EQ(msgs[0].data, "hello");
  20876. EXPECT_EQ(msgs[0].event, "message");
  20877. }
  20878. TEST_F(SSEParsingTest, MultiLineData) {
  20879. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20880. ASSERT_EQ(msgs.size(), 1u);
  20881. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20882. }
  20883. TEST_F(SSEParsingTest, CustomEventType) {
  20884. auto msgs = parse("event: update\ndata: payload\n\n");
  20885. ASSERT_EQ(msgs.size(), 1u);
  20886. EXPECT_EQ(msgs[0].event, "update");
  20887. EXPECT_EQ(msgs[0].data, "payload");
  20888. }
  20889. TEST_F(SSEParsingTest, EventIdHandling) {
  20890. auto msgs = parse("id: 12345\ndata: test\n\n");
  20891. ASSERT_EQ(msgs.size(), 1u);
  20892. EXPECT_EQ(msgs[0].id, "12345");
  20893. }
  20894. TEST_F(SSEParsingTest, EmptyEventId) {
  20895. auto msgs = parse("id:\ndata: test\n\n");
  20896. ASSERT_EQ(msgs.size(), 1u);
  20897. EXPECT_EQ(msgs[0].id, "");
  20898. }
  20899. TEST_F(SSEParsingTest, CommentsIgnored) {
  20900. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20901. ASSERT_EQ(msgs.size(), 1u);
  20902. EXPECT_EQ(msgs[0].data, "hello");
  20903. EXPECT_EQ(msgs[0].event, "message");
  20904. }
  20905. TEST_F(SSEParsingTest, ColonInValue) {
  20906. auto msgs = parse("data: hello:world:test\n\n");
  20907. ASSERT_EQ(msgs.size(), 1u);
  20908. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20909. }
  20910. TEST_F(SSEParsingTest, FieldNameOnly) {
  20911. // A line without a colon is a field name with an empty value
  20912. auto msgs = parse("data\n\n");
  20913. ASSERT_EQ(msgs.size(), 1u);
  20914. EXPECT_EQ(msgs[0].data, "");
  20915. }
  20916. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20917. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20918. ASSERT_EQ(msgs.size(), 1u);
  20919. EXPECT_EQ(msgs[0].event, "update");
  20920. EXPECT_EQ(msgs[0].data, "hello");
  20921. }
  20922. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20923. auto msgs = parse("data\r\n\r\n");
  20924. ASSERT_EQ(msgs.size(), 1u);
  20925. EXPECT_EQ(msgs[0].data, "");
  20926. }
  20927. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20928. auto msgs = parse("event: update\rdata: hello\r\r");
  20929. ASSERT_EQ(msgs.size(), 1u);
  20930. EXPECT_EQ(msgs[0].event, "update");
  20931. EXPECT_EQ(msgs[0].data, "hello");
  20932. }
  20933. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20934. // Chunk boundaries fall inside every \r\n and right before the first one
  20935. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20936. "\n\r", "\nevent: end\ndata: end\n\n"};
  20937. server_->Get("/split", [chunks](const Request &, Response &res) {
  20938. auto i = std::make_shared<size_t>(0);
  20939. res.set_chunked_content_provider(
  20940. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20941. if (*i == chunks.size()) {
  20942. sink.done();
  20943. } else {
  20944. sink.write(chunks[*i].data(), chunks[*i].size());
  20945. (*i)++;
  20946. }
  20947. return true;
  20948. });
  20949. });
  20950. auto msgs = collect("/split");
  20951. ASSERT_EQ(msgs.size(), 1u);
  20952. EXPECT_EQ(msgs[0].event, "update");
  20953. EXPECT_EQ(msgs[0].data, "hello");
  20954. }
  20955. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20956. // Only a BOM at the start of the stream is ignored
  20957. auto msgs = parse("\xEF\xBB\xBF"
  20958. "data: first\n\n"
  20959. "\xEF\xBB\xBF"
  20960. "data: second\n\n");
  20961. ASSERT_EQ(msgs.size(), 1u);
  20962. EXPECT_EQ(msgs[0].data, "first");
  20963. }
  20964. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20965. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20966. ASSERT_EQ(msgs.size(), 1u);
  20967. EXPECT_EQ(msgs[0].data, "hello");
  20968. EXPECT_EQ(msgs[0].event, "message");
  20969. }
  20970. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20971. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20972. ASSERT_EQ(msgs.size(), 2u);
  20973. EXPECT_EQ(msgs[0].data, "hello");
  20974. EXPECT_EQ(msgs[1].data, "hello");
  20975. }
  20976. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20977. // An event without data is not dispatched, and its type must not leak
  20978. // into the next event
  20979. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20980. ASSERT_EQ(msgs.size(), 1u);
  20981. EXPECT_EQ(msgs[0].event, "message");
  20982. EXPECT_EQ(msgs[0].data, "hello");
  20983. }
  20984. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20985. // The first connection sends only an id; the second echoes back the
  20986. // Last-Event-ID it was reconnected with
  20987. std::atomic<int> connection_count{0};
  20988. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20989. if (connection_count++ == 0) {
  20990. res.set_content("id: 42\n\n", "text/event-stream");
  20991. } else {
  20992. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20993. "\n\nevent: end\ndata: end\n\n",
  20994. "text/event-stream");
  20995. }
  20996. });
  20997. auto msgs = collect("/id-only");
  20998. ASSERT_EQ(msgs.size(), 1u);
  20999. EXPECT_EQ(msgs[0].data, "42");
  21000. }
  21001. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21002. // The first connection sets an id and then clears it with an empty one; the
  21003. // second reports whether it was reconnected with a Last-Event-ID
  21004. std::atomic<int> connection_count{0};
  21005. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21006. if (connection_count++ == 0) {
  21007. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21008. "text/event-stream");
  21009. } else {
  21010. res.set_content(
  21011. std::string("data: ") +
  21012. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21013. "\n\nevent: end\ndata: end\n\n",
  21014. "text/event-stream");
  21015. }
  21016. });
  21017. auto msgs = collect("/id-clear");
  21018. ASSERT_EQ(msgs.size(), 3u);
  21019. EXPECT_EQ(msgs[0].id, "1");
  21020. EXPECT_EQ(msgs[1].id, "");
  21021. EXPECT_EQ(msgs[2].data, "not sent");
  21022. }
  21023. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21024. // The first connection sets an id and then sends ids that cannot be carried
  21025. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21026. // with
  21027. std::atomic<int> connection_count{0};
  21028. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21029. if (connection_count++ == 0) {
  21030. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21031. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21032. "text/event-stream");
  21033. } else {
  21034. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21035. "\n\nevent: end\ndata: end\n\n",
  21036. "text/event-stream");
  21037. }
  21038. });
  21039. auto msgs = collect("/id-unsendable");
  21040. ASSERT_EQ(msgs.size(), 1u);
  21041. EXPECT_EQ(msgs[0].data, "42");
  21042. }
  21043. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21044. auto msgs = parse("event: notification\nid: evt-42\n"
  21045. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21046. ASSERT_EQ(msgs.size(), 1u);
  21047. EXPECT_EQ(msgs[0].event, "notification");
  21048. EXPECT_EQ(msgs[0].id, "evt-42");
  21049. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21050. }
  21051. TEST(SSEMessageTest, Clear) {
  21052. sse::SSEMessage msg;
  21053. msg.event = "custom";
  21054. msg.data = "some data";
  21055. msg.id = "123";
  21056. msg.clear();
  21057. EXPECT_EQ(msg.event, "message");
  21058. EXPECT_EQ(msg.data, "");
  21059. EXPECT_EQ(msg.id, "");
  21060. }
  21061. //==============================================================================
  21062. // SSE Integration Tests
  21063. //==============================================================================
  21064. // Test: Successful connection and on_open callback
  21065. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21066. // Add a simple endpoint that sends one event and closes
  21067. server_->Get("/simple-event", [](const Request &, Response &res) {
  21068. res.set_chunked_content_provider(
  21069. "text/event-stream", [](size_t offset, DataSink &sink) {
  21070. if (offset == 0) {
  21071. std::string event = "data: hello\n\n";
  21072. sink.write(event.data(), event.size());
  21073. }
  21074. return false; // Close stream after sending
  21075. });
  21076. });
  21077. Client client("localhost", get_port());
  21078. sse::SSEClient sse(client, "/simple-event");
  21079. std::atomic<bool> open_called{false};
  21080. std::atomic<bool> message_received{false};
  21081. sse.on_open([&open_called]() { open_called.store(true); });
  21082. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21083. if (msg.data == "hello") { message_received.store(true); }
  21084. });
  21085. sse.set_reconnect_interval(100);
  21086. sse.set_max_reconnect_attempts(1);
  21087. // Start async
  21088. sse.start_async();
  21089. // Wait for message to be processed
  21090. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21091. sse.stop();
  21092. EXPECT_TRUE(open_called.load());
  21093. EXPECT_TRUE(message_received.load());
  21094. }
  21095. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21096. // A data line that never ends.
  21097. server_->Get("/endless-line", [](const Request &, Response &res) {
  21098. res.set_chunked_content_provider(
  21099. "text/event-stream", [](size_t offset, DataSink &sink) {
  21100. if (offset == 0) { sink.write("data: ", 6); }
  21101. std::string chunk(64 * 1024, 'A');
  21102. return sink.write(chunk.data(), chunk.size());
  21103. });
  21104. });
  21105. Client client("localhost", get_port());
  21106. sse::SSEClient sse(client, "/endless-line");
  21107. std::atomic<bool> too_long{false};
  21108. sse.on_error([&](Error err) {
  21109. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21110. });
  21111. sse.set_max_reconnect_attempts(1);
  21112. sse.start_async();
  21113. for (int i = 0; i < 500 && !too_long; i++) {
  21114. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21115. }
  21116. sse.stop();
  21117. EXPECT_TRUE(too_long);
  21118. }
  21119. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21120. // Far more in all than the client's payload limit below.
  21121. server_->Get("/many-events", [](const Request &, Response &res) {
  21122. res.set_chunked_content_provider(
  21123. "text/event-stream", [](size_t offset, DataSink &sink) {
  21124. if (offset == 0) {
  21125. std::string events;
  21126. for (int i = 0; i < 1000; i++) {
  21127. events += "data: message\n\n";
  21128. }
  21129. sink.write(events.data(), events.size());
  21130. }
  21131. return false;
  21132. });
  21133. });
  21134. Client client("localhost", get_port());
  21135. client.set_payload_max_length(1024);
  21136. sse::SSEClient sse(client, "/many-events");
  21137. std::atomic<int> messages{0};
  21138. std::atomic<bool> too_large{false};
  21139. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21140. sse.on_error([&](Error err) {
  21141. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21142. });
  21143. sse.set_max_reconnect_attempts(1);
  21144. sse.start_async();
  21145. for (int i = 0; i < 500 && messages < 1000; i++) {
  21146. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21147. }
  21148. sse.stop();
  21149. EXPECT_GE(messages.load(), 1000);
  21150. EXPECT_FALSE(too_large);
  21151. }
  21152. // Test: on_message callback
  21153. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21154. // Endpoint that sends multiple events then closes
  21155. server_->Get("/multi-event", [](const Request &, Response &res) {
  21156. res.set_chunked_content_provider(
  21157. "text/event-stream", [](size_t offset, DataSink &sink) {
  21158. if (offset == 0) {
  21159. std::string events = "data: message1\n\ndata: message2\n\n";
  21160. sink.write(events.data(), events.size());
  21161. }
  21162. return false;
  21163. });
  21164. });
  21165. Client client("localhost", get_port());
  21166. sse::SSEClient sse(client, "/multi-event");
  21167. std::vector<std::string> received_messages;
  21168. std::mutex messages_mutex;
  21169. sse.on_message([&](const sse::SSEMessage &msg) {
  21170. std::lock_guard<std::mutex> lock(messages_mutex);
  21171. received_messages.push_back(msg.data);
  21172. });
  21173. sse.set_reconnect_interval(100);
  21174. sse.set_max_reconnect_attempts(1);
  21175. sse.start_async();
  21176. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21177. sse.stop();
  21178. std::lock_guard<std::mutex> lock(messages_mutex);
  21179. EXPECT_GE(received_messages.size(), 2u);
  21180. if (received_messages.size() >= 2) {
  21181. EXPECT_EQ(received_messages[0], "message1");
  21182. EXPECT_EQ(received_messages[1], "message2");
  21183. }
  21184. }
  21185. // Test: on_event for specific types
  21186. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21187. Client client("localhost", get_port());
  21188. sse::SSEClient sse(client, "/custom-events");
  21189. std::atomic<bool> update_received{false};
  21190. std::atomic<bool> delete_received{false};
  21191. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21192. if (msg.data == "updated") { update_received.store(true); }
  21193. });
  21194. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21195. if (msg.data == "deleted") { delete_received.store(true); }
  21196. });
  21197. sse.set_max_reconnect_attempts(1);
  21198. sse.start_async();
  21199. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21200. sse.stop();
  21201. EXPECT_TRUE(update_received.load());
  21202. EXPECT_TRUE(delete_received.load());
  21203. }
  21204. // Test: on_error callback on connection failure
  21205. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21206. // Connect to a non-existent port
  21207. Client client("localhost", 59999);
  21208. sse::SSEClient sse(client, "/events");
  21209. std::atomic<bool> error_called{false};
  21210. Error received_error = Error::Success;
  21211. sse.on_error([&](Error err) {
  21212. error_called.store(true);
  21213. received_error = err;
  21214. });
  21215. sse.set_reconnect_interval(50);
  21216. sse.set_max_reconnect_attempts(1);
  21217. sse.start_async();
  21218. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21219. sse.stop();
  21220. EXPECT_TRUE(error_called.load());
  21221. EXPECT_NE(received_error, Error::Success);
  21222. }
  21223. // Test: Last-Event-ID header sent on reconnect
  21224. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21225. // Endpoint that sends event with ID
  21226. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21227. res.set_chunked_content_provider(
  21228. "text/event-stream", [](size_t offset, DataSink &sink) {
  21229. if (offset == 0) {
  21230. std::string event = "id: evt-123\ndata: test\n\n";
  21231. sink.write(event.data(), event.size());
  21232. }
  21233. return false;
  21234. });
  21235. });
  21236. Client client("localhost", get_port());
  21237. sse::SSEClient sse(client, "/event-with-id");
  21238. std::atomic<bool> id_received{false};
  21239. sse.on_message([&](const sse::SSEMessage &msg) {
  21240. if (!msg.id.empty()) { id_received.store(true); }
  21241. });
  21242. sse.set_reconnect_interval(100);
  21243. sse.set_max_reconnect_attempts(1);
  21244. sse.start_async();
  21245. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21246. sse.stop();
  21247. EXPECT_TRUE(id_received.load());
  21248. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21249. }
  21250. // Test: Manual stop
  21251. TEST_F(SSEIntegrationTest, ManualStop) {
  21252. // Endpoint that sends one event and stays open briefly
  21253. std::atomic<bool> handler_running{true};
  21254. server_->Get("/stay-open", [&handler_running](const Request &,
  21255. Response &res) {
  21256. res.set_chunked_content_provider(
  21257. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21258. if (offset == 0) {
  21259. std::string event = "data: connected\n\n";
  21260. sink.write(event.data(), event.size());
  21261. }
  21262. // Keep connection open while handler_running is true
  21263. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21264. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21265. }
  21266. return false;
  21267. });
  21268. });
  21269. Client client("localhost", get_port());
  21270. sse::SSEClient sse(client, "/stay-open");
  21271. std::atomic<bool> connected{false};
  21272. sse.on_open([&connected]() { connected.store(true); });
  21273. sse.set_reconnect_interval(100);
  21274. sse.set_max_reconnect_attempts(1);
  21275. sse.start_async();
  21276. // Wait for connection to establish
  21277. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21278. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21279. }
  21280. EXPECT_TRUE(connected.load());
  21281. EXPECT_TRUE(sse.is_connected());
  21282. // Signal handler to stop
  21283. handler_running.store(false);
  21284. // Stop SSE client
  21285. sse.stop();
  21286. EXPECT_FALSE(sse.is_connected());
  21287. }
  21288. // Test: SSEClient with custom headers
  21289. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21290. // Setup a server endpoint that checks for custom header
  21291. std::atomic<bool> header_received{false};
  21292. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21293. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21294. header_received.store(true);
  21295. }
  21296. res.set_chunked_content_provider("text/event-stream",
  21297. [](size_t, DataSink &) { return false; });
  21298. });
  21299. Client client("localhost", get_port());
  21300. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21301. sse::SSEClient sse(client, "/header-check", headers);
  21302. sse.set_max_reconnect_attempts(1);
  21303. sse.start_async();
  21304. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21305. sse.stop();
  21306. EXPECT_TRUE(header_received.load());
  21307. }
  21308. // Test: Reconnect interval configuration
  21309. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21310. Client client("localhost", get_port());
  21311. sse::SSEClient sse(client, "/events");
  21312. auto &result = sse.set_reconnect_interval(500);
  21313. // Builder pattern should return reference to self
  21314. EXPECT_EQ(&result, &sse);
  21315. }
  21316. // Test: Max reconnect attempts
  21317. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21318. // Connect to non-existent port to force reconnects
  21319. Client client("localhost", 59998);
  21320. sse::SSEClient sse(client, "/events");
  21321. std::atomic<int> error_count{0};
  21322. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21323. sse.set_reconnect_interval(50);
  21324. sse.set_max_reconnect_attempts(2);
  21325. auto start = std::chrono::steady_clock::now();
  21326. sse.start(); // Blocking call
  21327. auto end = std::chrono::steady_clock::now();
  21328. // Should have stopped after 2 failed attempts
  21329. EXPECT_GE(error_count.load(), 2);
  21330. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21331. auto duration =
  21332. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21333. #ifdef _WIN32
  21334. // Windows is much slower for socket connection failures
  21335. EXPECT_LT(duration.count(), 7000);
  21336. #else
  21337. EXPECT_LT(duration.count(), 1000);
  21338. #endif
  21339. }
  21340. // Test: Multi-line data in integration
  21341. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21342. // Endpoint with multi-line data
  21343. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21344. res.set_chunked_content_provider(
  21345. "text/event-stream", [](size_t offset, DataSink &sink) {
  21346. if (offset == 0) {
  21347. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21348. sink.write(event.data(), event.size());
  21349. }
  21350. return false;
  21351. });
  21352. });
  21353. Client client("localhost", get_port());
  21354. sse::SSEClient sse(client, "/multiline-data");
  21355. std::string received_data;
  21356. std::mutex data_mutex;
  21357. sse.on_message([&](const sse::SSEMessage &msg) {
  21358. std::lock_guard<std::mutex> lock(data_mutex);
  21359. received_data = msg.data;
  21360. });
  21361. sse.set_reconnect_interval(100);
  21362. sse.set_max_reconnect_attempts(1);
  21363. sse.start_async();
  21364. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21365. sse.stop();
  21366. std::lock_guard<std::mutex> lock(data_mutex);
  21367. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21368. }
  21369. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21370. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21371. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21372. DataSink &sink) {
  21373. if (offset == 0) {
  21374. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21375. sink.write(events.data(), events.size());
  21376. }
  21377. return false;
  21378. });
  21379. });
  21380. Client client("localhost", get_port());
  21381. sse::SSEClient sse(client, "/empty-data-lines");
  21382. std::mutex mutex;
  21383. std::condition_variable cv;
  21384. std::vector<std::string> received;
  21385. sse.on_message([&](const sse::SSEMessage &msg) {
  21386. std::lock_guard<std::mutex> lock(mutex);
  21387. received.push_back(msg.data);
  21388. cv.notify_all();
  21389. });
  21390. sse.set_max_reconnect_attempts(1);
  21391. sse.start_async();
  21392. {
  21393. std::unique_lock<std::mutex> lock(mutex);
  21394. cv.wait_for(lock, std::chrono::seconds(2),
  21395. [&] { return received.size() >= 3; });
  21396. }
  21397. sse.stop();
  21398. ASSERT_GE(received.size(), 3u);
  21399. EXPECT_EQ(received[0], "");
  21400. EXPECT_EQ(received[1], "\nhello");
  21401. EXPECT_EQ(received[2], "");
  21402. }
  21403. // Test: Auto-reconnect after server disconnection
  21404. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21405. std::atomic<int> connection_count{0};
  21406. std::atomic<int> message_count{0};
  21407. // Endpoint that sends one event and closes, forcing reconnect
  21408. server_->Get("/reconnect-test",
  21409. [&connection_count](const Request &, Response &res) {
  21410. connection_count.fetch_add(1);
  21411. res.set_chunked_content_provider(
  21412. "text/event-stream", [](size_t offset, DataSink &sink) {
  21413. if (offset == 0) {
  21414. std::string event = "data: hello\n\n";
  21415. sink.write(event.data(), event.size());
  21416. }
  21417. return false; // Close connection after sending
  21418. });
  21419. });
  21420. Client client("localhost", get_port());
  21421. sse::SSEClient sse(client, "/reconnect-test");
  21422. sse.on_message([&message_count](const sse::SSEMessage &) {
  21423. message_count.fetch_add(1);
  21424. });
  21425. sse.set_reconnect_interval(100);
  21426. sse.set_max_reconnect_attempts(3);
  21427. sse.start_async();
  21428. // Wait long enough for multiple reconnects
  21429. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21430. sse.stop();
  21431. // Should have connected multiple times (initial + reconnects)
  21432. EXPECT_GE(connection_count.load(), 2);
  21433. // Should have received messages from multiple connections
  21434. EXPECT_GE(message_count.load(), 2);
  21435. }
  21436. // Test: A retry field that is not all ASCII digits is ignored
  21437. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21438. std::atomic<int> connection_count{0};
  21439. server_->Get("/bad-retry",
  21440. [&connection_count](const Request &, Response &res) {
  21441. connection_count.fetch_add(1);
  21442. res.set_chunked_content_provider(
  21443. "text/event-stream", [](size_t offset, DataSink &sink) {
  21444. if (offset == 0) {
  21445. std::string event = "retry: -1\ndata: hello\n\n";
  21446. sink.write(event.data(), event.size());
  21447. }
  21448. return false;
  21449. });
  21450. });
  21451. Client client("localhost", get_port());
  21452. sse::SSEClient sse(client, "/bad-retry");
  21453. sse.set_reconnect_interval(10000);
  21454. sse.start_async();
  21455. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21456. sse.stop();
  21457. EXPECT_EQ(connection_count.load(), 1);
  21458. }
  21459. // Test: A retry field of all ASCII digits sets the reconnection time
  21460. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21461. std::mutex mutex;
  21462. std::condition_variable cv;
  21463. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21464. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21465. {
  21466. std::lock_guard<std::mutex> lock(mutex);
  21467. connected_at.push_back(std::chrono::steady_clock::now());
  21468. cv.notify_all();
  21469. }
  21470. res.set_chunked_content_provider(
  21471. "text/event-stream", [](size_t offset, DataSink &sink) {
  21472. if (offset == 0) {
  21473. std::string event = "retry: 0\ndata: hello\n\n";
  21474. sink.write(event.data(), event.size());
  21475. }
  21476. return false;
  21477. });
  21478. });
  21479. Client client("localhost", get_port());
  21480. sse::SSEClient sse(client, "/zero-retry");
  21481. sse.set_reconnect_interval(10000);
  21482. sse.start_async();
  21483. {
  21484. std::unique_lock<std::mutex> lock(mutex);
  21485. cv.wait_for(lock, std::chrono::seconds(5),
  21486. [&] { return connected_at.size() >= 2; });
  21487. }
  21488. sse.stop();
  21489. // The server-supplied interval is applied, but never below 100ms, so
  21490. // "retry: 0" does not cause a busy reconnect loop
  21491. std::lock_guard<std::mutex> lock(mutex);
  21492. ASSERT_GE(connected_at.size(), 2u);
  21493. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21494. connected_at[1] - connected_at[0])
  21495. .count();
  21496. EXPECT_GE(interval_ms, 100);
  21497. }
  21498. // Test: Last-Event-ID sent on reconnect
  21499. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21500. std::atomic<int> connection_count{0};
  21501. std::vector<std::string> received_last_event_ids;
  21502. std::mutex id_mutex;
  21503. // Endpoint that checks Last-Event-ID header and sends event with ID
  21504. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21505. int conn = connection_count.fetch_add(1);
  21506. // Capture the Last-Event-ID header from each connection
  21507. {
  21508. std::lock_guard<std::mutex> lock(id_mutex);
  21509. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21510. }
  21511. res.set_chunked_content_provider(
  21512. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21513. if (offset == 0) {
  21514. std::string event =
  21515. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21516. sink.write(event.data(), event.size());
  21517. }
  21518. return false;
  21519. });
  21520. });
  21521. Client client("localhost", get_port());
  21522. sse::SSEClient sse(client, "/reconnect-with-id");
  21523. sse.set_reconnect_interval(100);
  21524. sse.set_max_reconnect_attempts(3);
  21525. sse.start_async();
  21526. // Wait for at least 2 connections
  21527. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21528. sse.stop();
  21529. // Verify behavior
  21530. std::lock_guard<std::mutex> lock(id_mutex);
  21531. EXPECT_GE(received_last_event_ids.size(), 2u);
  21532. // First connection should have no Last-Event-ID
  21533. if (!received_last_event_ids.empty()) {
  21534. EXPECT_EQ(received_last_event_ids[0], "");
  21535. }
  21536. // Second connection should have Last-Event-ID from first connection
  21537. if (received_last_event_ids.size() >= 2) {
  21538. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21539. }
  21540. }
  21541. // Test: set_headers updates headers used on reconnect
  21542. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21543. std::vector<std::string> received_tokens;
  21544. std::mutex token_mutex;
  21545. // Endpoint that captures Authorization header
  21546. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21547. {
  21548. std::lock_guard<std::mutex> lock(token_mutex);
  21549. received_tokens.push_back(req.get_header_value("Authorization"));
  21550. }
  21551. res.set_chunked_content_provider(
  21552. "text/event-stream", [](size_t offset, DataSink &sink) {
  21553. if (offset == 0) {
  21554. std::string event = "data: hello\n\n";
  21555. sink.write(event.data(), event.size());
  21556. }
  21557. return false; // Close connection to trigger reconnect
  21558. });
  21559. });
  21560. Client client("localhost", get_port());
  21561. Headers headers = {{"Authorization", "Bearer old-token"}};
  21562. sse::SSEClient sse(client, "/auth-check", headers);
  21563. // Update headers on each successful connection
  21564. sse.on_open(
  21565. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21566. sse.set_reconnect_interval(100);
  21567. sse.set_max_reconnect_attempts(3);
  21568. sse.start_async();
  21569. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21570. sse.stop();
  21571. std::lock_guard<std::mutex> lock(token_mutex);
  21572. ASSERT_GE(received_tokens.size(), 2u);
  21573. // First connection uses original header
  21574. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21575. // Second connection uses updated header from set_headers
  21576. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21577. }
  21578. // Test: 401 allows reconnection (so on_error can refresh headers)
  21579. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21580. std::atomic<int> connection_count{0};
  21581. // Endpoint: returns 401 on first attempt, 200 on second
  21582. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21583. int conn = connection_count.fetch_add(1);
  21584. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21585. res.status = StatusCode::Unauthorized_401;
  21586. res.set_content("Unauthorized", "text/plain");
  21587. return;
  21588. }
  21589. res.set_chunked_content_provider(
  21590. "text/event-stream", [](size_t offset, DataSink &sink) {
  21591. if (offset == 0) {
  21592. std::string event = "data: authenticated\n\n";
  21593. sink.write(event.data(), event.size());
  21594. }
  21595. return false;
  21596. });
  21597. });
  21598. Client client("localhost", get_port());
  21599. Headers headers = {{"Authorization", "Bearer expired"}};
  21600. sse::SSEClient sse(client, "/auth-retry", headers);
  21601. std::atomic<bool> message_received{false};
  21602. // Refresh token on error
  21603. sse.on_error(
  21604. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21605. sse.on_message([&](const sse::SSEMessage &msg) {
  21606. if (msg.data == "authenticated") { message_received.store(true); }
  21607. });
  21608. sse.set_reconnect_interval(100);
  21609. sse.set_max_reconnect_attempts(3);
  21610. sse.start_async();
  21611. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21612. sse.stop();
  21613. // Should have reconnected after 401 and succeeded with new token
  21614. EXPECT_GE(connection_count.load(), 2);
  21615. EXPECT_TRUE(message_received.load());
  21616. }
  21617. TEST(Issue2318Test, EmptyHostString) {
  21618. {
  21619. httplib::Client cli_empty("", PORT);
  21620. auto res = cli_empty.Get("/");
  21621. ASSERT_FALSE(res);
  21622. EXPECT_EQ(httplib::Error::Connection, res.error());
  21623. }
  21624. {
  21625. httplib::Client cli(" ", PORT);
  21626. auto res = cli.Get("/");
  21627. ASSERT_FALSE(res);
  21628. EXPECT_EQ(httplib::Error::Connection, res.error());
  21629. }
  21630. }
  21631. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21632. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21633. Server svr;
  21634. // Set a small payload limit (1KB)
  21635. svr.set_payload_max_length(1024);
  21636. svr.Post("/test", [&](const Request &req, Response &res) {
  21637. res.set_content("Body size: " + std::to_string(req.body.size()),
  21638. "text/plain");
  21639. });
  21640. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21641. auto se = detail::scope_exit([&] {
  21642. svr.stop();
  21643. listen_thread.join();
  21644. });
  21645. svr.wait_until_ready();
  21646. // Create data that compresses well but exceeds limit when decompressed
  21647. // 8KB of repeated null bytes compresses to a very small size
  21648. std::string original_data(8 * 1024, '\0');
  21649. // Compress the data using gzip
  21650. std::string compressed_data;
  21651. detail::gzip_compressor compressor;
  21652. compressor.compress(original_data.data(), original_data.size(), true,
  21653. [&](const char *data, size_t size) {
  21654. compressed_data.append(data, size);
  21655. return true;
  21656. });
  21657. // Verify compression worked (compressed should be much smaller)
  21658. ASSERT_LT(compressed_data.size(), original_data.size());
  21659. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21660. // Send compressed data with Content-Encoding: gzip
  21661. Client cli(HOST, PORT);
  21662. Headers headers = {{"Content-Encoding", "gzip"}};
  21663. auto res =
  21664. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21665. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21667. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21668. }
  21669. #endif
  21670. // ============================================================================
  21671. // OpenSSL-Specific Tests
  21672. // ============================================================================
  21673. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21674. X509 *readCertificate(const std::string &strFileName) {
  21675. std::ifstream inStream(strFileName);
  21676. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21677. std::istreambuf_iterator<char>());
  21678. if (strCertPEM.empty()) return (nullptr);
  21679. BIO *pbCert = BIO_new(BIO_s_mem());
  21680. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21681. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21682. BIO_free(pbCert);
  21683. return (pCert);
  21684. }
  21685. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21686. std::ifstream inStream(strFileName);
  21687. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21688. std::istreambuf_iterator<char>());
  21689. if (strPrivateKeyPEM.empty()) return (nullptr);
  21690. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21691. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21692. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21693. BIO_free(pbPrivKey);
  21694. return (pPrivateKey);
  21695. }
  21696. TEST(BindServerTest, UpdateCerts) {
  21697. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21698. int port = svr.bind_to_any_port("0.0.0.0");
  21699. ASSERT_TRUE(svr.is_valid());
  21700. ASSERT_TRUE(port > 0);
  21701. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21702. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21703. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21704. ASSERT_TRUE(cert != nullptr);
  21705. ASSERT_TRUE(ca_cert != nullptr);
  21706. ASSERT_TRUE(key != nullptr);
  21707. X509_STORE *cert_store = X509_STORE_new();
  21708. X509_STORE_add_cert(cert_store, ca_cert);
  21709. // svr.update_certs(cert, key, cert_store); // deprecated
  21710. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21711. CLIENT_CA_CERT_FILE);
  21712. ASSERT_TRUE(svr.is_valid());
  21713. svr.stop();
  21714. X509_STORE_free(cert_store);
  21715. X509_free(cert);
  21716. X509_free(ca_cert);
  21717. EVP_PKEY_free(key);
  21718. }
  21719. // Test that update_certs() updates client CA list correctly
  21720. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21721. // Start with file-based constructor
  21722. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21723. ASSERT_TRUE(svr.is_valid());
  21724. // Initially no client CA list should be set
  21725. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21726. ASSERT_TRUE(ssl_ctx != nullptr);
  21727. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21728. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21729. EXPECT_EQ(0, count_before);
  21730. // Now update with client CA (PEM string)
  21731. std::string cert_pem, key_pem, ca_pem;
  21732. read_file(SERVER_CERT_FILE, cert_pem);
  21733. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21734. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21735. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21736. ASSERT_TRUE(svr.is_valid());
  21737. // Now client CA list should be set
  21738. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21739. ASSERT_TRUE(ca_list_after != nullptr);
  21740. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21741. }
  21742. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21743. // Test that the file-path SSLServer constructor properly sets the client CA
  21744. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21746. ASSERT_TRUE(svr.is_valid());
  21747. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21748. ASSERT_TRUE(ssl_ctx != nullptr);
  21749. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21750. ASSERT_TRUE(ca_list != nullptr);
  21751. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21752. }
  21753. #endif
  21754. // ============================================================================
  21755. // MbedTLS-Specific Tests
  21756. // ============================================================================
  21757. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21758. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21759. using namespace httplib::tls;
  21760. // Track if callback was invoked
  21761. bool callback_invoked = false;
  21762. // The callback receives void* ctx which is actually MbedTlsContext*
  21763. // We can access the mbedtls_ssl_config via the context
  21764. auto setup_callback = [&callback_invoked](void *ctx) {
  21765. callback_invoked = true;
  21766. // Cast to MbedTlsContext* to access the ssl config
  21767. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21768. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21769. // Use static variables to hold certificate data (simplified for test)
  21770. static mbedtls_x509_crt own_cert;
  21771. static mbedtls_pk_context own_key;
  21772. static mbedtls_x509_crt ca_chain;
  21773. static bool initialized = false;
  21774. if (!initialized) {
  21775. mbedtls_x509_crt_init(&own_cert);
  21776. mbedtls_pk_init(&own_key);
  21777. mbedtls_x509_crt_init(&ca_chain);
  21778. // Load server certificate
  21779. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21780. return false;
  21781. }
  21782. // Load server private key.
  21783. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21784. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21785. #if MBEDTLS_VERSION_MAJOR == 3
  21786. ,
  21787. mbedtls_ctr_drbg_random, nullptr
  21788. #endif
  21789. ) != 0) {
  21790. return false;
  21791. }
  21792. // Load CA chain for client verification
  21793. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21794. return false;
  21795. }
  21796. initialized = true;
  21797. }
  21798. // Configure the SSL config
  21799. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21800. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21801. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21802. // Set minimum TLS version using mbedTLS native API
  21803. #if MBEDTLS_VERSION_MAJOR >= 3
  21804. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21805. #else
  21806. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21807. MBEDTLS_SSL_MINOR_VERSION_3);
  21808. #endif
  21809. return true;
  21810. };
  21811. SSLServer svr(setup_callback);
  21812. ASSERT_TRUE(svr.is_valid());
  21813. ASSERT_TRUE(callback_invoked);
  21814. svr.Get("/test", [&](const Request &req, Response &res) {
  21815. res.set_content("test", "text/plain");
  21816. auto cert = req.peer_cert();
  21817. ASSERT_TRUE(static_cast<bool>(cert));
  21818. auto common_name = cert.subject_cn();
  21819. EXPECT_EQ("Common Name", common_name);
  21820. });
  21821. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21822. auto se = detail::scope_exit([&] {
  21823. svr.stop();
  21824. t.join();
  21825. ASSERT_FALSE(svr.is_running());
  21826. });
  21827. svr.wait_until_ready();
  21828. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21829. cli.enable_server_certificate_verification(false);
  21830. cli.set_connection_timeout(30);
  21831. auto res = cli.Get("/test");
  21832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21833. ASSERT_EQ(StatusCode::OK_200, res->status);
  21834. }
  21835. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21836. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21837. // keep-alive SSL session, which reads through that config in
  21838. // mbedtls_ssl_close_notify.
  21839. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21840. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21841. ASSERT_TRUE(svr.is_valid());
  21842. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21843. res.set_content("test", "text/plain");
  21844. });
  21845. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21846. auto se = detail::scope_exit([&] {
  21847. svr.stop();
  21848. t.join();
  21849. ASSERT_FALSE(svr.is_running());
  21850. });
  21851. svr.wait_until_ready();
  21852. {
  21853. SSLClient cli(HOST, PORT);
  21854. cli.enable_server_certificate_verification(false);
  21855. cli.set_keep_alive(true);
  21856. auto res = cli.Get("/test");
  21857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21858. ASSERT_EQ(StatusCode::OK_200, res->status);
  21859. // cli is destructed here with the keep-alive SSL session still open.
  21860. }
  21861. }
  21862. #endif
  21863. // WebSocket Tests
  21864. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21865. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21866. // defining the meaning of these bits has been negotiated.
  21867. auto make_frame = [](uint8_t first_byte) {
  21868. std::string frame;
  21869. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21870. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21871. frame += "Hello";
  21872. return frame;
  21873. };
  21874. // RSV1 set (0x40)
  21875. {
  21876. detail::BufferStream strm;
  21877. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21878. ws::Opcode opcode;
  21879. std::string payload;
  21880. bool fin;
  21881. EXPECT_EQ(
  21882. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21883. ws::impl::FrameRead::Fail);
  21884. }
  21885. // RSV2 set (0x20)
  21886. {
  21887. detail::BufferStream strm;
  21888. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21889. ws::Opcode opcode;
  21890. std::string payload;
  21891. bool fin;
  21892. EXPECT_EQ(
  21893. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21894. ws::impl::FrameRead::Fail);
  21895. }
  21896. // RSV3 set (0x10)
  21897. {
  21898. detail::BufferStream strm;
  21899. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21900. ws::Opcode opcode;
  21901. std::string payload;
  21902. bool fin;
  21903. EXPECT_EQ(
  21904. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21905. ws::impl::FrameRead::Fail);
  21906. }
  21907. // No RSV bits set - should succeed
  21908. {
  21909. detail::BufferStream strm;
  21910. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  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::Ok);
  21917. EXPECT_EQ(ws::Opcode::Text, opcode);
  21918. EXPECT_EQ("Hello", payload);
  21919. EXPECT_TRUE(fin);
  21920. }
  21921. }
  21922. TEST(WebSocketTest, ControlFrameValidation) {
  21923. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21924. // payload length <= 125.
  21925. // Ping with FIN=0 - must be rejected
  21926. {
  21927. detail::BufferStream strm;
  21928. std::string frame;
  21929. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21930. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21931. strm.write(frame.data(), frame.size());
  21932. ws::Opcode opcode;
  21933. std::string payload;
  21934. bool fin;
  21935. EXPECT_EQ(
  21936. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21937. ws::impl::FrameRead::Fail);
  21938. }
  21939. // Close with FIN=0 - must be rejected
  21940. {
  21941. detail::BufferStream strm;
  21942. std::string frame;
  21943. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21944. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21945. strm.write(frame.data(), frame.size());
  21946. ws::Opcode opcode;
  21947. std::string payload;
  21948. bool fin;
  21949. EXPECT_EQ(
  21950. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21951. ws::impl::FrameRead::Fail);
  21952. }
  21953. // Ping with payload_len=126 (extended length) - must be rejected
  21954. {
  21955. detail::BufferStream strm;
  21956. std::string frame;
  21957. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21958. frame += static_cast<char>(126); // payload_len=126 (>125)
  21959. frame += static_cast<char>(0x00); // extended length high byte
  21960. frame += static_cast<char>(126); // extended length low byte
  21961. frame += std::string(126, 'x');
  21962. strm.write(frame.data(), frame.size());
  21963. ws::Opcode opcode;
  21964. std::string payload;
  21965. bool fin;
  21966. EXPECT_EQ(
  21967. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21968. ws::impl::FrameRead::Fail);
  21969. }
  21970. // Ping with FIN=1 and payload_len=125 - should succeed
  21971. {
  21972. detail::BufferStream strm;
  21973. std::string frame;
  21974. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21975. frame += static_cast<char>(125); // payload_len=125
  21976. frame += std::string(125, 'x');
  21977. strm.write(frame.data(), frame.size());
  21978. ws::Opcode opcode;
  21979. std::string payload;
  21980. bool fin;
  21981. EXPECT_EQ(
  21982. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21983. ws::impl::FrameRead::Ok);
  21984. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21985. EXPECT_EQ(125u, payload.size());
  21986. EXPECT_TRUE(fin);
  21987. }
  21988. }
  21989. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21990. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21991. // length MUST be 0.
  21992. // MSB set - must be rejected
  21993. {
  21994. detail::BufferStream strm;
  21995. std::string frame;
  21996. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21997. frame += static_cast<char>(127); // 64-bit extended length
  21998. frame += static_cast<char>(0x80); // MSB set (invalid)
  21999. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22000. strm.write(frame.data(), frame.size());
  22001. ws::Opcode opcode;
  22002. std::string payload;
  22003. bool fin;
  22004. EXPECT_EQ(
  22005. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22006. ws::impl::FrameRead::Fail);
  22007. }
  22008. // MSB clear - should pass length parsing (will be rejected by max_len,
  22009. // but that's a different check; use a small length to verify)
  22010. {
  22011. detail::BufferStream strm;
  22012. std::string frame;
  22013. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22014. frame += static_cast<char>(127); // 64-bit extended length
  22015. frame += std::string(7, '\0'); // high bytes = 0
  22016. frame += static_cast<char>(0x03); // length = 3
  22017. frame += "abc";
  22018. strm.write(frame.data(), frame.size());
  22019. ws::Opcode opcode;
  22020. std::string payload;
  22021. bool fin;
  22022. EXPECT_EQ(
  22023. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22024. ws::impl::FrameRead::Ok);
  22025. EXPECT_EQ(ws::Opcode::Text, opcode);
  22026. EXPECT_EQ("abc", payload);
  22027. }
  22028. }
  22029. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22030. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22031. // Valid UTF-8
  22032. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22033. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22034. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22035. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22036. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22037. // Invalid UTF-8
  22038. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22039. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22040. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22041. EXPECT_FALSE(
  22042. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22043. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22044. }
  22045. TEST(WebSocketTest, ConnectAndDisconnect) {
  22046. Server svr;
  22047. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22048. std::string msg;
  22049. while (ws.read(msg)) {}
  22050. });
  22051. auto port = svr.bind_to_any_port(HOST);
  22052. std::thread t([&]() { svr.listen_after_bind(); });
  22053. svr.wait_until_ready();
  22054. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22055. auto res = client.connect();
  22056. ASSERT_TRUE(res);
  22057. EXPECT_EQ(Error::Success, res.error());
  22058. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22059. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22060. EXPECT_TRUE(client.is_open());
  22061. client.close();
  22062. EXPECT_FALSE(client.is_open());
  22063. svr.stop();
  22064. t.join();
  22065. }
  22066. TEST(WebSocketTest, ValidURL) {
  22067. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22068. EXPECT_TRUE(ws1.is_valid());
  22069. ws::WebSocketClient ws2("ws://example.com/path");
  22070. EXPECT_TRUE(ws2.is_valid());
  22071. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22072. EXPECT_TRUE(ws3.is_valid());
  22073. #ifdef CPPHTTPLIB_SSL_ENABLED
  22074. ws::WebSocketClient wss1("wss://example.com/path");
  22075. EXPECT_TRUE(wss1.is_valid());
  22076. ws::WebSocketClient wss2("wss://example.com:443/path");
  22077. EXPECT_TRUE(wss2.is_valid());
  22078. #endif
  22079. }
  22080. TEST(WebSocketTest, InvalidURL) {
  22081. // No scheme
  22082. ws::WebSocketClient ws1("localhost:8080/path");
  22083. EXPECT_FALSE(ws1.is_valid());
  22084. // No path
  22085. ws::WebSocketClient ws2("ws://localhost:8080");
  22086. EXPECT_FALSE(ws2.is_valid());
  22087. // Empty string
  22088. ws::WebSocketClient ws3("");
  22089. EXPECT_FALSE(ws3.is_valid());
  22090. // Missing host
  22091. ws::WebSocketClient ws4("ws://:8080/path");
  22092. EXPECT_FALSE(ws4.is_valid());
  22093. // Port number overflow — should not crash
  22094. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22095. EXPECT_FALSE(ws5.is_valid());
  22096. // Port out of range
  22097. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22098. EXPECT_FALSE(ws6.is_valid());
  22099. }
  22100. TEST(WebSocketTest, UnsupportedScheme) {
  22101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22102. ws::WebSocketClient ws1("http://localhost:8080/path");
  22103. EXPECT_FALSE(ws1.is_valid());
  22104. ws::WebSocketClient ws2("https://localhost:8080/path");
  22105. EXPECT_FALSE(ws2.is_valid());
  22106. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22107. EXPECT_FALSE(ws3.is_valid());
  22108. #else
  22109. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22110. std::invalid_argument);
  22111. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22112. std::invalid_argument);
  22113. #endif
  22114. }
  22115. TEST(WebSocketTest, ConnectWhenInvalid) {
  22116. ws::WebSocketClient ws("not a valid url");
  22117. EXPECT_FALSE(ws.is_valid());
  22118. auto res = ws.connect();
  22119. EXPECT_FALSE(res);
  22120. EXPECT_EQ(Error::Connection, res.error());
  22121. EXPECT_EQ(-1, res.status());
  22122. }
  22123. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22124. // Grab a port that is free, then close it again so nothing listens there
  22125. Server svr;
  22126. auto port = svr.bind_to_any_port(HOST);
  22127. svr.stop();
  22128. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22129. auto res = client.connect();
  22130. ASSERT_FALSE(res);
  22131. EXPECT_EQ(Error::Connection, res.error());
  22132. EXPECT_EQ(-1, res.status());
  22133. }
  22134. TEST(WebSocketTest, DefaultPort) {
  22135. ws::WebSocketClient ws1("ws://example.com/path");
  22136. EXPECT_TRUE(ws1.is_valid());
  22137. // ws:// defaults to port 80 (verified by successful parse)
  22138. #ifdef CPPHTTPLIB_SSL_ENABLED
  22139. ws::WebSocketClient ws2("wss://example.com/path");
  22140. EXPECT_TRUE(ws2.is_valid());
  22141. // wss:// defaults to port 443 (verified by successful parse)
  22142. #endif
  22143. }
  22144. TEST(WebSocketTest, IPv6LiteralAddress) {
  22145. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22146. EXPECT_TRUE(ws1.is_valid());
  22147. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22148. EXPECT_TRUE(ws2.is_valid());
  22149. }
  22150. TEST(WebSocketTest, ComplexPath) {
  22151. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22152. EXPECT_TRUE(ws1.is_valid());
  22153. ws::WebSocketClient ws2("ws://localhost:8080/");
  22154. EXPECT_TRUE(ws2.is_valid());
  22155. }
  22156. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22157. Server svr;
  22158. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22159. std::string msg;
  22160. while (ws.read(msg)) {}
  22161. });
  22162. auto port = svr.bind_to_any_port(HOST);
  22163. std::thread t([&]() { svr.listen_after_bind(); });
  22164. svr.wait_until_ready();
  22165. auto another_host = "example.com";
  22166. auto wrong_ip = "192.0.2.1";
  22167. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22168. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22169. ASSERT_TRUE(client.connect());
  22170. EXPECT_TRUE(client.is_open());
  22171. client.close();
  22172. svr.stop();
  22173. t.join();
  22174. }
  22175. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22176. Server svr;
  22177. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22178. std::string msg;
  22179. while (ws.read(msg)) {}
  22180. });
  22181. auto port = svr.bind_to_any_port(HOST);
  22182. std::thread t([&]() { svr.listen_after_bind(); });
  22183. svr.wait_until_ready();
  22184. auto wrong_ip = "192.0.2.1";
  22185. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22186. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22187. client.set_connection_timeout(1);
  22188. client.set_read_timeout(1);
  22189. client.set_write_timeout(1);
  22190. EXPECT_FALSE(client.connect());
  22191. EXPECT_FALSE(client.is_open());
  22192. svr.stop();
  22193. t.join();
  22194. }
  22195. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22196. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22197. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22198. // (RFC 6761) is only a map key and the Host header value.
  22199. auto host = "target.invalid";
  22200. Server svr;
  22201. std::string received_host;
  22202. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22203. received_host = req.get_header_value("Host");
  22204. std::string msg;
  22205. while (ws.read(msg)) {}
  22206. });
  22207. auto port = svr.bind_to_any_port(HOST);
  22208. std::thread t([&]() { svr.listen_after_bind(); });
  22209. // ASSERT_* below returns from the test body, which would leave t joinable
  22210. // and make ~thread call std::terminate.
  22211. auto se = detail::scope_exit([&] {
  22212. svr.stop();
  22213. if (t.joinable()) { t.join(); }
  22214. });
  22215. svr.wait_until_ready();
  22216. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22217. std::to_string(port) + "/ws");
  22218. client.set_hostname_addr_map({{host, HOST}});
  22219. ASSERT_TRUE(client.connect());
  22220. EXPECT_TRUE(client.is_open());
  22221. client.close();
  22222. svr.stop();
  22223. t.join();
  22224. // The mapping only redirects the connection; the identity stays host_.
  22225. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22226. }
  22227. class WebSocketIntegrationTest : public ::testing::Test {
  22228. protected:
  22229. void SetUp() override {
  22230. server_ = httplib::detail::make_unique<Server>();
  22231. setup_server();
  22232. start_server();
  22233. }
  22234. void TearDown() override {
  22235. server_->stop();
  22236. if (server_thread_.joinable()) { server_thread_.join(); }
  22237. }
  22238. void setup_server() {
  22239. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22240. std::string msg;
  22241. ws::ReadResult ret;
  22242. while ((ret = ws.read(msg))) {
  22243. if (ret == ws::Binary) {
  22244. ws.send(msg.data(), msg.size());
  22245. } else {
  22246. ws.send(msg);
  22247. }
  22248. }
  22249. });
  22250. server_->WebSocket("/ws-echo-string",
  22251. [](const Request &, ws::WebSocket &ws) {
  22252. std::string msg;
  22253. while (ws.read(msg)) {
  22254. ws.send("echo: " + msg);
  22255. }
  22256. });
  22257. server_->WebSocket(
  22258. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22259. // Echo back request metadata
  22260. ws.send("path:" + req.path);
  22261. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22262. std::string msg;
  22263. while (ws.read(msg)) {}
  22264. });
  22265. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22266. std::string msg;
  22267. ws.read(msg); // wait for a message
  22268. ws.close();
  22269. });
  22270. server_->WebSocket("/ws-close-status",
  22271. [](const Request &, ws::WebSocket &ws) {
  22272. std::string msg;
  22273. ws.read(msg); // wait for a message
  22274. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22275. });
  22276. server_->WebSocket(
  22277. "/ws-subprotocol",
  22278. [](const Request &, ws::WebSocket &ws) {
  22279. std::string msg;
  22280. while (ws.read(msg)) {
  22281. ws.send(msg);
  22282. }
  22283. },
  22284. [](const std::vector<std::string> &protocols) -> std::string {
  22285. for (const auto &p : protocols) {
  22286. if (p == "graphql-ws") { return p; }
  22287. }
  22288. return "";
  22289. });
  22290. server_->WebSocket(
  22291. "/ws-subprotocol-unoffered",
  22292. [](const Request &, ws::WebSocket &ws) {
  22293. std::string msg;
  22294. while (ws.read(msg)) {
  22295. ws.send(msg);
  22296. }
  22297. },
  22298. [](const std::vector<std::string> &) -> std::string {
  22299. return "admin";
  22300. });
  22301. }
  22302. void start_server() {
  22303. port_ = server_->bind_to_any_port(HOST);
  22304. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22305. server_->wait_until_ready();
  22306. }
  22307. std::unique_ptr<Server> server_;
  22308. std::thread server_thread_;
  22309. int port_ = 0;
  22310. };
  22311. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22312. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22313. "/ws-echo");
  22314. ASSERT_TRUE(client.connect());
  22315. ASSERT_TRUE(client.is_open());
  22316. ASSERT_TRUE(client.send("Hello WebSocket"));
  22317. std::string msg;
  22318. EXPECT_EQ(ws::Text, client.read(msg));
  22319. EXPECT_EQ("Hello WebSocket", msg);
  22320. client.close();
  22321. }
  22322. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22323. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22324. "/ws-echo");
  22325. ASSERT_TRUE(client.connect());
  22326. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22327. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22328. std::string msg;
  22329. EXPECT_EQ(ws::Binary, client.read(msg));
  22330. EXPECT_EQ(binary_data, msg);
  22331. client.close();
  22332. }
  22333. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22334. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22335. "/ws-echo");
  22336. ASSERT_TRUE(client.connect());
  22337. for (int i = 0; i < 10; i++) {
  22338. auto text = "message " + std::to_string(i);
  22339. ASSERT_TRUE(client.send(text));
  22340. std::string msg;
  22341. ASSERT_TRUE(client.read(msg));
  22342. EXPECT_EQ(text, msg);
  22343. }
  22344. client.close();
  22345. }
  22346. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22347. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22348. "/ws-close");
  22349. ASSERT_TRUE(client.connect());
  22350. // Send a message to trigger the server to close
  22351. ASSERT_TRUE(client.send("trigger close"));
  22352. // The server will close, so read should return false
  22353. std::string msg;
  22354. EXPECT_FALSE(client.read(msg));
  22355. EXPECT_FALSE(client.is_open());
  22356. }
  22357. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22358. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22359. "/ws-echo");
  22360. ASSERT_TRUE(client.connect());
  22361. // 128KB message
  22362. std::string large_data(128 * 1024, 'X');
  22363. ASSERT_TRUE(client.send(large_data));
  22364. std::string msg;
  22365. ASSERT_TRUE(client.read(msg));
  22366. EXPECT_EQ(large_data, msg);
  22367. client.close();
  22368. }
  22369. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22370. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22371. "/ws-echo");
  22372. ASSERT_TRUE(client.connect());
  22373. const int num_threads = 4;
  22374. std::vector<std::thread> threads;
  22375. std::atomic<int> send_count{0};
  22376. for (int t = 0; t < num_threads; t++) {
  22377. threads.emplace_back([&client, &send_count, t]() {
  22378. for (int i = 0; i < 5; i++) {
  22379. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22380. if (client.send(text)) { send_count++; }
  22381. }
  22382. });
  22383. }
  22384. for (auto &th : threads) {
  22385. th.join();
  22386. }
  22387. int received = 0;
  22388. std::string msg;
  22389. while (received < send_count.load()) {
  22390. if (!client.read(msg)) { break; }
  22391. received++;
  22392. }
  22393. EXPECT_EQ(send_count.load(), received);
  22394. client.close();
  22395. }
  22396. TEST_F(WebSocketIntegrationTest, ReadString) {
  22397. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22398. "/ws-echo-string");
  22399. ASSERT_TRUE(client.connect());
  22400. ASSERT_TRUE(client.send("hello"));
  22401. std::string msg;
  22402. ASSERT_TRUE(client.read(msg));
  22403. EXPECT_EQ("echo: hello", msg);
  22404. ASSERT_TRUE(client.send("world"));
  22405. ASSERT_TRUE(client.read(msg));
  22406. EXPECT_EQ("echo: world", msg);
  22407. client.close();
  22408. }
  22409. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22410. Headers headers = {{"X-Test-Header", "test-value"}};
  22411. ws::WebSocketClient client(
  22412. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22413. ASSERT_TRUE(client.connect());
  22414. std::string msg;
  22415. ASSERT_TRUE(client.read(msg));
  22416. EXPECT_EQ("path:/ws-request-info", msg);
  22417. ASSERT_TRUE(client.read(msg));
  22418. EXPECT_EQ("header:test-value", msg);
  22419. client.close();
  22420. }
  22421. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22422. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22423. "/ws-echo");
  22424. client.set_read_timeout(1, 0); // 1 second
  22425. ASSERT_TRUE(client.connect());
  22426. // Don't send anything — server echo handler waits for a message, so read()
  22427. // should time out. The connection survives it: nothing was consumed.
  22428. std::string msg;
  22429. EXPECT_EQ(client.read(msg), ws::Timeout);
  22430. EXPECT_TRUE(client.is_open());
  22431. // And it is still usable afterwards.
  22432. EXPECT_TRUE(client.send("after timeout"));
  22433. EXPECT_EQ(client.read(msg), ws::Text);
  22434. EXPECT_EQ(msg, "after timeout");
  22435. }
  22436. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22437. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22438. "/ws-echo");
  22439. client.set_read_timeout(1, 0);
  22440. ASSERT_TRUE(client.connect());
  22441. ASSERT_TRUE(client.send("first"));
  22442. std::string msg;
  22443. ASSERT_EQ(client.read(msg), ws::Text);
  22444. ASSERT_EQ(msg, "first");
  22445. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22446. // not be used with a read timeout: it would reprocess the previous message.
  22447. EXPECT_EQ(client.read(msg), ws::Timeout);
  22448. EXPECT_EQ(msg, "first");
  22449. }
  22450. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22451. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22452. "/ws-echo");
  22453. ASSERT_TRUE(client.connect());
  22454. // Setting it once the connection is open reaches the live stream, not just
  22455. // the seed for the next connect().
  22456. client.set_read_timeout(1, 0);
  22457. std::string msg;
  22458. EXPECT_EQ(client.read(msg), ws::Timeout);
  22459. EXPECT_TRUE(client.is_open());
  22460. }
  22461. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22462. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22463. "/ws-echo");
  22464. client.set_read_timeout(5, 0);
  22465. ASSERT_TRUE(client.connect());
  22466. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22467. // The server should reject it and close the connection.
  22468. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22469. client.send(oversized);
  22470. // The server's read() should have failed due to payload limit,
  22471. // so our read() should return false (connection closed).
  22472. std::string msg;
  22473. EXPECT_FALSE(client.read(msg));
  22474. }
  22475. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22476. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22477. "/ws-echo");
  22478. client.set_read_timeout(10, 0);
  22479. ASSERT_TRUE(client.connect());
  22480. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22481. // This should succeed.
  22482. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22483. ASSERT_TRUE(client.send(at_limit));
  22484. std::string msg;
  22485. ASSERT_TRUE(client.read(msg));
  22486. EXPECT_EQ(at_limit.size(), msg.size());
  22487. client.close();
  22488. }
  22489. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22490. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22491. "/nonexistent");
  22492. auto res = client.connect();
  22493. EXPECT_FALSE(res);
  22494. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22495. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22496. EXPECT_FALSE(client.is_open());
  22497. }
  22498. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22499. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22500. "/ws-echo");
  22501. ASSERT_TRUE(client.connect());
  22502. ASSERT_TRUE(client.send(""));
  22503. std::string msg;
  22504. EXPECT_EQ(ws::Text, client.read(msg));
  22505. EXPECT_EQ("", msg);
  22506. client.close();
  22507. }
  22508. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22509. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22510. "/ws-echo");
  22511. // First connection
  22512. ASSERT_TRUE(client.connect());
  22513. ASSERT_TRUE(client.send("first"));
  22514. std::string msg;
  22515. ASSERT_TRUE(client.read(msg));
  22516. EXPECT_EQ("first", msg);
  22517. client.close();
  22518. EXPECT_FALSE(client.is_open());
  22519. // Reconnect using the same client object
  22520. ASSERT_TRUE(client.connect());
  22521. ASSERT_TRUE(client.is_open());
  22522. ASSERT_TRUE(client.send("second"));
  22523. ASSERT_TRUE(client.read(msg));
  22524. EXPECT_EQ("second", msg);
  22525. client.close();
  22526. }
  22527. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22528. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22529. "/ws-close-status");
  22530. ASSERT_TRUE(client.connect());
  22531. // Trigger the server to close with GoingAway status
  22532. ASSERT_TRUE(client.send("trigger"));
  22533. // read() should return false after receiving the close frame
  22534. std::string msg;
  22535. EXPECT_FALSE(client.read(msg));
  22536. EXPECT_FALSE(client.is_open());
  22537. }
  22538. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22539. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22540. "/ws-echo");
  22541. ASSERT_TRUE(client.connect());
  22542. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22543. EXPECT_FALSE(client.is_open());
  22544. }
  22545. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22546. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22547. ws::WebSocketClient client(
  22548. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22549. ASSERT_TRUE(client.connect());
  22550. // Server should have selected graphql-ws
  22551. EXPECT_EQ("graphql-ws", client.subprotocol());
  22552. client.close();
  22553. }
  22554. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22555. Headers headers;
  22556. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22557. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22558. ws::WebSocketClient client(
  22559. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22560. ASSERT_TRUE(client.connect());
  22561. // The offer on the second field line counts too, so graphql-ws is selected
  22562. EXPECT_EQ("graphql-ws", client.subprotocol());
  22563. client.close();
  22564. }
  22565. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22566. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22567. ws::WebSocketClient client(
  22568. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22569. ASSERT_TRUE(client.connect());
  22570. // Server should not have selected any subprotocol
  22571. EXPECT_TRUE(client.subprotocol().empty());
  22572. client.close();
  22573. }
  22574. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22575. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22576. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22577. "/ws-subprotocol-unoffered",
  22578. headers);
  22579. ASSERT_TRUE(client.connect());
  22580. EXPECT_TRUE(client.subprotocol().empty());
  22581. client.close();
  22582. }
  22583. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22584. // Connect without requesting any subprotocol
  22585. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22586. "/ws-subprotocol");
  22587. ASSERT_TRUE(client.connect());
  22588. EXPECT_TRUE(client.subprotocol().empty());
  22589. client.close();
  22590. }
  22591. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22592. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22593. "/ws-echo");
  22594. client.set_tcp_nodelay(true);
  22595. client.set_connection_timeout(3, 0);
  22596. bool socket_options_called = false;
  22597. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22598. ASSERT_TRUE(client.connect());
  22599. ASSERT_TRUE(client.is_open());
  22600. EXPECT_TRUE(socket_options_called);
  22601. ASSERT_TRUE(client.send("hello"));
  22602. std::string msg;
  22603. auto result = client.read(msg);
  22604. EXPECT_EQ(result, ws::ReadResult::Text);
  22605. EXPECT_EQ(msg, "hello");
  22606. client.close();
  22607. }
  22608. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22609. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22610. "/ws-echo");
  22611. client.set_connection_timeout(std::chrono::seconds(3));
  22612. client.set_write_timeout(std::chrono::seconds(3));
  22613. // A sub-second remainder exercises the seconds/microseconds split.
  22614. client.set_read_timeout(std::chrono::milliseconds(1500));
  22615. ASSERT_TRUE(client.connect());
  22616. auto start = std::chrono::steady_clock::now();
  22617. std::string msg;
  22618. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22619. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22620. std::chrono::steady_clock::now() - start)
  22621. .count();
  22622. // Above 1s so that dropping the microseconds half of the split fails here.
  22623. // Ignoring the setter altogether would not reach this line at all: a client
  22624. // waits forever by default.
  22625. EXPECT_GE(elapsed, 1400);
  22626. EXPECT_LT(elapsed, 30000);
  22627. }
  22628. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22629. Server svr;
  22630. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22631. if (!req.has_header("Authorization")) {
  22632. res.status = StatusCode::Unauthorized_401;
  22633. res.set_content("Unauthorized", "text/plain");
  22634. return Server::HandlerResponse::Handled;
  22635. }
  22636. return Server::HandlerResponse::Unhandled;
  22637. });
  22638. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22639. std::string msg;
  22640. while (ws.read(msg)) {
  22641. ws.send(msg);
  22642. }
  22643. });
  22644. auto port = svr.bind_to_any_port("localhost");
  22645. std::thread t([&]() { svr.listen_after_bind(); });
  22646. svr.wait_until_ready();
  22647. // Without Authorization header - should be rejected before upgrade
  22648. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22649. EXPECT_FALSE(client1.connect());
  22650. // The rejection is framed like any other HTTP response
  22651. {
  22652. Client cli("localhost", port);
  22653. Headers headers = {{"Upgrade", "websocket"},
  22654. {"Connection", "Upgrade"},
  22655. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22656. {"Sec-WebSocket-Version", "13"}};
  22657. auto res = cli.Get("/ws", headers);
  22658. ASSERT_TRUE(res);
  22659. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22660. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22661. EXPECT_EQ("Unauthorized", res->body);
  22662. }
  22663. // With Authorization header - should succeed
  22664. Headers headers = {{"Authorization", "Bearer token123"}};
  22665. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22666. headers);
  22667. ASSERT_TRUE(client2.connect());
  22668. ASSERT_TRUE(client2.send("hello"));
  22669. std::string msg;
  22670. ASSERT_TRUE(client2.read(msg));
  22671. EXPECT_EQ("hello", msg);
  22672. client2.close();
  22673. svr.stop();
  22674. t.join();
  22675. }
  22676. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22677. Server svr;
  22678. std::atomic<int> pre_request_calls{0};
  22679. std::atomic<bool> route_matched{false};
  22680. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22681. pre_request_calls++;
  22682. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22683. if (req.get_header_value("Authorization") != "Bearer token123") {
  22684. res.status = StatusCode::Unauthorized_401;
  22685. res.set_content("Unauthorized", "text/plain");
  22686. return Server::HandlerResponse::Handled;
  22687. }
  22688. return Server::HandlerResponse::Unhandled;
  22689. });
  22690. std::atomic<bool> handler_called{false};
  22691. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22692. handler_called = true;
  22693. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22694. });
  22695. auto port = svr.bind_to_any_port("localhost");
  22696. std::thread t([&]() { svr.listen_after_bind(); });
  22697. svr.wait_until_ready();
  22698. // Without Authorization header - should be rejected before upgrade
  22699. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22700. "/ws/1");
  22701. EXPECT_FALSE(client1.connect());
  22702. EXPECT_FALSE(handler_called);
  22703. EXPECT_EQ(1, pre_request_calls);
  22704. EXPECT_TRUE(route_matched);
  22705. // The rejection is an ordinary HTTP response, not a protocol switch
  22706. {
  22707. Client cli("localhost", port);
  22708. Headers headers = {{"Upgrade", "websocket"},
  22709. {"Connection", "Upgrade"},
  22710. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22711. {"Sec-WebSocket-Version", "13"}};
  22712. auto res = cli.Get("/ws/1", headers);
  22713. ASSERT_TRUE(res);
  22714. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22715. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22716. EXPECT_EQ("Unauthorized", res->body);
  22717. }
  22718. EXPECT_FALSE(handler_called);
  22719. // With Authorization header - should succeed
  22720. Headers headers = {{"Authorization", "Bearer token123"}};
  22721. ws::WebSocketClient client2(
  22722. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22723. ASSERT_TRUE(client2.connect());
  22724. std::string msg;
  22725. ASSERT_TRUE(client2.read(msg));
  22726. EXPECT_EQ("/ws/:id 2", msg);
  22727. EXPECT_TRUE(handler_called);
  22728. client2.close();
  22729. svr.stop();
  22730. t.join();
  22731. }
  22732. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22733. Server svr;
  22734. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22735. // A read timeout is how a handler gets control back. Without it, a handler
  22736. // parked in read() can never write on the connection it is reading.
  22737. ws.set_read_timeout(std::chrono::milliseconds(100));
  22738. std::string msg;
  22739. while (ws.is_open()) {
  22740. auto r = ws.read(msg);
  22741. if (r == httplib::ws::Timeout) {
  22742. ws.send("tick");
  22743. continue;
  22744. }
  22745. if (r == httplib::ws::Fail) { break; }
  22746. ws.send(msg);
  22747. }
  22748. });
  22749. auto port = svr.bind_to_any_port("localhost");
  22750. std::thread t([&]() { svr.listen_after_bind(); });
  22751. svr.wait_until_ready();
  22752. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22753. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22754. ASSERT_TRUE(client.connect());
  22755. // The client sends nothing, so anything it receives came out of the
  22756. // handler's timeout path.
  22757. std::string msg;
  22758. ASSERT_EQ(client.read(msg), ws::Text);
  22759. EXPECT_EQ("tick", msg);
  22760. client.close();
  22761. svr.stop();
  22762. t.join();
  22763. }
  22764. // Stream::read may return fewer bytes than asked for. This is that contract at
  22765. // its worst -- one byte per call -- which is what a frame header straddling a
  22766. // read buffer's boundary looks like to the frame parser.
  22767. class WsByteAtATimeStream : public Stream {
  22768. public:
  22769. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22770. bool is_readable() const override { return true; }
  22771. bool wait_readable() const override { return true; }
  22772. bool wait_writable() const override { return true; }
  22773. ssize_t read(char *ptr, size_t size) override {
  22774. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22775. *ptr = data_[pos_++];
  22776. return 1;
  22777. }
  22778. ssize_t write(const char *, size_t size) override {
  22779. return static_cast<ssize_t>(size);
  22780. }
  22781. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22782. ip = "127.0.0.1";
  22783. port = 0;
  22784. }
  22785. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22786. ip = "127.0.0.1";
  22787. port = 0;
  22788. }
  22789. socket_t socket() const override { return INVALID_SOCKET; }
  22790. time_t duration() const override { return 0; }
  22791. private:
  22792. std::string data_;
  22793. size_t pos_ = 0;
  22794. };
  22795. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22796. // The payload uses the 16-bit extended length, so the header, the length
  22797. // and the mask key are all multi-byte fields here. Each used to be read
  22798. // with a single read() call, which fails as soon as one is split. The
  22799. // payload is also a little over one read chunk, so it is read in two.
  22800. std::string body;
  22801. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22802. body += static_cast<char>(i % 251);
  22803. }
  22804. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22805. std::string frame;
  22806. frame += static_cast<char>(0x81); // FIN + Text
  22807. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22808. frame += static_cast<char>(body.size() >> 8);
  22809. frame += static_cast<char>(body.size() & 0xff);
  22810. for (size_t i = 0; i < 4; i++) {
  22811. frame += static_cast<char>(mask[i]);
  22812. }
  22813. for (size_t i = 0; i < body.size(); i++) {
  22814. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22815. }
  22816. WsByteAtATimeStream strm(frame);
  22817. ws::Opcode opcode;
  22818. std::string payload;
  22819. bool fin = false;
  22820. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22821. /*expect_masked=*/true, body.size()),
  22822. ws::impl::FrameRead::Ok);
  22823. EXPECT_TRUE(fin);
  22824. EXPECT_EQ(opcode, ws::Opcode::Text);
  22825. EXPECT_EQ(payload, body);
  22826. }
  22827. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22828. std::string body(2000, 'x');
  22829. std::string frame;
  22830. frame += static_cast<char>(0x82); // FIN + Binary
  22831. frame += static_cast<char>(126); // 16-bit length follows
  22832. frame += static_cast<char>(body.size() >> 8);
  22833. frame += static_cast<char>(body.size() & 0xff);
  22834. frame += body;
  22835. detail::BufferStream strm;
  22836. strm.write(frame.data(), frame.size());
  22837. ws::Opcode opcode;
  22838. std::string payload;
  22839. bool fin;
  22840. EXPECT_EQ(
  22841. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22842. ws::impl::FrameRead::Ok);
  22843. EXPECT_EQ(body, payload);
  22844. }
  22845. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22846. // The header announces the largest payload allowed, and only 3 bytes of it
  22847. // ever arrive.
  22848. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22849. std::string frame;
  22850. frame += static_cast<char>(0x82); // FIN + Binary
  22851. frame += static_cast<char>(127); // 64-bit length follows
  22852. for (int shift = 56; shift >= 0; shift -= 8) {
  22853. frame += static_cast<char>((len >> shift) & 0xff);
  22854. }
  22855. frame += "abc";
  22856. detail::BufferStream strm;
  22857. strm.write(frame.data(), frame.size());
  22858. ws::Opcode opcode;
  22859. std::string payload;
  22860. bool fin;
  22861. EXPECT_EQ(
  22862. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22863. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22864. ws::impl::FrameRead::Fail);
  22865. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22866. }
  22867. TEST(WebSocketTest, QueryStringInHandshake) {
  22868. Server svr;
  22869. std::mutex mtx;
  22870. std::string received_target;
  22871. std::string received_token;
  22872. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22873. {
  22874. std::lock_guard<std::mutex> lock(mtx);
  22875. received_target = req.target;
  22876. if (req.has_param("token")) {
  22877. received_token = req.get_param_value("token");
  22878. }
  22879. }
  22880. std::string msg;
  22881. while (ws.read(msg)) {
  22882. ws.send(msg);
  22883. }
  22884. });
  22885. auto port = svr.bind_to_any_port("localhost");
  22886. std::thread t([&]() { svr.listen_after_bind(); });
  22887. svr.wait_until_ready();
  22888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22889. "/ws?token=ABC&session=123");
  22890. ASSERT_TRUE(client.connect());
  22891. // Round-trip ensures the handler has run and captured the request.
  22892. ASSERT_TRUE(client.send("hello"));
  22893. std::string msg;
  22894. ASSERT_TRUE(client.read(msg));
  22895. EXPECT_EQ("hello", msg);
  22896. client.close();
  22897. {
  22898. std::lock_guard<std::mutex> lock(mtx);
  22899. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22900. EXPECT_EQ("ABC", received_token);
  22901. }
  22902. svr.stop();
  22903. t.join();
  22904. }
  22905. // Run a handshake against a throwaway server and hand the request the server
  22906. // received back to the caller, so tests can assert on the headers the client
  22907. // actually put on the wire.
  22908. static void capture_websocket_handshake_request(
  22909. const Headers &client_headers,
  22910. std::function<void(const Request &, int port)> verify) {
  22911. Server svr;
  22912. std::mutex mtx;
  22913. Request received;
  22914. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22915. {
  22916. std::lock_guard<std::mutex> lock(mtx);
  22917. received = req;
  22918. }
  22919. std::string msg;
  22920. while (ws.read(msg)) {
  22921. ws.send(msg);
  22922. }
  22923. });
  22924. auto port = svr.bind_to_any_port("localhost");
  22925. std::thread t([&]() { svr.listen_after_bind(); });
  22926. auto se = detail::scope_exit([&] {
  22927. svr.stop();
  22928. t.join();
  22929. });
  22930. svr.wait_until_ready();
  22931. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22932. client_headers);
  22933. ASSERT_TRUE(client.connect());
  22934. ASSERT_TRUE(client.send("hello"));
  22935. std::string msg;
  22936. ASSERT_TRUE(client.read(msg));
  22937. client.close();
  22938. {
  22939. std::lock_guard<std::mutex> lock(mtx);
  22940. verify(received, port);
  22941. }
  22942. }
  22943. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22944. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22945. // Non-default port must be present in the Host header. Default ports
  22946. // (80/443) are omitted; that logic is covered by
  22947. // MakeHostAndPortStringTest.
  22948. EXPECT_EQ("localhost:" + std::to_string(port),
  22949. req.get_header_value("Host"));
  22950. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22951. req.get_header_value("User-Agent"));
  22952. EXPECT_FALSE(req.has_header("Accept"));
  22953. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22954. EXPECT_FALSE(req.has_header("Content-Length"));
  22955. });
  22956. }
  22957. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22958. capture_websocket_handshake_request(
  22959. {{"Host", "example.com"},
  22960. {"User-Agent", "custom-agent"},
  22961. {"X-Custom", "value"}},
  22962. [](const Request &req, int) {
  22963. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22964. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22965. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22966. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22967. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22968. });
  22969. }
  22970. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22971. capture_websocket_handshake_request(
  22972. {{"Upgrade", "bogus"},
  22973. {"Connection", "close"},
  22974. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22975. {"Sec-WebSocket-Version", "8"}},
  22976. [](const Request &req, int) {
  22977. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22978. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22979. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22980. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22981. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22982. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22983. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22984. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22985. req.get_header_value("Sec-WebSocket-Key"));
  22986. });
  22987. }
  22988. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22989. // A header the client refuses to send must abort the handshake before any
  22990. // part of it reaches the wire; a lone request line would otherwise sit in
  22991. // the peer's buffer as a truncated request.
  22992. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22993. ASSERT_NE(INVALID_SOCKET, srv);
  22994. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22995. sockaddr_in addr{};
  22996. addr.sin_family = AF_INET;
  22997. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22998. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22999. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23000. ASSERT_EQ(0, ::listen(srv, 1));
  23001. sockaddr_in bound{};
  23002. socklen_t bound_len = sizeof(bound);
  23003. ASSERT_EQ(
  23004. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23005. auto port = ntohs(bound.sin_port);
  23006. ssize_t received = -1;
  23007. std::thread t([&] {
  23008. // Bound every blocking call so a regression fails the test with a bad
  23009. // value instead of hanging the suite.
  23010. fd_set rfds;
  23011. FD_ZERO(&rfds);
  23012. FD_SET(srv, &rfds);
  23013. timeval tv{5, 0};
  23014. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23015. 0) {
  23016. return;
  23017. }
  23018. sockaddr_in cli_addr{};
  23019. socklen_t cli_len = sizeof(cli_addr);
  23020. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23021. if (cli == INVALID_SOCKET) { return; }
  23022. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23023. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23024. char buf[4096];
  23025. received = ::recv(cli, buf, sizeof(buf), 0);
  23026. });
  23027. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23028. // connect() has already shut the socket down by the time it returns false,
  23029. // so the peer sees EOF without waiting for the client to be destroyed.
  23030. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23031. {{"X-Bad", "a\r\nInjected: 1"}});
  23032. EXPECT_FALSE(client.connect());
  23033. t.join();
  23034. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23035. EXPECT_EQ(0, received);
  23036. }
  23037. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23038. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23039. // contains "upgrade" as a substring is a different token and must not
  23040. // start a WebSocket handshake.
  23041. auto make_request = [](const std::vector<std::string> &connection_values) {
  23042. Request req;
  23043. req.method = "GET";
  23044. req.headers.emplace("Upgrade", "websocket");
  23045. for (const auto &value : connection_values) {
  23046. req.headers.emplace("Connection", value);
  23047. }
  23048. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23049. req.headers.emplace("Sec-WebSocket-Version", "13");
  23050. return req;
  23051. };
  23052. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23053. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23054. EXPECT_TRUE(
  23055. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23056. EXPECT_TRUE(
  23057. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23058. EXPECT_TRUE(
  23059. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23060. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23061. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23062. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23063. EXPECT_FALSE(
  23064. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23065. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23066. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23067. }
  23068. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23069. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23070. // asks recipients to match each protocol-name case-insensitively, and RFC
  23071. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23072. // client naming websocket alongside another protocol, or on a second field
  23073. // line, is offering websocket; a value that merely contains "websocket" as a
  23074. // substring is a different protocol name and is not.
  23075. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23076. Request req;
  23077. req.method = "GET";
  23078. for (const auto &value : upgrade_values) {
  23079. req.headers.emplace("Upgrade", value);
  23080. }
  23081. req.headers.emplace("Connection", "Upgrade");
  23082. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23083. req.headers.emplace("Sec-WebSocket-Version", "13");
  23084. return req;
  23085. };
  23086. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23087. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23088. EXPECT_TRUE(
  23089. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23090. EXPECT_TRUE(
  23091. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23092. EXPECT_TRUE(
  23093. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23094. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23095. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23096. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23097. EXPECT_FALSE(
  23098. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23099. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23100. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23101. }
  23102. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23103. Server svr;
  23104. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23105. auto port = svr.bind_to_any_port("localhost");
  23106. std::thread t([&]() { svr.listen_after_bind(); });
  23107. auto se = detail::scope_exit([&] {
  23108. svr.stop();
  23109. t.join();
  23110. });
  23111. svr.wait_until_ready();
  23112. Headers headers = {{"Upgrade", "websocket"},
  23113. {"Connection", "notupgrade"},
  23114. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23115. {"Sec-WebSocket-Version", "13"}};
  23116. Client cli("localhost", port);
  23117. auto res = cli.Get("/ws", headers);
  23118. // The route exists only as a WebSocket route, so a request that fails the
  23119. // handshake check falls through to ordinary routing.
  23120. ASSERT_TRUE(res);
  23121. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23122. }
  23123. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23124. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23125. // Connection value is the only thing left for the client to reject.
  23126. Server svr;
  23127. svr.Get("/ws", [](const Request &req, Response &res) {
  23128. res.status = StatusCode::SwitchingProtocol_101;
  23129. res.set_header("Upgrade", "websocket");
  23130. res.set_header("Connection", "notupgrade");
  23131. res.set_header("Sec-WebSocket-Accept",
  23132. detail::websocket_accept_key(
  23133. req.get_header_value("Sec-WebSocket-Key")));
  23134. });
  23135. auto port = svr.bind_to_any_port("localhost");
  23136. std::thread t([&]() { svr.listen_after_bind(); });
  23137. auto se = detail::scope_exit([&] {
  23138. svr.stop();
  23139. t.join();
  23140. });
  23141. svr.wait_until_ready();
  23142. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23143. auto res = client.connect();
  23144. EXPECT_FALSE(res);
  23145. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23146. EXPECT_FALSE(client.is_open());
  23147. }
  23148. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23149. Server svr;
  23150. svr.Get("/ws", [](const Request &req, Response &res) {
  23151. res.status = StatusCode::SwitchingProtocol_101;
  23152. res.set_header("Upgrade", "websocket");
  23153. res.set_header("Connection", "Upgrade");
  23154. res.set_header("Sec-WebSocket-Accept",
  23155. detail::websocket_accept_key(
  23156. req.get_header_value("Sec-WebSocket-Key")));
  23157. res.set_header("Sec-WebSocket-Protocol", "admin");
  23158. });
  23159. auto port = svr.bind_to_any_port("localhost");
  23160. std::thread t([&]() { svr.listen_after_bind(); });
  23161. auto se = detail::scope_exit([&] {
  23162. svr.stop();
  23163. t.join();
  23164. });
  23165. svr.wait_until_ready();
  23166. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23167. // Server selects a subprotocol the client never offered
  23168. {
  23169. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23170. ws::WebSocketClient client(url, headers);
  23171. auto res = client.connect();
  23172. EXPECT_FALSE(res);
  23173. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23174. EXPECT_FALSE(client.is_open());
  23175. EXPECT_TRUE(client.subprotocol().empty());
  23176. }
  23177. // Client offered none but the server named one anyway
  23178. {
  23179. ws::WebSocketClient client(url);
  23180. auto res = client.connect();
  23181. EXPECT_FALSE(res);
  23182. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23183. EXPECT_FALSE(client.is_open());
  23184. EXPECT_TRUE(client.subprotocol().empty());
  23185. }
  23186. }
  23187. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23188. // The socket path doubles as the URL host, so it must not contain '/'.
  23189. const char *shard = getenv("GTEST_SHARD_INDEX");
  23190. const std::string sock_path =
  23191. shard ? std::string("httplib-ws-") + shard + ".sock"
  23192. : std::string("httplib-ws.sock");
  23193. std::remove(sock_path.c_str());
  23194. Server svr;
  23195. std::mutex mtx;
  23196. std::string received_host;
  23197. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23198. {
  23199. std::lock_guard<std::mutex> lock(mtx);
  23200. received_host = req.get_header_value("Host");
  23201. }
  23202. std::string msg;
  23203. while (ws.read(msg)) {
  23204. ws.send(msg);
  23205. }
  23206. });
  23207. svr.set_address_family(AF_UNIX);
  23208. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23209. auto se = detail::scope_exit([&] {
  23210. svr.stop();
  23211. t.join();
  23212. std::remove(sock_path.c_str());
  23213. });
  23214. svr.wait_until_ready();
  23215. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23216. client.set_address_family(AF_UNIX);
  23217. ASSERT_TRUE(client.connect());
  23218. ASSERT_TRUE(client.send("hello"));
  23219. std::string msg;
  23220. ASSERT_TRUE(client.read(msg));
  23221. client.close();
  23222. {
  23223. std::lock_guard<std::mutex> lock(mtx);
  23224. // There is no host:port for a Unix socket, so the same "localhost"
  23225. // placeholder the HTTP client uses is expected.
  23226. EXPECT_EQ("localhost", received_host);
  23227. }
  23228. }
  23229. // Two threads must never parse WebSocket frames from the same stream.
  23230. // close() used to read the peer's Close reply with its own frame read, so it
  23231. // raced a reader thread that was in the middle of a payload: the payload loop
  23232. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23233. // so bytes taken by close() were replaced with bytes from further along the
  23234. // stream. The message kept its length and silently changed content.
  23235. //
  23236. // The raw peer below sends a frame header plus part of the payload, waits for
  23237. // the handler to call close(), and only then sends the rest. Whichever thread
  23238. // would win the race for those bytes, the message must arrive intact, because
  23239. // close() must not touch the stream while read() owns it.
  23240. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23241. #ifndef _WIN32
  23242. signal(SIGPIPE, SIG_IGN);
  23243. #endif
  23244. const size_t payload_len = 120; // fits the 7-bit length field
  23245. const size_t prefix_len = 8;
  23246. const int attempts = 8;
  23247. std::string expected(payload_len, '\0');
  23248. for (size_t i = 0; i < payload_len; i++) {
  23249. expected[i] = static_cast<char>('a' + i % 26);
  23250. }
  23251. std::atomic<bool> peer_stalled{false};
  23252. std::atomic<bool> handler_done{false};
  23253. std::mutex received_mutex;
  23254. std::vector<std::string> received;
  23255. // Bound every wait, so a regression fails the test instead of hanging the
  23256. // suite.
  23257. auto wait_for = [](const std::atomic<bool> &flag) {
  23258. for (int i = 0; i < 500 && !flag; i++) {
  23259. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23260. }
  23261. };
  23262. Server svr;
  23263. svr.set_websocket_ping_interval(0);
  23264. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23265. std::thread reader([&]() {
  23266. std::string msg;
  23267. while (ws.read(msg)) {
  23268. std::lock_guard<std::mutex> guard(received_mutex);
  23269. received.push_back(msg);
  23270. }
  23271. });
  23272. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23273. // inside read_websocket_frame() when close() runs.
  23274. wait_for(peer_stalled);
  23275. ws.close();
  23276. reader.join();
  23277. handler_done = true;
  23278. });
  23279. auto port = svr.bind_to_any_port("127.0.0.1");
  23280. std::thread t([&]() { svr.listen_after_bind(); });
  23281. auto se = detail::scope_exit([&] {
  23282. svr.stop();
  23283. t.join();
  23284. });
  23285. svr.wait_until_ready();
  23286. auto send_bytes = [](socket_t s, const std::string &data) {
  23287. #ifdef _WIN32
  23288. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23289. #else
  23290. auto n = ::send(s, data.data(), data.size(), 0);
  23291. #endif
  23292. return n == static_cast<decltype(n)>(data.size());
  23293. };
  23294. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23295. // Every length used here fits the 7-bit length field.
  23296. auto masked_header = [](uint8_t first_byte, size_t len) {
  23297. std::string h;
  23298. h += static_cast<char>(first_byte);
  23299. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23300. h.append(4, '\0'); // mask key
  23301. return h;
  23302. };
  23303. for (int attempt = 0; attempt < attempts; attempt++) {
  23304. peer_stalled = false;
  23305. handler_done = false;
  23306. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23307. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23308. auto se_sock = detail::scope_exit([&] {
  23309. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23310. });
  23311. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23312. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23313. sockaddr_in addr{};
  23314. addr.sin_family = AF_INET;
  23315. addr.sin_port = htons(static_cast<uint16_t>(port));
  23316. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23317. ASSERT_EQ(
  23318. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23319. << "attempt " << attempt;
  23320. ASSERT_TRUE(send_bytes(sock,
  23321. "GET /ws HTTP/1.1\r\n"
  23322. "Host: 127.0.0.1\r\n"
  23323. "Upgrade: websocket\r\n"
  23324. "Connection: Upgrade\r\n"
  23325. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23326. "Sec-WebSocket-Version: 13\r\n"
  23327. "\r\n"))
  23328. << "attempt " << attempt;
  23329. std::string response;
  23330. while (response.find("\r\n\r\n") == std::string::npos) {
  23331. char buf[512];
  23332. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23333. if (n <= 0) { break; }
  23334. response.append(buf, static_cast<size_t>(n));
  23335. }
  23336. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23337. << "attempt " << attempt;
  23338. // Send the header of a Binary message but only the first prefix_len bytes
  23339. // of its payload, leaving the reader thread stalled inside the payload.
  23340. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23341. expected.substr(0, prefix_len)))
  23342. << "attempt " << attempt;
  23343. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23344. peer_stalled = true;
  23345. // Let close() send its Close frame and park in its own read before the
  23346. // rest of the payload arrives, so both threads are waiting for it.
  23347. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23348. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23349. close_frame += static_cast<char>(0x03); // status 1000
  23350. close_frame += static_cast<char>(0xE8);
  23351. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23352. << "attempt " << attempt;
  23353. // Closing the peer releases the reader thread even on the buggy path,
  23354. // where it waits for bytes another thread already consumed.
  23355. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23356. detail::close_socket(sock);
  23357. sock = INVALID_SOCKET;
  23358. wait_for(handler_done);
  23359. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23360. }
  23361. std::lock_guard<std::mutex> guard(received_mutex);
  23362. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23363. << "a message in flight when close() ran was dropped";
  23364. for (size_t i = 0; i < received.size(); i++) {
  23365. EXPECT_EQ(expected, received[i]) << "message " << i;
  23366. }
  23367. }
  23368. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23369. // returning the socket, or INVALID_SOCKET.
  23370. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23371. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23372. if (sock == INVALID_SOCKET) { return sock; }
  23373. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23374. sockaddr_in addr{};
  23375. addr.sin_family = AF_INET;
  23376. addr.sin_port = htons(static_cast<uint16_t>(port));
  23377. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23378. std::string req = "GET " + path +
  23379. " HTTP/1.1\r\n"
  23380. "Host: 127.0.0.1\r\n"
  23381. "Upgrade: websocket\r\n"
  23382. "Connection: Upgrade\r\n"
  23383. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23384. "Sec-WebSocket-Version: 13\r\n"
  23385. "\r\n";
  23386. std::string res;
  23387. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23388. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23389. static_cast<int>(req.size())) {
  23390. char c;
  23391. while (res.find("\r\n\r\n") == std::string::npos &&
  23392. ::recv(sock, &c, 1, 0) == 1) {
  23393. res += c;
  23394. }
  23395. }
  23396. if (res.find(" 101 ") == std::string::npos) {
  23397. detail::close_socket(sock);
  23398. return INVALID_SOCKET;
  23399. }
  23400. return sock;
  23401. }
  23402. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23403. // The payload must fit the 7-bit length field.
  23404. static std::string masked_frame(uint8_t first_byte,
  23405. const std::string &payload) {
  23406. std::string f;
  23407. f += static_cast<char>(first_byte);
  23408. f += static_cast<char>(0x80 | payload.size());
  23409. f.append(4, '\0');
  23410. return f + payload;
  23411. }
  23412. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23413. std::atomic<bool> done{false};
  23414. std::string received;
  23415. Server svr;
  23416. svr.set_websocket_ping_interval(0);
  23417. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23418. std::string msg;
  23419. if (ws.read(msg) == ws::Binary) { received = msg; }
  23420. done = true;
  23421. });
  23422. auto port = svr.bind_to_any_port("127.0.0.1");
  23423. std::thread t([&]() { svr.listen_after_bind(); });
  23424. auto se = detail::scope_exit([&] {
  23425. svr.stop();
  23426. t.join();
  23427. });
  23428. svr.wait_until_ready();
  23429. auto sock = connect_raw_websocket(port, "/ws");
  23430. ASSERT_NE(INVALID_SOCKET, sock);
  23431. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23432. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23433. masked_frame(0x89, "p") + // FIN + Ping
  23434. masked_frame(0x80, "lo"); // FIN + Continuation
  23435. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23436. for (int i = 0; i < 500 && !done; i++) {
  23437. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23438. }
  23439. ASSERT_TRUE(done);
  23440. EXPECT_EQ("Hello", received);
  23441. // The Ping between the fragments is answered with a Pong.
  23442. char pong[3];
  23443. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23444. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23445. }
  23446. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23447. Server svr;
  23448. svr.set_websocket_ping_interval(-1);
  23449. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23450. std::string msg;
  23451. while (ws.read(msg)) {}
  23452. });
  23453. auto port = svr.bind_to_any_port("127.0.0.1");
  23454. std::thread t([&]() { svr.listen_after_bind(); });
  23455. auto se = detail::scope_exit([&] {
  23456. svr.stop();
  23457. t.join();
  23458. });
  23459. svr.wait_until_ready();
  23460. auto sock = connect_raw_websocket(port, "/ws");
  23461. ASSERT_NE(INVALID_SOCKET, sock);
  23462. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23463. // Nothing comes while the client stays quiet.
  23464. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23465. char c;
  23466. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23467. }
  23468. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23469. Server svr;
  23470. svr.set_websocket_ping_interval(0);
  23471. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23472. std::string msg;
  23473. while (ws.read(msg)) {}
  23474. });
  23475. auto port = svr.bind_to_any_port("127.0.0.1");
  23476. std::thread t([&]() { svr.listen_after_bind(); });
  23477. auto se = detail::scope_exit([&] {
  23478. svr.stop();
  23479. t.join();
  23480. });
  23481. svr.wait_until_ready();
  23482. // Each Close payload and the reply it should get: an echo when valid, 1002
  23483. // otherwise.
  23484. std::vector<std::pair<std::string, std::string>> cases = {
  23485. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23486. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23487. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23488. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23489. };
  23490. // Also between the fragments of a message.
  23491. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23492. for (const auto &c : cases) {
  23493. auto sock = connect_raw_websocket(port, "/ws");
  23494. ASSERT_NE(INVALID_SOCKET, sock);
  23495. auto frames = prefix + masked_frame(0x88, c.first);
  23496. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23497. std::string reply;
  23498. char buf[256];
  23499. while (reply.size() < 2 + c.second.size()) {
  23500. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23501. if (n <= 0) { break; }
  23502. reply.append(buf, static_cast<size_t>(n));
  23503. }
  23504. detail::close_socket(sock);
  23505. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23506. c.second,
  23507. reply);
  23508. }
  23509. }
  23510. }
  23511. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23512. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23513. protected:
  23514. void SetUp() override {
  23515. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23516. SERVER_PRIVATE_KEY_FILE);
  23517. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23518. std::string msg;
  23519. ws::ReadResult ret;
  23520. while ((ret = ws.read(msg))) {
  23521. if (ret == ws::Binary) {
  23522. ws.send(msg.data(), msg.size());
  23523. } else {
  23524. ws.send(msg);
  23525. }
  23526. }
  23527. });
  23528. port_ = server_->bind_to_any_port(HOST);
  23529. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23530. server_->wait_until_ready();
  23531. }
  23532. void TearDown() override {
  23533. server_->stop();
  23534. if (server_thread_.joinable()) { server_thread_.join(); }
  23535. }
  23536. std::unique_ptr<SSLServer> server_;
  23537. std::thread server_thread_;
  23538. int port_ = 0;
  23539. };
  23540. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23541. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23542. {
  23543. ws::WebSocketClient client(url);
  23544. client.enable_server_certificate_verification(false);
  23545. auto calls = 0;
  23546. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23547. calls++;
  23548. return false;
  23549. });
  23550. EXPECT_FALSE(client.connect());
  23551. EXPECT_GT(calls, 0);
  23552. }
  23553. {
  23554. ws::WebSocketClient client(url);
  23555. client.enable_server_certificate_verification(false);
  23556. client.set_session_verifier([](tls::session_t) {
  23557. return SSLVerifierResponse::CertificateRejected;
  23558. });
  23559. EXPECT_FALSE(client.connect());
  23560. }
  23561. {
  23562. ws::WebSocketClient client(url);
  23563. client.enable_server_certificate_verification(false);
  23564. client.set_session_verifier([](tls::session_t) {
  23565. return SSLVerifierResponse::CertificateAccepted;
  23566. });
  23567. EXPECT_TRUE(client.connect());
  23568. }
  23569. }
  23570. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23571. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23572. "/ws-echo");
  23573. client.enable_server_certificate_verification(false);
  23574. ASSERT_TRUE(client.connect());
  23575. ASSERT_TRUE(client.is_open());
  23576. ASSERT_TRUE(client.send("Hello WSS"));
  23577. std::string msg;
  23578. EXPECT_EQ(ws::Text, client.read(msg));
  23579. EXPECT_EQ("Hello WSS", msg);
  23580. client.close();
  23581. }
  23582. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23583. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23584. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23585. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23586. // client (without calling close() first) is the only path that runs
  23587. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23588. // bug exactly.
  23589. //
  23590. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23591. // when linked against an instrumented libssl; run under Valgrind to catch it
  23592. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23593. // suite (the freed session otherwise stalls on the close handshake) — this test
  23594. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23595. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23596. {
  23597. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23598. "/ws-echo");
  23599. client.enable_server_certificate_verification(false);
  23600. client.set_read_timeout(2, 0);
  23601. client.set_write_timeout(2, 0);
  23602. ASSERT_TRUE(client.connect());
  23603. ASSERT_TRUE(client.is_open());
  23604. ASSERT_TRUE(client.send("still open"));
  23605. // Intentionally do NOT call client.close(): leaving scope runs
  23606. // shutdown_and_close() with the WebSocket still open, which must send the
  23607. // close frame while the TLS session is still alive.
  23608. }
  23609. }
  23610. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23611. // shutdown_and_close() at the start of connect(), reproducing the same
  23612. // use-after-free within the test body rather than at scope exit. The second
  23613. // connect must succeed and echo, proving the close handshake ran over a live
  23614. // session. See the note above about memory-tool requirements.
  23615. TEST_F(WebSocketSSLIntegrationTest,
  23616. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23617. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23618. "/ws-echo");
  23619. client.enable_server_certificate_verification(false);
  23620. client.set_read_timeout(2, 0);
  23621. client.set_write_timeout(2, 0);
  23622. ASSERT_TRUE(client.connect());
  23623. ASSERT_TRUE(client.is_open());
  23624. ASSERT_TRUE(client.send("still open"));
  23625. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23626. // the still-open connection, which must not touch a freed TLS session.
  23627. ASSERT_TRUE(client.connect());
  23628. ASSERT_TRUE(client.is_open());
  23629. ASSERT_TRUE(client.send("after reconnect"));
  23630. std::string msg;
  23631. EXPECT_EQ(ws::Text, client.read(msg));
  23632. EXPECT_EQ("after reconnect", msg);
  23633. client.close();
  23634. }
  23635. #endif
  23636. #ifdef CPPHTTPLIB_SSL_ENABLED
  23637. class WebSocketSSLCATest : public ::testing::Test {
  23638. protected:
  23639. void SetUp() override {
  23640. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23641. SERVER_PRIVATE_KEY_FILE);
  23642. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23643. std::string msg;
  23644. while (ws.read(msg)) {
  23645. ws.send(msg);
  23646. }
  23647. });
  23648. port_ = server_->bind_to_any_port("127.0.0.1");
  23649. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23650. server_->wait_until_ready();
  23651. }
  23652. void TearDown() override {
  23653. server_->stop();
  23654. if (server_thread_.joinable()) { server_thread_.join(); }
  23655. }
  23656. std::string url() const {
  23657. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23658. }
  23659. std::unique_ptr<SSLServer> server_;
  23660. std::thread server_thread_;
  23661. int port_ = 0;
  23662. };
  23663. // A custom CA loaded as PEM verifies the server with full certificate
  23664. // verification enabled
  23665. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23666. ws::WebSocketClient client(url());
  23667. std::string cert;
  23668. read_file(SERVER_CERT2_FILE, cert);
  23669. client.load_ca_cert_store(cert.c_str(), cert.size());
  23670. ASSERT_TRUE(client.connect());
  23671. ASSERT_TRUE(client.send("hello"));
  23672. std::string msg;
  23673. EXPECT_EQ(ws::Text, client.read(msg));
  23674. EXPECT_EQ("hello", msg);
  23675. client.close();
  23676. }
  23677. // A custom CA that does not cover the server must fail verification (the
  23678. // custom CA is exclusive; system certs are not loaded alongside it)
  23679. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23680. ws::WebSocketClient client(url());
  23681. std::string cert;
  23682. read_file(CLIENT_CA_CERT_FILE, cert);
  23683. client.load_ca_cert_store(cert.c_str(), cert.size());
  23684. auto res = client.connect();
  23685. ASSERT_FALSE(res);
  23686. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23687. EXPECT_EQ(-1, res.status());
  23688. EXPECT_NE(0u, res.ssl_backend_error());
  23689. }
  23690. // The same CA as a file path rather than PEM in memory
  23691. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23692. ws::WebSocketClient client(url());
  23693. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23694. ASSERT_TRUE(client.connect());
  23695. ASSERT_TRUE(client.send("hello"));
  23696. std::string msg;
  23697. EXPECT_EQ(ws::Text, client.read(msg));
  23698. EXPECT_EQ("hello", msg);
  23699. client.close();
  23700. }
  23701. // ...and a CA file that does not cover the server still fails, so it is the
  23702. // path above that decides the outcome
  23703. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23704. ws::WebSocketClient client(url());
  23705. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23706. ASSERT_FALSE(client.connect());
  23707. }
  23708. // Regression test: reconnecting with a native custom CA store used to reuse
  23709. // a store handle the previous TLS context had already freed (use-after-free
  23710. // under the OpenSSL backend). The context now lives as long as the client.
  23711. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23712. ws::WebSocketClient client(url());
  23713. std::string cert;
  23714. read_file(SERVER_CERT2_FILE, cert);
  23715. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23716. ASSERT_TRUE(client.connect());
  23717. client.close();
  23718. ASSERT_TRUE(client.connect());
  23719. ASSERT_TRUE(client.send("again"));
  23720. std::string msg;
  23721. EXPECT_EQ(ws::Text, client.read(msg));
  23722. EXPECT_EQ("again", msg);
  23723. client.close();
  23724. }
  23725. // Regression test: a certificate with a trusted chain but no identity match
  23726. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23727. // verification entirely for IP hosts, so this connection succeeded there.
  23728. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23729. // chain verification while the identity check must still fail.
  23730. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23731. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23732. ASSERT_TRUE(svr.is_valid());
  23733. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23734. std::string msg;
  23735. while (ws.read(msg)) {
  23736. ws.send(msg);
  23737. }
  23738. });
  23739. auto port = svr.bind_to_any_port("127.0.0.1");
  23740. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23741. auto se = detail::scope_exit([&] {
  23742. svr.stop();
  23743. t.join();
  23744. });
  23745. svr.wait_until_ready();
  23746. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23747. "/echo");
  23748. std::string cert;
  23749. read_file(SERVER_CERT_FILE, cert);
  23750. client.load_ca_cert_store(cert.c_str(), cert.size());
  23751. ASSERT_FALSE(client.connect());
  23752. }
  23753. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23754. // SNI, so nothing binds the host name to the TLS session. These bind the
  23755. // server to "localhost" instead, the only shape that exercises the SNI and
  23756. // hostname-verification path with certificate verification left enabled.
  23757. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23758. protected:
  23759. void Start(const char *cert_file) {
  23760. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23761. SERVER_PRIVATE_KEY_FILE);
  23762. ASSERT_TRUE(server_->is_valid());
  23763. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23764. std::string msg;
  23765. while (ws.read(msg)) {
  23766. ws.send(msg);
  23767. }
  23768. });
  23769. port_ = server_->bind_to_any_port("localhost");
  23770. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23771. server_->wait_until_ready();
  23772. }
  23773. void TearDown() override {
  23774. if (server_) { server_->stop(); }
  23775. if (server_thread_.joinable()) { server_thread_.join(); }
  23776. }
  23777. std::string url() const {
  23778. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23779. }
  23780. std::unique_ptr<SSLServer> server_;
  23781. std::thread server_thread_;
  23782. int port_ = 0;
  23783. };
  23784. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23785. // out and the connection is usable
  23786. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23787. Start(SERVER_CERT2_FILE);
  23788. ws::WebSocketClient client(url());
  23789. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23790. ASSERT_TRUE(client.connect());
  23791. ASSERT_TRUE(client.send("hello"));
  23792. std::string msg;
  23793. EXPECT_EQ(ws::Text, client.read(msg));
  23794. EXPECT_EQ("hello", msg);
  23795. client.close();
  23796. }
  23797. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23798. // while the identity check must still reject "localhost"
  23799. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23800. Start(SERVER_CERT_FILE);
  23801. ws::WebSocketClient client(url());
  23802. client.set_ca_cert_path(SERVER_CERT_FILE);
  23803. auto res = client.connect();
  23804. ASSERT_FALSE(res);
  23805. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23806. EXPECT_EQ(-1, res.status());
  23807. }
  23808. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23809. // disabled: the chain is still checked, only the identity check is skipped
  23810. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23811. Start(SERVER_CERT_FILE);
  23812. ws::WebSocketClient client(url());
  23813. client.set_ca_cert_path(SERVER_CERT_FILE);
  23814. client.enable_server_hostname_verification(false);
  23815. ASSERT_TRUE(client.connect());
  23816. ASSERT_TRUE(client.send("hello"));
  23817. std::string msg;
  23818. EXPECT_EQ(ws::Text, client.read(msg));
  23819. EXPECT_EQ("hello", msg);
  23820. client.close();
  23821. }
  23822. // A CA that did not sign the server certificate fails the chain, even though
  23823. // the name would match
  23824. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23825. Start(SERVER_CERT2_FILE);
  23826. ws::WebSocketClient client(url());
  23827. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23828. ASSERT_FALSE(client.connect());
  23829. }
  23830. // With verification disabled, neither the chain nor the name is checked
  23831. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23832. Start(SERVER_CERT_FILE);
  23833. ws::WebSocketClient client(url());
  23834. client.enable_server_certificate_verification(false);
  23835. ASSERT_TRUE(client.connect());
  23836. ASSERT_TRUE(client.send("hello"));
  23837. std::string msg;
  23838. EXPECT_EQ(ws::Text, client.read(msg));
  23839. EXPECT_EQ("hello", msg);
  23840. client.close();
  23841. }
  23842. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23843. protected:
  23844. void SetUp() override {
  23845. server_ = httplib::detail::make_unique<SSLServer>(
  23846. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23847. ASSERT_TRUE(server_->is_valid());
  23848. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23849. std::string msg;
  23850. while (ws.read(msg)) {
  23851. ws.send(msg);
  23852. }
  23853. });
  23854. port_ = server_->bind_to_any_port("localhost");
  23855. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23856. server_->wait_until_ready();
  23857. }
  23858. void TearDown() override {
  23859. server_->stop();
  23860. if (server_thread_.joinable()) { server_thread_.join(); }
  23861. }
  23862. std::string url() const {
  23863. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23864. }
  23865. void ConnectWithClientCert(const std::string &client_cert_file,
  23866. const std::string &client_private_key_file,
  23867. const char *private_key_password) {
  23868. std::string cert_pem, key_pem;
  23869. read_file(client_cert_file, cert_pem);
  23870. read_file(client_private_key_file, key_pem);
  23871. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23872. key_pem.c_str(), key_pem.size(),
  23873. private_key_password};
  23874. ws::WebSocketClient client(url(), pem);
  23875. ASSERT_TRUE(client.is_valid());
  23876. client.enable_server_certificate_verification(false);
  23877. ASSERT_TRUE(client.connect());
  23878. ASSERT_TRUE(client.send("hello"));
  23879. std::string msg;
  23880. EXPECT_EQ(ws::Text, client.read(msg));
  23881. EXPECT_EQ("hello", msg);
  23882. client.close();
  23883. }
  23884. std::unique_ptr<SSLServer> server_;
  23885. std::thread server_thread_;
  23886. int port_ = 0;
  23887. };
  23888. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23889. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23890. }
  23891. // Control for the tests above: the fixture's server really does require a
  23892. // client certificate, so it is the PEM the constructor installed that decides
  23893. // the outcome.
  23894. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23895. ws::WebSocketClient client(url());
  23896. ASSERT_TRUE(client.is_valid());
  23897. client.enable_server_certificate_verification(false);
  23898. EXPECT_FALSE(client.connect());
  23899. }
  23900. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23901. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23902. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23903. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23904. }
  23905. #endif
  23906. #if !defined(_WIN32)
  23907. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23908. auto secret_dir = std::string("./symlink_test_secret");
  23909. auto served_dir = std::string("./symlink_test_served");
  23910. auto secret_file = secret_dir + "/secret.txt";
  23911. auto symlink_path = served_dir + "/escape";
  23912. // Setup: create directories and files
  23913. mkdir(secret_dir.c_str(), 0755);
  23914. mkdir(served_dir.c_str(), 0755);
  23915. {
  23916. std::ofstream ofs(secret_file);
  23917. ofs << "SECRET_DATA";
  23918. }
  23919. // Create symlink using absolute path so it resolves correctly
  23920. #ifdef PATH_MAX
  23921. char abs_secret[PATH_MAX];
  23922. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23923. #else
  23924. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23925. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23926. ASSERT_NE(nullptr, abs_secret);
  23927. #endif
  23928. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23929. auto se = detail::scope_exit([&] {
  23930. unlink(symlink_path.c_str());
  23931. unlink(secret_file.c_str());
  23932. rmdir(served_dir.c_str());
  23933. rmdir(secret_dir.c_str());
  23934. });
  23935. Server svr;
  23936. svr.set_mount_point("/", served_dir);
  23937. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23938. auto se2 = detail::scope_exit([&] {
  23939. svr.stop();
  23940. listen_thread.join();
  23941. });
  23942. svr.wait_until_ready();
  23943. Client cli("localhost", PORT);
  23944. // Symlink pointing outside base dir should be blocked
  23945. auto res = cli.Get("/escape/secret.txt");
  23946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23947. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23948. }
  23949. #endif
  23950. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23951. // "GET /smuggled" request), reads the first response, and only then sends the
  23952. // embedded request as the body. Returns how many times /smuggled ran.
  23953. //
  23954. // The body is sent AFTER receiving the first response (as in the original
  23955. // PoC) so that the stream_line_reader cannot buffer it together with the
  23956. // headers of the first request.
  23957. static int count_smuggled_requests(const std::string &outer_head,
  23958. std::string &first_response) {
  23959. Server svr;
  23960. svr.set_mount_point("/", "./www");
  23961. std::atomic<int> smuggled_count(0);
  23962. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23963. smuggled_count++;
  23964. res.set_content("oops", "text/plain");
  23965. });
  23966. svr.Post("/post", [&](const Request &req, Response &res) {
  23967. res.set_content(req.body, "text/plain");
  23968. });
  23969. auto port = svr.bind_to_any_port("localhost");
  23970. thread t = thread([&] { svr.listen_after_bind(); });
  23971. auto se = detail::scope_exit([&] {
  23972. svr.stop();
  23973. t.join();
  23974. });
  23975. svr.wait_until_ready();
  23976. auto error = Error::Success;
  23977. auto sock = detail::create_client_socket(
  23978. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23979. /*connection_timeout_sec=*/2, 0,
  23980. /*read_timeout_sec=*/2, 0,
  23981. /*write_timeout_sec=*/2, 0, std::string(), error);
  23982. EXPECT_NE(INVALID_SOCKET, sock);
  23983. if (sock == INVALID_SOCKET) { return -1; }
  23984. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23985. // The "smuggled" request will be sent as the body of the outer request
  23986. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23987. "Host: localhost\r\n"
  23988. "Connection: close\r\n"
  23989. "\r\n";
  23990. auto head = outer_head;
  23991. auto len = std::to_string(smuggled.size());
  23992. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23993. pos = head.find("{len}", pos + len.size())) {
  23994. head.replace(pos, 5, len);
  23995. }
  23996. // Step 1: Send only the outer request headers (no body yet)
  23997. auto sent = send(sock, head.data(), head.size(), 0);
  23998. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23999. // Step 2: Read the first response
  24000. char buf[4096];
  24001. for (;;) {
  24002. auto n = recv(sock, buf, sizeof(buf), 0);
  24003. if (n <= 0) break;
  24004. first_response.append(buf, static_cast<size_t>(n));
  24005. // Stop once we have a complete response (headers + body)
  24006. auto hdr_end = first_response.find("\r\n\r\n");
  24007. if (hdr_end != std::string::npos) {
  24008. // Check for Content-Length to know when the body is complete
  24009. auto cl_pos = first_response.find("Content-Length:");
  24010. if (cl_pos != std::string::npos) {
  24011. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24012. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24013. auto cl = std::stoul(
  24014. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24015. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24016. } else {
  24017. break; // No Content-Length, assume headers-only response
  24018. }
  24019. }
  24020. }
  24021. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24022. // vulnerable server the keep-alive loop reads this as a second request. The
  24023. // server may already have closed the connection, so the result is ignored.
  24024. send(sock, smuggled.data(), smuggled.size(), 0);
  24025. // Half-close so that a server which drained the body sees EOF and closes,
  24026. // instead of the read below waiting for the read timeout.
  24027. #ifdef _WIN32
  24028. ::shutdown(sock, SD_SEND);
  24029. #else
  24030. ::shutdown(sock, SHUT_WR);
  24031. #endif
  24032. // Step 4: Read until the server closes the connection
  24033. for (;;) {
  24034. auto n = recv(sock, buf, sizeof(buf), 0);
  24035. if (n <= 0) break;
  24036. }
  24037. return smuggled_count.load();
  24038. }
  24039. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24040. // A GET request with Content-Length to a static file handler must have its
  24041. // body drained before the keep-alive connection is reused. Otherwise the
  24042. // unread body bytes are interpreted as the next HTTP request.
  24043. std::string first_response;
  24044. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24045. "Host: localhost\r\n"
  24046. "Content-Length: {len}\r\n"
  24047. "\r\n",
  24048. first_response));
  24049. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24050. }
  24051. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24052. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24053. // be answered with 400 and the connection closed. Treating it as "no body"
  24054. // leaves the body to be parsed as the next request.
  24055. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24056. const char *targets[] = {
  24057. "GET /file", // handler that never reads the body
  24058. "GET /not-found", // no handler matches (404)
  24059. "POST /post", // handler that reads the body
  24060. };
  24061. for (auto target : targets) {
  24062. for (auto value : values) {
  24063. std::string first_response;
  24064. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24065. " HTTP/1.1\r\n"
  24066. "Host: localhost\r\n"
  24067. "Content-Length: " +
  24068. value + "\r\n\r\n",
  24069. first_response))
  24070. << target << " with Content-Length: " << value;
  24071. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24072. << target << " with Content-Length: " << value;
  24073. }
  24074. }
  24075. }
  24076. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24077. // A 400 for an unparseable request line leaves the rest of the message
  24078. // unread, so the connection must be closed rather than reused.
  24079. std::string first_response;
  24080. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24081. "Host: localhost\r\n"
  24082. "Content-Length: {len}\r\n"
  24083. "\r\n",
  24084. first_response));
  24085. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24086. }
  24087. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24088. // Same as above for a header block that fails to parse.
  24089. std::string first_response;
  24090. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24091. "Host: localhost\r\n"
  24092. "Bad Header\r\n"
  24093. "Content-Length: {len}\r\n"
  24094. "\r\n",
  24095. first_response));
  24096. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24097. }
  24098. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24099. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24100. // server must not read another request on that connection, even when the
  24101. // request had no body to drain.
  24102. std::string first_response;
  24103. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24104. "Host: localhost\r\n"
  24105. "\r\n",
  24106. first_response));
  24107. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24108. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24109. }
  24110. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24111. // A content reader that stops early leaves the stream inside the body.
  24112. // Draining the whole Content-Length from there, or reading the body again,
  24113. // reads into the next request, and whatever follows is parsed as a request
  24114. // of its own.
  24115. Server svr;
  24116. std::atomic<int> smuggled_count(0);
  24117. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24118. svr.Post("/upload", [](const Request &req, Response &res,
  24119. const ContentReader &content_reader) {
  24120. // Stop at the last chunk, so the whole body has been read however it
  24121. // arrives.
  24122. auto length = req.get_header_value_u64("Content-Length");
  24123. size_t total = 0;
  24124. auto consumed = content_reader([&](const char *, size_t n) {
  24125. total += n;
  24126. return total < length;
  24127. });
  24128. EXPECT_FALSE(consumed);
  24129. if (req.has_param("retry")) {
  24130. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24131. }
  24132. // Replace the 400 the aborted read set, which would close the connection.
  24133. res.set_redirect("/done");
  24134. });
  24135. auto port = svr.bind_to_any_port(HOST);
  24136. thread t = thread([&] { svr.listen_after_bind(); });
  24137. auto se = detail::scope_exit([&] {
  24138. svr.stop();
  24139. t.join();
  24140. });
  24141. svr.wait_until_ready();
  24142. // A front end sees the second request as a POST whose body is the GET. The
  24143. // first body is as long as the POST's headers, so draining it again reads
  24144. // exactly those and leaves the GET to be parsed next.
  24145. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24146. "Host: localhost\r\n"
  24147. "\r\n";
  24148. std::string second_head = "POST /post HTTP/1.1\r\n"
  24149. "Host: localhost\r\n"
  24150. "Content-Length: " +
  24151. std::to_string(inner.size()) +
  24152. "\r\n"
  24153. "\r\n";
  24154. for (auto target : {"/upload", "/upload?retry"}) {
  24155. smuggled_count = 0;
  24156. std::string request = "POST " + std::string(target) +
  24157. " HTTP/1.1\r\n"
  24158. "Host: localhost\r\n"
  24159. "Content-Length: " +
  24160. std::to_string(second_head.size()) +
  24161. "\r\n"
  24162. "\r\n" +
  24163. std::string(second_head.size(), 'A') + second_head +
  24164. inner;
  24165. std::string response;
  24166. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24167. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24168. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24169. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24170. EXPECT_EQ(0, smuggled_count.load()) << target;
  24171. }
  24172. }
  24173. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24174. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24175. // must be rejected with 400 Bad Request.
  24176. Server svr;
  24177. svr.Post("/test", [&](const Request &, Response &res) {
  24178. res.set_content("ok", "text/plain");
  24179. });
  24180. thread t = thread([&] { svr.listen(HOST, PORT); });
  24181. auto se = detail::scope_exit([&] {
  24182. svr.stop();
  24183. t.join();
  24184. ASSERT_FALSE(svr.is_running());
  24185. });
  24186. svr.wait_until_ready();
  24187. // Exact "chunked"
  24188. {
  24189. auto req = "POST /test HTTP/1.1\r\n"
  24190. "Host: localhost\r\n"
  24191. "Content-Length: 5\r\n"
  24192. "Transfer-Encoding: chunked\r\n"
  24193. "Connection: close\r\n"
  24194. "\r\n"
  24195. "hello";
  24196. std::string response;
  24197. ASSERT_TRUE(send_request(1, req, &response));
  24198. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24199. response.substr(0, response.find("\r\n")));
  24200. }
  24201. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24202. {
  24203. auto req = "POST /test HTTP/1.1\r\n"
  24204. "Host: localhost\r\n"
  24205. "Content-Length: 5\r\n"
  24206. "Transfer-Encoding: gzip, chunked\r\n"
  24207. "Connection: close\r\n"
  24208. "\r\n"
  24209. "hello";
  24210. std::string response;
  24211. ASSERT_TRUE(send_request(1, req, &response));
  24212. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24213. response.substr(0, response.find("\r\n")));
  24214. }
  24215. }
  24216. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24217. Server svr;
  24218. svr.Post("/test", [&](const Request &, Response &res) {
  24219. res.set_content("ok", "text/plain");
  24220. });
  24221. thread t = thread([&] { svr.listen(HOST, PORT); });
  24222. auto se = detail::scope_exit([&] {
  24223. svr.stop();
  24224. t.join();
  24225. ASSERT_FALSE(svr.is_running());
  24226. });
  24227. svr.wait_until_ready();
  24228. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24229. // length cannot be determined, so the server must answer 400 and close
  24230. // rather than treat the request as bodyless and leave the body in the
  24231. // socket for the next request to pick up.
  24232. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24233. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24234. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24235. std::string response;
  24236. ASSERT_TRUE(send_request(1, req, &response));
  24237. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24238. response.substr(0, response.find("\r\n")))
  24239. << transfer_encoding;
  24240. }
  24241. // RFC 9110 5.3: the codings may also be split across several
  24242. // Transfer-Encoding lines, which combine in the order they were received.
  24243. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24244. // just like the single-line "chunked, gzip" above.
  24245. {
  24246. auto req = "POST /test HTTP/1.1\r\n"
  24247. "Host: localhost\r\n"
  24248. "Transfer-Encoding: chunked\r\n"
  24249. "Transfer-Encoding: gzip\r\n"
  24250. "\r\n"
  24251. "0\r\n\r\n";
  24252. std::string response;
  24253. ASSERT_TRUE(send_request(1, req, &response));
  24254. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24255. response.substr(0, response.find("\r\n")));
  24256. }
  24257. // A sequence ending in chunked stays valid.
  24258. auto req = "POST /test HTTP/1.1\r\n"
  24259. "Host: localhost\r\n"
  24260. "Transfer-Encoding: gzip, chunked\r\n"
  24261. "Connection: close\r\n"
  24262. "\r\n"
  24263. "0\r\n\r\n";
  24264. std::string response;
  24265. ASSERT_TRUE(send_request(1, req, &response));
  24266. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24267. // ...including when it is spread over several lines.
  24268. auto split_req = "POST /test HTTP/1.1\r\n"
  24269. "Host: localhost\r\n"
  24270. "Transfer-Encoding: gzip\r\n"
  24271. "Transfer-Encoding: chunked\r\n"
  24272. "Connection: close\r\n"
  24273. "\r\n"
  24274. "0\r\n\r\n";
  24275. std::string split_response;
  24276. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24277. EXPECT_EQ("HTTP/1.1 200 OK",
  24278. split_response.substr(0, split_response.find("\r\n")));
  24279. }
  24280. // Regression for issue #2450: a DELETE without Content-Length on a
  24281. // keep-alive connection must not let the post-response drain consume the
  24282. // next request's bytes.
  24283. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24284. Server svr;
  24285. std::atomic<int> delete_count(0);
  24286. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24287. delete_count++;
  24288. res.status = StatusCode::NoContent_204;
  24289. });
  24290. auto port = svr.bind_to_any_port(HOST);
  24291. thread t = thread([&] { svr.listen_after_bind(); });
  24292. auto se = detail::scope_exit([&] {
  24293. svr.stop();
  24294. t.join();
  24295. });
  24296. svr.wait_until_ready();
  24297. auto error = Error::Success;
  24298. auto sock = detail::create_client_socket(
  24299. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24300. /*connection_timeout_sec=*/2, 0,
  24301. /*read_timeout_sec=*/2, 0,
  24302. /*write_timeout_sec=*/2, 0, std::string(), error);
  24303. ASSERT_NE(INVALID_SOCKET, sock);
  24304. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24305. auto send_request_and_read_response = [&](const std::string &req,
  24306. std::string &out) -> bool {
  24307. auto sent = send(sock, req.data(), req.size(), 0);
  24308. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24309. char buf[4096];
  24310. for (;;) {
  24311. auto n = recv(sock, buf, sizeof(buf), 0);
  24312. if (n <= 0) { return !out.empty(); }
  24313. out.append(buf, static_cast<size_t>(n));
  24314. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24315. }
  24316. };
  24317. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24318. "Host: localhost\r\n"
  24319. "\r\n";
  24320. std::string resp1;
  24321. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24322. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24323. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24324. "Host: localhost\r\n"
  24325. "Connection: close\r\n"
  24326. "\r\n";
  24327. std::string resp2;
  24328. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24329. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24330. EXPECT_EQ(2, delete_count.load());
  24331. }
  24332. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24333. Server svr;
  24334. svr.Post("/ingest", [&](const Request &, Response &res,
  24335. const ContentReader &content_reader) {
  24336. auto consumed = content_reader([](const char *, size_t) { return false; });
  24337. EXPECT_FALSE(consumed);
  24338. res.status = StatusCode::Conflict_409;
  24339. res.set_header("Connection", "close");
  24340. });
  24341. auto port = svr.bind_to_any_port(HOST);
  24342. thread t = thread([&] { svr.listen_after_bind(); });
  24343. auto se = detail::scope_exit([&] {
  24344. svr.stop();
  24345. t.join();
  24346. });
  24347. svr.wait_until_ready();
  24348. auto error = Error::Success;
  24349. auto sock = detail::create_client_socket(
  24350. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24351. /*connection_timeout_sec=*/2, 0,
  24352. /*read_timeout_sec=*/1, 0,
  24353. /*write_timeout_sec=*/2, 0, std::string(), error);
  24354. ASSERT_NE(INVALID_SOCKET, sock);
  24355. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24356. std::string request = "POST /ingest HTTP/1.1\r\n"
  24357. "Host: localhost\r\n"
  24358. "Transfer-Encoding: chunked\r\n"
  24359. "\r\n"
  24360. "4\r\n"
  24361. "data\r\n";
  24362. auto sent = send(sock, request.data(), request.size(), 0);
  24363. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24364. std::string response;
  24365. ssize_t received = 0;
  24366. do {
  24367. char buf[4096];
  24368. received = recv(sock, buf, sizeof(buf), 0);
  24369. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24370. } while (received > 0);
  24371. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24372. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24373. EXPECT_EQ(0, received);
  24374. }
  24375. namespace no_proxy_test {
  24376. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24377. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24378. // calling listen().
  24379. class ScopedServer {
  24380. public:
  24381. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24382. ~ScopedServer() {
  24383. svr_.stop();
  24384. if (th_.joinable()) { th_.join(); }
  24385. }
  24386. Server &svr() { return svr_; }
  24387. int port() const { return port_; }
  24388. void listen() {
  24389. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24390. svr_.wait_until_ready();
  24391. }
  24392. private:
  24393. Server svr_;
  24394. std::thread th_;
  24395. int port_ = 0;
  24396. };
  24397. class ProxyAndTargetServers {
  24398. public:
  24399. ProxyAndTargetServers() {
  24400. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24401. proxy_hits_++;
  24402. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24403. res.set_content("via-proxy", "text/plain");
  24404. });
  24405. target_.Get(".*", [this](const Request &req, Response &res) {
  24406. target_hits_++;
  24407. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24408. res.set_content("direct", "text/plain");
  24409. });
  24410. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24411. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24412. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24413. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24414. proxy_mock_.wait_until_ready();
  24415. target_.wait_until_ready();
  24416. }
  24417. ~ProxyAndTargetServers() {
  24418. proxy_mock_.stop();
  24419. target_.stop();
  24420. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24421. if (target_thread_.joinable()) { target_thread_.join(); }
  24422. }
  24423. Server &proxy_mock() { return proxy_mock_; }
  24424. Server &target() { return target_; }
  24425. int proxy_port() const { return proxy_port_; }
  24426. int target_port() const { return target_port_; }
  24427. int proxy_hits() const { return proxy_hits_.load(); }
  24428. int target_hits() const { return target_hits_.load(); }
  24429. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24430. void reset_counters() {
  24431. proxy_hits_ = 0;
  24432. target_hits_ = 0;
  24433. last_had_proxy_authz_ = false;
  24434. }
  24435. private:
  24436. Server proxy_mock_;
  24437. Server target_;
  24438. std::thread proxy_thread_;
  24439. std::thread target_thread_;
  24440. int proxy_port_ = 0;
  24441. int target_port_ = 0;
  24442. std::atomic<int> proxy_hits_{0};
  24443. std::atomic<int> target_hits_{0};
  24444. std::atomic<bool> last_had_proxy_authz_{false};
  24445. };
  24446. inline std::unique_ptr<Client> make_client(const std::string &host,
  24447. ProxyAndTargetServers &s) {
  24448. auto cli = detail::make_unique<Client>(host, s.target_port());
  24449. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24450. cli->set_proxy("127.0.0.1", s.proxy_port());
  24451. return cli;
  24452. }
  24453. } // namespace no_proxy_test
  24454. using no_proxy_test::make_client;
  24455. using no_proxy_test::ProxyAndTargetServers;
  24456. TEST(NoProxyTest, ExactHostnameBypasses) {
  24457. ProxyAndTargetServers s;
  24458. auto cli = make_client("example.com", s);
  24459. cli->set_no_proxy({"example.com"});
  24460. auto res = cli->Get("/");
  24461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24462. EXPECT_EQ(0, s.proxy_hits());
  24463. EXPECT_EQ(1, s.target_hits());
  24464. }
  24465. TEST(NoProxyTest, SubdomainBypasses) {
  24466. ProxyAndTargetServers s;
  24467. auto cli = make_client("foo.example.com", s);
  24468. cli->set_no_proxy({"example.com"});
  24469. auto res = cli->Get("/");
  24470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24471. EXPECT_EQ(0, s.proxy_hits());
  24472. EXPECT_EQ(1, s.target_hits());
  24473. }
  24474. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24475. // Regression guard: "evilexample.com" must not be considered a subdomain
  24476. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24477. // check would let traffic bypass the proxy and leak credentials direct
  24478. // to the attacker host.
  24479. ProxyAndTargetServers s;
  24480. auto cli = make_client("evilexample.com", s);
  24481. cli->set_no_proxy({"example.com"});
  24482. auto res = cli->Get("/");
  24483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24484. EXPECT_GE(s.proxy_hits(), 1);
  24485. EXPECT_EQ(0, s.target_hits());
  24486. }
  24487. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24488. ProxyAndTargetServers s;
  24489. auto cli = make_client("example.com.evil.com", s);
  24490. cli->set_no_proxy({"example.com"});
  24491. auto res = cli->Get("/");
  24492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24493. EXPECT_GE(s.proxy_hits(), 1);
  24494. EXPECT_EQ(0, s.target_hits());
  24495. }
  24496. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24497. ProxyAndTargetServers s;
  24498. auto cli = make_client("example.com", s);
  24499. cli->set_no_proxy({".example.com"});
  24500. auto res = cli->Get("/");
  24501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24502. EXPECT_EQ(0, s.proxy_hits());
  24503. EXPECT_EQ(1, s.target_hits());
  24504. }
  24505. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24506. ProxyAndTargetServers s;
  24507. auto cli = make_client("Example.COM", s);
  24508. cli->set_no_proxy({"EXAMPLE.com"});
  24509. auto res = cli->Get("/");
  24510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24511. EXPECT_EQ(0, s.proxy_hits());
  24512. EXPECT_EQ(1, s.target_hits());
  24513. }
  24514. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24515. ProxyAndTargetServers s;
  24516. auto cli = make_client("example.com.", s);
  24517. cli->set_no_proxy({"example.com"});
  24518. auto res = cli->Get("/");
  24519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24520. EXPECT_EQ(0, s.proxy_hits());
  24521. EXPECT_EQ(1, s.target_hits());
  24522. }
  24523. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24524. // Trailing dots must be normalized on BOTH sides — host and entry.
  24525. // An implementation that only strips the host-side trailing dot would
  24526. // fail to match host "example.com" against entry "example.com." because
  24527. // a literal substring search would compare 11 chars against 12.
  24528. ProxyAndTargetServers s;
  24529. auto cli = make_client("example.com", s);
  24530. cli->set_no_proxy({"example.com."});
  24531. auto res = cli->Get("/");
  24532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24533. EXPECT_EQ(0, s.proxy_hits());
  24534. EXPECT_EQ(1, s.target_hits());
  24535. }
  24536. TEST(NoProxyTest, WildcardBypassesEverything) {
  24537. ProxyAndTargetServers s;
  24538. auto cli = make_client("anything.invalid.test", s);
  24539. cli->set_no_proxy({"*"});
  24540. auto res = cli->Get("/");
  24541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24542. EXPECT_EQ(0, s.proxy_hits());
  24543. EXPECT_EQ(1, s.target_hits());
  24544. }
  24545. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24546. ProxyAndTargetServers s;
  24547. Client cli("127.0.0.1", s.target_port());
  24548. cli.set_proxy("127.0.0.1", s.proxy_port());
  24549. cli.set_no_proxy({"127.0.0.1"});
  24550. auto res = cli.Get("/");
  24551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24552. EXPECT_EQ(0, s.proxy_hits());
  24553. EXPECT_EQ(1, s.target_hits());
  24554. }
  24555. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24556. ProxyAndTargetServers s;
  24557. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24558. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24559. cli.set_proxy("127.0.0.1", s.proxy_port());
  24560. cli.set_no_proxy({"::1"});
  24561. auto res = cli.Get("/");
  24562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24563. EXPECT_EQ(0, s.proxy_hits());
  24564. EXPECT_EQ(1, s.target_hits());
  24565. }
  24566. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24567. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24568. // must still be recognized as IPv6 for CIDR matching. Implementations
  24569. // that detect IPv6 only when the host begins with '[' would parse the
  24570. // host as a hostname and miss the match.
  24571. ProxyAndTargetServers s;
  24572. Client cli("fe80::1", s.target_port());
  24573. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24574. cli.set_proxy("127.0.0.1", s.proxy_port());
  24575. cli.set_no_proxy({"fe80::/10"});
  24576. auto res = cli.Get("/");
  24577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24578. EXPECT_EQ(0, s.proxy_hits());
  24579. EXPECT_EQ(1, s.target_hits());
  24580. }
  24581. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24582. ProxyAndTargetServers s;
  24583. Client cli("::1", s.target_port());
  24584. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24585. cli.set_proxy("127.0.0.1", s.proxy_port());
  24586. cli.set_no_proxy({"[::1]"});
  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, BracketedIPv6CidrEntryAccepted) {
  24593. ProxyAndTargetServers s;
  24594. Client cli("fe80::1", s.target_port());
  24595. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24596. cli.set_proxy("127.0.0.1", s.proxy_port());
  24597. cli.set_no_proxy({"[fe80::]/10"});
  24598. auto res = cli.Get("/");
  24599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24600. EXPECT_EQ(0, s.proxy_hits());
  24601. EXPECT_EQ(1, s.target_hits());
  24602. }
  24603. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24604. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24605. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24606. // tricks via address-family conversion.
  24607. ProxyAndTargetServers s;
  24608. Client cli("::ffff:127.0.0.1", s.target_port());
  24609. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24610. cli.set_proxy("127.0.0.1", s.proxy_port());
  24611. cli.set_no_proxy({"127.0.0.1"});
  24612. auto res = cli.Get("/");
  24613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24614. EXPECT_GE(s.proxy_hits(), 1);
  24615. EXPECT_EQ(0, s.target_hits());
  24616. }
  24617. TEST(NoProxyTest, IPv4CidrMatch) {
  24618. ProxyAndTargetServers s;
  24619. Client cli("127.0.0.1", s.target_port());
  24620. cli.set_proxy("127.0.0.1", s.proxy_port());
  24621. cli.set_no_proxy({"127.0.0.0/8"});
  24622. auto res = cli.Get("/");
  24623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24624. EXPECT_EQ(0, s.proxy_hits());
  24625. EXPECT_EQ(1, s.target_hits());
  24626. }
  24627. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24628. ProxyAndTargetServers s;
  24629. Client cli("127.0.0.1", s.target_port());
  24630. cli.set_proxy("127.0.0.1", s.proxy_port());
  24631. cli.set_no_proxy({"10.0.0.0/8"});
  24632. auto res = cli.Get("/");
  24633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24634. EXPECT_GE(s.proxy_hits(), 1);
  24635. EXPECT_EQ(0, s.target_hits());
  24636. }
  24637. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24638. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24639. // IPv4 target matches.
  24640. ProxyAndTargetServers s;
  24641. Client cli("127.0.0.1", s.target_port());
  24642. cli.set_proxy("127.0.0.1", s.proxy_port());
  24643. cli.set_no_proxy({"0.0.0.0/0"});
  24644. auto res = cli.Get("/");
  24645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24646. EXPECT_EQ(0, s.proxy_hits());
  24647. EXPECT_EQ(1, s.target_hits());
  24648. }
  24649. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24650. ProxyAndTargetServers s;
  24651. Client cli("127.0.0.1", s.target_port());
  24652. cli.set_proxy("127.0.0.1", s.proxy_port());
  24653. cli.set_no_proxy({"127.0.0.1"});
  24654. auto res = cli.Get("/");
  24655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24656. EXPECT_EQ(0, s.proxy_hits());
  24657. EXPECT_EQ(1, s.target_hits());
  24658. }
  24659. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24660. ProxyAndTargetServers s;
  24661. Client cli("127.0.0.1", s.target_port());
  24662. cli.set_proxy("127.0.0.1", s.proxy_port());
  24663. cli.set_no_proxy({"127.0.0.0/33"});
  24664. auto res = cli.Get("/");
  24665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24666. EXPECT_GE(s.proxy_hits(), 1);
  24667. EXPECT_EQ(0, s.target_hits());
  24668. }
  24669. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24670. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24671. ProxyAndTargetServers s;
  24672. Client cli("127.0.0.1", s.target_port());
  24673. cli.set_proxy("127.0.0.1", s.proxy_port());
  24674. cli.set_no_proxy({"127.0.0.1/"});
  24675. auto res = cli.Get("/");
  24676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24677. EXPECT_GE(s.proxy_hits(), 1);
  24678. EXPECT_EQ(0, s.target_hits());
  24679. }
  24680. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24681. ProxyAndTargetServers s;
  24682. auto cli = make_client("internal.corp", s);
  24683. cli->set_proxy_basic_auth("u", "p");
  24684. cli->set_no_proxy({"internal.corp"});
  24685. auto res = cli->Get("/");
  24686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24687. EXPECT_EQ(1, s.target_hits());
  24688. EXPECT_EQ(0, s.proxy_hits());
  24689. EXPECT_FALSE(s.last_had_proxy_authz())
  24690. << "Proxy-Authorization must not be sent direct to the target";
  24691. }
  24692. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24693. ProxyAndTargetServers s;
  24694. auto cli = make_client("public.example", s);
  24695. cli->set_proxy_basic_auth("u", "p");
  24696. cli->set_no_proxy({"internal.corp"}); // does not match
  24697. auto res = cli->Get("/");
  24698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24699. EXPECT_GE(s.proxy_hits(), 1);
  24700. EXPECT_TRUE(s.last_had_proxy_authz());
  24701. }
  24702. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24703. std::atomic<int> hits{0};
  24704. std::atomic<int> hits_with_authz{0};
  24705. no_proxy_test::ScopedServer proxy_mock;
  24706. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24707. hits++;
  24708. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24709. if (req.target.find("/redir") != std::string::npos) {
  24710. res.set_redirect("http://other.example/landed");
  24711. } else {
  24712. res.set_content("via-proxy", "text/plain");
  24713. }
  24714. });
  24715. proxy_mock.listen();
  24716. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24717. hits = 0;
  24718. hits_with_authz = 0;
  24719. Client cli("public.example", 80);
  24720. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24721. cli.set_proxy_basic_auth(c.first, c.second);
  24722. cli.set_follow_location(true);
  24723. // The redirect to another host goes through the proxy as well
  24724. auto res = cli.Get("/redir");
  24725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24726. EXPECT_EQ(2, hits.load());
  24727. EXPECT_EQ(2, hits_with_authz.load());
  24728. }
  24729. }
  24730. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24731. ProxyAndTargetServers s;
  24732. auto cli = make_client("anything.test", s);
  24733. auto res = cli->Get("/");
  24734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24735. EXPECT_GE(s.proxy_hits(), 1);
  24736. EXPECT_EQ(0, s.target_hits());
  24737. }
  24738. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24739. ProxyAndTargetServers s;
  24740. auto cli = make_client("example.com", s);
  24741. cli->set_no_proxy({"example.com:8080"});
  24742. auto res = cli->Get("/");
  24743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24744. EXPECT_GE(s.proxy_hits(), 1);
  24745. EXPECT_EQ(0, s.target_hits());
  24746. }
  24747. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24748. ProxyAndTargetServers s;
  24749. auto cli = make_client("anything.test", s);
  24750. cli->set_no_proxy({"", " ", "\t"});
  24751. auto res = cli->Get("/");
  24752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24753. EXPECT_GE(s.proxy_hits(), 1);
  24754. EXPECT_EQ(0, s.target_hits());
  24755. }
  24756. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24757. // An entry with leading/trailing whitespace must still match — env-style
  24758. // values are commonly pasted with stray spaces and an implementation
  24759. // that feeds the raw token directly to inet_pton would fail to match
  24760. // valid CIDRs because of the spaces.
  24761. ProxyAndTargetServers s;
  24762. Client cli("127.0.0.1", s.target_port());
  24763. cli.set_proxy("127.0.0.1", s.proxy_port());
  24764. cli.set_no_proxy({" 127.0.0.0/8 "});
  24765. auto res = cli.Get("/");
  24766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24767. EXPECT_EQ(0, s.proxy_hits());
  24768. EXPECT_EQ(1, s.target_hits());
  24769. }
  24770. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24771. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24772. // go direct and must NOT carry Proxy-Authorization.
  24773. std::atomic<int> proxy_hits{0};
  24774. std::atomic<int> target_hits{0};
  24775. std::atomic<bool> target_saw_authz{false};
  24776. no_proxy_test::ScopedServer proxy_mock, target;
  24777. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24778. proxy_hits++;
  24779. res.status = 302;
  24780. res.set_header("Location", "http://127.0.0.1:" +
  24781. std::to_string(target.port()) + "/landed");
  24782. });
  24783. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24784. target_hits++;
  24785. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24786. res.set_content("direct", "text/plain");
  24787. });
  24788. proxy_mock.listen();
  24789. target.listen();
  24790. Client cli("public.example", target.port());
  24791. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24792. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24793. cli.set_proxy_basic_auth("u", "p");
  24794. cli.set_no_proxy({"127.0.0.1"});
  24795. cli.set_follow_location(true);
  24796. auto res = cli.Get("/redir");
  24797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24798. EXPECT_GE(proxy_hits.load(), 1);
  24799. EXPECT_GE(target_hits.load(), 1);
  24800. EXPECT_FALSE(target_saw_authz.load());
  24801. }
  24802. #ifdef CPPHTTPLIB_SSL_ENABLED
  24803. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24804. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24805. // proxy creds would be sent to the (possibly hostile) origin.
  24806. std::atomic<int> target_hits{0};
  24807. std::atomic<bool> target_saw_proxy_authz{false};
  24808. no_proxy_test::ScopedServer target;
  24809. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24810. target_hits++;
  24811. if (req.has_header("Proxy-Authorization")) {
  24812. target_saw_proxy_authz = true;
  24813. }
  24814. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24815. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24816. "nonce=\"abc\", algorithm=MD5");
  24817. });
  24818. target.listen();
  24819. // The proxy address is set to the target's port: the bypass MUST kick in;
  24820. // if it doesn't, the test still routes "via proxy" to the same server and
  24821. // the Proxy-Authorization assertion below catches the leak.
  24822. Client cli("evil.example", target.port());
  24823. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24824. cli.set_proxy("127.0.0.1", target.port());
  24825. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24826. cli.set_no_proxy({"evil.example"});
  24827. auto res = cli.Get("/x");
  24828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24829. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24830. EXPECT_EQ(1, target_hits.load());
  24831. EXPECT_FALSE(target_saw_proxy_authz.load());
  24832. }
  24833. #endif
  24834. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24835. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24836. std::atomic<int> proxy_hits{0};
  24837. std::atomic<int> bypass_hits{0};
  24838. std::atomic<bool> proxy_saw_c_url{false};
  24839. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24840. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24841. proxy_hits++;
  24842. if (req.path.find("/start") != std::string::npos) {
  24843. res.status = 302;
  24844. res.set_header("Location", "http://127.0.0.1:" +
  24845. std::to_string(bypass_server.port()) +
  24846. "/middle");
  24847. return;
  24848. }
  24849. if (req.path.find("/end") != std::string::npos) {
  24850. proxy_saw_c_url = true;
  24851. res.set_content("c-via-proxy", "text/plain");
  24852. return;
  24853. }
  24854. res.set_content("unexpected", "text/plain");
  24855. });
  24856. // public.example's "advertised" port is arbitrary (the request never lands
  24857. // there — it goes through the proxy), but use a dynamic value to stay
  24858. // friendly with sharded parallel runs.
  24859. int public_port = bypass_server.port();
  24860. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24861. bypass_hits++;
  24862. res.status = 302;
  24863. res.set_header("Location", "http://public.example:" +
  24864. std::to_string(public_port) + "/end");
  24865. });
  24866. proxy_mock.listen();
  24867. bypass_server.listen();
  24868. Client cli("public.example", public_port);
  24869. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24870. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24871. cli.set_no_proxy({"127.0.0.1"});
  24872. cli.set_follow_location(true);
  24873. auto res = cli.Get("/start");
  24874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24875. EXPECT_EQ(StatusCode::OK_200, res->status);
  24876. EXPECT_EQ("c-via-proxy", res->body);
  24877. EXPECT_GE(proxy_hits.load(), 2);
  24878. EXPECT_GE(bypass_hits.load(), 1);
  24879. EXPECT_TRUE(proxy_saw_c_url.load());
  24880. }
  24881. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24882. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24883. // request reconnects to the correct endpoint.
  24884. std::atomic<int> proxy_hits{0};
  24885. std::atomic<int> target_hits{0};
  24886. no_proxy_test::ScopedServer proxy_mock, target;
  24887. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24888. proxy_hits++;
  24889. res.set_content("via-proxy", "text/plain");
  24890. });
  24891. target.svr().Get(".*", [&](const Request &, Response &res) {
  24892. target_hits++;
  24893. res.set_content("direct", "text/plain");
  24894. });
  24895. proxy_mock.listen();
  24896. target.listen();
  24897. Client cli("public.example", target.port());
  24898. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24899. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24900. cli.set_keep_alive(true);
  24901. auto res1 = cli.Get("/a");
  24902. ASSERT_TRUE(res1);
  24903. EXPECT_EQ("via-proxy", res1->body);
  24904. EXPECT_EQ(1, proxy_hits.load());
  24905. EXPECT_EQ(0, target_hits.load());
  24906. cli.set_no_proxy({"public.example"});
  24907. auto res2 = cli.Get("/b");
  24908. ASSERT_TRUE(res2);
  24909. EXPECT_EQ("direct", res2->body);
  24910. EXPECT_EQ(1, proxy_hits.load());
  24911. EXPECT_EQ(1, target_hits.load());
  24912. }
  24913. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24914. namespace proxy_tunnel_test {
  24915. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24916. class ScopedSSLServer {
  24917. public:
  24918. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24919. port_ = svr_.bind_to_any_port("127.0.0.1");
  24920. }
  24921. ~ScopedSSLServer() {
  24922. svr_.stop();
  24923. if (th_.joinable()) { th_.join(); }
  24924. }
  24925. SSLServer &svr() { return svr_; }
  24926. int port() const { return port_; }
  24927. void listen() {
  24928. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24929. svr_.wait_until_ready();
  24930. }
  24931. private:
  24932. SSLServer svr_;
  24933. std::thread th_;
  24934. int port_ = 0;
  24935. };
  24936. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24937. class ScopedConnectProxy {
  24938. public:
  24939. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24940. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24941. if (listen_fd_ < 0) { return; }
  24942. int yes = 1;
  24943. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24944. sockaddr_in a{};
  24945. a.sin_family = AF_INET;
  24946. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24947. a.sin_port = 0;
  24948. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24949. return;
  24950. }
  24951. socklen_t alen = sizeof(a);
  24952. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24953. 0) {
  24954. return;
  24955. }
  24956. port_ = ntohs(a.sin_port);
  24957. if (::listen(listen_fd_, 1) != 0) { return; }
  24958. th_ = std::thread([this] { run(); });
  24959. }
  24960. ~ScopedConnectProxy() {
  24961. stop_ = true;
  24962. if (listen_fd_ >= 0) {
  24963. ::shutdown(listen_fd_, SHUT_RDWR);
  24964. ::close(listen_fd_);
  24965. }
  24966. if (th_.joinable()) { th_.join(); }
  24967. }
  24968. int port() const { return port_; }
  24969. int connect_hits() const { return connect_hits_.load(); }
  24970. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24971. std::string connect_request() const {
  24972. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24973. return connect_request_;
  24974. }
  24975. private:
  24976. void run() {
  24977. while (!stop_.load()) {
  24978. fd_set rfds;
  24979. FD_ZERO(&rfds);
  24980. FD_SET(listen_fd_, &rfds);
  24981. timeval tv{0, 100 * 1000};
  24982. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24983. if (sel <= 0) { continue; }
  24984. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24985. if (client_fd < 0) { continue; }
  24986. std::string req;
  24987. char buf[2048];
  24988. while (req.find("\r\n\r\n") == std::string::npos) {
  24989. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24990. if (n <= 0) { break; }
  24991. req.append(buf, static_cast<size_t>(n));
  24992. }
  24993. if (req.compare(0, 7, "CONNECT") != 0) {
  24994. ::close(client_fd);
  24995. continue;
  24996. }
  24997. connect_hits_++;
  24998. {
  24999. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25000. connect_request_ = req;
  25001. }
  25002. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  25003. ::send(client_fd, ok, std::strlen(ok), 0);
  25004. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  25005. sockaddr_in o{};
  25006. o.sin_family = AF_INET;
  25007. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25008. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  25009. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  25010. 0) {
  25011. ::close(client_fd);
  25012. ::close(origin_fd);
  25013. continue;
  25014. }
  25015. auto forward = [](int from, int to) {
  25016. char b[8192];
  25017. for (;;) {
  25018. ssize_t n = ::recv(from, b, sizeof(b), 0);
  25019. if (n <= 0) { break; }
  25020. ssize_t off = 0;
  25021. while (off < n) {
  25022. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  25023. if (s <= 0) {
  25024. off = n;
  25025. break;
  25026. }
  25027. off += s;
  25028. }
  25029. }
  25030. ::shutdown(to, SHUT_WR);
  25031. };
  25032. std::thread t1([&] { forward(client_fd, origin_fd); });
  25033. std::thread t2([&] { forward(origin_fd, client_fd); });
  25034. t1.join();
  25035. t2.join();
  25036. ::close(client_fd);
  25037. ::close(origin_fd);
  25038. }
  25039. }
  25040. int forward_port_ = -1;
  25041. int listen_fd_ = -1;
  25042. int port_ = 0;
  25043. std::thread th_;
  25044. std::atomic<bool> stop_{false};
  25045. std::atomic<int> connect_hits_{0};
  25046. mutable std::mutex connect_request_mutex_;
  25047. std::string connect_request_;
  25048. };
  25049. // Sends one request through the CONNECT proxy to the TLS origin with a
  25050. // credential configured for each hop, and checks that each credential reaches
  25051. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25052. // origin's (every header in origin_headers) on the tunnelled request.
  25053. void CredentialsStayWithTheirHop(
  25054. const std::function<void(SSLClient &)> &set_credentials,
  25055. const std::string &scheme,
  25056. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  25057. std::atomic<int> origin_hits{0};
  25058. std::atomic<bool> origin_saw_proxy_authz{false};
  25059. std::atomic<bool> origin_saw_headers{false};
  25060. ScopedSSLServer origin;
  25061. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25062. origin_hits++;
  25063. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  25064. origin_saw_headers =
  25065. std::all_of(origin_headers.begin(), origin_headers.end(),
  25066. [&](const std::string &h) { return req.has_header(h); });
  25067. res.set_content("ok", "text/plain");
  25068. });
  25069. origin.listen();
  25070. ScopedConnectProxy proxy(origin.port());
  25071. ASSERT_NE(0, proxy.port());
  25072. // Pinned to 127.0.0.1 for the same reason as the test below.
  25073. SSLClient cli("127.0.0.1", origin.port());
  25074. cli.enable_server_certificate_verification(false);
  25075. cli.set_proxy("127.0.0.1", proxy.port());
  25076. set_credentials(cli);
  25077. auto res = cli.Get("/x");
  25078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25079. EXPECT_EQ(StatusCode::OK_200, res->status);
  25080. EXPECT_EQ(1, origin_hits.load());
  25081. EXPECT_EQ(1, proxy.connect_hits());
  25082. EXPECT_TRUE(origin_saw_headers.load());
  25083. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25084. << "Proxy-Authorization must not be sent inside the tunnel";
  25085. auto connect_req = proxy.connect_request();
  25086. EXPECT_NE(std::string::npos,
  25087. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25088. for (const auto &h : origin_headers) {
  25089. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25090. << h << " must not be sent to the proxy on CONNECT";
  25091. }
  25092. }
  25093. } // namespace proxy_tunnel_test
  25094. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25095. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25096. [](SSLClient &cli) {
  25097. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25098. cli.set_basic_auth("origin-user", "origin-pass");
  25099. },
  25100. "Basic");
  25101. }
  25102. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25103. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25104. [](SSLClient &cli) {
  25105. cli.set_proxy_bearer_token_auth("proxy-token");
  25106. cli.set_bearer_token_auth("origin-token");
  25107. },
  25108. "Bearer");
  25109. }
  25110. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25111. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25112. [](SSLClient &cli) {
  25113. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25114. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25115. {"Cookie", "sid=origin-session"},
  25116. {"X-Api-Key", "origin-key"}});
  25117. },
  25118. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25119. }
  25120. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25121. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25122. // retry; otherwise proxy creds would be sent to the origin.
  25123. std::atomic<int> origin_hits{0};
  25124. std::atomic<bool> origin_saw_proxy_authz{false};
  25125. proxy_tunnel_test::ScopedSSLServer origin;
  25126. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25127. origin_hits++;
  25128. if (req.has_header("Proxy-Authorization")) {
  25129. origin_saw_proxy_authz = true;
  25130. }
  25131. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25132. res.set_header("Proxy-Authenticate",
  25133. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25134. "algorithm=MD5");
  25135. });
  25136. origin.listen();
  25137. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25138. ASSERT_NE(0, proxy.port());
  25139. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25140. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25141. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25142. // and answer with its own status, making this test flaky.
  25143. SSLClient cli("127.0.0.1", origin.port());
  25144. cli.enable_server_certificate_verification(false);
  25145. cli.set_proxy("127.0.0.1", proxy.port());
  25146. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25147. auto res = cli.Get("/x");
  25148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25149. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25150. EXPECT_EQ(1, origin_hits.load());
  25151. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25152. EXPECT_EQ(1, proxy.connect_hits());
  25153. }
  25154. #endif