test.cc 966 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. }
  153. #if defined(__linux__) || \
  154. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  155. TEST_F(UnixSocketTest, PeerPid) {
  156. httplib::Server svr;
  157. std::string remote_port_val;
  158. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  159. res.set_content(content_, "text/plain");
  160. remote_port_val = std::to_string(req.remote_port);
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(pathname_);
  173. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  174. }
  175. #endif
  176. #ifdef __linux__
  177. TEST_F(UnixSocketTest, abstract) {
  178. constexpr char svr_path[]{"\x00httplib-server.sock"};
  179. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  180. httplib::Server svr;
  181. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  182. res.set_content(content_, "text/plain");
  183. });
  184. std::thread t{[&] {
  185. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  186. }};
  187. auto se = detail::scope_exit([&] {
  188. svr.stop();
  189. t.join();
  190. ASSERT_FALSE(svr.is_running());
  191. });
  192. svr.wait_until_ready();
  193. ASSERT_TRUE(svr.is_running());
  194. client_GET(abstract_addr);
  195. }
  196. #endif
  197. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  198. httplib::Server svr;
  199. std::string received_host_header;
  200. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  201. // Capture the Host header sent by the client
  202. auto host_iter = req.headers.find("Host");
  203. if (host_iter != req.headers.end()) {
  204. received_host_header = host_iter->second;
  205. }
  206. res.set_content(content_, "text/plain");
  207. });
  208. std::thread t{[&] {
  209. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  210. }};
  211. auto se = detail::scope_exit([&] {
  212. svr.stop();
  213. t.join();
  214. ASSERT_FALSE(svr.is_running());
  215. });
  216. svr.wait_until_ready();
  217. ASSERT_TRUE(svr.is_running());
  218. // Test that Host header is automatically set to "localhost" for Unix socket
  219. // connections
  220. httplib::Client cli{pathname_};
  221. cli.set_address_family(AF_UNIX);
  222. ASSERT_TRUE(cli.is_valid());
  223. const auto &result = cli.Get(pattern_);
  224. ASSERT_TRUE(result) << "error: " << result.error();
  225. const auto &resp = result.value();
  226. EXPECT_EQ(resp.status, StatusCode::OK_200);
  227. EXPECT_EQ(resp.body, content_);
  228. // Verify that Host header was automatically set to "localhost"
  229. EXPECT_EQ(received_host_header, "localhost");
  230. }
  231. #ifndef _WIN32
  232. TEST(SocketStream, wait_writable_UNIX) {
  233. int fds[2];
  234. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  235. const auto asSocketStream = [&](socket_t fd,
  236. std::function<bool(Stream &)> func) {
  237. return detail::process_client_socket(
  238. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  239. };
  240. asSocketStream(fds[0], [&](Stream &s0) {
  241. EXPECT_EQ(s0.socket(), fds[0]);
  242. EXPECT_TRUE(s0.wait_writable());
  243. EXPECT_TRUE(s0.is_peer_alive());
  244. EXPECT_EQ(0, close(fds[1]));
  245. EXPECT_FALSE(s0.is_peer_alive());
  246. return true;
  247. });
  248. EXPECT_EQ(0, close(fds[0]));
  249. }
  250. TEST(SocketStream, wait_writable_INET) {
  251. sockaddr_in addr;
  252. memset(&addr, 0, sizeof(addr));
  253. addr.sin_family = AF_INET;
  254. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  255. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  256. int disconnected_svr_sock = -1;
  257. std::thread svr{[&] {
  258. const int s = socket(AF_INET, SOCK_STREAM, 0);
  259. ASSERT_LE(0, s);
  260. // PORT + 1 is shared with the SSL redirect tests and with
  261. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  262. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  263. // because that happens on a worker thread the ASSERT does not stop the
  264. // test: it runs on and fails at the disconnected_svr_sock check instead.
  265. default_socket_options(s);
  266. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, listen(s, 1));
  268. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  269. ASSERT_EQ(0, close(s));
  270. }};
  271. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  272. std::thread cli{[&] {
  273. const int s = socket(AF_INET, SOCK_STREAM, 0);
  274. ASSERT_LE(0, s);
  275. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  276. ASSERT_EQ(0, close(s));
  277. }};
  278. cli.join();
  279. svr.join();
  280. ASSERT_NE(disconnected_svr_sock, -1);
  281. const auto asSocketStream = [&](socket_t fd,
  282. std::function<bool(Stream &)> func) {
  283. return detail::process_client_socket(
  284. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  285. };
  286. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  287. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  288. // wait_writable() returns true because select_write() only checks if the
  289. // send buffer has space. Peer disconnection is detected later by send().
  290. EXPECT_TRUE(ss.wait_writable());
  291. return true;
  292. });
  293. ASSERT_EQ(0, close(disconnected_svr_sock));
  294. }
  295. #endif // #ifndef _WIN32
  296. TEST(SetSocketOptTest, TcpNoDelay) {
  297. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  298. ASSERT_NE(sock, INVALID_SOCKET);
  299. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  300. int val = 0;
  301. socklen_t len = sizeof(val);
  302. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  303. reinterpret_cast<char *>(&val), &len));
  304. EXPECT_NE(val, 0);
  305. detail::close_socket(sock);
  306. }
  307. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  308. // accept() reports failures through WSAGetLastError() on Windows and through
  309. // errno everywhere else. Asking the wrong one is what made the accept loop
  310. // treat every recoverable failure as fatal on Windows.
  311. struct Classification {
  312. bool resource;
  313. bool transient;
  314. };
  315. auto classify = [](int err) {
  316. #ifdef _WIN32
  317. WSASetLastError(err);
  318. #else
  319. errno = err;
  320. #endif
  321. // Read both before asserting: an assertion may clobber the error slot.
  322. Classification c;
  323. c.resource = detail::is_accept_resource_error();
  324. c.transient = detail::is_accept_transient_error();
  325. return c;
  326. };
  327. #ifdef _WIN32
  328. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  329. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  330. WSAECONNRESET, WSAECONNABORTED};
  331. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  332. #else
  333. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  334. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  335. ECONNABORTED};
  336. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  337. #endif
  338. for (auto err : resource_errors) {
  339. const auto c = classify(err);
  340. EXPECT_TRUE(c.resource) << "error " << err;
  341. EXPECT_FALSE(c.transient) << "error " << err;
  342. }
  343. for (auto err : transient_errors) {
  344. const auto c = classify(err);
  345. EXPECT_TRUE(c.transient) << "error " << err;
  346. EXPECT_FALSE(c.resource) << "error " << err;
  347. }
  348. for (auto err : fatal_errors) {
  349. const auto c = classify(err);
  350. EXPECT_FALSE(c.resource) << "error " << err;
  351. EXPECT_FALSE(c.transient) << "error " << err;
  352. }
  353. #ifdef _WIN32
  354. WSASetLastError(0);
  355. #else
  356. errno = 0;
  357. #endif
  358. }
  359. TEST(ClientTest, MoveConstructible) {
  360. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  361. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  362. }
  363. TEST(ClientTest, MoveAssignable) {
  364. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  365. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  366. }
  367. #ifdef _WIN32
  368. TEST(StartupTest, WSAStartup) {
  369. WSADATA wsaData;
  370. int ret = WSAStartup(0x0002, &wsaData);
  371. ASSERT_EQ(0, ret);
  372. }
  373. #endif
  374. TEST(DecodePathTest, PercentCharacter) {
  375. EXPECT_EQ(
  376. decode_path_component(
  377. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  378. U8("descrip=Gastos áéíóúñÑ 6"));
  379. }
  380. TEST(DecodePathTest, PercentCharacterNUL) {
  381. string expected;
  382. expected.push_back('x');
  383. expected.push_back('\0');
  384. expected.push_back('x');
  385. EXPECT_EQ(decode_path_component("x%00x"), expected);
  386. }
  387. TEST(DecodePathTest, UnicodeEncoding) {
  388. // %u0041 = 'A' (1-byte UTF-8)
  389. EXPECT_EQ("A", decode_path_component("%u0041"));
  390. // %u00E9 = 'é' (2-byte UTF-8)
  391. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  392. // %u3042 = 'あ' (3-byte UTF-8)
  393. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  394. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  395. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  396. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  397. // neighbours)
  398. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  399. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  400. }
  401. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  402. // A sign or whitespace inside the two-character escape window must not be
  403. // accepted as a valid percent-encoding; the sequence is passed through
  404. // literally, matching decode_uri_component / decode_path_component.
  405. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  406. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  407. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  408. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  409. // Well-formed escapes still decode.
  410. EXPECT_EQ("-", decode_query_component("%2D", false));
  411. EXPECT_EQ("A", decode_query_component("%41", false));
  412. }
  413. TEST(SanitizeFilenameTest, VariousPatterns) {
  414. // Path traversal
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  416. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  417. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  418. // Normal and edge cases
  419. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  420. EXPECT_EQ("filename.txt",
  421. httplib::sanitize_filename("/path/to/filename.txt"));
  422. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  423. EXPECT_EQ("", httplib::sanitize_filename(".."));
  424. EXPECT_EQ("", httplib::sanitize_filename(""));
  425. // Null bytes stripped
  426. EXPECT_EQ("safe.txt",
  427. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  428. // Whitespace-only rejected
  429. EXPECT_EQ("", httplib::sanitize_filename(" "));
  430. }
  431. // Forward declaration (see the base64_encode note below): split builds move the
  432. // definition into httplib.cc, so re-declaring it here lets the test link.
  433. namespace httplib {
  434. namespace detail {
  435. bool is_chunked_transfer_encoding(const Headers &headers);
  436. } // namespace detail
  437. } // namespace httplib
  438. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  439. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  440. auto make = [](std::initializer_list<const char *> lines) {
  441. Headers h;
  442. for (auto te : lines) {
  443. if (te) { h.emplace("Transfer-Encoding", te); }
  444. }
  445. return h;
  446. };
  447. // Sole coding, matched case-insensitively.
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  451. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  455. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  460. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  461. // were received, into one list. Headers preserves that order, so the answer
  462. // is decided by the last coding of the last line and the order the lines
  463. // arrived in is significant.
  464. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  466. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  467. // The split can fall anywhere in the list.
  468. EXPECT_TRUE(
  469. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  470. EXPECT_FALSE(
  471. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  472. // A trailing line naming no coding leaves the list ending in nothing, so it
  473. // must not inherit the chunked from the line before it.
  474. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  475. }
  476. // Forward declarations (see the base64_encode note below).
  477. namespace httplib {
  478. namespace detail {
  479. bool parse_status_line(const char *line, std::string &version, int &status,
  480. std::string &reason);
  481. std::string file_extension(const std::string &path);
  482. std::string
  483. find_content_type(const std::string &path,
  484. const std::map<std::string, std::string> &user_data,
  485. const std::string &default_content_type);
  486. bool can_compress_content_type(const std::string &content_type);
  487. bool is_prohibited_header_name(const std::string &name);
  488. #ifdef CPPHTTPLIB_SSL_ENABLED
  489. bool match_hostname(const std::string &pattern, const std::string &hostname);
  490. #endif
  491. } // namespace detail
  492. } // namespace httplib
  493. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  494. struct {
  495. const char *line;
  496. const char *version;
  497. int status;
  498. const char *reason;
  499. } cases[] = {
  500. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  501. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  502. // The reason phrase may be empty, or left out along with its space.
  503. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  504. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  505. };
  506. for (const auto &c : cases) {
  507. std::string version;
  508. int status = 0;
  509. std::string reason = "unset";
  510. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  511. << c.line;
  512. EXPECT_EQ(c.version, version);
  513. EXPECT_EQ(c.status, status);
  514. EXPECT_EQ(c.reason, reason);
  515. }
  516. }
  517. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  518. const char *lines[] = {
  519. "HTTP/2 200 OK\r\n",
  520. "HTTP/1.2 200 OK\r\n",
  521. "HTTP/1.1 20 OK\r\n",
  522. "HTTP/1.1 2000 OK\r\n",
  523. "HTTP/1.1 2x0 OK\r\n",
  524. "HTTP/1.1 200 OK\r\n",
  525. "HTTP/1.1 200OK\r\n",
  526. "HTTP/1.1 200 O\rK\r\n",
  527. "HTTP/1.1 200 OK",
  528. "HTTP/1.1 200 OK\r\nX",
  529. "",
  530. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  531. "HTTP/1.1 200 OK\n",
  532. #endif
  533. };
  534. for (auto line : lines) {
  535. std::string version;
  536. int status = 0;
  537. std::string reason;
  538. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  539. << line;
  540. }
  541. }
  542. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  543. // Long enough to overflow the stack when matched with std::regex.
  544. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  545. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  546. std::string version;
  547. int status = 0;
  548. std::string reason;
  549. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  550. EXPECT_EQ(200, status);
  551. EXPECT_EQ(long_reason, reason);
  552. }
  553. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  554. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  555. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  556. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  557. EXPECT_EQ("", detail::file_extension("noext"));
  558. EXPECT_EQ("", detail::file_extension("a."));
  559. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  560. EXPECT_EQ("", detail::file_extension("a.b-c"));
  561. // Long enough to overflow the stack when matched with std::regex.
  562. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  563. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  564. }
  565. #ifdef CPPHTTPLIB_SSL_ENABLED
  566. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  567. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  569. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  570. // A wildcard needs two labels after it, in the leftmost label only
  571. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  572. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  573. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  574. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  575. EXPECT_FALSE(
  576. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  577. // No name may have an empty label
  578. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  579. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  580. }
  581. #endif
  582. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  583. detail::case_ignore::hash hash;
  584. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  585. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  586. // Long enough to overflow the stack if hashed one call per character.
  587. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  588. }
  589. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  590. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  591. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  592. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  593. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  594. // Same 26-bit hash as html, svg and js.
  595. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  597. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  598. }
  599. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  600. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  601. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  602. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  603. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  604. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  605. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  606. // Same 26-bit hash as application/json.
  607. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  608. }
  609. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  610. Request req;
  611. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  612. EXPECT_TRUE(req.is_multipart_form_data());
  613. std::string boundary;
  614. EXPECT_TRUE(detail::parse_multipart_boundary(
  615. req.get_header_value("Content-Type"), boundary));
  616. EXPECT_EQ("x", boundary);
  617. }
  618. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  619. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  620. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  621. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  623. // Same 26-bit hash as REMOTE_ADDR.
  624. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  625. }
  626. // Forward declaration: in split builds split.py strips `inline` and moves the
  627. // definition into httplib.cc, so detail::base64_encode is not visible from the
  628. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  629. // in both header-only and split builds.
  630. namespace httplib {
  631. namespace detail {
  632. std::string base64_encode(const std::string &in);
  633. } // namespace detail
  634. } // namespace httplib
  635. TEST(Base64EncodeTest, KnownAnswers) {
  636. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  637. // where the accumulator's top bit is already set before the next shift.
  638. EXPECT_EQ("", detail::base64_encode(""));
  639. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  640. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  641. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  642. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  643. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  644. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  645. // High bytes keep the top bit set across several rounds.
  646. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  647. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  648. }
  649. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  650. string unescapedCharacters = "-_.!~*'()";
  651. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  652. }
  653. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  654. string reservedCharacters = ";,/?:@&=+$";
  655. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  656. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  657. }
  658. TEST(ClientQueryOrder, PreserveOrder) {
  659. // This test reproduces Issue #2259: client may reorder query parameters
  660. // when sending a GET request. The expected behavior is that the client
  661. // preserves the original query string order when the caller supplied it
  662. // as part of the path.
  663. Server svr;
  664. svr.Get("/", [&](const Request &req, Response &res) {
  665. // Echo back the raw target so the test can assert ordering
  666. res.set_content(req.target, "text/plain");
  667. });
  668. std::thread t{[&] { svr.listen(HOST, PORT); }};
  669. auto se = detail::scope_exit([&] {
  670. svr.stop();
  671. t.join();
  672. ASSERT_FALSE(svr.is_running());
  673. });
  674. svr.wait_until_ready();
  675. Client cli(HOST, PORT);
  676. ASSERT_TRUE(cli.is_valid());
  677. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  678. auto res = cli.Get(original);
  679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  680. // Expect the echoed target to exactly match the original path (order
  681. // preserved)
  682. EXPECT_EQ(res->body, original);
  683. }
  684. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  685. string chineseCharacters = U8("中国語");
  686. string russianCharacters = U8("дом");
  687. string brazilianCharacters = U8("óculos");
  688. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  689. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  690. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  691. "%D0%B4%D0%BE%D0%BC");
  692. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  693. }
  694. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  695. string unescapedCharacters = "-_.!~*'()";
  696. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  697. }
  698. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  699. string reservedCharacters = ";,/?:@&=+$";
  700. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  701. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  702. }
  703. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  704. string chineseCharacters = U8("中国語");
  705. string russianCharacters = U8("дом");
  706. string brazilianCharacters = U8("óculos");
  707. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  708. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  709. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  710. "%D0%B4%D0%BE%D0%BC");
  711. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  712. }
  713. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  714. // Issue #2082 use case: encoding path component with ampersand
  715. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  716. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  717. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  718. }
  719. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  720. string unescapedCharacters = "-_.!~*'()";
  721. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  722. }
  723. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  724. string reservedCharacters = ";,/?:@&=+$#";
  725. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  726. }
  727. TEST(EncodeUriTest, TestUTF8Characters) {
  728. string chineseCharacters = U8("中国語");
  729. string russianCharacters = U8("дом");
  730. string brazilianCharacters = U8("óculos");
  731. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  732. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  733. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  734. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  735. }
  736. TEST(EncodeUriTest, TestCompleteUri) {
  737. string uri =
  738. "https://example.com/path/to/resource?query=value&param=test#fragment";
  739. EXPECT_EQ(
  740. httplib::encode_uri(uri),
  741. "https://example.com/path/to/resource?query=value&param=test#fragment");
  742. }
  743. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  744. string uri =
  745. "https://example.com/path with spaces/file name.html?q=hello world";
  746. EXPECT_EQ(httplib::encode_uri(uri),
  747. "https://example.com/path%20with%20spaces/"
  748. "file%20name.html?q=hello%20world");
  749. }
  750. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  751. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  752. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  753. }
  754. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  755. string unescapedCharacters = "-_.!~*'()";
  756. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  757. }
  758. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  759. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  760. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  761. string encodedBrazilian = "%C3%B3culos";
  762. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  764. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  765. }
  766. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  767. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  768. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  769. "Piri Tommy Villiers - on & on");
  770. }
  771. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  772. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  773. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  774. }
  775. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  776. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  777. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  778. }
  779. TEST(DecodeUriTest, TestUTF8Characters) {
  780. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  781. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  782. string encodedBrazilian = "%C3%B3culos";
  783. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  784. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  785. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  786. }
  787. TEST(DecodeUriTest, TestCompleteUri) {
  788. string encodedUri = "https://example.com/path%20with%20spaces/"
  789. "file%20name.html?q=hello%20world";
  790. EXPECT_EQ(
  791. httplib::decode_uri(encodedUri),
  792. "https://example.com/path with spaces/file name.html?q=hello world");
  793. }
  794. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  795. string original =
  796. "https://example.com/path with spaces/file name.html?q=hello world";
  797. string encoded = httplib::encode_uri(original);
  798. string decoded = httplib::decode_uri(encoded);
  799. EXPECT_EQ(decoded, original);
  800. }
  801. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  802. // decode_uri is the inverse of encode_uri: an escaped reserved character
  803. // stays encoded so it is not promoted into a real delimiter, while
  804. // non-reserved escapes still decode (like JS decodeURI).
  805. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  806. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  807. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  808. "%3F%3A%40%26%3D%2B%24%2C%3B");
  809. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  810. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  811. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  812. "http://example.com/a%2Fb");
  813. // decode_uri_component still decodes the reserved character.
  814. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  815. }
  816. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  817. string original = "Piri Tommy Villiers - on & on";
  818. string encoded = httplib::encode_uri_component(original);
  819. string decoded = httplib::decode_uri_component(encoded);
  820. EXPECT_EQ(decoded, original);
  821. }
  822. TEST(TrimTests, TrimStringTests) {
  823. EXPECT_EQ("abc", detail::trim_copy("abc"));
  824. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  825. EXPECT_TRUE(detail::trim_copy("").empty());
  826. }
  827. TEST(AsciiTest, LocaleIndependentClassification) {
  828. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  829. // which consult the global C locale: std::isalnum(0xC5) can return true
  830. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  831. // helpers must classify every byte by the ASCII grammar alone.
  832. for (int i = 0; i < 256; i++) {
  833. auto c = static_cast<char>(i);
  834. auto is_digit = i >= '0' && i <= '9';
  835. auto is_upper = i >= 'A' && i <= 'Z';
  836. auto is_lower = i >= 'a' && i <= 'z';
  837. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  838. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  839. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  840. << "byte " << i;
  841. }
  842. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  843. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  844. // Non-ASCII bytes must be percent-encoded, never passed through as
  845. // alphanumeric.
  846. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  847. }
  848. TEST(FromCharsTest, Double) {
  849. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  850. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  851. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  852. auto parse = [](const std::string &s, double &v) {
  853. return detail::from_chars(s.data(), s.data() + s.size(), v);
  854. };
  855. double v = -1.0;
  856. // Representative quality values.
  857. EXPECT_EQ(parse("0", v).ec, std::errc{});
  858. EXPECT_DOUBLE_EQ(v, 0.0);
  859. EXPECT_EQ(parse("1", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 1.0);
  861. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 0.8);
  863. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.001);
  865. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 1.0);
  867. // A missing integer or fractional part is tolerated.
  868. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 0.5);
  870. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 5.0);
  872. // Values outside [0, 1] still parse; the caller range-checks them.
  873. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 123.456);
  875. // Stops at the first byte that is not part of the number and reports where.
  876. std::string trailing = "0.9, text/html";
  877. auto r = parse(trailing, v);
  878. EXPECT_EQ(r.ec, std::errc{});
  879. EXPECT_DOUBLE_EQ(v, 0.9);
  880. EXPECT_EQ(*r.ptr, ',');
  881. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  882. // outright, and an 'e'/'E' simply ends the number.
  883. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  884. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  885. std::string exp_input = "1.5e3";
  886. r = parse(exp_input, v);
  887. EXPECT_EQ(r.ec, std::errc{});
  888. EXPECT_DOUBLE_EQ(v, 1.5);
  889. EXPECT_EQ(*r.ptr, 'e');
  890. // Invalid inputs.
  891. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  896. // Pathological but well-formed inputs must stay bounded (no overflow, no
  897. // out-of-bounds table access) and stay within [0, 1] for the caller.
  898. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  899. std::errc{});
  900. EXPECT_DOUBLE_EQ(v, 0.0);
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  902. std::errc{});
  903. EXPECT_GE(v, 0.0);
  904. EXPECT_LE(v, 1.0);
  905. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  906. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  907. }
  908. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  909. // Simple case without quality values
  910. std::vector<std::string> result1;
  911. EXPECT_TRUE(detail::parse_accept_header(
  912. "text/html,application/json,text/plain", result1));
  913. EXPECT_EQ(result1.size(), 3U);
  914. EXPECT_EQ(result1[0], "text/html");
  915. EXPECT_EQ(result1[1], "application/json");
  916. EXPECT_EQ(result1[2], "text/plain");
  917. // With quality values
  918. std::vector<std::string> result2;
  919. EXPECT_TRUE(detail::parse_accept_header(
  920. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  921. EXPECT_EQ(result2.size(), 3U);
  922. EXPECT_EQ(result2[0], "application/json"); // highest q value
  923. EXPECT_EQ(result2[1], "text/html");
  924. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  925. }
  926. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  927. // Mixed with and without quality values
  928. std::vector<std::string> result;
  929. EXPECT_TRUE(detail::parse_accept_header(
  930. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  931. EXPECT_EQ(result.size(), 3U);
  932. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  933. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  934. EXPECT_EQ(result[2], "application/json"); // q=0.5
  935. }
  936. TEST(ParseAcceptHeaderTest, EdgeCases) {
  937. // Empty header
  938. std::vector<std::string> empty_result;
  939. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  940. EXPECT_TRUE(empty_result.empty());
  941. // Single type
  942. std::vector<std::string> single_result;
  943. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  944. EXPECT_EQ(single_result.size(), 1U);
  945. EXPECT_EQ(single_result[0], "application/json");
  946. // Wildcard types
  947. std::vector<std::string> wildcard_result;
  948. EXPECT_TRUE(detail::parse_accept_header(
  949. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  950. EXPECT_EQ(wildcard_result.size(), 3U);
  951. EXPECT_EQ(wildcard_result[0], "application/json");
  952. EXPECT_EQ(wildcard_result[1], "text/*");
  953. EXPECT_EQ(wildcard_result[2], "*/*");
  954. }
  955. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  956. // Common browser Accept header
  957. std::vector<std::string> browser_result;
  958. EXPECT_TRUE(
  959. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  960. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  961. browser_result));
  962. EXPECT_EQ(browser_result.size(), 6U);
  963. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  968. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  969. // API client header
  970. std::vector<std::string> api_result;
  971. EXPECT_TRUE(detail::parse_accept_header(
  972. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  973. api_result));
  974. EXPECT_EQ(api_result.size(), 3U);
  975. EXPECT_EQ(api_result[0], "application/json");
  976. EXPECT_EQ(api_result[1], "application/xml");
  977. EXPECT_EQ(api_result[2], "text/plain");
  978. }
  979. TEST(ParseAcceptHeaderTest, SpecialCases) {
  980. // Quality value with 3 decimal places
  981. std::vector<std::string> decimal_result;
  982. EXPECT_TRUE(detail::parse_accept_header(
  983. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  984. EXPECT_EQ(decimal_result.size(), 2U);
  985. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  986. EXPECT_EQ(decimal_result[1], "text/html");
  987. // Zero quality (should still be included but with lowest priority)
  988. std::vector<std::string> zero_q_result;
  989. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  990. zero_q_result));
  991. EXPECT_EQ(zero_q_result.size(), 2U);
  992. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  993. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  994. // No spaces around commas
  995. std::vector<std::string> no_space_result;
  996. EXPECT_TRUE(detail::parse_accept_header(
  997. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  998. no_space_result));
  999. EXPECT_EQ(no_space_result.size(), 3U);
  1000. EXPECT_EQ(no_space_result[0], "text/html");
  1001. EXPECT_EQ(no_space_result[1], "application/json");
  1002. EXPECT_EQ(no_space_result[2], "text/plain");
  1003. }
  1004. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1005. // Quality values always use '.' as the decimal separator, so parsing must
  1006. // not depend on the process locale. An embedding application may have
  1007. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1008. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1009. std::string saved = cur ? cur : "C";
  1010. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1011. "fr_FR.UTF-8"};
  1012. bool switched = false;
  1013. for (const auto loc : comma_locales) {
  1014. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1015. std::localeconv()->decimal_point[0] == ',') {
  1016. switched = true;
  1017. break;
  1018. }
  1019. }
  1020. if (!switched) {
  1021. std::setlocale(LC_NUMERIC, saved.c_str());
  1022. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1023. }
  1024. // The higher-weighted type appears later in the list, so a correct parse
  1025. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1026. // sensitive parse reads both weights as 0 and leaves the original order.
  1027. std::vector<std::string> result;
  1028. EXPECT_TRUE(detail::parse_accept_header(
  1029. "application/json;q=0.1,text/html;q=0.9", result));
  1030. ASSERT_EQ(result.size(), 2U);
  1031. EXPECT_EQ(result[0], "text/html");
  1032. EXPECT_EQ(result[1], "application/json");
  1033. std::setlocale(LC_NUMERIC, saved.c_str());
  1034. }
  1035. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1036. std::vector<std::string> result;
  1037. // Invalid quality value (> 1.0)
  1038. EXPECT_FALSE(
  1039. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1040. // Invalid quality value (< 0.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1043. // Invalid quality value (not a number)
  1044. EXPECT_FALSE(detail::parse_accept_header(
  1045. "text/html;q=invalid,application/json", result));
  1046. // A valid numeric prefix does not make the entire quality value valid.
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=0.5junk,application/json", result));
  1049. // Empty quality value
  1050. EXPECT_FALSE(
  1051. detail::parse_accept_header("text/html;q=,application/json", result));
  1052. // Invalid media type format (no slash and not wildcard)
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("invalidtype,application/json", result));
  1055. // Valid cases should still work
  1056. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1057. EXPECT_EQ(result.size(), 1U);
  1058. EXPECT_EQ(result[0], "*/*");
  1059. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*");
  1062. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "text/*");
  1065. }
  1066. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1067. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1068. // and must not be answered with 400 Bad Request.
  1069. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1070. struct {
  1071. const char *value;
  1072. std::vector<std::string> expected;
  1073. } cases[] = {
  1074. {",application/json", {"application/json"}},
  1075. {"text/html,", {"text/html"}},
  1076. {"text/html,,*/*", {"text/html", "*/*"}},
  1077. // An empty element may be spelled with whitespace in it
  1078. {"text/html, , application/json", {"text/html", "application/json"}},
  1079. // Nothing but empty elements is an empty list, which means the same
  1080. // thing as no Accept header at all
  1081. {",,,", {}},
  1082. // Quality values still apply across ignored empty elements
  1083. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1084. };
  1085. for (const auto &c : cases) {
  1086. std::vector<std::string> result;
  1087. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1088. << "value: " << c.value;
  1089. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1090. }
  1091. // An invalid entry is still rejected when empty elements surround it
  1092. std::vector<std::string> result;
  1093. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1094. }
  1095. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1096. // or ';' inside one does not end the list element or the parameter. Section
  1097. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1098. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1099. struct {
  1100. const char *value;
  1101. std::vector<std::string> expected;
  1102. } cases[] = {
  1103. {"text/html;profile=\"a,b\",application/json",
  1104. {"text/html", "application/json"}},
  1105. // A "q=" inside a quoted value is not the weight
  1106. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1107. {"text/html", "application/json"}},
  1108. // The weight after a quoted value still applies
  1109. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1110. {"application/json", "text/html"}},
  1111. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\"b\",application/json",
  1114. {"text/html", "application/json"}},
  1115. // An escaped backslash does not escape the '"' after it
  1116. {"text/html;profile=\"a\\\\\",application/json",
  1117. {"text/html", "application/json"}},
  1118. };
  1119. for (const auto &c : cases) {
  1120. std::vector<std::string> result;
  1121. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1122. << "value: " << c.value;
  1123. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1124. }
  1125. }
  1126. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1127. Server svr;
  1128. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1129. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1130. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1131. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1132. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1133. res.set_content("ok", "text/plain");
  1134. });
  1135. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1136. EXPECT_TRUE(false);
  1137. res.set_content("bad request", "text/plain");
  1138. });
  1139. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1140. auto se = detail::scope_exit([&] {
  1141. svr.stop();
  1142. listen_thread.join();
  1143. ASSERT_FALSE(svr.is_running());
  1144. });
  1145. svr.wait_until_ready();
  1146. Client cli("localhost", PORT);
  1147. {
  1148. auto res = cli.Get(
  1149. "/accept_ok",
  1150. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. }
  1154. {
  1155. auto res = cli.Get("/accept_bad_request",
  1156. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1158. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1159. }
  1160. }
  1161. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1162. Server svr;
  1163. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1164. res.set_content("ok", "text/plain");
  1165. });
  1166. std::atomic<int> start_count{0};
  1167. std::atomic<bool> running_when_called{false};
  1168. svr.set_start_handler([&]() {
  1169. running_when_called = svr.is_running();
  1170. start_count++;
  1171. });
  1172. auto port = svr.bind_to_any_port(HOST);
  1173. std::thread t([&]() { svr.listen_after_bind(); });
  1174. auto se = detail::scope_exit([&] {
  1175. svr.stop();
  1176. t.join();
  1177. ASSERT_FALSE(svr.is_running());
  1178. });
  1179. svr.wait_until_ready();
  1180. // A successful request proves the accept loop is running, which the start
  1181. // handler precedes; so by now the handler must have run exactly once.
  1182. Client cli(HOST, port);
  1183. cli.set_connection_timeout(std::chrono::seconds(5));
  1184. auto res = cli.Get("/");
  1185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1186. EXPECT_EQ(StatusCode::OK_200, res->status);
  1187. EXPECT_EQ(1, start_count.load());
  1188. EXPECT_TRUE(running_when_called.load());
  1189. }
  1190. TEST(DivideTest, DivideStringTests) {
  1191. auto divide = [](const std::string &str, char d) {
  1192. std::string lhs;
  1193. std::string rhs;
  1194. detail::divide(str, d,
  1195. [&](const char *lhs_data, std::size_t lhs_size,
  1196. const char *rhs_data, std::size_t rhs_size) {
  1197. lhs.assign(lhs_data, lhs_size);
  1198. rhs.assign(rhs_data, rhs_size);
  1199. });
  1200. return std::make_pair(std::move(lhs), std::move(rhs));
  1201. };
  1202. {
  1203. const auto res = divide("", '=');
  1204. EXPECT_EQ(res.first, "");
  1205. EXPECT_EQ(res.second, "");
  1206. }
  1207. {
  1208. const auto res = divide("=", '=');
  1209. EXPECT_EQ(res.first, "");
  1210. EXPECT_EQ(res.second, "");
  1211. }
  1212. {
  1213. const auto res = divide(" ", '=');
  1214. EXPECT_EQ(res.first, " ");
  1215. EXPECT_EQ(res.second, "");
  1216. }
  1217. {
  1218. const auto res = divide("a", '=');
  1219. EXPECT_EQ(res.first, "a");
  1220. EXPECT_EQ(res.second, "");
  1221. }
  1222. {
  1223. const auto res = divide("a=", '=');
  1224. EXPECT_EQ(res.first, "a");
  1225. EXPECT_EQ(res.second, "");
  1226. }
  1227. {
  1228. const auto res = divide("=b", '=');
  1229. EXPECT_EQ(res.first, "");
  1230. EXPECT_EQ(res.second, "b");
  1231. }
  1232. {
  1233. const auto res = divide("a=b", '=');
  1234. EXPECT_EQ(res.first, "a");
  1235. EXPECT_EQ(res.second, "b");
  1236. }
  1237. {
  1238. const auto res = divide("a=b=", '=');
  1239. EXPECT_EQ(res.first, "a");
  1240. EXPECT_EQ(res.second, "b=");
  1241. }
  1242. {
  1243. const auto res = divide("a=b=c", '=');
  1244. EXPECT_EQ(res.first, "a");
  1245. EXPECT_EQ(res.second, "b=c");
  1246. }
  1247. }
  1248. TEST(SplitTest, ParseQueryString) {
  1249. string s = "key1=val1&key2=val2&key3=val3";
  1250. Params dic;
  1251. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1252. [&](const char *b, const char *e) {
  1253. string key, val;
  1254. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1255. if (key.empty()) {
  1256. key.assign(b2, e2);
  1257. } else {
  1258. val.assign(b2, e2);
  1259. }
  1260. });
  1261. dic.emplace(key, val);
  1262. });
  1263. EXPECT_EQ("val1", dic.find("key1")->second);
  1264. EXPECT_EQ("val2", dic.find("key2")->second);
  1265. EXPECT_EQ("val3", dic.find("key3")->second);
  1266. }
  1267. TEST(SplitTest, ParseInvalidQueryTests) {
  1268. {
  1269. string s = " ";
  1270. Params dict;
  1271. detail::parse_query_text(s, dict);
  1272. EXPECT_TRUE(dict.empty());
  1273. }
  1274. {
  1275. string s = " = =";
  1276. Params dict;
  1277. detail::parse_query_text(s, dict);
  1278. EXPECT_TRUE(dict.empty());
  1279. }
  1280. }
  1281. TEST(ParseQueryTest, ParseQueryString) {
  1282. {
  1283. std::string s = "key1=val1&key2=val2&key3=val3";
  1284. Params dic;
  1285. detail::parse_query_text(s, dic);
  1286. EXPECT_EQ("val1", dic.find("key1")->second);
  1287. EXPECT_EQ("val2", dic.find("key2")->second);
  1288. EXPECT_EQ("val3", dic.find("key3")->second);
  1289. }
  1290. {
  1291. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1292. Params dic;
  1293. detail::parse_query_text(s, dic);
  1294. EXPECT_EQ("", dic.find("key1")->second);
  1295. EXPECT_EQ("val1", dic.find("key2")->second);
  1296. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1297. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1298. }
  1299. }
  1300. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1301. Params dic;
  1302. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1303. dic.emplace("key1", "val1");
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1305. dic.emplace("key2", "val2");
  1306. dic.emplace("key3", "val3");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1308. }
  1309. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1310. Params params;
  1311. params.emplace("a", "1");
  1312. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1313. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1314. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1315. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1316. // Long enough to overflow the stack when matched with std::regex.
  1317. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1318. EXPECT_EQ("/p?" + long_query + "&a=1",
  1319. append_query_params("/p?" + long_query, params));
  1320. }
  1321. // Joins every entry of a Headers or Params into "key=value " so a whole
  1322. // traversal can be compared in one assertion. Both are instantiations of the
  1323. // same insertion-ordered container, so one helper serves both.
  1324. template <typename Map> static std::string entries_to_string(const Map &m) {
  1325. std::string s;
  1326. for (const auto &entry : m) {
  1327. s += entry.first + "=" + entry.second + " ";
  1328. }
  1329. return s;
  1330. }
  1331. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1332. // Params used to be a std::multimap, which sorted by name and handed the
  1333. // caller's query back alphabetised. A client signing its query string could
  1334. // not reproduce the order it asked for.
  1335. Params dic;
  1336. dic.emplace("zulu", "1");
  1337. dic.emplace("alpha", "2");
  1338. dic.emplace("mike", "3");
  1339. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1340. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1341. }
  1342. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1343. Params dic;
  1344. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1345. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1346. }
  1347. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1348. Request req;
  1349. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1350. req.params);
  1351. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag"));
  1353. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1354. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1355. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1356. EXPECT_EQ("", req.get_param_value("tag", 3));
  1357. }
  1358. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1359. // Params shares its container with Headers, which matches field names
  1360. // case-insensitively. Parameter names must not pick that up.
  1361. Params dic;
  1362. dic.emplace("Key", "upper");
  1363. dic.emplace("key", "lower");
  1364. EXPECT_EQ(2U, dic.size());
  1365. EXPECT_EQ(1U, dic.count("Key"));
  1366. EXPECT_EQ(1U, dic.count("key"));
  1367. EXPECT_EQ("upper", dic.find("Key")->second);
  1368. EXPECT_EQ("lower", dic.find("key")->second);
  1369. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1370. }
  1371. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1372. Server svr;
  1373. std::string order;
  1374. svr.Get("/order", [&](const Request &req, Response &res) {
  1375. order = entries_to_string(req.params);
  1376. res.set_content("ok", "text/plain");
  1377. });
  1378. auto port = svr.bind_to_any_port(HOST);
  1379. thread t = thread([&] { svr.listen_after_bind(); });
  1380. auto se = detail::scope_exit([&] {
  1381. svr.stop();
  1382. t.join();
  1383. ASSERT_FALSE(svr.is_running());
  1384. });
  1385. svr.wait_until_ready();
  1386. Client cli(HOST, port);
  1387. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1388. ASSERT_TRUE(res);
  1389. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1390. }
  1391. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1392. Server svr;
  1393. std::string field_order, file_order;
  1394. svr.Post("/order", [&](const Request &req, Response &res) {
  1395. for (const auto &field : req.form.fields) {
  1396. field_order += field.first + "=" + field.second.content + " ";
  1397. }
  1398. for (const auto &file : req.form.files) {
  1399. file_order += file.first + "=" + file.second.filename + " ";
  1400. }
  1401. res.set_content("ok", "text/plain");
  1402. });
  1403. auto port = svr.bind_to_any_port(HOST);
  1404. thread t = thread([&] { svr.listen_after_bind(); });
  1405. auto se = detail::scope_exit([&] {
  1406. svr.stop();
  1407. t.join();
  1408. ASSERT_FALSE(svr.is_running());
  1409. });
  1410. svr.wait_until_ready();
  1411. UploadFormDataItems items = {
  1412. {"zulu", "1", "", ""},
  1413. {"alpha", "2", "", ""},
  1414. {"mike", "3", "", ""},
  1415. {"zebra", "z", "z.txt", "text/plain"},
  1416. {"apple", "a", "a.txt", "text/plain"},
  1417. };
  1418. Client cli(HOST, port);
  1419. auto res = cli.Post("/order", items);
  1420. ASSERT_TRUE(res);
  1421. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1422. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1423. }
  1424. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1425. Server svr;
  1426. std::vector<std::string> values;
  1427. std::string first, second, out_of_range, order;
  1428. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1429. values = req.form.get_fields("tag");
  1430. first = req.form.get_field("tag", 0);
  1431. second = req.form.get_field("tag", 1);
  1432. out_of_range = req.form.get_field("tag", 2);
  1433. for (const auto &field : req.form.fields) {
  1434. order += field.first + "=" + field.second.content + " ";
  1435. }
  1436. res.set_content("ok", "text/plain");
  1437. });
  1438. auto port = svr.bind_to_any_port(HOST);
  1439. thread t = thread([&] { svr.listen_after_bind(); });
  1440. auto se = detail::scope_exit([&] {
  1441. svr.stop();
  1442. t.join();
  1443. ASSERT_FALSE(svr.is_running());
  1444. });
  1445. svr.wait_until_ready();
  1446. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1447. // not adjacent in the container.
  1448. UploadFormDataItems items = {
  1449. {"tag", "first", "", ""},
  1450. {"other", "x", "", ""},
  1451. {"tag", "second", "", ""},
  1452. };
  1453. Client cli(HOST, port);
  1454. auto res = cli.Post("/repeated", items);
  1455. ASSERT_TRUE(res);
  1456. ASSERT_EQ(2U, values.size());
  1457. EXPECT_EQ("first", values[0]);
  1458. EXPECT_EQ("second", values[1]);
  1459. EXPECT_EQ("first", first);
  1460. EXPECT_EQ("second", second);
  1461. // std::multimap already kept entries sharing a name in insertion order, so
  1462. // everything above passes without this change too. The whole traversal is
  1463. // what tells the two apart: sorting by name would hoist "other" to the front
  1464. // and the two "tag" parts would end up adjacent.
  1465. EXPECT_EQ("tag=first other=x tag=second ", order);
  1466. // Advancing past the last entry of a name used to run off the container;
  1467. // the container's saturating increment makes it return the default instead.
  1468. EXPECT_EQ("", out_of_range);
  1469. }
  1470. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1471. Server svr;
  1472. std::string file_names;
  1473. svr.Post("/upload", [&](const Request &req, Response &res) {
  1474. for (const auto &file : req.form.files) {
  1475. file_names += file.first + "|" + file.second.filename + " ";
  1476. }
  1477. res.set_content("ok", "text/plain");
  1478. });
  1479. auto port = svr.bind_to_any_port(HOST);
  1480. thread t = thread([&] { svr.listen_after_bind(); });
  1481. auto se = detail::scope_exit([&] {
  1482. svr.stop();
  1483. t.join();
  1484. ASSERT_FALSE(svr.is_running());
  1485. });
  1486. svr.wait_until_ready();
  1487. // A trailing backslash would otherwise escape the closing quote.
  1488. UploadFormDataItems items = {
  1489. {"dir\\", "x", "a.txt", "text/plain"},
  1490. {"b", "y", "a\\\\b.txt", "text/plain"},
  1491. };
  1492. Client cli(HOST, port);
  1493. auto res = cli.Post("/upload", items);
  1494. ASSERT_TRUE(res);
  1495. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1496. }
  1497. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1498. // Server::read_content() keeps a FormFields::iterator alive across the
  1499. // content callbacks that fill the part it points at. The container is
  1500. // vector-backed, so a later emplace can reallocate and invalidate an older
  1501. // iterator; 64 parts grow the vector through seven reallocations, which
  1502. // checks that every part's content still lands in its own entry.
  1503. const size_t part_count = 64;
  1504. // One formula for both the parts sent and the values expected back, so the
  1505. // two cannot drift apart.
  1506. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1507. auto content_of = [](size_t i) {
  1508. return std::string(64, static_cast<char>('a' + (i % 26)));
  1509. };
  1510. Server svr;
  1511. std::vector<std::pair<std::string, std::string>> received;
  1512. svr.Post("/many", [&](const Request &req, Response &res) {
  1513. for (const auto &field : req.form.fields) {
  1514. received.emplace_back(field.first, field.second.content);
  1515. }
  1516. res.set_content("ok", "text/plain");
  1517. });
  1518. auto port = svr.bind_to_any_port(HOST);
  1519. thread t = thread([&] { svr.listen_after_bind(); });
  1520. auto se = detail::scope_exit([&] {
  1521. svr.stop();
  1522. t.join();
  1523. ASSERT_FALSE(svr.is_running());
  1524. });
  1525. svr.wait_until_ready();
  1526. UploadFormDataItems items;
  1527. for (size_t i = 0; i < part_count; i++) {
  1528. items.push_back({name_of(i), content_of(i), "", ""});
  1529. }
  1530. Client cli(HOST, port);
  1531. auto res = cli.Post("/many", items);
  1532. ASSERT_TRUE(res);
  1533. ASSERT_EQ(part_count, received.size());
  1534. for (size_t i = 0; i < part_count; i++) {
  1535. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1536. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1537. }
  1538. }
  1539. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1540. string content_type = "multipart/form-data; boundary=something";
  1541. string boundary;
  1542. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1543. EXPECT_TRUE(ret);
  1544. EXPECT_EQ(boundary, "something");
  1545. }
  1546. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1547. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1548. string boundary;
  1549. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1550. EXPECT_TRUE(ret);
  1551. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1552. }
  1553. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1554. string content_type =
  1555. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1556. string boundary;
  1557. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1558. EXPECT_TRUE(ret);
  1559. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1560. }
  1561. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1562. string content_type =
  1563. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1564. string boundary;
  1565. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1566. EXPECT_TRUE(ret);
  1567. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1568. }
  1569. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1570. const string boundary(70, 'a');
  1571. string content_type = "multipart/form-data; boundary=" + boundary;
  1572. string parsed;
  1573. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1574. EXPECT_TRUE(ret);
  1575. EXPECT_EQ(parsed, boundary);
  1576. }
  1577. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1578. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1579. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1580. string parsed;
  1581. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1582. EXPECT_FALSE(ret);
  1583. }
  1584. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1585. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1586. // is 72 characters on the wire and still valid.
  1587. const string boundary(70, 'a');
  1588. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1589. string parsed;
  1590. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1591. EXPECT_EQ(parsed, boundary);
  1592. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1593. parsed.clear();
  1594. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1595. }
  1596. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1597. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1598. // The parameter parser must not treat that '=' as the key/value separator.
  1599. string content_type =
  1600. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1601. "charset=UTF-8";
  1602. string parsed;
  1603. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1604. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1605. }
  1606. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1607. // A ';' inside the quoted-string is part of the value, not a parameter
  1608. // separator, so it must not truncate the boundary.
  1609. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1610. string parsed;
  1611. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1612. EXPECT_EQ(parsed, "a;b");
  1613. }
  1614. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1615. string parsed;
  1616. EXPECT_TRUE(detail::parse_multipart_boundary(
  1617. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1618. EXPECT_EQ("a\\b", parsed);
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1621. EXPECT_EQ("a\"b", parsed);
  1622. }
  1623. TEST(ParseDispositionParamsTest, QuotedValues) {
  1624. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1625. // ';' and '=' are ordinary characters inside one.
  1626. struct {
  1627. const char *value;
  1628. std::vector<std::pair<const char *, const char *>> expected;
  1629. } cases[] = {
  1630. {"name=\"file1\"; filename=\"a.txt\"",
  1631. {{"name", "file1"}, {"filename", "a.txt"}}},
  1632. // Whitespace around '=' and ';' is still trimmed
  1633. {"name=\"file2\" ;filename = \"a.html\"",
  1634. {{"name", "file2"}, {"filename", "a.html"}}},
  1635. // '=' inside the value used to leave only the text after the last one
  1636. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1637. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1638. {"name=\"x=y\"", {{"name", "x=y"}}},
  1639. // ';' inside the value used to truncate the pair and leave a bogus one
  1640. {"name=\"file3\"; filename=\"a;b.txt\"",
  1641. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1642. // An unquoted value keeps working, and so does filename*
  1643. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1644. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1645. // A parameter with no key is dropped rather than turned into one whose
  1646. // key is the value
  1647. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1648. // An escaped quote does not end the value
  1649. {"name=\"a\\\"; filename=evil.php\"",
  1650. {{"name", "a\"; filename=evil.php"}}},
  1651. // Other backslashes, as in a Windows path, are kept
  1652. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1653. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1654. };
  1655. for (const auto &c : cases) {
  1656. Params params;
  1657. detail::parse_disposition_params(c.value, params);
  1658. for (const auto &kv : c.expected) {
  1659. auto it = params.find(kv.first);
  1660. ASSERT_NE(it, params.end())
  1661. << "value: " << c.value << ", key: " << kv.first;
  1662. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1663. }
  1664. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1665. }
  1666. }
  1667. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1668. Server svr;
  1669. std::string filename;
  1670. std::string content;
  1671. svr.Post("/upload", [&](const Request &req, Response &) {
  1672. const auto &file = req.form.get_file("file");
  1673. filename = file.filename;
  1674. content = file.content;
  1675. });
  1676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1677. auto se = detail::scope_exit([&] {
  1678. svr.stop();
  1679. thread.join();
  1680. ASSERT_FALSE(svr.is_running());
  1681. });
  1682. svr.wait_until_ready();
  1683. std::string body = "--B\r\n"
  1684. "Content-Disposition: form-data; name=\"file\"; "
  1685. "filename=\"a.txt\"\r\n"
  1686. "Content-Type: text/plain\r\n"
  1687. "\r\n"
  1688. "hello\r\n"
  1689. "--B--\r\n";
  1690. Client cli(HOST, PORT);
  1691. auto res = cli.Post(
  1692. "/upload",
  1693. [&](size_t offset, DataSink &sink) {
  1694. if (offset < body.size()) {
  1695. sink.write(&body[offset], 1);
  1696. } else {
  1697. sink.done();
  1698. }
  1699. return true;
  1700. },
  1701. "multipart/form-data; boundary=B");
  1702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1703. EXPECT_EQ(StatusCode::OK_200, res->status);
  1704. EXPECT_EQ("a.txt", filename);
  1705. EXPECT_EQ("hello", content);
  1706. }
  1707. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1708. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1709. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1710. Server svr;
  1711. std::string field_value, file_name, file_filename;
  1712. bool has_field = false, has_file = false;
  1713. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1714. has_field = req.form.has_field("x=y");
  1715. field_value = req.form.get_field("x=y");
  1716. has_file = req.form.has_file("file1");
  1717. const auto &file = req.form.get_file("file1");
  1718. file_name = file.name;
  1719. file_filename = file.filename;
  1720. res.set_content("ok", "text/plain");
  1721. });
  1722. auto port = svr.bind_to_any_port(HOST);
  1723. thread t = thread([&] { svr.listen_after_bind(); });
  1724. auto se = detail::scope_exit([&] {
  1725. svr.stop();
  1726. t.join();
  1727. ASSERT_FALSE(svr.is_running());
  1728. });
  1729. svr.wait_until_ready();
  1730. UploadFormDataItems items = {
  1731. {"x=y", "field-value", "", ""},
  1732. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1733. };
  1734. Client cli(HOST, port);
  1735. auto res = cli.Post("/quoted", items);
  1736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1737. ASSERT_EQ(StatusCode::OK_200, res->status);
  1738. EXPECT_TRUE(has_field);
  1739. EXPECT_EQ("field-value", field_value);
  1740. EXPECT_TRUE(has_file);
  1741. EXPECT_EQ("file1", file_name);
  1742. EXPECT_EQ("a;b=report.pdf", file_filename);
  1743. }
  1744. TEST(GetHeaderValueTest, DefaultValue) {
  1745. Headers headers = {{"Dummy", "Dummy"}};
  1746. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1747. EXPECT_STREQ("text/plain", val);
  1748. }
  1749. TEST(GetHeaderValueTest, DefaultValueInt) {
  1750. Headers headers = {{"Dummy", "Dummy"}};
  1751. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1752. EXPECT_EQ(100ull, val);
  1753. }
  1754. TEST(GetHeaderValueTest, RegularValue) {
  1755. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1756. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1757. EXPECT_STREQ("text/html", val);
  1758. }
  1759. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1760. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1761. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1762. EXPECT_STREQ("text/html", val);
  1763. }
  1764. TEST(GetHeaderValueTest, SetContent) {
  1765. Response res;
  1766. res.set_content("html", "text/html");
  1767. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1768. res.set_content("text", "text/plain");
  1769. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1770. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1771. }
  1772. TEST(GetHeaderValueTest, RegularValueInt) {
  1773. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1774. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1775. EXPECT_EQ(100ull, val);
  1776. }
  1777. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1778. Headers headers = {{"Content-Length", "x"}};
  1779. auto is_invalid_value = false;
  1780. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1781. is_invalid_value);
  1782. EXPECT_EQ(0ull, val);
  1783. EXPECT_TRUE(is_invalid_value);
  1784. }
  1785. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1786. // An all-digit value that overflows size_t must be reported as invalid, not
  1787. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1788. // a large length to a small one on 32-bit builds, leaving the framing length
  1789. // wrong while is_invalid_value stayed false.
  1790. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1791. auto is_invalid_value = false;
  1792. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1793. is_invalid_value);
  1794. EXPECT_TRUE(is_invalid_value);
  1795. // A well-formed length is unaffected.
  1796. Headers ok = {{"Content-Length", "1234"}};
  1797. is_invalid_value = false;
  1798. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1799. is_invalid_value);
  1800. EXPECT_EQ(1234ull, val);
  1801. EXPECT_FALSE(is_invalid_value);
  1802. }
  1803. TEST(GetHeaderValueTest, Range) {
  1804. {
  1805. Headers headers = {make_range_header({{1, -1}})};
  1806. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1807. EXPECT_STREQ("bytes=1-", val);
  1808. }
  1809. {
  1810. Headers headers = {make_range_header({{-1, 1}})};
  1811. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1812. EXPECT_STREQ("bytes=-1", val);
  1813. }
  1814. {
  1815. Headers headers = {make_range_header({{1, 10}})};
  1816. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1817. EXPECT_STREQ("bytes=1-10", val);
  1818. }
  1819. {
  1820. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1821. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1822. EXPECT_STREQ("bytes=1-10, 100-", val);
  1823. }
  1824. {
  1825. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1826. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1827. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1828. }
  1829. {
  1830. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1831. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1832. EXPECT_STREQ("bytes=0-0, -1", val);
  1833. }
  1834. }
  1835. TEST(BearerTokenAuthTest, SchemeValidation) {
  1836. // A value shorter than "Bearer " must not throw from the fixed-length
  1837. // substr, and a non-Bearer scheme must not be reported as a token.
  1838. struct {
  1839. const char *value;
  1840. const char *expected;
  1841. } cases[] = {
  1842. {"x", ""},
  1843. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1844. {"Bearer abc123", "abc123"},
  1845. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1846. };
  1847. for (const auto &c : cases) {
  1848. Request req;
  1849. req.set_header("Authorization", c.value);
  1850. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1851. }
  1852. }
  1853. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1854. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1855. // to depend on the standard library (libstdc++ handed back duplicates in
  1856. // reverse insertion order, libc++ in insertion order).
  1857. Request req;
  1858. req.set_header("Accept-Encoding", "gzip");
  1859. req.set_header("Accept-Encoding", "deflate");
  1860. req.set_header("Accept-Encoding", "br");
  1861. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1862. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1863. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1864. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1865. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1866. }
  1867. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1868. Request req;
  1869. req.set_header("X-Test", "only");
  1870. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1871. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1872. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1873. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1874. }
  1875. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1876. Request req;
  1877. req.set_header("X-First", "1");
  1878. req.set_header("X-Test", "2");
  1879. req.params.emplace("first", "1");
  1880. req.params.emplace("test", "2");
  1881. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1882. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1883. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1884. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1885. // The second one is negative when read as a signed value
  1886. const auto max_id = (std::numeric_limits<size_t>::max)();
  1887. for (auto id : {max_id / 2, max_id}) {
  1888. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1889. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1890. EXPECT_EQ("", req.get_param_value("test", id));
  1891. EXPECT_EQ("", req.form.get_field("test", id));
  1892. EXPECT_EQ("", req.form.get_file("test", id).content);
  1893. }
  1894. }
  1895. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1896. Headers headers;
  1897. headers.emplace("Host", "example.com");
  1898. headers.emplace("Accept-Encoding", "gzip");
  1899. headers.emplace("User-Agent", "test");
  1900. headers.emplace("Accept-Encoding", "deflate");
  1901. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1902. "Accept-Encoding=deflate ",
  1903. entries_to_string(headers));
  1904. }
  1905. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1906. Headers headers = {{"Content-Type", "text/html"},
  1907. {"CONTENT-TYPE", "text/xml"}};
  1908. EXPECT_EQ(2U, headers.count("content-type"));
  1909. auto it = headers.find("content-type");
  1910. ASSERT_TRUE(it != headers.end());
  1911. EXPECT_EQ("text/html", it->second);
  1912. }
  1913. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1914. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1915. // drop only those fields and leave everything positioned between them.
  1916. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1917. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1918. auto rng = headers.equal_range("a");
  1919. headers.erase(rng.first, rng.second);
  1920. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1921. }
  1922. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1923. Headers headers = {
  1924. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1925. EXPECT_EQ(3U, headers.erase("A"));
  1926. EXPECT_EQ(0U, headers.count("A"));
  1927. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1928. }
  1929. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1930. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1931. headers.emplace_front("Host", "example.com");
  1932. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1933. entries_to_string(headers));
  1934. }
  1935. TEST(ParseHeaderValueTest, Range) {
  1936. {
  1937. Ranges ranges;
  1938. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1939. EXPECT_TRUE(ret);
  1940. EXPECT_EQ(1u, ranges.size());
  1941. EXPECT_EQ(1u, ranges[0].first);
  1942. EXPECT_EQ(-1, ranges[0].second);
  1943. }
  1944. {
  1945. Ranges ranges;
  1946. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1947. EXPECT_TRUE(ret);
  1948. EXPECT_EQ(1u, ranges.size());
  1949. EXPECT_EQ(-1, ranges[0].first);
  1950. EXPECT_EQ(1u, ranges[0].second);
  1951. }
  1952. {
  1953. Ranges ranges;
  1954. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1955. EXPECT_TRUE(ret);
  1956. EXPECT_EQ(1u, ranges.size());
  1957. EXPECT_EQ(1u, ranges[0].first);
  1958. EXPECT_EQ(10u, ranges[0].second);
  1959. }
  1960. {
  1961. Ranges ranges;
  1962. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1963. EXPECT_FALSE(ret);
  1964. }
  1965. {
  1966. Ranges ranges;
  1967. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1968. EXPECT_TRUE(ret);
  1969. EXPECT_EQ(2u, ranges.size());
  1970. EXPECT_EQ(1u, ranges[0].first);
  1971. EXPECT_EQ(10u, ranges[0].second);
  1972. EXPECT_EQ(100u, ranges[1].first);
  1973. EXPECT_EQ(-1, ranges[1].second);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. auto ret =
  1978. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1979. EXPECT_TRUE(ret);
  1980. EXPECT_EQ(3u, ranges.size());
  1981. EXPECT_EQ(1u, ranges[0].first);
  1982. EXPECT_EQ(10u, ranges[0].second);
  1983. EXPECT_EQ(100u, ranges[1].first);
  1984. EXPECT_EQ(200u, ranges[1].second);
  1985. EXPECT_EQ(300u, ranges[2].first);
  1986. EXPECT_EQ(400u, ranges[2].second);
  1987. }
  1988. {
  1989. Ranges ranges;
  1990. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2003. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2004. EXPECT_FALSE(
  2005. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2006. EXPECT_TRUE(ranges.empty());
  2007. }
  2008. {
  2009. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2010. // remainder of the representation, so it stays accepted.
  2011. Ranges ranges;
  2012. auto ret =
  2013. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2014. EXPECT_TRUE(ret);
  2015. ASSERT_EQ(1u, ranges.size());
  2016. EXPECT_EQ(0, ranges[0].first);
  2017. EXPECT_EQ(-1, ranges[0].second);
  2018. }
  2019. // RFC 9110 14.1: range unit names are case-insensitive.
  2020. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2021. Ranges ranges;
  2022. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2023. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2024. }
  2025. }
  2026. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2027. Request req;
  2028. req.set_header("Accept-Encoding", "gzip");
  2029. Response res;
  2030. res.set_header("Content-Type", "text/plain");
  2031. auto ret = detail::encoding_type(req, res);
  2032. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2033. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2034. #else
  2035. EXPECT_TRUE(ret == detail::EncodingType::None);
  2036. #endif
  2037. }
  2038. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2039. Request req;
  2040. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2041. Response res;
  2042. res.set_header("Content-Type", "text/plain");
  2043. auto ret = detail::encoding_type(req, res);
  2044. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2046. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2048. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2050. #else
  2051. EXPECT_TRUE(ret == detail::EncodingType::None);
  2052. #endif
  2053. }
  2054. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2055. Request req;
  2056. req.set_header("Accept-Encoding",
  2057. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2058. Response res;
  2059. res.set_header("Content-Type", "text/plain");
  2060. auto ret = detail::encoding_type(req, res);
  2061. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2063. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2065. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2067. #else
  2068. EXPECT_TRUE(ret == detail::EncodingType::None);
  2069. #endif
  2070. }
  2071. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2072. // All supported encodings rejected with q=0 should return None
  2073. Request req;
  2074. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2075. Response res;
  2076. res.set_header("Content-Type", "text/plain");
  2077. auto ret = detail::encoding_type(req, res);
  2078. EXPECT_TRUE(ret == detail::EncodingType::None);
  2079. }
  2080. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2081. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2082. Request req;
  2083. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2084. Response res;
  2085. res.set_header("Content-Type", "text/plain");
  2086. auto ret = detail::encoding_type(req, res);
  2087. EXPECT_TRUE(ret == detail::EncodingType::None);
  2088. }
  2089. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2092. Response res;
  2093. res.set_header("Content-Type", "text/plain");
  2094. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2095. }
  2096. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2097. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2098. Request req;
  2099. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2100. Response res;
  2101. res.set_header("Content-Type", "text/plain");
  2102. auto ret = detail::encoding_type(req, res);
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. }
  2105. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2106. // RFC 7231: Accept-Encoding values are case-insensitive
  2107. Request req;
  2108. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2109. Response res;
  2110. res.set_header("Content-Type", "text/plain");
  2111. auto ret = detail::encoding_type(req, res);
  2112. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2113. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2114. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2116. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2118. #else
  2119. EXPECT_TRUE(ret == detail::EncodingType::None);
  2120. #endif
  2121. }
  2122. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2123. // q value should determine priority, not hardcoded order
  2124. Request req;
  2125. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2126. Response res;
  2127. res.set_header("Content-Type", "text/plain");
  2128. auto ret = detail::encoding_type(req, res);
  2129. // gzip has highest q=1.0, so it should be selected even though
  2130. // br and zstd are also supported
  2131. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2132. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2133. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2135. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2137. #else
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. #endif
  2140. }
  2141. TEST(BufferStreamTest, read) {
  2142. detail::BufferStream strm1;
  2143. Stream &strm = strm1;
  2144. EXPECT_EQ(5, strm.write("hello"));
  2145. char buf[512];
  2146. EXPECT_EQ(2, strm.read(buf, 2));
  2147. EXPECT_EQ('h', buf[0]);
  2148. EXPECT_EQ('e', buf[1]);
  2149. EXPECT_EQ(2, strm.read(buf, 2));
  2150. EXPECT_EQ('l', buf[0]);
  2151. EXPECT_EQ('l', buf[1]);
  2152. EXPECT_EQ(1, strm.read(buf, 1));
  2153. EXPECT_EQ('o', buf[0]);
  2154. EXPECT_EQ(0, strm.read(buf, 1));
  2155. }
  2156. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2157. auto host = "www.httpwatch.com";
  2158. auto ip = hosted_at(host);
  2159. EXPECT_EQ("23.96.13.243", ip);
  2160. std::vector<std::string> addrs;
  2161. hosted_at(host, addrs);
  2162. EXPECT_EQ(1u, addrs.size());
  2163. }
  2164. #if 0 // It depends on each test environment...
  2165. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2166. auto host = "www.youtube.com";
  2167. std::vector<std::string> addrs;
  2168. hosted_at(host, addrs);
  2169. EXPECT_EQ(20u, addrs.size());
  2170. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2171. EXPECT_TRUE(it != addrs.end());
  2172. }
  2173. #endif
  2174. class ChunkedEncodingTest : public ::testing::Test {
  2175. protected:
  2176. ChunkedEncodingTest()
  2177. : cli_(HOST, PORT)
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. ,
  2180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2181. #endif
  2182. {
  2183. cli_.set_connection_timeout(2);
  2184. #ifdef CPPHTTPLIB_SSL_ENABLED
  2185. cli_.enable_server_certificate_verification(false);
  2186. #endif
  2187. }
  2188. virtual void SetUp() {
  2189. read_file("./image.jpg", image_data_);
  2190. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2191. res.set_content("Hello World!", "text/plain");
  2192. });
  2193. svr_.Get(
  2194. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2195. res.set_chunked_content_provider(
  2196. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2197. size_t remaining = image_data_.size() - offset;
  2198. if (remaining == 0) {
  2199. sink.done();
  2200. } else {
  2201. constexpr size_t CHUNK_SIZE = 1024;
  2202. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2203. sink.write(&image_data_[offset], send_size);
  2204. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2205. }
  2206. return true;
  2207. });
  2208. });
  2209. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2210. svr_.wait_until_ready();
  2211. }
  2212. virtual void TearDown() {
  2213. svr_.stop();
  2214. if (!request_threads_.empty()) {
  2215. std::this_thread::sleep_for(std::chrono::seconds(1));
  2216. for (auto &t : request_threads_) {
  2217. t.join();
  2218. }
  2219. }
  2220. t_.join();
  2221. }
  2222. #ifdef CPPHTTPLIB_SSL_ENABLED
  2223. SSLClient cli_;
  2224. SSLServer svr_;
  2225. #else
  2226. Client cli_;
  2227. Server svr_;
  2228. #endif
  2229. thread t_;
  2230. std::vector<thread> request_threads_;
  2231. std::string image_data_;
  2232. };
  2233. TEST_F(ChunkedEncodingTest, NormalGet) {
  2234. auto res = cli_.Get("/chunked");
  2235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2236. std::string out;
  2237. read_file("./image.jpg", out);
  2238. EXPECT_EQ(StatusCode::OK_200, res->status);
  2239. EXPECT_EQ(out, res->body);
  2240. }
  2241. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2242. std::string body;
  2243. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2244. body.append(data, data_length);
  2245. return true;
  2246. });
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. std::string out;
  2249. read_file("./image.jpg", out);
  2250. EXPECT_EQ(StatusCode::OK_200, res->status);
  2251. EXPECT_EQ(out, body);
  2252. }
  2253. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2254. std::string body;
  2255. auto res = cli_.Get(
  2256. "/chunked",
  2257. [&](const Response &response) {
  2258. EXPECT_EQ(StatusCode::OK_200, response.status);
  2259. return true;
  2260. },
  2261. [&](const char *data, size_t data_length) {
  2262. body.append(data, data_length);
  2263. return true;
  2264. });
  2265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2266. std::string out;
  2267. read_file("./image.jpg", out);
  2268. EXPECT_EQ(StatusCode::OK_200, res->status);
  2269. EXPECT_EQ(out, body);
  2270. }
  2271. TEST(RangeTest, FromHTTPBin_Online) {
  2272. auto host = "httpbingo.org";
  2273. auto path = std::string{"/range/32"};
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. auto port = 443;
  2276. SSLClient cli(host, port);
  2277. #else
  2278. auto port = 80;
  2279. Client cli(host, port);
  2280. #endif
  2281. cli.set_connection_timeout(5);
  2282. {
  2283. auto res = cli.Get(path);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2286. EXPECT_EQ(StatusCode::OK_200, res->status);
  2287. }
  2288. {
  2289. Headers headers = {make_range_header({{1, -1}})};
  2290. auto res = cli.Get(path, headers);
  2291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2292. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2294. }
  2295. {
  2296. Headers headers = {make_range_header({{1, 10}})};
  2297. auto res = cli.Get(path, headers);
  2298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2299. EXPECT_EQ("bcdefghijk", res->body);
  2300. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2301. }
  2302. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2303. // entire resource, while the original httpbin returned 200. Both are
  2304. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2305. {
  2306. Headers headers = {make_range_header({{0, 31}})};
  2307. auto res = cli.Get(path, headers);
  2308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2309. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2310. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2311. res->status == StatusCode::PartialContent_206);
  2312. }
  2313. {
  2314. Headers headers = {make_range_header({{0, -1}})};
  2315. auto res = cli.Get(path, headers);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2318. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2319. res->status == StatusCode::PartialContent_206);
  2320. }
  2321. // go-httpbin returns 206 with clamped range for over-range requests,
  2322. // while the original httpbin returned 416. Both behaviors are observed
  2323. // in real servers, so we only verify the request succeeds.
  2324. {
  2325. Headers headers = {make_range_header({{0, 32}})};
  2326. auto res = cli.Get(path, headers);
  2327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2328. }
  2329. }
  2330. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2331. auto host = "unresolvableaddress.local";
  2332. auto path = std::string{"/"};
  2333. #ifdef CPPHTTPLIB_SSL_ENABLED
  2334. auto port = 443;
  2335. SSLClient cli(host, port);
  2336. #else
  2337. auto port = 80;
  2338. Client cli(host, port);
  2339. #endif
  2340. cli.set_connection_timeout(1);
  2341. {
  2342. auto res = cli.Get(path);
  2343. ASSERT_FALSE(res);
  2344. }
  2345. std::this_thread::sleep_for(std::chrono::seconds(8));
  2346. }
  2347. #if defined(__linux__) && defined(__GLIBC__) && \
  2348. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2349. // Forward declaration: in split builds split.py strips `inline` and moves the
  2350. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2351. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2352. // against the symbol in both header-only and split builds.
  2353. namespace httplib {
  2354. namespace detail {
  2355. int getaddrinfo_with_timeout(const char *node, const char *service,
  2356. const struct addrinfo *hints,
  2357. struct addrinfo **res, time_t timeout_sec);
  2358. } // namespace detail
  2359. } // namespace httplib
  2360. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2361. //
  2362. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2363. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2364. // gai_suspend() call hits the connection timeout the function calls
  2365. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2366. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2367. // still alive and still references the now-destroyed stack frame.
  2368. //
  2369. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2370. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2371. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2372. // and runs them in a container.
  2373. namespace {
  2374. bool should_run_issue_2431_tests() {
  2375. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2376. return v && *v && std::string(v) != "0";
  2377. }
  2378. std::string unique_unresolvable_host(int n) {
  2379. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2380. // glibc still asks the configured nameserver — which is exactly the path
  2381. // we want to exercise. A unique label per call avoids the resolver cache.
  2382. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2383. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2384. std::to_string(n) + ".invalid";
  2385. }
  2386. } // namespace
  2387. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2388. if (!should_run_issue_2431_tests()) {
  2389. GTEST_SKIP()
  2390. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2391. }
  2392. for (int i = 0; i < 8; ++i) {
  2393. struct addrinfo hints;
  2394. memset(&hints, 0, sizeof(hints));
  2395. hints.ai_family = AF_UNSPEC;
  2396. hints.ai_socktype = SOCK_STREAM;
  2397. auto host = unique_unresolvable_host(i);
  2398. struct addrinfo *result = nullptr;
  2399. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2400. &result, /*timeout_sec=*/1);
  2401. if (rc == 0 && result) { freeaddrinfo(result); }
  2402. }
  2403. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2404. // stack region they still believe holds their gaicb.
  2405. std::this_thread::sleep_for(std::chrono::seconds(3));
  2406. }
  2407. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2408. if (!should_run_issue_2431_tests()) {
  2409. GTEST_SKIP()
  2410. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2411. }
  2412. std::atomic<bool> stop{false};
  2413. std::vector<std::thread> threads;
  2414. for (int t = 0; t < 8; ++t) {
  2415. threads.emplace_back([t, &stop] {
  2416. int i = 0;
  2417. while (!stop.load(std::memory_order_relaxed)) {
  2418. struct addrinfo hints;
  2419. memset(&hints, 0, sizeof(hints));
  2420. hints.ai_family = AF_UNSPEC;
  2421. hints.ai_socktype = SOCK_STREAM;
  2422. auto host = unique_unresolvable_host(t * 100000 + i++);
  2423. struct addrinfo *result = nullptr;
  2424. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2425. &result, /*timeout_sec=*/1);
  2426. if (rc == 0 && result) { freeaddrinfo(result); }
  2427. }
  2428. });
  2429. }
  2430. std::this_thread::sleep_for(std::chrono::seconds(8));
  2431. stop.store(true, std::memory_order_relaxed);
  2432. for (auto &th : threads) {
  2433. th.join();
  2434. }
  2435. std::this_thread::sleep_for(std::chrono::seconds(3));
  2436. }
  2437. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2438. if (!should_run_issue_2431_tests()) {
  2439. GTEST_SKIP()
  2440. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2441. }
  2442. std::atomic<bool> stop{false};
  2443. std::vector<std::thread> threads;
  2444. for (int t = 0; t < 8; ++t) {
  2445. threads.emplace_back([t, &stop] {
  2446. int i = 0;
  2447. while (!stop.load(std::memory_order_relaxed)) {
  2448. auto host = unique_unresolvable_host(t * 100000 + i++);
  2449. Client cli(host, 80);
  2450. cli.set_connection_timeout(1, 0);
  2451. cli.set_read_timeout(1, 0);
  2452. cli.set_write_timeout(1, 0);
  2453. (void)cli.Get("/");
  2454. }
  2455. });
  2456. }
  2457. std::this_thread::sleep_for(std::chrono::seconds(8));
  2458. stop.store(true, std::memory_order_relaxed);
  2459. for (auto &th : threads) {
  2460. th.join();
  2461. }
  2462. std::this_thread::sleep_for(std::chrono::seconds(3));
  2463. }
  2464. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2465. TEST(ConnectionErrorTest, InvalidHost) {
  2466. auto host = "-abcde.com";
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. auto port = 443;
  2469. SSLClient cli(host, port);
  2470. #else
  2471. auto port = 80;
  2472. Client cli(host, port);
  2473. #endif
  2474. cli.set_connection_timeout(std::chrono::seconds(2));
  2475. auto res = cli.Get("/");
  2476. ASSERT_TRUE(!res);
  2477. EXPECT_EQ(Error::Connection, res.error());
  2478. }
  2479. TEST(ConnectionErrorTest, InvalidHost2) {
  2480. auto host = "httpcan.org/";
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. SSLClient cli(host);
  2483. #else
  2484. Client cli(host);
  2485. #endif
  2486. cli.set_connection_timeout(std::chrono::seconds(2));
  2487. auto res = cli.Get("/");
  2488. ASSERT_TRUE(!res);
  2489. EXPECT_EQ(Error::Connection, res.error());
  2490. }
  2491. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2492. auto host = "httpcan.org/";
  2493. #ifdef CPPHTTPLIB_SSL_ENABLED
  2494. SSLClient cli(host);
  2495. #else
  2496. Client cli(host);
  2497. #endif
  2498. cli.set_connection_timeout(std::chrono::seconds(2));
  2499. auto res = cli.Get("/");
  2500. ASSERT_TRUE(!res);
  2501. stringstream s;
  2502. s << "error code: " << res.error();
  2503. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2504. }
  2505. TEST(ConnectionErrorTest, InvalidPort) {
  2506. auto host = "localhost";
  2507. auto port = 44380;
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. SSLClient cli(host, port);
  2510. #else
  2511. Client cli(host, port);
  2512. #endif
  2513. cli.set_connection_timeout(std::chrono::seconds(2));
  2514. auto res = cli.Get("/");
  2515. ASSERT_TRUE(!res);
  2516. EXPECT_TRUE(Error::Connection == res.error() ||
  2517. Error::ConnectionTimeout == res.error());
  2518. }
  2519. TEST(ConnectionErrorTest, Timeout_Online) {
  2520. auto host = "google.com";
  2521. #ifdef CPPHTTPLIB_SSL_ENABLED
  2522. auto port = 44380;
  2523. SSLClient cli(host, port);
  2524. #else
  2525. auto port = 8080;
  2526. Client cli(host, port);
  2527. #endif
  2528. cli.set_connection_timeout(std::chrono::seconds(2));
  2529. // only probe one address type so that the error reason
  2530. // correlates to the timed-out IPv4, not the unsupported
  2531. // IPv6 connection attempt
  2532. cli.set_address_family(AF_INET);
  2533. auto res = cli.Get("/");
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2536. }
  2537. TEST(CancelTest, NoCancel_Online) {
  2538. auto host = "httpbingo.org";
  2539. auto path = std::string{"/range/32"};
  2540. #ifdef CPPHTTPLIB_SSL_ENABLED
  2541. auto port = 443;
  2542. SSLClient cli(host, port);
  2543. #else
  2544. auto port = 80;
  2545. Client cli(host, port);
  2546. #endif
  2547. cli.set_connection_timeout(std::chrono::seconds(5));
  2548. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2550. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2551. EXPECT_EQ(StatusCode::OK_200, res->status);
  2552. }
  2553. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2554. // Use /bytes with a large payload so that the DownloadProgress callback
  2555. // (which only fires for Content-Length responses) is invoked before the
  2556. // entire body is received, giving cancellation a chance to fire.
  2557. auto host = "httpbingo.org";
  2558. auto path = std::string{"/bytes/524288"};
  2559. #ifdef CPPHTTPLIB_SSL_ENABLED
  2560. auto port = 443;
  2561. SSLClient cli(host, port);
  2562. #else
  2563. auto port = 80;
  2564. Client cli(host, port);
  2565. #endif
  2566. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2567. cli.set_connection_timeout(std::chrono::seconds(5));
  2568. ASSERT_TRUE(!res);
  2569. EXPECT_EQ(Error::Canceled, res.error());
  2570. }
  2571. TEST(CancelTest, WithCancelLargePayload_Online) {
  2572. auto host = "httpbingo.org";
  2573. auto path = std::string{"/bytes/524288"};
  2574. #ifdef CPPHTTPLIB_SSL_ENABLED
  2575. auto port = 443;
  2576. SSLClient cli(host, port);
  2577. #else
  2578. auto port = 80;
  2579. Client cli(host, port);
  2580. #endif
  2581. cli.set_connection_timeout(std::chrono::seconds(5));
  2582. uint32_t count = 0;
  2583. auto res =
  2584. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2585. ASSERT_TRUE(!res);
  2586. EXPECT_EQ(Error::Canceled, res.error());
  2587. }
  2588. TEST(CancelTest, NoCancelPost) {
  2589. Server svr;
  2590. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2591. res.set_content("Hello World!", "text/plain");
  2592. });
  2593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2594. auto se = detail::scope_exit([&] {
  2595. svr.stop();
  2596. thread.join();
  2597. ASSERT_FALSE(svr.is_running());
  2598. });
  2599. svr.wait_until_ready();
  2600. Client cli(HOST, PORT);
  2601. cli.set_connection_timeout(std::chrono::seconds(5));
  2602. auto res =
  2603. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2604. "application/json", [](uint64_t, uint64_t) { return true; });
  2605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2606. EXPECT_EQ("Hello World!", res->body);
  2607. EXPECT_EQ(StatusCode::OK_200, res->status);
  2608. }
  2609. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2610. Server svr;
  2611. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2612. res.set_content("Hello World!", "text/plain");
  2613. });
  2614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2615. auto se = detail::scope_exit([&] {
  2616. svr.stop();
  2617. thread.join();
  2618. ASSERT_FALSE(svr.is_running());
  2619. });
  2620. svr.wait_until_ready();
  2621. Client cli(HOST, PORT);
  2622. cli.set_connection_timeout(std::chrono::seconds(5));
  2623. auto res =
  2624. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2625. "application/json", [](uint64_t, uint64_t) { return false; });
  2626. ASSERT_TRUE(!res);
  2627. EXPECT_EQ(Error::Canceled, res.error());
  2628. }
  2629. TEST(CancelTest, WithCancelLargePayloadPost) {
  2630. Server svr;
  2631. svr.set_payload_max_length(200 * 1024 * 1024);
  2632. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2633. res.set_content(LARGE_DATA, "text/plain");
  2634. });
  2635. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2636. auto se = detail::scope_exit([&] {
  2637. svr.stop();
  2638. thread.join();
  2639. ASSERT_FALSE(svr.is_running());
  2640. });
  2641. svr.wait_until_ready();
  2642. Client cli(HOST, PORT);
  2643. cli.set_payload_max_length(200 * 1024 * 1024);
  2644. cli.set_connection_timeout(std::chrono::seconds(5));
  2645. auto res =
  2646. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2647. "application/json", [](uint64_t, uint64_t) { return false; });
  2648. ASSERT_TRUE(!res);
  2649. EXPECT_EQ(Error::Canceled, res.error());
  2650. }
  2651. TEST(CancelTest, NoCancelPut) {
  2652. Server svr;
  2653. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2654. res.set_content("Hello World!", "text/plain");
  2655. });
  2656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2657. auto se = detail::scope_exit([&] {
  2658. svr.stop();
  2659. thread.join();
  2660. ASSERT_FALSE(svr.is_running());
  2661. });
  2662. svr.wait_until_ready();
  2663. Client cli(HOST, PORT);
  2664. cli.set_connection_timeout(std::chrono::seconds(5));
  2665. auto res =
  2666. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2667. "application/json", [](uint64_t, uint64_t) { return true; });
  2668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2669. EXPECT_EQ("Hello World!", res->body);
  2670. EXPECT_EQ(StatusCode::OK_200, res->status);
  2671. }
  2672. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2673. Server svr;
  2674. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2675. res.set_content("Hello World!", "text/plain");
  2676. });
  2677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2678. auto se = detail::scope_exit([&] {
  2679. svr.stop();
  2680. thread.join();
  2681. ASSERT_FALSE(svr.is_running());
  2682. });
  2683. svr.wait_until_ready();
  2684. Client cli(HOST, PORT);
  2685. cli.set_connection_timeout(std::chrono::seconds(5));
  2686. auto res =
  2687. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2688. "application/json", [](uint64_t, uint64_t) { return false; });
  2689. ASSERT_TRUE(!res);
  2690. EXPECT_EQ(Error::Canceled, res.error());
  2691. }
  2692. TEST(CancelTest, WithCancelLargePayloadPut) {
  2693. Server svr;
  2694. svr.set_payload_max_length(200 * 1024 * 1024);
  2695. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2696. res.set_content(LARGE_DATA, "text/plain");
  2697. });
  2698. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2699. auto se = detail::scope_exit([&] {
  2700. svr.stop();
  2701. thread.join();
  2702. ASSERT_FALSE(svr.is_running());
  2703. });
  2704. svr.wait_until_ready();
  2705. Client cli(HOST, PORT);
  2706. cli.set_payload_max_length(200 * 1024 * 1024);
  2707. cli.set_connection_timeout(std::chrono::seconds(5));
  2708. auto res =
  2709. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2710. "application/json", [](uint64_t, uint64_t) { return false; });
  2711. ASSERT_TRUE(!res);
  2712. EXPECT_EQ(Error::Canceled, res.error());
  2713. }
  2714. TEST(CancelTest, NoCancelPatch) {
  2715. Server svr;
  2716. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2717. res.set_content("Hello World!", "text/plain");
  2718. });
  2719. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2720. auto se = detail::scope_exit([&] {
  2721. svr.stop();
  2722. thread.join();
  2723. ASSERT_FALSE(svr.is_running());
  2724. });
  2725. svr.wait_until_ready();
  2726. Client cli(HOST, PORT);
  2727. cli.set_connection_timeout(std::chrono::seconds(5));
  2728. auto res =
  2729. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2730. "application/json", [](uint64_t, uint64_t) { return true; });
  2731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2732. EXPECT_EQ("Hello World!", res->body);
  2733. EXPECT_EQ(StatusCode::OK_200, res->status);
  2734. }
  2735. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2736. Server svr;
  2737. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2738. res.set_content("Hello World!", "text/plain");
  2739. });
  2740. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2741. auto se = detail::scope_exit([&] {
  2742. svr.stop();
  2743. thread.join();
  2744. ASSERT_FALSE(svr.is_running());
  2745. });
  2746. svr.wait_until_ready();
  2747. Client cli(HOST, PORT);
  2748. cli.set_connection_timeout(std::chrono::seconds(5));
  2749. auto res =
  2750. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2751. "application/json", [](uint64_t, uint64_t) { return false; });
  2752. ASSERT_TRUE(!res);
  2753. EXPECT_EQ(Error::Canceled, res.error());
  2754. }
  2755. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2756. Server svr;
  2757. svr.set_payload_max_length(200 * 1024 * 1024);
  2758. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2759. res.set_content(LARGE_DATA, "text/plain");
  2760. });
  2761. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2762. auto se = detail::scope_exit([&] {
  2763. svr.stop();
  2764. thread.join();
  2765. ASSERT_FALSE(svr.is_running());
  2766. });
  2767. svr.wait_until_ready();
  2768. Client cli(HOST, PORT);
  2769. cli.set_payload_max_length(200 * 1024 * 1024);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, NoCancelDelete) {
  2778. Server svr;
  2779. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2780. res.set_content("Hello World!", "text/plain");
  2781. });
  2782. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2783. auto se = detail::scope_exit([&] {
  2784. svr.stop();
  2785. thread.join();
  2786. ASSERT_FALSE(svr.is_running());
  2787. });
  2788. svr.wait_until_ready();
  2789. Client cli(HOST, PORT);
  2790. cli.set_connection_timeout(std::chrono::seconds(5));
  2791. auto res =
  2792. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2793. "application/json", [](uint64_t, uint64_t) { return true; });
  2794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2795. EXPECT_EQ("Hello World!", res->body);
  2796. EXPECT_EQ(StatusCode::OK_200, res->status);
  2797. }
  2798. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2799. Server svr;
  2800. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2801. res.set_content("Hello World!", "text/plain");
  2802. });
  2803. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2804. auto se = detail::scope_exit([&] {
  2805. svr.stop();
  2806. thread.join();
  2807. ASSERT_FALSE(svr.is_running());
  2808. });
  2809. svr.wait_until_ready();
  2810. Client cli(HOST, PORT);
  2811. cli.set_connection_timeout(std::chrono::seconds(5));
  2812. auto res =
  2813. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2814. "application/json", [](uint64_t, uint64_t) { return false; });
  2815. ASSERT_TRUE(!res);
  2816. EXPECT_EQ(Error::Canceled, res.error());
  2817. }
  2818. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2819. Server svr;
  2820. svr.set_payload_max_length(200 * 1024 * 1024);
  2821. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2822. res.set_content(LARGE_DATA, "text/plain");
  2823. });
  2824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2825. auto se = detail::scope_exit([&] {
  2826. svr.stop();
  2827. thread.join();
  2828. ASSERT_FALSE(svr.is_running());
  2829. });
  2830. svr.wait_until_ready();
  2831. Client cli(HOST, PORT);
  2832. cli.set_payload_max_length(200 * 1024 * 1024);
  2833. cli.set_connection_timeout(std::chrono::seconds(5));
  2834. auto res =
  2835. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2836. "application/json", [](uint64_t, uint64_t) { return false; });
  2837. ASSERT_TRUE(!res);
  2838. EXPECT_EQ(Error::Canceled, res.error());
  2839. }
  2840. static std::string remove_whitespace(const std::string &input) {
  2841. std::string output;
  2842. output.reserve(input.size());
  2843. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2844. [](unsigned char c) { return !std::isspace(c); });
  2845. return output;
  2846. }
  2847. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2848. auto host = "httpbingo.org";
  2849. auto path = std::string{"/basic-auth/hello/world"};
  2850. #ifdef CPPHTTPLIB_SSL_ENABLED
  2851. auto port = 443;
  2852. SSLClient cli(host, port);
  2853. #else
  2854. auto port = 80;
  2855. Client cli(host, port);
  2856. #endif
  2857. {
  2858. auto res = cli.Get(path);
  2859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2860. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2861. }
  2862. {
  2863. auto res = cli.Get(
  2864. path, Headers{make_basic_authentication_header("hello", "world")});
  2865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2866. auto body = remove_whitespace(res->body);
  2867. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2868. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. }
  2871. {
  2872. cli.set_basic_auth("hello", "world");
  2873. auto res = cli.Get(path);
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. auto body = remove_whitespace(res->body);
  2876. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2877. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. {
  2881. cli.set_basic_auth("hello", "bad");
  2882. auto res = cli.Get(path);
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2885. }
  2886. {
  2887. cli.set_basic_auth("bad", "world");
  2888. auto res = cli.Get(path);
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2891. }
  2892. }
  2893. #ifdef CPPHTTPLIB_SSL_ENABLED
  2894. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2895. auto host = "httpbingo.org";
  2896. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2897. auto paths = std::vector<std::string>{
  2898. "/digest-auth/auth/hello/world/MD5",
  2899. "/digest-auth/auth/hello/world/SHA-256",
  2900. };
  2901. auto port = 443;
  2902. SSLClient cli(host, port);
  2903. {
  2904. auto res = cli.Get(unauth_path);
  2905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2906. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2907. }
  2908. {
  2909. cli.set_digest_auth("hello", "world");
  2910. for (const auto &path : paths) {
  2911. auto res = cli.Get(path.c_str());
  2912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2913. auto body = remove_whitespace(res->body);
  2914. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2915. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2916. EXPECT_EQ(StatusCode::OK_200, res->status);
  2917. }
  2918. cli.set_digest_auth("hello", "bad");
  2919. for (const auto &path : paths) {
  2920. auto res = cli.Get(path.c_str());
  2921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2922. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2923. }
  2924. }
  2925. }
  2926. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2927. // comma-separated list of challenges, and each challenge may itself carry a
  2928. // comma-separated auth-param list, so a server can legally offer Basic
  2929. // before Digest, either as two field lines or packed into one. Runs one 401
  2930. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2931. // value() joins them in receipt order) and checks that the retry carries a
  2932. // well-formed Digest Authorization header naming expected_realm.
  2933. static void
  2934. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2935. const std::string &expected_realm) {
  2936. std::atomic<int> hits{0};
  2937. Server svr;
  2938. svr.Get("/x", [&](const Request &req, Response &res) {
  2939. if (++hits == 1) {
  2940. res.status = StatusCode::Unauthorized_401;
  2941. for (const auto &challenge : challenges) {
  2942. res.set_header("WWW-Authenticate", challenge);
  2943. }
  2944. } else {
  2945. auto authorization = req.get_header_value("Authorization");
  2946. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2947. EXPECT_NE(std::string::npos,
  2948. authorization.find("realm=\"" + expected_realm + "\""));
  2949. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2950. res.set_content("ok", "text/plain");
  2951. }
  2952. });
  2953. auto port = svr.bind_to_any_port(HOST);
  2954. std::thread t([&]() { svr.listen_after_bind(); });
  2955. auto se = detail::scope_exit([&] {
  2956. svr.stop();
  2957. t.join();
  2958. });
  2959. svr.wait_until_ready();
  2960. Client cli(HOST, port);
  2961. cli.set_digest_auth("hello", "world");
  2962. auto res = cli.Get("/x");
  2963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2964. EXPECT_EQ(2, hits.load());
  2965. }
  2966. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2967. static const char *kDigestChallenge =
  2968. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2969. "algorithm=MD5";
  2970. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2971. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2972. "testrealm");
  2973. }
  2974. // Same challenge list with the schemes in the opposite order, to make sure
  2975. // the fix above didn't just special-case "Basic first".
  2976. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2977. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2978. "testrealm");
  2979. }
  2980. // A comma inside a quoted auth-param value must not be mistaken for the
  2981. // separator between two challenges (or two auth-params).
  2982. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2983. run_digest_challenge_list_test(
  2984. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2985. "algorithm=MD5"},
  2986. "test,realm");
  2987. }
  2988. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2989. // the params and leaves out the fragment.
  2990. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2991. Server svr;
  2992. std::string uri, target;
  2993. svr.Get("/a b", [&](const Request &req, Response &res) {
  2994. auto auth = req.get_header_value("Authorization");
  2995. if (auth.empty()) {
  2996. res.status = StatusCode::Unauthorized_401;
  2997. res.set_header("WWW-Authenticate",
  2998. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2999. return;
  3000. }
  3001. auto b = auth.find("uri=\"") + 5;
  3002. uri = auth.substr(b, auth.find('"', b) - b);
  3003. target = req.target;
  3004. });
  3005. auto port = svr.bind_to_any_port(HOST);
  3006. std::thread t([&]() { svr.listen_after_bind(); });
  3007. auto se = detail::scope_exit([&] {
  3008. svr.stop();
  3009. t.join();
  3010. });
  3011. svr.wait_until_ready();
  3012. Client cli(HOST, port);
  3013. cli.set_digest_auth("hello", "world");
  3014. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ("/a%20b?x=1", target);
  3017. EXPECT_EQ(target, uri);
  3018. }
  3019. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3020. // make_digest_authentication_header() dereferences both unconditionally, so
  3021. // a server sending a challenge missing either one must not be treated as
  3022. // usable -- doing so used to crash the client with std::out_of_range.
  3023. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3024. Server svr;
  3025. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3026. res.status = StatusCode::Unauthorized_401;
  3027. res.set_header("WWW-Authenticate", challenge);
  3028. });
  3029. auto port = svr.bind_to_any_port(HOST);
  3030. std::thread t([&]() { svr.listen_after_bind(); });
  3031. auto se = detail::scope_exit([&] {
  3032. svr.stop();
  3033. t.join();
  3034. });
  3035. svr.wait_until_ready();
  3036. Client cli(HOST, port);
  3037. cli.set_digest_auth("hello", "world");
  3038. auto res = cli.Get("/x");
  3039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3040. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3041. }
  3042. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3043. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3044. }
  3045. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3046. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3047. }
  3048. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3049. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3050. }
  3051. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3052. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3053. // when storing the values, so the header builder has to re-escape them (and
  3054. // keep algorithm a bare token); otherwise the value breaks out of its
  3055. // quoted-string and injects extra auth-params into the client's Authorization.
  3056. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3057. std::atomic<int> hits{0};
  3058. std::string authorization;
  3059. Server svr;
  3060. svr.Get("/x", [&](const Request &req, Response &res) {
  3061. if (++hits == 1) {
  3062. res.status = StatusCode::Unauthorized_401;
  3063. // On the wire the quotes embedded in the values are backslash-escaped.
  3064. res.set_header("WWW-Authenticate",
  3065. "Digest realm=\"testrealm\", "
  3066. "nonce=\"n\\\"; injected=\\\"x\", "
  3067. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3068. } else {
  3069. authorization = req.get_header_value("Authorization");
  3070. res.set_content("ok", "text/plain");
  3071. }
  3072. });
  3073. auto port = svr.bind_to_any_port(HOST);
  3074. std::thread t([&]() { svr.listen_after_bind(); });
  3075. auto se = detail::scope_exit([&] {
  3076. svr.stop();
  3077. t.join();
  3078. });
  3079. svr.wait_until_ready();
  3080. Client cli(HOST, port);
  3081. cli.set_digest_auth("hello", "world");
  3082. auto res = cli.Get("/x");
  3083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3084. EXPECT_EQ(2, hits.load());
  3085. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3086. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3087. // inside its quoted-string rather than starting an "injected" auth-param.
  3088. EXPECT_NE(std::string::npos,
  3089. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3090. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3091. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3092. }
  3093. #endif
  3094. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3095. auto host = "google.com";
  3096. auto another_host = "example.com";
  3097. auto wrong_ip = "0.0.0.0";
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. SSLClient cli(host);
  3100. #else
  3101. Client cli(host);
  3102. #endif
  3103. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3104. auto res = cli.Get("/");
  3105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3106. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3107. }
  3108. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3109. auto host = "google.com";
  3110. auto wrong_ip = "0.0.0.0";
  3111. #ifdef CPPHTTPLIB_SSL_ENABLED
  3112. SSLClient cli(host);
  3113. #else
  3114. Client cli(host);
  3115. #endif
  3116. cli.set_hostname_addr_map({{host, wrong_ip}});
  3117. auto res = cli.Get("/");
  3118. ASSERT_TRUE(!res);
  3119. EXPECT_EQ(Error::Connection, res.error());
  3120. }
  3121. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3122. // A mapped value that is not an IP literal must be resolved. "localhost"
  3123. // resolves from the hosts file, so this test needs no external DNS.
  3124. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3125. auto host = "target.invalid";
  3126. Server svr;
  3127. std::string received_host;
  3128. svr.Get("/hi", [&](const Request &req, Response &res) {
  3129. received_host = req.get_header_value("Host");
  3130. res.set_content("Hello World!", "text/plain");
  3131. });
  3132. auto port = svr.bind_to_any_port(HOST);
  3133. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3134. auto se = detail::scope_exit([&] {
  3135. svr.stop();
  3136. thread.join();
  3137. ASSERT_FALSE(svr.is_running());
  3138. });
  3139. svr.wait_until_ready();
  3140. Client cli(host, port);
  3141. cli.set_hostname_addr_map({{host, HOST}});
  3142. auto res = cli.Get("/hi");
  3143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3144. EXPECT_EQ(StatusCode::OK_200, res->status);
  3145. // The mapping only redirects the connection; the identity stays host_.
  3146. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3147. }
  3148. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3149. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3150. auto host = "target.invalid";
  3151. Server svr;
  3152. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3153. res.set_content("Hello World!", "text/plain");
  3154. });
  3155. auto port = svr.bind_to_any_port("127.0.0.1");
  3156. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3157. auto se = detail::scope_exit([&] {
  3158. svr.stop();
  3159. thread.join();
  3160. ASSERT_FALSE(svr.is_running());
  3161. });
  3162. svr.wait_until_ready();
  3163. Client cli(host, port);
  3164. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3165. auto res = cli.Get("/hi");
  3166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3167. EXPECT_EQ(StatusCode::OK_200, res->status);
  3168. }
  3169. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3170. // An empty mapped value must leave host_ as the connection target. Without
  3171. // that guard the empty value would become the host argument, getaddrinfo
  3172. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3173. // loopback - silently connecting somewhere the caller never asked for.
  3174. // The server listens on loopback, so such a fallback would succeed and is
  3175. // therefore observable as a failure of this test.
  3176. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3177. Server svr;
  3178. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3179. res.set_content("Hello World!", "text/plain");
  3180. });
  3181. auto port = svr.bind_to_any_port(HOST);
  3182. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3183. auto se = detail::scope_exit([&] {
  3184. svr.stop();
  3185. thread.join();
  3186. ASSERT_FALSE(svr.is_running());
  3187. });
  3188. svr.wait_until_ready();
  3189. Client cli(blackhole, port);
  3190. cli.set_hostname_addr_map({{blackhole, ""}});
  3191. cli.set_connection_timeout(1);
  3192. auto res = cli.Get("/hi");
  3193. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3194. }
  3195. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3196. auto host = "httpbingo.org";
  3197. auto path = std::string{"/absolute-redirect/3"};
  3198. #ifdef CPPHTTPLIB_SSL_ENABLED
  3199. SSLClient cli(host);
  3200. #else
  3201. Client cli(host);
  3202. #endif
  3203. cli.set_follow_location(true);
  3204. auto res = cli.Get(path);
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(RedirectTest, Redirect_Online) {
  3209. auto host = "httpbingo.org";
  3210. auto path = std::string{"/redirect/3"};
  3211. #ifdef CPPHTTPLIB_SSL_ENABLED
  3212. SSLClient cli(host);
  3213. #else
  3214. Client cli(host);
  3215. #endif
  3216. cli.set_follow_location(true);
  3217. auto res = cli.Get(path);
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(RelativeRedirectTest, Redirect_Online) {
  3222. auto host = "httpbingo.org";
  3223. auto path = std::string{"/relative-redirect/3"};
  3224. #ifdef CPPHTTPLIB_SSL_ENABLED
  3225. SSLClient cli(host);
  3226. #else
  3227. Client cli(host);
  3228. #endif
  3229. cli.set_follow_location(true);
  3230. auto res = cli.Get(path);
  3231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3232. EXPECT_EQ(StatusCode::OK_200, res->status);
  3233. }
  3234. TEST(TooManyRedirectTest, Redirect_Online) {
  3235. auto host = "httpbingo.org";
  3236. auto path = std::string{"/redirect/21"};
  3237. #ifdef CPPHTTPLIB_SSL_ENABLED
  3238. SSLClient cli(host);
  3239. #else
  3240. Client cli(host);
  3241. #endif
  3242. cli.set_follow_location(true);
  3243. auto res = cli.Get(path);
  3244. ASSERT_TRUE(!res);
  3245. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3246. }
  3247. #ifdef CPPHTTPLIB_SSL_ENABLED
  3248. TEST(YahooRedirectTest, Redirect_Online) {
  3249. Client cli("yahoo.com");
  3250. auto res = cli.Get("/");
  3251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3252. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3253. cli.set_follow_location(true);
  3254. res = cli.Get("/");
  3255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3256. EXPECT_EQ(StatusCode::OK_200, res->status);
  3257. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3258. }
  3259. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3260. #define REDIR_HOST "httpbingo.org"
  3261. #define REDIR_PATH "/redirect-to"
  3262. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3263. SSLClient cli(REDIR_HOST);
  3264. cli.set_follow_location(true);
  3265. auto res =
  3266. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3268. EXPECT_EQ(StatusCode::OK_200, res->status);
  3269. }
  3270. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3271. SSLClient cli(REDIR_HOST);
  3272. cli.set_follow_location(true);
  3273. Params params;
  3274. params.emplace("url", "http://example.com");
  3275. params.emplace("status_code", "302");
  3276. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3278. EXPECT_EQ(StatusCode::OK_200, res->status);
  3279. }
  3280. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3281. SSLClient cli(REDIR_HOST);
  3282. cli.set_follow_location(true);
  3283. Params params;
  3284. params.emplace("url", "http://example.com");
  3285. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. TEST(UrlWithSpace, Redirect_Online) {
  3290. SSLClient cli("edge.forgecdn.net");
  3291. cli.set_follow_location(true);
  3292. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3294. EXPECT_EQ(StatusCode::OK_200, res->status);
  3295. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3296. }
  3297. #endif
  3298. #if !defined(_WIN32) && !defined(_WIN64)
  3299. TEST(ReceiveSignals, Signal) {
  3300. auto setupSignalHandlers = []() {
  3301. struct sigaction act;
  3302. sigemptyset(&act.sa_mask);
  3303. act.sa_flags = SA_SIGINFO;
  3304. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3305. switch (sig) {
  3306. case SIGINT:
  3307. default: break;
  3308. }
  3309. };
  3310. ::sigaction(SIGINT, &act, nullptr);
  3311. };
  3312. Server svr;
  3313. int port = 0;
  3314. auto thread = std::thread([&]() {
  3315. setupSignalHandlers();
  3316. port = svr.bind_to_any_port(HOST);
  3317. svr.listen_after_bind();
  3318. });
  3319. auto se = detail::scope_exit([&] {
  3320. svr.stop();
  3321. thread.join();
  3322. ASSERT_FALSE(svr.is_running());
  3323. });
  3324. svr.wait_until_ready();
  3325. ASSERT_TRUE(svr.is_running());
  3326. pthread_kill(thread.native_handle(), SIGINT);
  3327. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3328. ASSERT_TRUE(svr.is_running());
  3329. }
  3330. #endif
  3331. TEST(RedirectToDifferentPort, Redirect) {
  3332. Server svr1;
  3333. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3334. res.set_content("Hello World!", "text/plain");
  3335. });
  3336. int svr1_port = 0;
  3337. auto thread1 = std::thread([&]() {
  3338. svr1_port = svr1.bind_to_any_port(HOST);
  3339. svr1.listen_after_bind();
  3340. });
  3341. Server svr2;
  3342. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3343. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3344. });
  3345. int svr2_port = 0;
  3346. auto thread2 = std::thread([&]() {
  3347. svr2_port = svr2.bind_to_any_port(HOST);
  3348. svr2.listen_after_bind();
  3349. });
  3350. auto se = detail::scope_exit([&] {
  3351. svr2.stop();
  3352. thread2.join();
  3353. svr1.stop();
  3354. thread1.join();
  3355. ASSERT_FALSE(svr2.is_running());
  3356. ASSERT_FALSE(svr1.is_running());
  3357. });
  3358. svr1.wait_until_ready();
  3359. svr2.wait_until_ready();
  3360. Client cli("localhost", svr2_port);
  3361. cli.set_follow_location(true);
  3362. auto res = cli.Get("/2");
  3363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3364. EXPECT_EQ(StatusCode::OK_200, res->status);
  3365. EXPECT_EQ("Hello World!", res->body);
  3366. }
  3367. // GET /redir on one server redirects to /target on another port, so the
  3368. // client follows it with a new client.
  3369. static Result
  3370. GetThroughRedirectToDifferentPort(Server::Handler target,
  3371. const std::function<void(Client &)> &setup,
  3372. const Headers &headers = Headers()) {
  3373. Server target_svr;
  3374. target_svr.Get("/target", target);
  3375. int target_port = 0;
  3376. auto target_thread = std::thread([&]() {
  3377. target_port = target_svr.bind_to_any_port(HOST);
  3378. target_svr.listen_after_bind();
  3379. });
  3380. Server origin_svr;
  3381. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3382. res.set_redirect(
  3383. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3384. });
  3385. int origin_port = 0;
  3386. auto origin_thread = std::thread([&]() {
  3387. origin_port = origin_svr.bind_to_any_port(HOST);
  3388. origin_svr.listen_after_bind();
  3389. });
  3390. auto se = detail::scope_exit([&] {
  3391. origin_svr.stop();
  3392. origin_thread.join();
  3393. target_svr.stop();
  3394. target_thread.join();
  3395. });
  3396. target_svr.wait_until_ready();
  3397. origin_svr.wait_until_ready();
  3398. Client cli("localhost", origin_port);
  3399. cli.set_follow_location(true);
  3400. setup(cli);
  3401. return cli.Get("/redir", headers);
  3402. }
  3403. static void
  3404. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3405. std::string captured_authorization;
  3406. auto result = GetThroughRedirectToDifferentPort(
  3407. [&](const Request &req, Response &res) {
  3408. captured_authorization = req.get_header_value("Authorization");
  3409. res.set_content("OK", "text/plain");
  3410. },
  3411. set_auth);
  3412. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3413. EXPECT_EQ(StatusCode::OK_200, result->status);
  3414. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3415. EXPECT_TRUE(captured_authorization.empty());
  3416. }
  3417. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3418. TestDoNotForwardCredentialsOnRedirect(
  3419. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3420. }
  3421. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3422. TestDoNotForwardCredentialsOnRedirect(
  3423. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3424. }
  3425. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3426. std::string captured_cookie;
  3427. auto result = GetThroughRedirectToDifferentPort(
  3428. [&](const Request &req, Response &res) {
  3429. captured_cookie = req.get_header_value("Cookie");
  3430. res.set_content("OK", "text/plain");
  3431. },
  3432. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3433. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3434. EXPECT_EQ(StatusCode::OK_200, result->status);
  3435. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3436. EXPECT_TRUE(captured_cookie.empty());
  3437. }
  3438. TEST(RedirectToSamePort, ForwardCookie) {
  3439. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3440. // header so that ordinary session flows keep working.
  3441. Server svr;
  3442. std::string captured_cookie;
  3443. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3444. res.set_redirect("/target", 302);
  3445. });
  3446. svr.Get("/target", [&](const Request &req, Response &res) {
  3447. captured_cookie = req.get_header_value("Cookie");
  3448. res.set_content("OK", "text/plain");
  3449. });
  3450. auto port = svr.bind_to_any_port(HOST);
  3451. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3452. auto se = detail::scope_exit([&] {
  3453. svr.stop();
  3454. thread.join();
  3455. ASSERT_FALSE(svr.is_running());
  3456. });
  3457. svr.wait_until_ready();
  3458. Client cli(HOST, port);
  3459. cli.set_follow_location(true);
  3460. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3461. auto res = cli.Get("/redir", headers);
  3462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3465. }
  3466. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3467. std::string authorization;
  3468. std::string trace_id;
  3469. auto result = GetThroughRedirectToDifferentPort(
  3470. [&](const Request &req, Response &res) {
  3471. authorization = req.get_header_value("Authorization");
  3472. trace_id = req.get_header_value("X-Trace-Id");
  3473. res.set_content("OK", "text/plain");
  3474. },
  3475. [](Client &cli) {
  3476. cli.set_default_headers(
  3477. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3478. });
  3479. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3480. EXPECT_EQ(StatusCode::OK_200, result->status);
  3481. // Like a header given with the request, a default one goes along unless it
  3482. // carries credentials (RFC 9110 15.4).
  3483. EXPECT_TRUE(authorization.empty());
  3484. EXPECT_EQ("42", trace_id);
  3485. }
  3486. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3487. auto result = GetThroughRedirectToDifferentPort(
  3488. [](const Request &, Response &res) {
  3489. res.set_content(std::string(2048, 'x'), "text/plain");
  3490. },
  3491. [](Client &cli) { cli.set_payload_max_length(1024); });
  3492. EXPECT_FALSE(result);
  3493. }
  3494. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3495. auto result = GetThroughRedirectToDifferentPort(
  3496. [](const Request &req, Response &res) {
  3497. // Answer after a second, or once the client gives up.
  3498. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3499. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3500. }
  3501. res.set_content("late", "text/plain");
  3502. },
  3503. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3504. ASSERT_FALSE(result);
  3505. EXPECT_EQ(Error::Read, result.error());
  3506. }
  3507. #ifdef CPPHTTPLIB_SSL_ENABLED
  3508. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3509. auto result = GetThroughRedirectToDifferentPort(
  3510. [](const Request &, Response &res) {
  3511. res.status = StatusCode::Unauthorized_401;
  3512. res.set_header("WWW-Authenticate",
  3513. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3514. },
  3515. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3516. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3517. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3518. }
  3519. #endif
  3520. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3521. Server svr;
  3522. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3523. // Port number that overflows int — should not crash
  3524. res.set_redirect("http://localhost:99999999999999999999/target");
  3525. });
  3526. auto port = svr.bind_to_any_port(HOST);
  3527. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3528. auto se = detail::scope_exit([&] {
  3529. svr.stop();
  3530. thread.join();
  3531. ASSERT_FALSE(svr.is_running());
  3532. });
  3533. svr.wait_until_ready();
  3534. Client cli(HOST, port);
  3535. cli.set_follow_location(true);
  3536. auto res = cli.Get("/redir");
  3537. // Should fail gracefully, not crash (no valid response due to bad port)
  3538. EXPECT_FALSE(res);
  3539. }
  3540. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3541. Server svr;
  3542. auto port = svr.bind_to_any_port(HOST);
  3543. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3544. // The server's own port followed by junk must not be followed
  3545. res.set_redirect("http://" + std::string(HOST) + ":" +
  3546. std::to_string(port) + "junk/target");
  3547. });
  3548. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3549. res.set_content("target", "text/plain");
  3550. });
  3551. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. thread.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. svr.wait_until_ready();
  3558. Client cli(HOST, port);
  3559. cli.set_follow_location(true);
  3560. auto res = cli.Get("/redir");
  3561. EXPECT_FALSE(res);
  3562. }
  3563. TEST(RedirectFromPageWithContent, Redirect) {
  3564. Server svr;
  3565. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3566. res.set_content("___", "text/plain");
  3567. res.set_redirect("/2");
  3568. });
  3569. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3570. res.set_content("Hello World!", "text/plain");
  3571. });
  3572. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3573. auto se = detail::scope_exit([&] {
  3574. svr.stop();
  3575. th.join();
  3576. ASSERT_FALSE(svr.is_running());
  3577. });
  3578. svr.wait_until_ready();
  3579. {
  3580. Client cli("localhost", PORT);
  3581. cli.set_follow_location(true);
  3582. std::string body;
  3583. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3584. body.append(data, data_length);
  3585. return true;
  3586. });
  3587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3588. EXPECT_EQ(StatusCode::OK_200, res->status);
  3589. EXPECT_EQ("Hello World!", body);
  3590. }
  3591. {
  3592. Client cli("localhost", PORT);
  3593. std::string body;
  3594. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3595. body.append(data, data_length);
  3596. return true;
  3597. });
  3598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3599. EXPECT_EQ(StatusCode::Found_302, res->status);
  3600. EXPECT_EQ("___", body);
  3601. }
  3602. }
  3603. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3604. Server svr;
  3605. auto port_str = std::to_string(PORT);
  3606. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3607. auto expected_host = "[::1]:" + port_str;
  3608. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3609. res.set_content("___", "text/plain");
  3610. // res.set_redirect("/2");
  3611. res.set_redirect(redirect_url);
  3612. });
  3613. svr.Get("/2", [&](const Request &req, Response &res) {
  3614. auto host_header = req.headers.find("Host");
  3615. ASSERT_TRUE(host_header != req.headers.end());
  3616. EXPECT_EQ(expected_host, host_header->second);
  3617. res.set_content("Hello World!", "text/plain");
  3618. });
  3619. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3620. auto se = detail::scope_exit([&] {
  3621. svr.stop();
  3622. th.join();
  3623. ASSERT_FALSE(svr.is_running());
  3624. });
  3625. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3626. // actually starts anything, so the condition !svr.is_running() will
  3627. // always remain true, and the loop never stops.
  3628. // This basically counts how many milliseconds have passed since the
  3629. // call to svr.listen(), and if after 5 seconds nothing started yet
  3630. // aborts the test.
  3631. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3632. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3633. ASSERT_LT(milliseconds, 5000U);
  3634. }
  3635. {
  3636. Client cli("::1", PORT);
  3637. cli.set_follow_location(true);
  3638. std::string body;
  3639. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3640. body.append(data, data_length);
  3641. return true;
  3642. });
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(StatusCode::OK_200, res->status);
  3645. EXPECT_EQ("Hello World!", body);
  3646. }
  3647. {
  3648. Client cli("::1", PORT);
  3649. std::string body;
  3650. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3651. body.append(data, data_length);
  3652. return true;
  3653. });
  3654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3655. EXPECT_EQ(StatusCode::Found_302, res->status);
  3656. EXPECT_EQ("___", body);
  3657. }
  3658. }
  3659. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3660. Server svr;
  3661. svr.Get("/foo", [](const Request &req, Response &res) {
  3662. auto a = req.params.find("a");
  3663. if (a != req.params.end()) {
  3664. res.set_content((*a).second, "text/plain");
  3665. res.status = StatusCode::OK_200;
  3666. } else {
  3667. res.status = StatusCode::BadRequest_400;
  3668. }
  3669. });
  3670. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3671. auto se = detail::scope_exit([&] {
  3672. svr.stop();
  3673. thread.join();
  3674. ASSERT_FALSE(svr.is_running());
  3675. });
  3676. svr.wait_until_ready();
  3677. {
  3678. Client cli(HOST, PORT);
  3679. cli.set_path_encode(false);
  3680. auto res = cli.Get("/foo?a=explicitly+encoded");
  3681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3682. EXPECT_EQ(StatusCode::OK_200, res->status);
  3683. // This expects it back with a space, as the `+` won't have been
  3684. // url-encoded, and server-side the params get decoded turning `+`
  3685. // into spaces.
  3686. EXPECT_EQ("explicitly encoded", res->body);
  3687. }
  3688. }
  3689. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3690. // When path encoding is disabled the client must transmit the supplied
  3691. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3692. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3693. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3694. // than a space (0x20). Assert on the raw wire target to catch this.
  3695. Server svr;
  3696. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3697. svr.Get("/foo", [&](const Request &req, Response &res) {
  3698. EXPECT_EQ(expected_target, req.target);
  3699. res.status = StatusCode::OK_200;
  3700. });
  3701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3702. auto se = detail::scope_exit([&] {
  3703. svr.stop();
  3704. thread.join();
  3705. ASSERT_FALSE(svr.is_running());
  3706. });
  3707. svr.wait_until_ready();
  3708. {
  3709. Client cli(HOST, PORT);
  3710. cli.set_path_encode(false);
  3711. auto res = cli.Get(expected_target.c_str());
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. }
  3715. }
  3716. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3717. // `open_stream()` used to skip the path encoding that the buffered send
  3718. // path applies, so the same `path` produced different bytes in the request
  3719. // line depending on which API was used. Assert the two agree.
  3720. Server svr;
  3721. std::string target;
  3722. svr.Get(".*", [&](const Request &req, Response &res) {
  3723. target = req.target;
  3724. res.status = StatusCode::OK_200;
  3725. });
  3726. auto port = svr.bind_to_any_port(HOST);
  3727. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3728. auto se = detail::scope_exit([&] {
  3729. svr.stop();
  3730. thread.join();
  3731. ASSERT_FALSE(svr.is_running());
  3732. });
  3733. svr.wait_until_ready();
  3734. struct {
  3735. const char *path;
  3736. const char *expected;
  3737. } cases[] = {
  3738. {"/a b?x=1", "/a%20b?x=1"},
  3739. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3740. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3741. };
  3742. for (const auto &c : cases) {
  3743. Client cli(HOST, port);
  3744. target.clear();
  3745. auto res = cli.Get(c.path);
  3746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3747. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3748. auto buffered_target = target;
  3749. target.clear();
  3750. auto handle = cli.open_stream("GET", c.path);
  3751. EXPECT_TRUE(handle.is_valid())
  3752. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3753. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3754. }
  3755. }
  3756. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3757. // The `set_path_encode(false)` contract — transmit the supplied target
  3758. // verbatim — must hold for the streaming API too.
  3759. Server svr;
  3760. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3761. std::string target;
  3762. svr.Get("/foo", [&](const Request &req, Response &res) {
  3763. target = req.target;
  3764. res.status = StatusCode::OK_200;
  3765. });
  3766. auto port = svr.bind_to_any_port(HOST);
  3767. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3768. auto se = detail::scope_exit([&] {
  3769. svr.stop();
  3770. thread.join();
  3771. ASSERT_FALSE(svr.is_running());
  3772. });
  3773. svr.wait_until_ready();
  3774. {
  3775. Client cli(HOST, port);
  3776. cli.set_path_encode(false);
  3777. auto handle = cli.open_stream("GET", expected_target);
  3778. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3779. EXPECT_EQ(expected_target, target);
  3780. }
  3781. }
  3782. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3783. // With path encoding enabled a CR/LF in the target is percent-encoded
  3784. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3785. // write_request_line still backstops `set_path_encode(false)`, which is
  3786. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3787. Server svr;
  3788. // Captured before routing: the decoded path contains a newline, which a
  3789. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3790. std::string target;
  3791. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3792. target = req.target;
  3793. res.status = StatusCode::OK_200;
  3794. return Server::HandlerResponse::Handled;
  3795. });
  3796. auto port = svr.bind_to_any_port(HOST);
  3797. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3798. auto se = detail::scope_exit([&] {
  3799. svr.stop();
  3800. thread.join();
  3801. ASSERT_FALSE(svr.is_running());
  3802. });
  3803. svr.wait_until_ready();
  3804. {
  3805. Client cli(HOST, port);
  3806. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3807. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3808. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3809. }
  3810. }
  3811. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3812. // Every control character is percent-encoded, not just CR/LF, so the target
  3813. // passes the request-target check in write_request_line.
  3814. Server svr;
  3815. std::string target;
  3816. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3817. target = req.target;
  3818. res.status = StatusCode::OK_200;
  3819. return Server::HandlerResponse::Handled;
  3820. });
  3821. auto port = svr.bind_to_any_port(HOST);
  3822. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3823. auto se = detail::scope_exit([&] {
  3824. svr.stop();
  3825. thread.join();
  3826. ASSERT_FALSE(svr.is_running());
  3827. });
  3828. svr.wait_until_ready();
  3829. {
  3830. Client cli(HOST, port);
  3831. auto res = cli.Get("/a\tb\x1b\x7f");
  3832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3833. EXPECT_EQ("/a%09b%1B%7F", target);
  3834. }
  3835. }
  3836. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3837. // Nothing may reach the wire: a raw CR/LF target would split the request
  3838. // line and inject headers.
  3839. Server svr;
  3840. // Pre-routing so that "not called" means nothing reached the server at all,
  3841. // rather than merely failing to match a handler pattern.
  3842. auto handler_called = false;
  3843. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3844. handler_called = true;
  3845. res.status = StatusCode::OK_200;
  3846. return Server::HandlerResponse::Handled;
  3847. });
  3848. auto port = svr.bind_to_any_port(HOST);
  3849. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3850. auto se = detail::scope_exit([&] {
  3851. svr.stop();
  3852. thread.join();
  3853. ASSERT_FALSE(svr.is_running());
  3854. });
  3855. svr.wait_until_ready();
  3856. {
  3857. Client cli(HOST, port);
  3858. cli.set_path_encode(false);
  3859. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3860. EXPECT_FALSE(handle.is_valid());
  3861. EXPECT_EQ(Error::Write, handle.error);
  3862. EXPECT_FALSE(handler_called);
  3863. }
  3864. }
  3865. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3866. // Which of the two branches runs is decided by whether the query component
  3867. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3868. // an empty query and must still fall back to building one from
  3869. // `req.params`, while a non-empty query must win over `req.params`.
  3870. Server svr;
  3871. std::string target;
  3872. svr.Get("/foo", [&](const Request &req, Response &res) {
  3873. target = req.target;
  3874. res.status = StatusCode::OK_200;
  3875. });
  3876. auto port = svr.bind_to_any_port(HOST);
  3877. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3878. auto se = detail::scope_exit([&] {
  3879. svr.stop();
  3880. thread.join();
  3881. ASSERT_FALSE(svr.is_running());
  3882. });
  3883. svr.wait_until_ready();
  3884. {
  3885. // Trailing `?` -> empty query component -> `req.params` is used.
  3886. Client cli(HOST, port);
  3887. Request req;
  3888. req.method = "GET";
  3889. req.path = "/foo?";
  3890. req.params.emplace("a", "1");
  3891. target.clear();
  3892. auto res = cli.send(req);
  3893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3894. EXPECT_EQ("/foo?a=1", target);
  3895. }
  3896. {
  3897. // Non-empty query in `req.path` -> `req.params` is not appended.
  3898. Client cli(HOST, port);
  3899. Request req;
  3900. req.method = "GET";
  3901. req.path = "/foo?b=2";
  3902. req.params.emplace("a", "1");
  3903. target.clear();
  3904. auto res = cli.send(req);
  3905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3906. EXPECT_EQ("/foo?b=2", target);
  3907. }
  3908. }
  3909. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3910. Server svr;
  3911. svr.Get("/", [](const Request &req, Response &) {
  3912. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3913. });
  3914. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3915. auto se = detail::scope_exit([&] {
  3916. svr.stop();
  3917. thread.join();
  3918. ASSERT_FALSE(svr.is_running());
  3919. });
  3920. svr.wait_until_ready();
  3921. {
  3922. Client cli(HOST, PORT);
  3923. cli.set_path_encode(false);
  3924. auto res = cli.Get("/?something=%0A");
  3925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3926. EXPECT_EQ(StatusCode::OK_200, res->status);
  3927. }
  3928. }
  3929. TEST(BindServerTest, BindDualStack) {
  3930. Server svr;
  3931. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3932. res.set_content("Hello World!", "text/plain");
  3933. });
  3934. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3935. auto se = detail::scope_exit([&] {
  3936. svr.stop();
  3937. thread.join();
  3938. ASSERT_FALSE(svr.is_running());
  3939. });
  3940. svr.wait_until_ready();
  3941. {
  3942. Client cli("127.0.0.1", PORT);
  3943. auto res = cli.Get("/1");
  3944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. EXPECT_EQ("Hello World!", res->body);
  3947. }
  3948. {
  3949. Client cli("::1", PORT);
  3950. auto res = cli.Get("/1");
  3951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3952. EXPECT_EQ(StatusCode::OK_200, res->status);
  3953. EXPECT_EQ("Hello World!", res->body);
  3954. }
  3955. }
  3956. TEST(BindServerTest, BindAndListenSeparately) {
  3957. Server svr;
  3958. int port = svr.bind_to_any_port("0.0.0.0");
  3959. ASSERT_TRUE(svr.is_valid());
  3960. ASSERT_TRUE(port > 0);
  3961. svr.stop();
  3962. }
  3963. // Reports whether anything is still listening on a loopback port. A plain
  3964. // connect() is used instead of a Client request because a socket left bound by
  3965. // mistake accepts the connection into its backlog and never answers, which
  3966. // would hang the test instead of failing it.
  3967. static bool is_loopback_port_accepting(int port) {
  3968. sockaddr_in addr{};
  3969. addr.sin_family = AF_INET;
  3970. addr.sin_port = htons(static_cast<uint16_t>(port));
  3971. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3972. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3973. EXPECT_NE(sock, INVALID_SOCKET);
  3974. if (sock == INVALID_SOCKET) { return false; }
  3975. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3976. static_cast<socklen_t>(sizeof(addr)));
  3977. detail::close_socket(sock);
  3978. return ret == 0;
  3979. }
  3980. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3981. Server svr;
  3982. auto port = svr.bind_to_any_port("127.0.0.1");
  3983. ASSERT_TRUE(port > 0);
  3984. svr.stop();
  3985. // bind_to_any_port() already called listen(2), so until stop() closed the
  3986. // descriptor the port kept accepting connections into the backlog. ASSERT
  3987. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3988. // below blocks forever in the accept loop.
  3989. ASSERT_FALSE(is_loopback_port_accepting(port));
  3990. // Nothing is left to accept on, so listen_after_bind() must report failure
  3991. // instead of returning success without ever serving.
  3992. EXPECT_FALSE(svr.listen_after_bind());
  3993. // The failed listen marks the server decommissioned, so a waiter returns
  3994. // instead of spinning forever.
  3995. svr.wait_until_ready();
  3996. }
  3997. #ifdef CPPHTTPLIB_SSL_ENABLED
  3998. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3999. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4000. CLIENT_CA_CERT_DIR);
  4001. int port = svr.bind_to_any_port("0.0.0.0");
  4002. ASSERT_TRUE(svr.is_valid());
  4003. ASSERT_TRUE(port > 0);
  4004. svr.stop();
  4005. }
  4006. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4007. // or a rejected CustomRoute() registration would not stop the server binding.
  4008. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4009. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4010. CLIENT_CA_CERT_DIR);
  4011. ASSERT_TRUE(svr.is_valid());
  4012. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4013. EXPECT_FALSE(svr.is_valid());
  4014. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4015. }
  4016. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4017. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4018. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4019. int port = svr.bind_to_any_port("0.0.0.0");
  4020. ASSERT_TRUE(svr.is_valid());
  4021. ASSERT_TRUE(port > 0);
  4022. svr.stop();
  4023. }
  4024. TEST(BindServerTest, UpdateCertsPem) {
  4025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4026. int port = svr.bind_to_any_port("0.0.0.0");
  4027. ASSERT_TRUE(svr.is_valid());
  4028. ASSERT_TRUE(port > 0);
  4029. // Read PEM files
  4030. std::string cert_pem, key_pem, ca_pem;
  4031. read_file(SERVER_CERT_FILE, cert_pem);
  4032. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4033. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4034. // Update server certificates using PEM API
  4035. ASSERT_TRUE(
  4036. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4037. ASSERT_TRUE(svr.is_valid());
  4038. svr.stop();
  4039. }
  4040. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4041. // Start server with client CA (enables client auth)
  4042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4043. ASSERT_TRUE(svr.is_valid());
  4044. bool handler_called = false;
  4045. svr.Get("/test", [&](const Request &req, Response &res) {
  4046. handler_called = true;
  4047. // Verify client certificate is present
  4048. auto cert = req.peer_cert();
  4049. EXPECT_TRUE(static_cast<bool>(cert));
  4050. res.set_content("ok", "text/plain");
  4051. });
  4052. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4053. auto se = detail::scope_exit([&] {
  4054. svr.stop();
  4055. t.join();
  4056. ASSERT_FALSE(svr.is_running());
  4057. });
  4058. svr.wait_until_ready();
  4059. // Read PEM files
  4060. std::string cert_pem, key_pem, ca_pem;
  4061. read_file(SERVER_CERT_FILE, cert_pem);
  4062. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4063. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4064. // Update server certificates and client CA using PEM API while server running
  4065. ASSERT_TRUE(
  4066. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4067. // Connect with client certificate
  4068. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4069. cli.enable_server_certificate_verification(false);
  4070. cli.set_connection_timeout(30);
  4071. auto res = cli.Get("/test");
  4072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4073. ASSERT_EQ(StatusCode::OK_200, res->status);
  4074. ASSERT_TRUE(handler_called);
  4075. EXPECT_EQ("ok", res->body);
  4076. }
  4077. // Puts a CA that did not sign the client's certificate in the old one's place.
  4078. static bool replace_client_ca(SSLServer &svr) {
  4079. std::string cert_pem, key_pem, ca_pem;
  4080. read_file(SERVER_CERT_FILE, cert_pem);
  4081. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4082. read_file(SERVER_CERT2_FILE, ca_pem);
  4083. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4084. ca_pem.c_str());
  4085. }
  4086. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4088. ASSERT_TRUE(svr.is_valid());
  4089. svr.Get("/test", [](const Request &, Response &res) {
  4090. res.set_content("ok", "text/plain");
  4091. });
  4092. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4093. auto se = detail::scope_exit([&] {
  4094. svr.stop();
  4095. t.join();
  4096. ASSERT_FALSE(svr.is_running());
  4097. });
  4098. svr.wait_until_ready();
  4099. auto get = [] {
  4100. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4101. cli.enable_server_certificate_verification(false);
  4102. return cli.Get("/test");
  4103. };
  4104. ASSERT_TRUE(get());
  4105. ASSERT_TRUE(replace_client_ca(svr));
  4106. EXPECT_FALSE(get());
  4107. }
  4108. TEST(SSLClientServerTest, VerifyCallbackKeepsClientCertificateRequired) {
  4109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4110. ASSERT_TRUE(svr.is_valid());
  4111. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4112. return v.preverify_ok;
  4113. });
  4114. svr.Get("/test", [](const Request &, Response &res) {
  4115. res.set_content("ok", "text/plain");
  4116. });
  4117. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4118. auto se = detail::scope_exit([&] {
  4119. svr.stop();
  4120. t.join();
  4121. ASSERT_FALSE(svr.is_running());
  4122. });
  4123. svr.wait_until_ready();
  4124. SSLClient without_cert(HOST, PORT);
  4125. without_cert.enable_server_certificate_verification(false);
  4126. EXPECT_FALSE(without_cert.Get("/test"));
  4127. SSLClient with_cert(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4128. with_cert.enable_server_certificate_verification(false);
  4129. auto res = with_cert.Get("/test");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ("ok", res->body);
  4132. }
  4133. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4134. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4135. ASSERT_TRUE(svr.is_valid());
  4136. tls::set_verify_callback(svr.tls_context(),
  4137. [](const tls::VerifyContext &) -> bool {
  4138. throw std::runtime_error("verify");
  4139. });
  4140. svr.Get("/test", [](const Request &, Response &res) {
  4141. res.set_content("ok", "text/plain");
  4142. });
  4143. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4144. auto se = detail::scope_exit([&] {
  4145. svr.stop();
  4146. t.join();
  4147. ASSERT_FALSE(svr.is_running());
  4148. });
  4149. svr.wait_until_ready();
  4150. auto get = [] {
  4151. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4152. cli.enable_server_certificate_verification(false);
  4153. return cli.Get("/test");
  4154. };
  4155. EXPECT_FALSE(get());
  4156. // The handshake is over, so an update does not wait for it.
  4157. std::string cert_pem, key_pem;
  4158. read_file(SERVER_CERT_FILE, cert_pem);
  4159. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4160. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4161. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4162. return v.preverify_ok;
  4163. });
  4164. auto res = get();
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ("ok", res->body);
  4167. }
  4168. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4169. // A client that resumes its session gets through, but not once the client CA
  4170. // has changed, as a resumed session does not show the certificate again.
  4171. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4173. ASSERT_TRUE(svr.is_valid());
  4174. svr.Get("/test", [](const Request &, Response &res) {
  4175. res.set_content("ok", "text/plain");
  4176. });
  4177. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4178. auto se = detail::scope_exit([&] {
  4179. svr.stop();
  4180. t.join();
  4181. ASSERT_FALSE(svr.is_running());
  4182. });
  4183. svr.wait_until_ready();
  4184. auto ctx = SSL_CTX_new(TLS_client_method());
  4185. auto ctx_se = detail::scope_exit([&] { SSL_CTX_free(ctx); });
  4186. ASSERT_EQ(
  4187. 1, SSL_CTX_use_certificate_file(ctx, CLIENT_CERT_FILE, SSL_FILETYPE_PEM));
  4188. ASSERT_EQ(1, SSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4189. SSL_FILETYPE_PEM));
  4190. SSL_SESSION *session = nullptr;
  4191. auto session_se = detail::scope_exit([&] { SSL_SESSION_free(session); });
  4192. // A request over a new connection, resuming `session` when there is one and
  4193. // keeping the connection's own in its place. Tells whether it was answered.
  4194. auto reused = false;
  4195. auto get = [&]() {
  4196. auto error = Error::Success;
  4197. auto sock = detail::create_client_socket(
  4198. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4199. /*connection_timeout_sec=*/5, 0,
  4200. /*read_timeout_sec=*/5, 0,
  4201. /*write_timeout_sec=*/5, 0, std::string(), error);
  4202. if (sock == INVALID_SOCKET) { return false; }
  4203. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4204. auto ssl = SSL_new(ctx);
  4205. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4206. SSL_set_fd(ssl, static_cast<int>(sock));
  4207. if (session) { SSL_set_session(ssl, session); }
  4208. if (SSL_connect(ssl) != 1) { return false; }
  4209. reused = SSL_session_reused(ssl) == 1;
  4210. // Reading the response also takes in a TLS 1.3 session ticket.
  4211. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4212. "Connection: close\r\n\r\n";
  4213. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4214. std::string res;
  4215. char buf[256];
  4216. int n;
  4217. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4218. res.append(buf, static_cast<size_t>(n));
  4219. }
  4220. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4221. SSL_shutdown(ssl);
  4222. SSL_SESSION_free(session);
  4223. session = SSL_get1_session(ssl);
  4224. return res.find("200 OK") != std::string::npos;
  4225. };
  4226. ASSERT_TRUE(get());
  4227. ASSERT_TRUE(get());
  4228. EXPECT_TRUE(reused);
  4229. ASSERT_TRUE(replace_client_ca(svr));
  4230. EXPECT_FALSE(get());
  4231. }
  4232. #endif
  4233. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4234. // wolfSSL shares its session cache between contexts, so a resumed session
  4235. // could carry a client certificate checked against another server's CA, or
  4236. // against a client CA since replaced.
  4237. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4238. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4239. ASSERT_TRUE(svr.is_valid());
  4240. // Trusts a CA that did not sign the client's certificate.
  4241. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4242. ASSERT_TRUE(other.is_valid());
  4243. for (auto s : {&svr, &other}) {
  4244. s->Get("/test", [](const Request &, Response &res) {
  4245. res.set_content("ok", "text/plain");
  4246. });
  4247. }
  4248. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4249. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4250. auto se = detail::scope_exit([&] {
  4251. other.stop();
  4252. svr.stop();
  4253. t2.join();
  4254. t.join();
  4255. });
  4256. svr.wait_until_ready();
  4257. other.wait_until_ready();
  4258. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4259. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4260. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4261. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4262. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4263. ASSERT_EQ(WOLFSSL_SUCCESS,
  4264. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4265. WOLFSSL_FILETYPE_PEM));
  4266. WOLFSSL_SESSION *session = nullptr;
  4267. auto session_se = detail::scope_exit([&] {
  4268. if (session) { wolfSSL_SESSION_free(session); }
  4269. });
  4270. // A request over a new connection, resuming `session` when there is one and
  4271. // keeping the connection's own in its place. Tells whether it was answered.
  4272. auto get = [&](int port) {
  4273. auto error = Error::Success;
  4274. auto sock = detail::create_client_socket(
  4275. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4276. /*connection_timeout_sec=*/5, 0,
  4277. /*read_timeout_sec=*/5, 0,
  4278. /*write_timeout_sec=*/5, 0, std::string(), error);
  4279. if (sock == INVALID_SOCKET) { return false; }
  4280. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4281. auto ssl = wolfSSL_new(ctx);
  4282. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4283. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4284. if (session) { wolfSSL_set_session(ssl, session); }
  4285. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4286. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4287. "Connection: close\r\n\r\n";
  4288. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4289. std::string res;
  4290. char buf[256];
  4291. int n;
  4292. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4293. res.append(buf, static_cast<size_t>(n));
  4294. }
  4295. wolfSSL_shutdown(ssl);
  4296. if (session) { wolfSSL_SESSION_free(session); }
  4297. session = wolfSSL_get1_session(ssl);
  4298. return res.find("200 OK") != std::string::npos;
  4299. };
  4300. ASSERT_TRUE(get(PORT));
  4301. EXPECT_FALSE(get(PORT + 1));
  4302. ASSERT_TRUE(get(PORT));
  4303. ASSERT_TRUE(replace_client_ca(svr));
  4304. EXPECT_FALSE(get(PORT));
  4305. }
  4306. #endif
  4307. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4309. ASSERT_TRUE(svr.is_valid());
  4310. svr.Get("/test", [](const Request &, Response &res) {
  4311. res.set_content("ok", "text/plain");
  4312. });
  4313. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4314. auto se = detail::scope_exit([&] {
  4315. svr.stop();
  4316. t.join();
  4317. ASSERT_FALSE(svr.is_running());
  4318. });
  4319. svr.wait_until_ready();
  4320. // A connection that sends no ClientHello keeps its handshake in progress,
  4321. // once the server has had a moment to start it.
  4322. auto error = Error::Success;
  4323. auto sock = detail::create_client_socket(
  4324. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4325. /*connection_timeout_sec=*/5, 0,
  4326. /*read_timeout_sec=*/5, 0,
  4327. /*write_timeout_sec=*/5, 0, std::string(), error);
  4328. ASSERT_NE(INVALID_SOCKET, sock);
  4329. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4330. std::string cert_pem, key_pem;
  4331. read_file(SERVER_CERT_FILE, cert_pem);
  4332. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4333. auto update = std::async(std::launch::async, [&]() {
  4334. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4335. });
  4336. EXPECT_EQ(std::future_status::timeout,
  4337. update.wait_for(std::chrono::milliseconds(200)));
  4338. detail::close_socket(sock);
  4339. EXPECT_TRUE(update.get());
  4340. SSLClient cli(HOST, PORT);
  4341. cli.enable_server_certificate_verification(false);
  4342. auto res = cli.Get("/test");
  4343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4344. EXPECT_EQ(StatusCode::OK_200, res->status);
  4345. }
  4346. #endif
  4347. TEST(ErrorHandlerTest, ContentLength) {
  4348. Server svr;
  4349. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4350. res.status = StatusCode::OK_200;
  4351. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4352. "text/html"); // <= Content-Length still 13
  4353. });
  4354. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4355. res.set_content("Hello World!\n", "text/plain");
  4356. res.status = 524;
  4357. });
  4358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4359. auto se = detail::scope_exit([&] {
  4360. svr.stop();
  4361. thread.join();
  4362. ASSERT_FALSE(svr.is_running());
  4363. });
  4364. svr.wait_until_ready();
  4365. {
  4366. Client cli(HOST, PORT);
  4367. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4371. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4372. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4373. }
  4374. }
  4375. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4376. TEST(ExceptionTest, WithoutExceptionHandler) {
  4377. Server svr;
  4378. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4379. throw std::runtime_error("exception...");
  4380. });
  4381. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4382. throw std::runtime_error("exception\r\n...");
  4383. });
  4384. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4385. auto se = detail::scope_exit([&] {
  4386. svr.stop();
  4387. listen_thread.join();
  4388. ASSERT_FALSE(svr.is_running());
  4389. });
  4390. svr.wait_until_ready();
  4391. Client cli("localhost", PORT);
  4392. {
  4393. auto res = cli.Get("/exception");
  4394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4395. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4396. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4397. }
  4398. {
  4399. auto res = cli.Get("/unknown");
  4400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4401. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4402. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4403. }
  4404. }
  4405. TEST(ExceptionTest, WithExceptionHandler) {
  4406. Server svr;
  4407. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4408. std::exception_ptr ep) {
  4409. EXPECT_FALSE(ep == nullptr);
  4410. try {
  4411. std::rethrow_exception(ep);
  4412. } catch (std::exception &e) {
  4413. EXPECT_EQ("abc", std::string(e.what()));
  4414. } catch (...) {}
  4415. res.status = StatusCode::InternalServerError_500;
  4416. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4417. "text/html"); // <= Content-Length still 13 at this point
  4418. });
  4419. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4420. res.set_content("Hello World!\n", "text/plain");
  4421. throw std::runtime_error("abc");
  4422. });
  4423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4424. auto se = detail::scope_exit([&] {
  4425. svr.stop();
  4426. thread.join();
  4427. ASSERT_FALSE(svr.is_running());
  4428. });
  4429. svr.wait_until_ready();
  4430. for (size_t i = 0; i < 10; i++) {
  4431. Client cli(HOST, PORT);
  4432. for (size_t j = 0; j < 100; j++) {
  4433. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4435. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4436. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4437. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4438. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4439. }
  4440. cli.set_keep_alive(true);
  4441. for (size_t j = 0; j < 100; j++) {
  4442. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4444. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4445. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4446. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4447. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4448. }
  4449. }
  4450. }
  4451. TEST(ExceptionTest, AndErrorHandler) {
  4452. Server svr;
  4453. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4454. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4455. });
  4456. svr.set_exception_handler(
  4457. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4458. EXPECT_FALSE(ep == nullptr);
  4459. try {
  4460. std::rethrow_exception(ep);
  4461. } catch (std::exception &e) {
  4462. res.set_content(e.what(), "text/html");
  4463. } catch (...) {}
  4464. res.status = StatusCode::InternalServerError_500;
  4465. });
  4466. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4467. throw std::runtime_error("EXCEPTION");
  4468. });
  4469. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4470. res.set_content("ERROR", "text/html");
  4471. res.status = StatusCode::InternalServerError_500;
  4472. });
  4473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4474. auto se = detail::scope_exit([&] {
  4475. svr.stop();
  4476. thread.join();
  4477. ASSERT_FALSE(svr.is_running());
  4478. });
  4479. svr.wait_until_ready();
  4480. Client cli(HOST, PORT);
  4481. {
  4482. auto res = cli.Get("/exception");
  4483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4484. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4485. EXPECT_EQ("EXCEPTION", res->body);
  4486. }
  4487. {
  4488. auto res = cli.Get("/error");
  4489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4490. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4491. EXPECT_EQ("ERROR", res->body);
  4492. }
  4493. {
  4494. auto res = cli.Get("/invalid");
  4495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4496. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4497. EXPECT_EQ("NOT_FOUND", res->body);
  4498. }
  4499. }
  4500. #endif
  4501. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4502. // process_request() wraps only routing() in a try/catch, so an exception from
  4503. // any other user callback used to unwind into the task queue - which does not
  4504. // catch - and terminate the process. Each test below runs the server on a
  4505. // single worker thread: a guard that catches the exception but still loses the
  4506. // thread would otherwise be hidden by a spare worker serving the follow-up
  4507. // request. Note that a regression here aborts the whole test binary rather
  4508. // than failing one test.
  4509. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4510. Server svr;
  4511. svr.new_task_queue = [] { return new ThreadPool(1); };
  4512. std::atomic<int> reported{0};
  4513. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4514. if (err == Error::UserCallbackException) { reported++; }
  4515. });
  4516. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4517. res.set_content_provider(
  4518. 1024, "text/plain",
  4519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4520. sink.write("hello", 5);
  4521. throw std::runtime_error("from the content provider");
  4522. });
  4523. });
  4524. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4525. res.set_content("ok", "text/plain");
  4526. });
  4527. auto port = svr.bind_to_any_port(HOST);
  4528. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4529. auto se = detail::scope_exit([&] {
  4530. svr.stop();
  4531. listen_thread.join();
  4532. ASSERT_FALSE(svr.is_running());
  4533. });
  4534. svr.wait_until_ready();
  4535. {
  4536. Client cli(HOST, port);
  4537. cli.set_read_timeout(5, 0);
  4538. EXPECT_FALSE(cli.Get("/throw"));
  4539. }
  4540. EXPECT_TRUE(svr.is_running());
  4541. EXPECT_EQ(1, reported.load());
  4542. // A request on a fresh connection is still served.
  4543. {
  4544. Client cli(HOST, port);
  4545. auto res = cli.Get("/ok");
  4546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4547. EXPECT_EQ(StatusCode::OK_200, res->status);
  4548. EXPECT_EQ("ok", res->body);
  4549. }
  4550. }
  4551. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4552. Server svr;
  4553. svr.new_task_queue = [] { return new ThreadPool(1); };
  4554. std::atomic<bool> should_throw{true};
  4555. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4556. res.set_content("hi", "text/plain");
  4557. });
  4558. svr.set_post_routing_handler(
  4559. [&](const Request & /*req*/, Response & /*res*/) {
  4560. if (should_throw) {
  4561. throw std::runtime_error("from the post-routing handler");
  4562. }
  4563. });
  4564. auto port = svr.bind_to_any_port(HOST);
  4565. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4566. auto se = detail::scope_exit([&] {
  4567. svr.stop();
  4568. listen_thread.join();
  4569. ASSERT_FALSE(svr.is_running());
  4570. });
  4571. svr.wait_until_ready();
  4572. {
  4573. Client cli(HOST, port);
  4574. cli.set_read_timeout(5, 0);
  4575. EXPECT_FALSE(cli.Get("/hi"));
  4576. }
  4577. EXPECT_TRUE(svr.is_running());
  4578. should_throw = false;
  4579. {
  4580. Client cli(HOST, port);
  4581. auto res = cli.Get("/hi");
  4582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. EXPECT_EQ("hi", res->body);
  4585. }
  4586. }
  4587. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4588. // The guard reports the caught exception through the error logger, which is
  4589. // a user callback too. A logger that throws has to be contained as well, or
  4590. // the process would terminate from inside the catch.
  4591. Server svr;
  4592. svr.new_task_queue = [] { return new ThreadPool(1); };
  4593. std::atomic<int> reported{0};
  4594. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4595. if (err == Error::UserCallbackException) {
  4596. reported++;
  4597. throw std::runtime_error("from the error logger");
  4598. }
  4599. });
  4600. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4601. res.set_content_provider(
  4602. 1024, "text/plain",
  4603. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4604. sink.write("hello", 5);
  4605. throw std::runtime_error("from the content provider");
  4606. });
  4607. });
  4608. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4609. res.set_content("ok", "text/plain");
  4610. });
  4611. auto port = svr.bind_to_any_port(HOST);
  4612. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4613. auto se = detail::scope_exit([&] {
  4614. svr.stop();
  4615. listen_thread.join();
  4616. ASSERT_FALSE(svr.is_running());
  4617. });
  4618. svr.wait_until_ready();
  4619. {
  4620. Client cli(HOST, port);
  4621. cli.set_read_timeout(5, 0);
  4622. EXPECT_FALSE(cli.Get("/throw"));
  4623. }
  4624. EXPECT_TRUE(svr.is_running());
  4625. EXPECT_EQ(1, reported.load());
  4626. {
  4627. Client cli(HOST, port);
  4628. auto res = cli.Get("/ok");
  4629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4630. EXPECT_EQ(StatusCode::OK_200, res->status);
  4631. EXPECT_EQ("ok", res->body);
  4632. }
  4633. }
  4634. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4635. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4636. // so the exception unwinds through the ws::WebSocket object on its way to
  4637. // the guard. None of the HTTP cases above cross that.
  4638. Server svr;
  4639. svr.new_task_queue = [] { return new ThreadPool(1); };
  4640. std::atomic<int> reported{0};
  4641. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4642. if (err == Error::UserCallbackException) { reported++; }
  4643. });
  4644. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4645. throw std::runtime_error("from the WebSocket handler");
  4646. });
  4647. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4648. res.set_content("ok", "text/plain");
  4649. });
  4650. auto port = svr.bind_to_any_port(HOST);
  4651. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4652. auto se = detail::scope_exit([&] {
  4653. svr.stop();
  4654. listen_thread.join();
  4655. ASSERT_FALSE(svr.is_running());
  4656. });
  4657. svr.wait_until_ready();
  4658. {
  4659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4660. "/ws");
  4661. auto res = client.connect();
  4662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4663. // The server dropped the connection instead of dying.
  4664. std::string msg;
  4665. EXPECT_FALSE(client.read(msg));
  4666. client.close();
  4667. }
  4668. EXPECT_TRUE(svr.is_running());
  4669. EXPECT_EQ(1, reported.load());
  4670. {
  4671. Client cli(HOST, port);
  4672. auto res = cli.Get("/ok");
  4673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4674. EXPECT_EQ(StatusCode::OK_200, res->status);
  4675. EXPECT_EQ("ok", res->body);
  4676. }
  4677. }
  4678. #ifdef CPPHTTPLIB_SSL_ENABLED
  4679. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4680. // SSLServer::process_and_close_socket() is a separate overload with its own
  4681. // guard, so it is exercised on its own.
  4682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4683. ASSERT_TRUE(svr.is_valid());
  4684. svr.new_task_queue = [] { return new ThreadPool(1); };
  4685. std::atomic<int> reported{0};
  4686. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4687. if (err == Error::UserCallbackException) { reported++; }
  4688. });
  4689. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4690. res.set_content_provider(
  4691. 1024, "text/plain",
  4692. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4693. sink.write("hello", 5);
  4694. throw std::runtime_error("from the content provider");
  4695. });
  4696. });
  4697. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4698. res.set_content("ok", "text/plain");
  4699. });
  4700. auto port = svr.bind_to_any_port(HOST);
  4701. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4702. auto se = detail::scope_exit([&] {
  4703. svr.stop();
  4704. listen_thread.join();
  4705. ASSERT_FALSE(svr.is_running());
  4706. });
  4707. svr.wait_until_ready();
  4708. {
  4709. SSLClient cli(HOST, port);
  4710. cli.enable_server_certificate_verification(false);
  4711. cli.set_read_timeout(5, 0);
  4712. EXPECT_FALSE(cli.Get("/throw"));
  4713. }
  4714. EXPECT_TRUE(svr.is_running());
  4715. EXPECT_EQ(1, reported.load());
  4716. {
  4717. SSLClient cli(HOST, port);
  4718. cli.enable_server_certificate_verification(false);
  4719. auto res = cli.Get("/ok");
  4720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4721. EXPECT_EQ(StatusCode::OK_200, res->status);
  4722. EXPECT_EQ("ok", res->body);
  4723. }
  4724. }
  4725. #endif
  4726. #endif
  4727. TEST(NoContentTest, ContentLength) {
  4728. Server svr;
  4729. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4730. res.status = StatusCode::NoContent_204;
  4731. });
  4732. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4733. auto se = detail::scope_exit([&] {
  4734. svr.stop();
  4735. thread.join();
  4736. ASSERT_FALSE(svr.is_running());
  4737. });
  4738. svr.wait_until_ready();
  4739. {
  4740. Client cli(HOST, PORT);
  4741. auto res = cli.Get("/hi");
  4742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4743. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4744. // RFC 9110 8.6: none in a 204 response
  4745. EXPECT_FALSE(res->has_header("Content-Length"));
  4746. }
  4747. }
  4748. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4749. Server svr;
  4750. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4751. res.set_header("Content-Length", "5");
  4752. res.set_content("hello world", "text/plain");
  4753. });
  4754. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4755. // A body that reads as the last chunk, were it taken as chunked
  4756. res.set_header("Transfer-Encoding", "chunked");
  4757. res.set_content("0\r\n\r\n", "text/plain");
  4758. });
  4759. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4760. res.set_header("Content-Length", "2");
  4761. res.set_content_provider(5, "text/plain",
  4762. [](size_t offset, size_t length, DataSink &sink) {
  4763. sink.write(&"hello"[offset], length);
  4764. return true;
  4765. });
  4766. });
  4767. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4768. res.set_header("Content-Length", "1234");
  4769. });
  4770. thread t = thread([&] { svr.listen(HOST, PORT); });
  4771. auto se = detail::scope_exit([&] {
  4772. svr.stop();
  4773. t.join();
  4774. ASSERT_FALSE(svr.is_running());
  4775. });
  4776. svr.wait_until_ready();
  4777. Client cli(HOST, PORT);
  4778. cli.set_read_timeout(1, 0);
  4779. auto expect_body = [&](const Result &res, const std::string &body) {
  4780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4781. EXPECT_EQ(body, res->body);
  4782. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4783. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4784. };
  4785. Headers identity{{"Accept-Encoding", ""}};
  4786. expect_body(cli.Get("/body", identity), "hello world");
  4787. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4788. expect_body(cli.Get("/body",
  4789. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4790. "he");
  4791. expect_body(cli.Get("/provider", identity), "hello");
  4792. expect_body(cli.Get("/empty", identity), "");
  4793. // A HEAD response may give the length of the body a GET would get.
  4794. auto res = cli.Head("/empty");
  4795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4796. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4797. }
  4798. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4799. Server svr;
  4800. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4801. res.set_content("short", "text/plain");
  4802. });
  4803. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4804. res.body += " with a footer";
  4805. res.set_header("Transfer-Encoding", "chunked");
  4806. });
  4807. thread t = thread([&] { svr.listen(HOST, PORT); });
  4808. auto se = detail::scope_exit([&] {
  4809. svr.stop();
  4810. t.join();
  4811. ASSERT_FALSE(svr.is_running());
  4812. });
  4813. svr.wait_until_ready();
  4814. Client cli(HOST, PORT);
  4815. cli.set_read_timeout(1, 0);
  4816. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4818. EXPECT_EQ("short with a footer", res->body);
  4819. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4820. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4821. }
  4822. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4823. #ifdef CPPHTTPLIB_SSL_ENABLED
  4824. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4825. ASSERT_TRUE(svr.is_valid());
  4826. #else
  4827. Server svr;
  4828. #endif
  4829. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4830. if (req.path == "/routing_handler") {
  4831. res.set_header("PRE_ROUTING", "on");
  4832. res.set_content("Routing Handler", "text/plain");
  4833. return httplib::Server::HandlerResponse::Handled;
  4834. }
  4835. return httplib::Server::HandlerResponse::Unhandled;
  4836. });
  4837. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4838. res.set_content("Error", "text/html");
  4839. });
  4840. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4841. if (req.path == "/routing_handler") {
  4842. res.set_header("POST_ROUTING", "on");
  4843. }
  4844. });
  4845. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4846. res.set_content("Hello World!\n", "text/plain");
  4847. });
  4848. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4849. auto se = detail::scope_exit([&] {
  4850. svr.stop();
  4851. thread.join();
  4852. ASSERT_FALSE(svr.is_running());
  4853. });
  4854. svr.wait_until_ready();
  4855. {
  4856. #ifdef CPPHTTPLIB_SSL_ENABLED
  4857. SSLClient cli(HOST, PORT);
  4858. cli.enable_server_certificate_verification(false);
  4859. #else
  4860. Client cli(HOST, PORT);
  4861. #endif
  4862. auto res = cli.Get("/routing_handler");
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. EXPECT_EQ(StatusCode::OK_200, res->status);
  4865. EXPECT_EQ("Routing Handler", res->body);
  4866. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4867. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4868. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4869. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4870. }
  4871. {
  4872. #ifdef CPPHTTPLIB_SSL_ENABLED
  4873. SSLClient cli(HOST, PORT);
  4874. cli.enable_server_certificate_verification(false);
  4875. #else
  4876. Client cli(HOST, PORT);
  4877. #endif
  4878. auto res = cli.Get("/hi");
  4879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4880. EXPECT_EQ(StatusCode::OK_200, res->status);
  4881. EXPECT_EQ("Hello World!\n", res->body);
  4882. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4883. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4884. }
  4885. {
  4886. #ifdef CPPHTTPLIB_SSL_ENABLED
  4887. SSLClient cli(HOST, PORT);
  4888. cli.enable_server_certificate_verification(false);
  4889. #else
  4890. Client cli(HOST, PORT);
  4891. #endif
  4892. auto res = cli.Get("/aaa");
  4893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4894. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4895. EXPECT_EQ("Error", res->body);
  4896. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4897. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4898. }
  4899. }
  4900. TEST(RequestHandlerTest, PreRequestHandler) {
  4901. auto route_path = "/user/:user";
  4902. Server svr;
  4903. svr.Get("/hi", [](const Request &, Response &res) {
  4904. res.set_content("hi", "text/plain");
  4905. });
  4906. svr.Get(route_path, [](const Request &req, Response &res) {
  4907. res.set_content(req.path_params.at("user"), "text/plain");
  4908. });
  4909. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4910. if (req.matched_route == route_path) {
  4911. auto user = req.path_params.at("user");
  4912. if (user != "john") {
  4913. res.status = StatusCode::Forbidden_403;
  4914. res.set_content("error", "text/html");
  4915. return Server::HandlerResponse::Handled;
  4916. }
  4917. }
  4918. return Server::HandlerResponse::Unhandled;
  4919. });
  4920. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4921. auto se = detail::scope_exit([&] {
  4922. svr.stop();
  4923. thread.join();
  4924. ASSERT_FALSE(svr.is_running());
  4925. });
  4926. svr.wait_until_ready();
  4927. Client cli(HOST, PORT);
  4928. {
  4929. auto res = cli.Get("/hi");
  4930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4931. EXPECT_EQ(StatusCode::OK_200, res->status);
  4932. EXPECT_EQ("hi", res->body);
  4933. }
  4934. {
  4935. auto res = cli.Get("/user/john");
  4936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4937. EXPECT_EQ(StatusCode::OK_200, res->status);
  4938. EXPECT_EQ("john", res->body);
  4939. }
  4940. {
  4941. auto res = cli.Get("/user/invalid-user");
  4942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4943. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4944. EXPECT_EQ("error", res->body);
  4945. }
  4946. }
  4947. // The pre-request handler must run before the request body is read, so a
  4948. // rejected request never forces the server to buffer a (potentially large)
  4949. // body. Here the posted body is larger than the payload limit: if the body
  4950. // were read first the server would answer 413, but because the pre-request
  4951. // handler runs first it answers 403 and the body is never read.
  4952. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4953. Server svr;
  4954. svr.set_payload_max_length(8);
  4955. auto handler_ran = false;
  4956. svr.Post("/reject", [&](const Request &req, Response &res) {
  4957. handler_ran = true;
  4958. res.set_content(req.body, "text/plain");
  4959. });
  4960. svr.Post("/accept", [](const Request &req, Response &res) {
  4961. res.set_content(req.body, "text/plain");
  4962. });
  4963. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4964. if (req.matched_route == "/reject") {
  4965. res.status = StatusCode::Forbidden_403;
  4966. res.set_content("denied", "text/plain");
  4967. return Server::HandlerResponse::Handled;
  4968. }
  4969. return Server::HandlerResponse::Unhandled;
  4970. });
  4971. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4972. auto se = detail::scope_exit([&] {
  4973. svr.stop();
  4974. thread.join();
  4975. ASSERT_FALSE(svr.is_running());
  4976. });
  4977. svr.wait_until_ready();
  4978. Client cli(HOST, PORT);
  4979. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4980. // rejects with 403 before the body is read, so 413 is never reached.
  4981. {
  4982. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4985. EXPECT_EQ("denied", res->body);
  4986. EXPECT_FALSE(handler_ran);
  4987. }
  4988. // An approved route still reads the body and enforces the payload limit.
  4989. {
  4990. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4992. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4993. }
  4994. }
  4995. TEST(UserDataTest, BasicOperations) {
  4996. httplib::UserData ud;
  4997. // Initially empty
  4998. EXPECT_FALSE(ud.has("key"));
  4999. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5000. // set and get
  5001. ud.set("key", 42);
  5002. EXPECT_TRUE(ud.has("key"));
  5003. auto *p = ud.get<int>("key");
  5004. ASSERT_NE(nullptr, p);
  5005. EXPECT_EQ(42, *p);
  5006. // Type mismatch → nullptr
  5007. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5008. // Overwrite with different type
  5009. ud.set("key", std::string("hello"));
  5010. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5011. auto *s = ud.get<std::string>("key");
  5012. ASSERT_NE(nullptr, s);
  5013. EXPECT_EQ("hello", *s);
  5014. // erase
  5015. ud.erase("key");
  5016. EXPECT_FALSE(ud.has("key"));
  5017. // clear
  5018. ud.set("a", 1);
  5019. ud.set("b", 2);
  5020. ud.clear();
  5021. EXPECT_FALSE(ud.has("a"));
  5022. EXPECT_FALSE(ud.has("b"));
  5023. }
  5024. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5025. struct AuthCtx {
  5026. std::string user_id;
  5027. };
  5028. Server svr;
  5029. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5030. res.user_data.set("auth", AuthCtx{"alice"});
  5031. return Server::HandlerResponse::Unhandled;
  5032. });
  5033. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5034. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5035. ASSERT_NE(nullptr, ctx);
  5036. res.set_content("Hello " + ctx->user_id, "text/plain");
  5037. });
  5038. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5039. auto se = detail::scope_exit([&] {
  5040. svr.stop();
  5041. thread.join();
  5042. ASSERT_FALSE(svr.is_running());
  5043. });
  5044. svr.wait_until_ready();
  5045. Client cli(HOST, PORT);
  5046. auto res = cli.Get("/me");
  5047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5048. EXPECT_EQ(StatusCode::OK_200, res->status);
  5049. EXPECT_EQ("Hello alice", res->body);
  5050. }
  5051. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5052. struct RoleCtx {
  5053. std::string role;
  5054. };
  5055. Server svr;
  5056. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5057. res.user_data.set("role", RoleCtx{"admin"});
  5058. return Server::HandlerResponse::Unhandled;
  5059. });
  5060. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5061. auto *ctx = res.user_data.get<RoleCtx>("role");
  5062. ASSERT_NE(nullptr, ctx);
  5063. res.set_content(ctx->role, "text/plain");
  5064. });
  5065. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5066. auto se = detail::scope_exit([&] {
  5067. svr.stop();
  5068. thread.join();
  5069. ASSERT_FALSE(svr.is_running());
  5070. });
  5071. svr.wait_until_ready();
  5072. Client cli(HOST, PORT);
  5073. auto res = cli.Get("/role");
  5074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5075. EXPECT_EQ(StatusCode::OK_200, res->status);
  5076. EXPECT_EQ("admin", res->body);
  5077. }
  5078. TEST(InvalidFormatTest, StatusCode) {
  5079. Server svr;
  5080. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5081. res.set_content("Hello World!\n", "text/plain");
  5082. res.status = 9999; // Status should be a three-digit code...
  5083. });
  5084. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5085. auto se = detail::scope_exit([&] {
  5086. svr.stop();
  5087. thread.join();
  5088. ASSERT_FALSE(svr.is_running());
  5089. });
  5090. svr.wait_until_ready();
  5091. {
  5092. Client cli(HOST, PORT);
  5093. auto res = cli.Get("/hi");
  5094. ASSERT_FALSE(res);
  5095. }
  5096. }
  5097. TEST(URLFragmentTest, WithFragment) {
  5098. Server svr;
  5099. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5100. EXPECT_TRUE(req.target == "/hi");
  5101. });
  5102. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5103. auto se = detail::scope_exit([&] {
  5104. svr.stop();
  5105. thread.join();
  5106. ASSERT_FALSE(svr.is_running());
  5107. });
  5108. svr.wait_until_ready();
  5109. {
  5110. Client cli(HOST, PORT);
  5111. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5112. EXPECT_TRUE(res);
  5113. EXPECT_EQ(StatusCode::OK_200, res->status);
  5114. res = cli.Get("/hi%23key1=val1=key2=val2");
  5115. EXPECT_TRUE(res);
  5116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5117. }
  5118. }
  5119. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5120. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5121. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5122. Server svr;
  5123. std::vector<std::string> targets;
  5124. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5125. targets.push_back(req.target);
  5126. });
  5127. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5128. auto se = detail::scope_exit([&] {
  5129. svr.stop();
  5130. thread.join();
  5131. ASSERT_FALSE(svr.is_running());
  5132. });
  5133. svr.wait_until_ready();
  5134. Client cli(HOST, PORT);
  5135. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5136. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5137. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5138. // A '?' after the '#' belongs to the fragment, not to the query.
  5139. Request req;
  5140. req.method = "GET";
  5141. req.path = "/hi#f?x=1";
  5142. req.params.emplace("a", "1");
  5143. Response res;
  5144. auto error = Error::Success;
  5145. EXPECT_TRUE(cli.send(req, res, error));
  5146. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5147. "/hi?a=1"}),
  5148. targets);
  5149. }
  5150. TEST(HeaderWriter, SetHeaderWriter) {
  5151. Server svr;
  5152. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5153. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5154. return detail::write_headers(strm, hdrs);
  5155. });
  5156. svr.Get("/hi", [](const Request &req, Response &res) {
  5157. auto it = req.headers.find("CustomClientHeader");
  5158. EXPECT_TRUE(it != req.headers.end());
  5159. EXPECT_EQ(it->second, "CustomClientValue");
  5160. res.set_content("Hello World!\n", "text/plain");
  5161. });
  5162. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5163. auto se = detail::scope_exit([&] {
  5164. svr.stop();
  5165. thread.join();
  5166. ASSERT_FALSE(svr.is_running());
  5167. });
  5168. svr.wait_until_ready();
  5169. {
  5170. Client cli(HOST, PORT);
  5171. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5172. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5173. return detail::write_headers(strm, hdrs);
  5174. });
  5175. auto res = cli.Get("/hi");
  5176. EXPECT_TRUE(res);
  5177. EXPECT_EQ(StatusCode::OK_200, res->status);
  5178. auto it = res->headers.find("CustomServerHeader");
  5179. EXPECT_TRUE(it != res->headers.end());
  5180. EXPECT_EQ(it->second, "CustomServerValue");
  5181. }
  5182. }
  5183. class ServerTest : public ::testing::Test {
  5184. protected:
  5185. ServerTest()
  5186. : cli_(HOST, PORT)
  5187. #ifdef CPPHTTPLIB_SSL_ENABLED
  5188. ,
  5189. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5190. #endif
  5191. {
  5192. #ifdef CPPHTTPLIB_SSL_ENABLED
  5193. cli_.enable_server_certificate_verification(false);
  5194. #endif
  5195. // Allow LARGE_DATA (100MB) responses
  5196. cli_.set_payload_max_length(200 * 1024 * 1024);
  5197. }
  5198. virtual void SetUp() {
  5199. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5200. svr_.set_payload_max_length(200 * 1024 * 1024);
  5201. svr_.set_mount_point("/", "./www");
  5202. svr_.set_mount_point("/mount", "./www2");
  5203. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5204. svr_.Get("/hi",
  5205. [&](const Request & /*req*/, Response &res) {
  5206. res.set_content("Hello World!", "text/plain");
  5207. })
  5208. .Get("/file_content",
  5209. [&](const Request & /*req*/, Response &res) {
  5210. res.set_file_content("./www/dir/test.html");
  5211. })
  5212. .Get("/file_content_with_content_type",
  5213. [&](const Request & /*req*/, Response &res) {
  5214. res.set_file_content("./www/file", "text/plain");
  5215. })
  5216. .Get("/invalid_file_content",
  5217. [&](const Request & /*req*/, Response &res) {
  5218. res.set_file_content("./www/dir/invalid_file_path");
  5219. })
  5220. .Get("/http_response_splitting",
  5221. [&](const Request & /*req*/, Response &res) {
  5222. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5223. EXPECT_EQ(0U, res.headers.size());
  5224. EXPECT_FALSE(res.has_header("a"));
  5225. res.set_header("a", "1\nSet-Cookie: a=1");
  5226. EXPECT_EQ(0U, res.headers.size());
  5227. EXPECT_FALSE(res.has_header("a"));
  5228. res.set_header("a", "1\rSet-Cookie: a=1");
  5229. EXPECT_EQ(0U, res.headers.size());
  5230. EXPECT_FALSE(res.has_header("a"));
  5231. res.set_header("a\r\nb", "0");
  5232. EXPECT_EQ(0U, res.headers.size());
  5233. EXPECT_FALSE(res.has_header("a"));
  5234. res.set_header("a\rb", "0");
  5235. EXPECT_EQ(0U, res.headers.size());
  5236. EXPECT_FALSE(res.has_header("a"));
  5237. res.set_header("a\nb", "0");
  5238. EXPECT_EQ(0U, res.headers.size());
  5239. EXPECT_FALSE(res.has_header("a"));
  5240. res.set_redirect("1\r\nSet-Cookie: a=1");
  5241. EXPECT_EQ(0U, res.headers.size());
  5242. EXPECT_FALSE(res.has_header("Location"));
  5243. })
  5244. .Get("/slow",
  5245. [&](const Request & /*req*/, Response &res) {
  5246. std::this_thread::sleep_for(std::chrono::seconds(4));
  5247. res.set_content("slow", "text/plain");
  5248. })
  5249. #if 0
  5250. .Post("/slowpost",
  5251. [&](const Request & /*req*/, Response &res) {
  5252. std::this_thread::sleep_for(std::chrono::seconds(2));
  5253. res.set_content("slow", "text/plain");
  5254. })
  5255. #endif
  5256. .Get("/remote_addr",
  5257. [&](const Request &req, Response &res) {
  5258. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5259. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5260. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5261. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5262. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5263. #endif
  5264. res.set_content(req.remote_addr, "text/plain");
  5265. })
  5266. .Get("/local_addr",
  5267. [&](const Request &req, Response &res) {
  5268. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5269. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5270. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5271. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5272. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5273. #endif
  5274. auto local_addr = req.local_addr;
  5275. auto local_port = std::to_string(req.local_port);
  5276. res.set_content(local_addr.append(":").append(local_port),
  5277. "text/plain");
  5278. })
  5279. .Get("/endwith%",
  5280. [&](const Request & /*req*/, Response &res) {
  5281. res.set_content("Hello World!", "text/plain");
  5282. })
  5283. .Get("/a\\+\\+b",
  5284. [&](const Request &req, Response &res) {
  5285. ASSERT_TRUE(req.has_param("a +b"));
  5286. auto val = req.get_param_value("a +b");
  5287. res.set_content(val, "text/plain");
  5288. })
  5289. .Get("/", [&](const Request & /*req*/,
  5290. Response &res) { res.set_redirect("/hi"); })
  5291. .Post("/1",
  5292. [](const Request & /*req*/, Response &res) {
  5293. res.set_redirect("/2", StatusCode::SeeOther_303);
  5294. })
  5295. .Get("/2",
  5296. [](const Request & /*req*/, Response &res) {
  5297. res.set_content("redirected.", "text/plain");
  5298. res.status = StatusCode::OK_200;
  5299. })
  5300. .Post("/person",
  5301. [&](const Request &req, Response &res) {
  5302. if (req.has_param("name") && req.has_param("note")) {
  5303. persons_[req.get_param_value("name")] =
  5304. req.get_param_value("note");
  5305. } else {
  5306. res.status = StatusCode::BadRequest_400;
  5307. }
  5308. })
  5309. .Put("/person",
  5310. [&](const Request &req, Response &res) {
  5311. if (req.has_param("name") && req.has_param("note")) {
  5312. persons_[req.get_param_value("name")] =
  5313. req.get_param_value("note");
  5314. } else {
  5315. res.status = StatusCode::BadRequest_400;
  5316. }
  5317. })
  5318. .Get("/person/(.*)",
  5319. [&](const Request &req, Response &res) {
  5320. string name = req.matches[1];
  5321. if (persons_.find(name) != persons_.end()) {
  5322. auto note = persons_[name];
  5323. res.set_content(note, "text/plain");
  5324. } else {
  5325. res.status = StatusCode::NotFound_404;
  5326. }
  5327. })
  5328. .Delete("/person",
  5329. [&](const Request &req, Response &res) {
  5330. if (req.has_param("name")) {
  5331. string name = req.get_param_value("name");
  5332. if (persons_.find(name) != persons_.end()) {
  5333. persons_.erase(name);
  5334. res.set_content("DELETED", "text/plain");
  5335. } else {
  5336. res.status = StatusCode::NotFound_404;
  5337. }
  5338. } else {
  5339. res.status = StatusCode::BadRequest_400;
  5340. }
  5341. })
  5342. .Post("/x-www-form-urlencoded-json",
  5343. [&](const Request &req, Response &res) {
  5344. auto json = req.get_param_value("json");
  5345. ASSERT_EQ(JSON_DATA, json);
  5346. res.set_content(json, "appliation/json");
  5347. res.status = StatusCode::OK_200;
  5348. })
  5349. .Get("/streamed-chunked",
  5350. [&](const Request & /*req*/, Response &res) {
  5351. res.set_chunked_content_provider(
  5352. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5353. sink.os << "123";
  5354. sink.os << "456";
  5355. sink.os << "789";
  5356. sink.done();
  5357. return true;
  5358. });
  5359. })
  5360. .Get("/streamed-chunked-with-prohibited-trailer",
  5361. [&](const Request & /*req*/, Response &res) {
  5362. auto i = new int(0);
  5363. // Declare both a prohibited trailer (Content-Length) and an
  5364. // allowed one
  5365. res.set_header("Trailer", "Content-Length, X-Allowed");
  5366. res.set_chunked_content_provider(
  5367. "text/plain",
  5368. [i](size_t /*offset*/, DataSink &sink) {
  5369. switch (*i) {
  5370. case 0: sink.os << "123"; break;
  5371. case 1: sink.os << "456"; break;
  5372. case 2: sink.os << "789"; break;
  5373. case 3: {
  5374. sink.done_with_trailer(
  5375. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5376. } break;
  5377. }
  5378. (*i)++;
  5379. return true;
  5380. },
  5381. [i](bool success) {
  5382. EXPECT_TRUE(success);
  5383. delete i;
  5384. });
  5385. })
  5386. .Get("/streamed-chunked2",
  5387. [&](const Request & /*req*/, Response &res) {
  5388. auto i = new int(0);
  5389. res.set_chunked_content_provider(
  5390. "text/plain",
  5391. [i](size_t /*offset*/, DataSink &sink) {
  5392. switch (*i) {
  5393. case 0: sink.os << "123"; break;
  5394. case 1: sink.os << "456"; break;
  5395. case 2: sink.os << "789"; break;
  5396. case 3: sink.done(); break;
  5397. }
  5398. (*i)++;
  5399. return true;
  5400. },
  5401. [i](bool success) {
  5402. EXPECT_TRUE(success);
  5403. delete i;
  5404. });
  5405. })
  5406. .Get("/streamed-chunked-with-trailer",
  5407. [&](const Request & /*req*/, Response &res) {
  5408. auto i = new int(0);
  5409. res.set_header("Trailer", "Dummy1, Dummy2");
  5410. res.set_chunked_content_provider(
  5411. "text/plain",
  5412. [i](size_t /*offset*/, DataSink &sink) {
  5413. switch (*i) {
  5414. case 0: sink.os << "123"; break;
  5415. case 1: sink.os << "456"; break;
  5416. case 2: sink.os << "789"; break;
  5417. case 3: {
  5418. sink.done_with_trailer(
  5419. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5420. } break;
  5421. }
  5422. (*i)++;
  5423. return true;
  5424. },
  5425. [i](bool success) {
  5426. EXPECT_TRUE(success);
  5427. delete i;
  5428. });
  5429. })
  5430. .Get("/streamed",
  5431. [&](const Request & /*req*/, Response &res) {
  5432. res.set_content_provider(
  5433. 6, "text/plain",
  5434. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5435. sink.os << (offset < 3 ? "a" : "b");
  5436. return true;
  5437. });
  5438. })
  5439. .Get("/streamed-without-length",
  5440. [&](const Request & /*req*/, Response &res) {
  5441. auto data = new std::string("abcdefg");
  5442. res.set_content_provider(
  5443. "text/plain",
  5444. [data](size_t offset, DataSink &sink) {
  5445. if (offset < data->size()) {
  5446. sink.os << data->substr(offset);
  5447. }
  5448. sink.done();
  5449. return true;
  5450. },
  5451. [data](bool success) {
  5452. EXPECT_TRUE(success);
  5453. delete data;
  5454. });
  5455. })
  5456. .Get("/streamed-with-range",
  5457. [&](const Request &req, Response &res) {
  5458. auto data = new std::string("abcdefg");
  5459. // An explicit status keeps the server from picking the 206 it
  5460. // would otherwise choose for a ranged request, so the response
  5461. // is not a partial representation.
  5462. auto status = req.get_param_value("status");
  5463. if (status == "200") {
  5464. res.status = StatusCode::OK_200;
  5465. } else if (status == "403") {
  5466. res.status = StatusCode::Forbidden_403;
  5467. }
  5468. res.set_content_provider(
  5469. data->size(), "text/plain",
  5470. [data](size_t offset, size_t length, DataSink &sink) {
  5471. size_t DATA_CHUNK_SIZE = 4;
  5472. const auto &d = *data;
  5473. auto out_len =
  5474. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5475. auto ret =
  5476. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5477. EXPECT_TRUE(ret);
  5478. return true;
  5479. },
  5480. [data, &req](bool success) {
  5481. EXPECT_EQ(success, !req.has_param("error"));
  5482. delete data;
  5483. });
  5484. })
  5485. .Get("/streamed-cancel",
  5486. [&](const Request & /*req*/, Response &res) {
  5487. res.set_content_provider(
  5488. size_t(-1), "text/plain",
  5489. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5490. sink.os << "data_chunk";
  5491. return true;
  5492. });
  5493. })
  5494. .Get("/regex-with-delimiter",
  5495. [&](const Request &req, Response & /*res*/) {
  5496. ASSERT_TRUE(req.has_param("key"));
  5497. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5498. })
  5499. .Get("/with-range",
  5500. [&](const Request & /*req*/, Response &res) {
  5501. res.set_content("abcdefg", "text/plain");
  5502. })
  5503. .Get("/test-start-time",
  5504. [&](const Request &req, Response & /*res*/) {
  5505. EXPECT_NE(req.start_time_,
  5506. std::chrono::steady_clock::time_point::min());
  5507. })
  5508. .Get("/with-range-customized-response",
  5509. [&](const Request & /*req*/, Response &res) {
  5510. res.status = StatusCode::BadRequest_400;
  5511. res.set_content(JSON_DATA, "application/json");
  5512. })
  5513. .Post("/chunked",
  5514. [&](const Request &req, Response & /*res*/) {
  5515. EXPECT_EQ(req.body, "dechunked post body");
  5516. })
  5517. .Post("/large-chunked",
  5518. [&](const Request &req, Response & /*res*/) {
  5519. std::string expected(6 * 30 * 1024u, 'a');
  5520. EXPECT_EQ(req.body, expected);
  5521. })
  5522. .Post("/multipart",
  5523. [&](const Request &req, Response & /*res*/) {
  5524. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5525. req.form.get_field_count("text2") +
  5526. req.form.get_field_count("file3") +
  5527. req.form.get_field_count("file4"));
  5528. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5529. req.form.get_file_count("file2"));
  5530. ASSERT_TRUE(!req.form.has_file("???"));
  5531. ASSERT_TRUE(!req.form.has_field("???"));
  5532. ASSERT_TRUE(req.body.empty());
  5533. {
  5534. const auto &text = req.form.get_field("text1");
  5535. EXPECT_EQ("text default", text);
  5536. }
  5537. {
  5538. const auto &text = req.form.get_field("text2");
  5539. EXPECT_EQ("aωb", text);
  5540. }
  5541. {
  5542. const auto &file = req.form.get_file("file1");
  5543. EXPECT_EQ("hello.txt", file.filename);
  5544. EXPECT_EQ("text/plain", file.content_type);
  5545. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5546. }
  5547. {
  5548. const auto &file = req.form.get_file("file2");
  5549. EXPECT_EQ("world.json", file.filename);
  5550. EXPECT_EQ("application/json", file.content_type);
  5551. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5552. }
  5553. {
  5554. const auto &text = req.form.get_field("file3");
  5555. EXPECT_EQ(0u, text.size());
  5556. }
  5557. {
  5558. const auto &text = req.form.get_field("file4");
  5559. EXPECT_EQ(0u, text.size());
  5560. }
  5561. })
  5562. .Post("/multipart/multi_file_values",
  5563. [&](const Request &req, Response & /*res*/) {
  5564. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5565. req.form.get_field_count("multi_text1"));
  5566. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5567. ASSERT_TRUE(!req.form.has_file("???"));
  5568. ASSERT_TRUE(!req.form.has_field("???"));
  5569. ASSERT_TRUE(req.body.empty());
  5570. {
  5571. const auto &text = req.form.get_field("text");
  5572. EXPECT_EQ("default text", text);
  5573. }
  5574. {
  5575. const auto &text1_values = req.form.get_fields("multi_text1");
  5576. EXPECT_EQ(2u, text1_values.size());
  5577. EXPECT_EQ("aaaaa", text1_values[0]);
  5578. EXPECT_EQ("bbbbb", text1_values[1]);
  5579. }
  5580. {
  5581. const auto &file1_values = req.form.get_files("multi_file1");
  5582. EXPECT_EQ(2u, file1_values.size());
  5583. auto file1 = file1_values[0];
  5584. EXPECT_EQ(file1.filename, "hello.txt");
  5585. EXPECT_EQ(file1.content_type, "text/plain");
  5586. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5587. auto file2 = file1_values[1];
  5588. EXPECT_EQ(file2.filename, "world.json");
  5589. EXPECT_EQ(file2.content_type, "application/json");
  5590. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5591. }
  5592. })
  5593. .Post("/empty",
  5594. [&](const Request &req, Response &res) {
  5595. EXPECT_EQ(req.body, "");
  5596. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5597. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5598. res.set_content("empty", "text/plain");
  5599. })
  5600. .Post("/empty-no-content-type",
  5601. [&](const Request &req, Response &res) {
  5602. EXPECT_EQ(req.body, "");
  5603. EXPECT_FALSE(req.has_header("Content-Type"));
  5604. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5605. res.set_content("empty-no-content-type", "text/plain");
  5606. })
  5607. .Post("/path-only",
  5608. [&](const Request &req, Response &res) {
  5609. EXPECT_EQ(req.body, "");
  5610. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5611. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5612. res.set_content("path-only", "text/plain");
  5613. })
  5614. .Post("/path-headers-only",
  5615. [&](const Request &req, Response &res) {
  5616. EXPECT_EQ(req.body, "");
  5617. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5618. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5619. EXPECT_EQ("world", req.get_header_value("hello"));
  5620. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5621. res.set_content("path-headers-only", "text/plain");
  5622. })
  5623. .Post("/post-large",
  5624. [&](const Request &req, Response &res) {
  5625. EXPECT_EQ(req.body, LARGE_DATA);
  5626. res.set_content(req.body, "text/plain");
  5627. })
  5628. .Post("/post-loopback",
  5629. [&](const Request &, Response &res,
  5630. ContentReader const &content_reader) {
  5631. std::string body;
  5632. content_reader([&](const char *data, size_t data_length) {
  5633. body.append(data, data_length);
  5634. return true;
  5635. });
  5636. res.set_content(body, "text/plain");
  5637. })
  5638. .Put("/put-loopback",
  5639. [&](const Request &, Response &res,
  5640. ContentReader const &content_reader) {
  5641. std::string body;
  5642. content_reader([&](const char *data, size_t data_length) {
  5643. body.append(data, data_length);
  5644. return true;
  5645. });
  5646. res.set_content(body, "text/plain");
  5647. })
  5648. .Patch("/patch-loopback",
  5649. [&](const Request &, Response &res,
  5650. ContentReader const &content_reader) {
  5651. std::string body;
  5652. content_reader([&](const char *data, size_t data_length) {
  5653. body.append(data, data_length);
  5654. return true;
  5655. });
  5656. res.set_content(body, "text/plain");
  5657. })
  5658. .Put("/empty-no-content-type",
  5659. [&](const Request &req, Response &res) {
  5660. EXPECT_EQ(req.body, "");
  5661. EXPECT_FALSE(req.has_header("Content-Type"));
  5662. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5663. res.set_content("empty-no-content-type", "text/plain");
  5664. })
  5665. .Put("/put",
  5666. [&](const Request &req, Response &res) {
  5667. EXPECT_EQ(req.body, "PUT");
  5668. res.set_content(req.body, "text/plain");
  5669. })
  5670. .Put("/put-large",
  5671. [&](const Request &req, Response &res) {
  5672. EXPECT_EQ(req.body, LARGE_DATA);
  5673. res.set_content(req.body, "text/plain");
  5674. })
  5675. .Patch("/patch",
  5676. [&](const Request &req, Response &res) {
  5677. EXPECT_EQ(req.body, "PATCH");
  5678. res.set_content(req.body, "text/plain");
  5679. })
  5680. .Delete("/delete",
  5681. [&](const Request & /*req*/, Response &res) {
  5682. res.set_content("DELETE", "text/plain");
  5683. })
  5684. .Delete("/delete-body",
  5685. [&](const Request &req, Response &res) {
  5686. EXPECT_EQ(req.body, "content");
  5687. res.set_content(req.body, "text/plain");
  5688. })
  5689. .Options(R"(\*)",
  5690. [&](const Request & /*req*/, Response &res) {
  5691. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5692. })
  5693. .CustomRoute("PROPFIND", "/dav/:id",
  5694. [&](const Request &req, Response &res) {
  5695. res.set_header("x-body-size",
  5696. std::to_string(req.body.size()));
  5697. res.set_header("x-matched-route", req.matched_route);
  5698. res.set_header("x-dav-id", req.path_params.at("id"));
  5699. res.status = StatusCode::MultiStatus_207;
  5700. res.set_content(req.body, "application/xml");
  5701. })
  5702. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5703. [&](const Request &req, Response &res) {
  5704. res.set_header("x-dav-match", req.matches[1]);
  5705. res.status = StatusCode::MultiStatus_207;
  5706. })
  5707. .CustomRoute("MKCOL", "/dav-mkcol",
  5708. [&](const Request &req, Response &res) {
  5709. EXPECT_TRUE(req.body.empty());
  5710. res.status = StatusCode::Created_201;
  5711. })
  5712. .CustomRoute(
  5713. "REPORT", "/dav-report",
  5714. [&](const Request & /*req*/, Response &res,
  5715. const ContentReader &content_reader) {
  5716. std::string body;
  5717. content_reader([&](const char *data, size_t data_length) {
  5718. body.append(data, data_length);
  5719. return true;
  5720. });
  5721. res.set_header("x-body-size", std::to_string(body.size()));
  5722. res.status = StatusCode::MultiStatus_207;
  5723. res.set_content(body, "application/xml");
  5724. })
  5725. .Get("/request-target",
  5726. [&](const Request &req, Response & /*res*/) {
  5727. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5728. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5729. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5730. })
  5731. .Get("/long-query-value",
  5732. [&](const Request &req, Response & /*res*/) {
  5733. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5734. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5735. })
  5736. .Get("/too-long-query-value",
  5737. [&](const Request &req, Response & /*res*/) {
  5738. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5739. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5740. })
  5741. .Get("/array-param",
  5742. [&](const Request &req, Response & /*res*/) {
  5743. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5744. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5745. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5746. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5747. })
  5748. .Get("/array-param-values",
  5749. [&](const Request &req, Response & /*res*/) {
  5750. auto values = req.get_param_values("array");
  5751. EXPECT_EQ(3u, values.size());
  5752. EXPECT_EQ("value1", values[0]);
  5753. EXPECT_EQ("value2", values[1]);
  5754. EXPECT_EQ("value3", values[2]);
  5755. auto empty = req.get_param_values("nonexistent");
  5756. EXPECT_TRUE(empty.empty());
  5757. })
  5758. .Post("/validate-no-multiple-headers",
  5759. [&](const Request &req, Response & /*res*/) {
  5760. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5761. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5762. })
  5763. .Post("/content_receiver",
  5764. [&](const Request &req, Response &res,
  5765. const ContentReader &content_reader) {
  5766. if (req.is_multipart_form_data()) {
  5767. std::vector<FormData> items;
  5768. content_reader(
  5769. [&](const FormData &file) {
  5770. items.push_back(file);
  5771. return true;
  5772. },
  5773. [&](const char *data, size_t data_length) {
  5774. items.back().content.append(data, data_length);
  5775. return true;
  5776. });
  5777. EXPECT_EQ(5u, items.size());
  5778. {
  5779. const auto &file = get_file_value(items, "text1");
  5780. EXPECT_TRUE(file.filename.empty());
  5781. EXPECT_EQ("text default", file.content);
  5782. }
  5783. {
  5784. const auto &file = get_file_value(items, "text2");
  5785. EXPECT_TRUE(file.filename.empty());
  5786. EXPECT_EQ("aωb", file.content);
  5787. }
  5788. {
  5789. const auto &file = get_file_value(items, "file1");
  5790. EXPECT_EQ("hello.txt", file.filename);
  5791. EXPECT_EQ("text/plain", file.content_type);
  5792. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5793. }
  5794. {
  5795. const auto &file = get_file_value(items, "file2");
  5796. EXPECT_EQ("world.json", file.filename);
  5797. EXPECT_EQ("application/json", file.content_type);
  5798. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5799. }
  5800. {
  5801. const auto &file = get_file_value(items, "file3");
  5802. EXPECT_TRUE(file.filename.empty());
  5803. EXPECT_EQ("application/octet-stream", file.content_type);
  5804. EXPECT_EQ(0u, file.content.size());
  5805. }
  5806. } else {
  5807. std::string body;
  5808. content_reader([&](const char *data, size_t data_length) {
  5809. EXPECT_EQ(7U, data_length);
  5810. body.append(data, data_length);
  5811. return true;
  5812. });
  5813. EXPECT_EQ(body, "content");
  5814. res.set_content(body, "text/plain");
  5815. }
  5816. })
  5817. .Put("/content_receiver",
  5818. [&](const Request & /*req*/, Response &res,
  5819. const ContentReader &content_reader) {
  5820. std::string body;
  5821. content_reader([&](const char *data, size_t data_length) {
  5822. body.append(data, data_length);
  5823. return true;
  5824. });
  5825. EXPECT_EQ(body, "content");
  5826. res.set_content(body, "text/plain");
  5827. })
  5828. .Patch("/content_receiver",
  5829. [&](const Request & /*req*/, Response &res,
  5830. const ContentReader &content_reader) {
  5831. std::string body;
  5832. content_reader([&](const char *data, size_t data_length) {
  5833. body.append(data, data_length);
  5834. return true;
  5835. });
  5836. EXPECT_EQ(body, "content");
  5837. res.set_content(body, "text/plain");
  5838. })
  5839. .Post("/query-string-and-body",
  5840. [&](const Request &req, Response & /*res*/) {
  5841. ASSERT_TRUE(req.has_param("key"));
  5842. EXPECT_EQ(req.get_param_value("key"), "value");
  5843. EXPECT_EQ(req.body, "content");
  5844. })
  5845. .Get("/last-request",
  5846. [&](const Request &req, Response & /*res*/) {
  5847. EXPECT_EQ("close", req.get_header_value("Connection"));
  5848. })
  5849. .Get(R"(/redirect/(\d+))",
  5850. [&](const Request &req, Response &res) {
  5851. auto num = std::stoi(req.matches[1]) + 1;
  5852. std::string url = "/redirect/" + std::to_string(num);
  5853. res.set_redirect(url);
  5854. })
  5855. .Post("/binary",
  5856. [&](const Request &req, Response &res) {
  5857. EXPECT_EQ(4U, req.body.size());
  5858. EXPECT_EQ("application/octet-stream",
  5859. req.get_header_value("Content-Type"));
  5860. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5861. res.set_content(req.body, "application/octet-stream");
  5862. })
  5863. .Put("/binary",
  5864. [&](const Request &req, Response &res) {
  5865. EXPECT_EQ(4U, req.body.size());
  5866. EXPECT_EQ("application/octet-stream",
  5867. req.get_header_value("Content-Type"));
  5868. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5869. res.set_content(req.body, "application/octet-stream");
  5870. })
  5871. .Patch("/binary",
  5872. [&](const Request &req, Response &res) {
  5873. EXPECT_EQ(4U, req.body.size());
  5874. EXPECT_EQ("application/octet-stream",
  5875. req.get_header_value("Content-Type"));
  5876. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5877. res.set_content(req.body, "application/octet-stream");
  5878. })
  5879. .Delete("/binary",
  5880. [&](const Request &req, Response &res) {
  5881. EXPECT_EQ(4U, req.body.size());
  5882. EXPECT_EQ("application/octet-stream",
  5883. req.get_header_value("Content-Type"));
  5884. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5885. res.set_content(req.body, "application/octet-stream");
  5886. })
  5887. .Get("/issue1772",
  5888. [&](const Request & /*req*/, Response &res) {
  5889. res.status = 401;
  5890. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5891. })
  5892. .Delete("/issue609",
  5893. [](const httplib::Request &, httplib::Response &res,
  5894. const httplib::ContentReader &) {
  5895. res.set_content("ok", "text/plain");
  5896. })
  5897. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5898. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5899. .Get("/compress",
  5900. [&](const Request & /*req*/, Response &res) {
  5901. res.set_content(
  5902. "12345678901234567890123456789012345678901234567890123456789"
  5903. "01234567890123456789012345678901234567890",
  5904. "text/plain");
  5905. })
  5906. .Get("/compress-with-charset",
  5907. [&](const Request & /*req*/, Response &res) {
  5908. res.set_content(
  5909. "12345678901234567890123456789012345678901234567890123456789"
  5910. "01234567890123456789012345678901234567890",
  5911. "application/json; charset=utf-8");
  5912. })
  5913. .Get("/nocompress",
  5914. [&](const Request & /*req*/, Response &res) {
  5915. res.set_content(
  5916. "12345678901234567890123456789012345678901234567890123456789"
  5917. "01234567890123456789012345678901234567890",
  5918. "application/octet-stream");
  5919. })
  5920. .Post("/compress-multipart",
  5921. [&](const Request &req, Response & /*res*/) {
  5922. EXPECT_EQ(2u, req.form.fields.size());
  5923. ASSERT_TRUE(!req.form.has_field("???"));
  5924. {
  5925. const auto &text = req.form.get_field("key1");
  5926. EXPECT_EQ("test", text);
  5927. }
  5928. {
  5929. const auto &text = req.form.get_field("key2");
  5930. EXPECT_EQ("--abcdefg123", text);
  5931. }
  5932. })
  5933. #endif
  5934. ;
  5935. persons_["john"] = "programmer";
  5936. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5937. svr_.wait_until_ready();
  5938. }
  5939. virtual void TearDown() {
  5940. svr_.stop();
  5941. if (!request_threads_.empty()) {
  5942. std::this_thread::sleep_for(std::chrono::seconds(1));
  5943. for (auto &t : request_threads_) {
  5944. t.join();
  5945. }
  5946. }
  5947. t_.join();
  5948. }
  5949. map<string, string> persons_;
  5950. #ifdef CPPHTTPLIB_SSL_ENABLED
  5951. SSLClient cli_;
  5952. SSLServer svr_;
  5953. #else
  5954. Client cli_;
  5955. Server svr_;
  5956. #endif
  5957. thread t_;
  5958. std::vector<thread> request_threads_;
  5959. };
  5960. TEST_F(ServerTest, GetMethod200) {
  5961. auto res = cli_.Get("/hi");
  5962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5963. EXPECT_EQ("HTTP/1.1", res->version);
  5964. EXPECT_EQ(StatusCode::OK_200, res->status);
  5965. EXPECT_EQ("OK", res->reason);
  5966. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5967. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5968. EXPECT_EQ("Hello World!", res->body);
  5969. }
  5970. TEST_F(ServerTest, GetEmptyFile) {
  5971. auto res = cli_.Get("/empty_file");
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::OK_200, res->status);
  5974. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5975. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5976. EXPECT_EQ("", res->body);
  5977. }
  5978. TEST_F(ServerTest, GetFileContent) {
  5979. auto res = cli_.Get("/file_content");
  5980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5981. EXPECT_EQ(StatusCode::OK_200, res->status);
  5982. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5983. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5984. EXPECT_EQ("test.html", res->body);
  5985. }
  5986. TEST_F(ServerTest, GetFileContentWithRange) {
  5987. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5989. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5990. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5991. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5992. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5993. EXPECT_EQ("est", res->body);
  5994. }
  5995. TEST_F(ServerTest, GetFileContentWithContentType) {
  5996. auto res = cli_.Get("/file_content_with_content_type");
  5997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5998. EXPECT_EQ(StatusCode::OK_200, res->status);
  5999. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6000. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6001. EXPECT_EQ("file\n", res->body);
  6002. }
  6003. TEST_F(ServerTest, GetInvalidFileContent) {
  6004. auto res = cli_.Get("/invalid_file_content");
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6007. }
  6008. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6009. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6011. EXPECT_EQ("HTTP/1.1", res->version);
  6012. EXPECT_EQ(StatusCode::OK_200, res->status);
  6013. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6014. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6015. EXPECT_EQ("Hello World!", res->body);
  6016. }
  6017. TEST_F(ServerTest, GetMethod302) {
  6018. auto res = cli_.Get("/");
  6019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6020. EXPECT_EQ(StatusCode::Found_302, res->status);
  6021. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6022. }
  6023. TEST_F(ServerTest, GetMethod302Redirect) {
  6024. cli_.set_follow_location(true);
  6025. auto res = cli_.Get("/");
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::OK_200, res->status);
  6028. EXPECT_EQ("Hello World!", res->body);
  6029. EXPECT_EQ("/hi", res->location);
  6030. }
  6031. TEST_F(ServerTest, GetMethod404) {
  6032. auto res = cli_.Get("/invalid");
  6033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6034. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6035. }
  6036. TEST_F(ServerTest, HeadMethod200) {
  6037. auto res = cli_.Head("/hi");
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. EXPECT_EQ(StatusCode::OK_200, res->status);
  6040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6041. EXPECT_TRUE(res->body.empty());
  6042. }
  6043. TEST_F(ServerTest, HeadMethod200Static) {
  6044. auto res = cli_.Head("/mount/dir/index.html");
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::OK_200, res->status);
  6047. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6048. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6049. EXPECT_TRUE(res->body.empty());
  6050. }
  6051. TEST_F(ServerTest, HeadMethod404) {
  6052. auto res = cli_.Head("/invalid");
  6053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6055. EXPECT_TRUE(res->body.empty());
  6056. }
  6057. TEST_F(ServerTest, GetMethodPersonJohn) {
  6058. auto res = cli_.Get("/person/john");
  6059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6060. EXPECT_EQ(StatusCode::OK_200, res->status);
  6061. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6062. EXPECT_EQ("programmer", res->body);
  6063. }
  6064. TEST_F(ServerTest, PostMethod1) {
  6065. auto res = cli_.Get("/person/john1");
  6066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6067. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6068. res = cli_.Post("/person", "name=john1&note=coder",
  6069. "application/x-www-form-urlencoded");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. ASSERT_EQ(StatusCode::OK_200, res->status);
  6072. res = cli_.Get("/person/john1");
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. ASSERT_EQ(StatusCode::OK_200, res->status);
  6075. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6076. ASSERT_EQ("coder", res->body);
  6077. }
  6078. TEST_F(ServerTest, PostMethod2) {
  6079. auto res = cli_.Get("/person/john2");
  6080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6081. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6082. Params params;
  6083. params.emplace("name", "john2");
  6084. params.emplace("note", "coder");
  6085. res = cli_.Post("/person", params);
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. ASSERT_EQ(StatusCode::OK_200, res->status);
  6088. res = cli_.Get("/person/john2");
  6089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6090. ASSERT_EQ(StatusCode::OK_200, res->status);
  6091. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6092. ASSERT_EQ("coder", res->body);
  6093. }
  6094. TEST_F(ServerTest, PutMethod3) {
  6095. auto res = cli_.Get("/person/john3");
  6096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6097. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6098. Params params;
  6099. params.emplace("name", "john3");
  6100. params.emplace("note", "coder");
  6101. res = cli_.Put("/person", params);
  6102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6103. ASSERT_EQ(StatusCode::OK_200, res->status);
  6104. res = cli_.Get("/person/john3");
  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, DeleteMethod1) {
  6111. auto res = cli_.Get("/person/john4");
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6114. Params params;
  6115. params.emplace("name", "john4");
  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/john4");
  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. Params delete_params;
  6126. delete_params.emplace("name", "john4");
  6127. res = cli_.Delete("/person", delete_params);
  6128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6129. ASSERT_EQ(StatusCode::OK_200, res->status);
  6130. ASSERT_EQ("DELETED", res->body);
  6131. res = cli_.Get("/person/john4");
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6134. }
  6135. TEST_F(ServerTest, DeleteMethod2) {
  6136. auto res = cli_.Get("/person/john5");
  6137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6138. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6139. Params params;
  6140. params.emplace("name", "john5");
  6141. params.emplace("note", "developer");
  6142. res = cli_.Post("/person", params);
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. ASSERT_EQ(StatusCode::OK_200, res->status);
  6145. res = cli_.Get("/person/john5");
  6146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6147. ASSERT_EQ(StatusCode::OK_200, res->status);
  6148. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6149. ASSERT_EQ("developer", res->body);
  6150. Params delete_params;
  6151. delete_params.emplace("name", "john5");
  6152. Headers headers;
  6153. headers.emplace("Custom-Header", "test-value");
  6154. res = cli_.Delete("/person", headers, delete_params);
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. ASSERT_EQ(StatusCode::OK_200, res->status);
  6157. ASSERT_EQ("DELETED", res->body);
  6158. res = cli_.Get("/person/john5");
  6159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6160. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6161. }
  6162. TEST_F(ServerTest, DeleteMethod3) {
  6163. auto res = cli_.Get("/person/john6");
  6164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6165. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6166. Params params;
  6167. params.emplace("name", "john6");
  6168. params.emplace("note", "tester");
  6169. res = cli_.Post("/person", params);
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. ASSERT_EQ(StatusCode::OK_200, res->status);
  6172. res = cli_.Get("/person/john6");
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. ASSERT_EQ(StatusCode::OK_200, res->status);
  6175. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6176. ASSERT_EQ("tester", res->body);
  6177. Params delete_params;
  6178. delete_params.emplace("name", "john6");
  6179. Headers headers;
  6180. headers.emplace("Custom-Header", "test-value");
  6181. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6183. ASSERT_EQ(StatusCode::OK_200, res->status);
  6184. ASSERT_EQ("DELETED", res->body);
  6185. res = cli_.Get("/person/john6");
  6186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6187. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6188. }
  6189. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6190. Params params;
  6191. params.emplace("json", JSON_DATA);
  6192. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. ASSERT_EQ(StatusCode::OK_200, res->status);
  6195. ASSERT_EQ(JSON_DATA, res->body);
  6196. }
  6197. TEST_F(ServerTest, PostEmptyContent) {
  6198. auto res = cli_.Post("/empty", "", "text/plain");
  6199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6200. ASSERT_EQ(StatusCode::OK_200, res->status);
  6201. ASSERT_EQ("empty", res->body);
  6202. }
  6203. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6204. auto res = cli_.Post("/empty-no-content-type");
  6205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6206. ASSERT_EQ(StatusCode::OK_200, res->status);
  6207. ASSERT_EQ("empty-no-content-type", res->body);
  6208. }
  6209. TEST_F(ServerTest, PostPathOnly) {
  6210. auto res = cli_.Post("/path-only");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. ASSERT_EQ(StatusCode::OK_200, res->status);
  6213. ASSERT_EQ("path-only", res->body);
  6214. }
  6215. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6216. auto res = cli_.Post("/path-headers-only",
  6217. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. ASSERT_EQ(StatusCode::OK_200, res->status);
  6220. ASSERT_EQ("path-headers-only", res->body);
  6221. }
  6222. TEST_F(ServerTest, PostLarge) {
  6223. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::OK_200, res->status);
  6226. EXPECT_EQ(LARGE_DATA, res->body);
  6227. }
  6228. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6229. auto res = cli_.Put("/empty-no-content-type");
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::OK_200, res->status);
  6232. ASSERT_EQ("empty-no-content-type", res->body);
  6233. }
  6234. TEST_F(ServerTest, GetMethodDir) {
  6235. auto res = cli_.Get("/dir/");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::OK_200, res->status);
  6238. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6239. auto body = R"(<html>
  6240. <head>
  6241. </head>
  6242. <body>
  6243. <a href="/dir/test.html">Test</a>
  6244. <a href="/hi">hi</a>
  6245. </body>
  6246. </html>
  6247. )";
  6248. EXPECT_EQ(body, res->body);
  6249. }
  6250. TEST_F(ServerTest, GetMethodDirTest) {
  6251. auto res = cli_.Get("/dir/test.html");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. EXPECT_EQ(StatusCode::OK_200, res->status);
  6254. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6255. EXPECT_EQ("test.html", res->body);
  6256. }
  6257. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6258. auto res = cli_.Get("/dir/../dir/test.html");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::OK_200, res->status);
  6261. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6262. EXPECT_EQ("test.html", res->body);
  6263. }
  6264. TEST_F(ServerTest, GetMethodInvalidPath) {
  6265. auto res = cli_.Get("/dir/../test.html");
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6268. }
  6269. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6270. auto res = cli_.Get("/../www/dir/test.html");
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6273. }
  6274. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6275. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6277. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6278. }
  6279. TEST_F(ServerTest, GetMethodDirMountTest) {
  6280. auto res = cli_.Get("/mount/dir/test.html");
  6281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6282. EXPECT_EQ(StatusCode::OK_200, res->status);
  6283. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6284. EXPECT_EQ("test.html", res->body);
  6285. }
  6286. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6287. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6289. EXPECT_EQ(StatusCode::OK_200, res->status);
  6290. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6291. EXPECT_EQ("test.html", res->body);
  6292. }
  6293. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6294. auto res = cli_.Get("/mount/dir/../test.html");
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6297. }
  6298. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6299. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6301. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6302. }
  6303. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6304. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6307. }
  6308. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6309. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6311. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6312. }
  6313. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6314. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6316. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6317. }
  6318. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6319. auto res = cli_.Get("/mount/dir");
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6322. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6323. }
  6324. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6325. auto res = cli_.Get("//dir");
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6328. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6329. }
  6330. TEST_F(ServerTest, PostMethod303) {
  6331. auto res = cli_.Post("/1", "body", "text/plain");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6334. EXPECT_EQ("/2", res->get_header_value("Location"));
  6335. }
  6336. TEST_F(ServerTest, PostMethod303Redirect) {
  6337. cli_.set_follow_location(true);
  6338. auto res = cli_.Post("/1", "body", "text/plain");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::OK_200, res->status);
  6341. EXPECT_EQ("redirected.", res->body);
  6342. EXPECT_EQ("/2", res->location);
  6343. }
  6344. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6345. auto res = cli_.Get("/dir/test.abcde");
  6346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6347. EXPECT_EQ(StatusCode::OK_200, res->status);
  6348. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6349. EXPECT_EQ("abcde", res->body);
  6350. }
  6351. TEST_F(ServerTest, StaticFileRange) {
  6352. auto res =
  6353. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6355. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6356. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6357. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6358. EXPECT_EQ(true, res->has_header("Content-Range"));
  6359. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6360. EXPECT_EQ(std::string("cd"), res->body);
  6361. }
  6362. TEST_F(ServerTest, StaticFileRanges) {
  6363. auto res = cli_.Get("/dir/test.abcde",
  6364. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6366. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6367. EXPECT_TRUE(
  6368. res->get_header_value("Content-Type")
  6369. .find(
  6370. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6371. 0);
  6372. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6373. }
  6374. TEST_F(ServerTest, StaticFileRangeHead) {
  6375. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6378. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6379. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6380. EXPECT_EQ(true, res->has_header("Content-Range"));
  6381. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6382. }
  6383. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6384. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6387. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6388. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6389. EXPECT_EQ(true, res->has_header("Content-Range"));
  6390. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6391. res->get_header_value("Content-Range"));
  6392. EXPECT_EQ("LAST\n", res->body);
  6393. }
  6394. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6395. auto res =
  6396. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6398. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6399. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6400. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6401. EXPECT_EQ(true, res->has_header("Content-Range"));
  6402. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6403. }
  6404. TEST_F(ServerTest, StaticFileBigFile) {
  6405. auto res = cli_.Get("/dir/1MB.txt");
  6406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6407. EXPECT_EQ(StatusCode::OK_200, res->status);
  6408. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6409. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6410. }
  6411. TEST_F(ServerTest, InvalidBaseDirMount) {
  6412. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6413. }
  6414. TEST_F(ServerTest, Binary) {
  6415. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6416. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6417. "application/octet-stream");
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. ASSERT_EQ(StatusCode::OK_200, res->status);
  6420. ASSERT_EQ(4U, res->body.size());
  6421. res = cli_.Put("/binary", binary.data(), binary.size(),
  6422. "application/octet-stream");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. ASSERT_EQ(StatusCode::OK_200, res->status);
  6425. ASSERT_EQ(4U, res->body.size());
  6426. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6427. "application/octet-stream");
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. ASSERT_EQ(StatusCode::OK_200, res->status);
  6430. ASSERT_EQ(4U, res->body.size());
  6431. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6432. "application/octet-stream");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. ASSERT_EQ(StatusCode::OK_200, res->status);
  6435. ASSERT_EQ(4U, res->body.size());
  6436. }
  6437. TEST_F(ServerTest, BinaryString) {
  6438. auto binary = std::string("\x00\x01\x02\x03", 4);
  6439. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. ASSERT_EQ(StatusCode::OK_200, res->status);
  6442. ASSERT_EQ(4U, res->body.size());
  6443. res = cli_.Put("/binary", binary, "application/octet-stream");
  6444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6445. ASSERT_EQ(StatusCode::OK_200, res->status);
  6446. ASSERT_EQ(4U, res->body.size());
  6447. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. ASSERT_EQ(StatusCode::OK_200, res->status);
  6450. ASSERT_EQ(4U, res->body.size());
  6451. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. ASSERT_EQ(StatusCode::OK_200, res->status);
  6454. ASSERT_EQ(4U, res->body.size());
  6455. }
  6456. TEST_F(ServerTest, EmptyRequest) {
  6457. auto res = cli_.Get("");
  6458. ASSERT_TRUE(!res);
  6459. EXPECT_EQ(Error::Connection, res.error());
  6460. }
  6461. TEST_F(ServerTest, LongRequest) {
  6462. std::string request;
  6463. for (size_t i = 0; i < 545; i++) {
  6464. request += "/TooLongRequest";
  6465. }
  6466. request += "OK";
  6467. auto res = cli_.Get(request.c_str());
  6468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6470. }
  6471. TEST_F(ServerTest, TooLongRequest) {
  6472. std::string request;
  6473. for (size_t i = 0; i < 546; i++) {
  6474. request += "/TooLongRequest";
  6475. }
  6476. request += "_NG";
  6477. auto start = std::chrono::high_resolution_clock::now();
  6478. cli_.set_keep_alive(true);
  6479. auto res = cli_.Get(request.c_str());
  6480. auto end = std::chrono::high_resolution_clock::now();
  6481. auto elapsed =
  6482. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6483. .count();
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6486. EXPECT_LE(elapsed, 1000);
  6487. EXPECT_EQ("close", res->get_header_value("Connection"));
  6488. EXPECT_FALSE(cli_.is_socket_open());
  6489. }
  6490. TEST_F(ServerTest, AlmostTooLongRequest) {
  6491. // test for #2046 - URI length check shouldn't include other content on req
  6492. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6493. // leading /, space, HTTP/1.1)
  6494. std::string request =
  6495. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6496. auto res = cli_.Get(request.c_str());
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6499. }
  6500. TEST_F(ServerTest, LongHeader) {
  6501. Request req;
  6502. req.method = "GET";
  6503. req.path = "/hi";
  6504. std::string host_and_port;
  6505. host_and_port += HOST;
  6506. host_and_port += ":";
  6507. host_and_port += std::to_string(PORT);
  6508. req.headers.emplace("Host", host_and_port.c_str());
  6509. req.headers.emplace("Accept", "*/*");
  6510. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6511. req.headers.emplace(
  6512. "Header-Name",
  6513. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6514. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6515. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6516. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6517. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6518. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6524. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6525. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6526. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6527. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6528. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6529. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6530. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6531. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6532. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6533. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6534. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6535. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6536. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6537. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6538. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6539. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6540. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6541. "@@@@@@@@@@@@@@@@");
  6542. auto res = std::make_shared<Response>();
  6543. auto error = Error::Success;
  6544. auto ret = cli_.send(req, *res, error);
  6545. ASSERT_TRUE(ret);
  6546. EXPECT_EQ(StatusCode::OK_200, res->status);
  6547. }
  6548. TEST_F(ServerTest, LongQueryValue) {
  6549. auto start = std::chrono::high_resolution_clock::now();
  6550. cli_.set_keep_alive(true);
  6551. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6552. auto end = std::chrono::high_resolution_clock::now();
  6553. auto elapsed =
  6554. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6555. .count();
  6556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6557. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6558. EXPECT_LE(elapsed, 1000);
  6559. EXPECT_EQ("close", res->get_header_value("Connection"));
  6560. EXPECT_FALSE(cli_.is_socket_open());
  6561. }
  6562. TEST_F(ServerTest, TooLongQueryValue) {
  6563. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6564. ASSERT_FALSE(res);
  6565. EXPECT_EQ(Error::Read, res.error());
  6566. }
  6567. TEST_F(ServerTest, TooLongHeader) {
  6568. Request req;
  6569. req.method = "GET";
  6570. req.path = "/hi";
  6571. std::string host_and_port;
  6572. host_and_port += HOST;
  6573. host_and_port += ":";
  6574. host_and_port += std::to_string(PORT);
  6575. req.headers.emplace("Host", host_and_port.c_str());
  6576. req.headers.emplace("Accept", "*/*");
  6577. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6578. req.headers.emplace(
  6579. "Header-Name",
  6580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6597. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6600. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6601. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6602. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6608. "@@@@@@@@@@@@@@@@@");
  6609. auto res = std::make_shared<Response>();
  6610. auto error = Error::Success;
  6611. auto ret = cli_.send(req, *res, error);
  6612. ASSERT_TRUE(ret);
  6613. EXPECT_EQ(StatusCode::OK_200, res->status);
  6614. }
  6615. TEST_F(ServerTest, HeaderCountAtLimit) {
  6616. // Test with headers just under the 100 limit
  6617. httplib::Headers headers;
  6618. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6619. // This should keep us just under the 100 header limit
  6620. for (int i = 0; i < 95; i++) {
  6621. std::string name = "X-Test-Header-" + std::to_string(i);
  6622. std::string value = "value" + std::to_string(i);
  6623. headers.emplace(name, value);
  6624. }
  6625. // This should work fine as we're under the limit
  6626. auto res = cli_.Get("/hi", headers);
  6627. EXPECT_TRUE(res);
  6628. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6629. }
  6630. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6631. // Test with many headers to exceed the 100 limit
  6632. httplib::Headers headers;
  6633. // Add 150 headers to definitely exceed the 100 limit
  6634. for (int i = 0; i < 150; i++) {
  6635. std::string name = "X-Test-Header-" + std::to_string(i);
  6636. std::string value = "value" + std::to_string(i);
  6637. headers.emplace(name, value);
  6638. }
  6639. // This should fail due to exceeding header count limit
  6640. cli_.set_keep_alive(true);
  6641. auto res = cli_.Get("/hi", headers);
  6642. // The server should respond with 400 Bad Request
  6643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6644. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6645. EXPECT_EQ("close", res->get_header_value("Connection"));
  6646. EXPECT_FALSE(cli_.is_socket_open());
  6647. }
  6648. TEST_F(ServerTest, PercentEncoding) {
  6649. auto res = cli_.Get("/e%6edwith%");
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::OK_200, res->status);
  6652. }
  6653. TEST_F(ServerTest, PercentEncodingUnicode) {
  6654. auto res = cli_.Get("/e%u006edwith%");
  6655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6656. EXPECT_EQ(StatusCode::OK_200, res->status);
  6657. }
  6658. TEST_F(ServerTest, InvalidPercentEncoding) {
  6659. auto res = cli_.Get("/%endwith%");
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6662. }
  6663. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6664. auto res = cli_.Get("/%uendwith%");
  6665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6666. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6667. }
  6668. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6669. auto res = cli_.Get("/hello?aaa=bbb%");
  6670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6671. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6672. }
  6673. TEST_F(ServerTest, PlusSignEncoding) {
  6674. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::OK_200, res->status);
  6677. EXPECT_EQ("a +b", res->body);
  6678. }
  6679. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6680. // This test simulates a potential DoS attack using many headers
  6681. // to verify our security fix prevents memory exhaustion
  6682. httplib::Headers attack_headers;
  6683. // Attempt to add many headers like an attacker would (200 headers to far
  6684. // exceed limit)
  6685. for (int i = 0; i < 200; i++) {
  6686. std::string name = "X-Attack-Header-" + std::to_string(i);
  6687. std::string value = "attack_payload_" + std::to_string(i);
  6688. attack_headers.emplace(name, value);
  6689. }
  6690. // Try to POST with excessive headers
  6691. cli_.set_keep_alive(true);
  6692. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6693. // Should either fail or return 400 Bad Request due to security limit
  6694. if (res) {
  6695. // If we get a response, it should be 400 Bad Request
  6696. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6697. EXPECT_EQ("close", res->get_header_value("Connection"));
  6698. }
  6699. EXPECT_FALSE(cli_.is_socket_open());
  6700. }
  6701. TEST_F(ServerTest, MultipartFormData) {
  6702. UploadFormDataItems items = {
  6703. {"text1", "text default", "", ""},
  6704. {"text2", "aωb", "", ""},
  6705. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6706. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6707. {"file3", "", "", "application/octet-stream"},
  6708. {"file4", "", "", " application/json tmp-string "}};
  6709. auto res = cli_.Post("/multipart", items);
  6710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6711. EXPECT_EQ(StatusCode::OK_200, res->status);
  6712. }
  6713. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6714. UploadFormDataItems items = {
  6715. {"text", "default text", "", ""},
  6716. {"multi_text1", "aaaaa", "", ""},
  6717. {"multi_text1", "bbbbb", "", ""},
  6718. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6719. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6720. "application/json"},
  6721. };
  6722. auto res = cli_.Post("/multipart/multi_file_values", items);
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::OK_200, res->status);
  6725. }
  6726. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6727. auto res = cli_.Get("/hi");
  6728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6731. EXPECT_EQ("Hello World!", res->body);
  6732. }
  6733. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6734. Request req;
  6735. req.method = "POST";
  6736. req.path = "/chunked";
  6737. std::string host_and_port;
  6738. host_and_port += HOST;
  6739. host_and_port += ":";
  6740. host_and_port += std::to_string(PORT);
  6741. req.headers.emplace("Host", host_and_port.c_str());
  6742. req.headers.emplace("Accept", "*/*");
  6743. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6744. req.headers.emplace("Content-Type", "text/plain");
  6745. req.headers.emplace("Content-Length", "0");
  6746. req.headers.emplace(
  6747. "Transfer-Encoding",
  6748. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6749. // Client does not chunk, so make a chunked body manually.
  6750. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6751. auto res = std::make_shared<Response>();
  6752. auto error = Error::Success;
  6753. auto ret = cli_.send(req, *res, error);
  6754. ASSERT_TRUE(ret);
  6755. EXPECT_EQ(StatusCode::OK_200, res->status);
  6756. }
  6757. template <typename ClientT>
  6758. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6759. int expected_status) {
  6760. Request req;
  6761. req.method = "POST";
  6762. req.path = "/chunked";
  6763. std::string host_and_port;
  6764. host_and_port += HOST;
  6765. host_and_port += ":";
  6766. host_and_port += std::to_string(PORT);
  6767. req.headers.emplace("Host", host_and_port.c_str());
  6768. req.headers.emplace("Content-Length", "0");
  6769. req.headers.emplace("Transfer-Encoding", "chunked");
  6770. req.body = body;
  6771. auto res = std::make_shared<Response>();
  6772. auto error = Error::Success;
  6773. ASSERT_TRUE(cli.send(req, *res, error));
  6774. EXPECT_EQ(expected_status, res->status);
  6775. }
  6776. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6777. // rather than treat them as valid lengths.
  6778. template <typename ClientT>
  6779. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6780. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6781. }
  6782. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6783. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6784. }
  6785. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6786. expect_chunked_body_rejected(
  6787. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6788. }
  6789. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6790. // chunk-size line carries no CR, LF or other control character ahead of its
  6791. // terminator. Such a line must be refused rather than read as extension text.
  6792. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6793. expect_chunked_body_rejected(
  6794. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6795. }
  6796. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6797. expect_chunked_body_rejected(
  6798. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6799. }
  6800. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6801. expect_chunked_body_rejected(
  6802. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6803. }
  6804. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6805. // The literal stays split: a hex escape consumes every hex digit that
  6806. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6807. expect_chunked_body_rejected(
  6808. cli_, "4;a\x01"
  6809. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6810. }
  6811. TEST_F(ServerTest, AcceptsChunkExtension) {
  6812. expect_chunked_body_status(cli_,
  6813. "4;name=value\r\ndech\r\n"
  6814. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6815. "0;last\r\n\r\n",
  6816. StatusCode::OK_200);
  6817. }
  6818. TEST_F(ServerTest, GetStreamed2) {
  6819. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6822. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6823. EXPECT_EQ(true, res->has_header("Content-Range"));
  6824. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6825. EXPECT_EQ(std::string("ab"), res->body);
  6826. }
  6827. TEST_F(ServerTest, GetStreamed) {
  6828. auto res = cli_.Get("/streamed");
  6829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6830. EXPECT_EQ(StatusCode::OK_200, res->status);
  6831. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6832. EXPECT_EQ(std::string("aaabbb"), res->body);
  6833. }
  6834. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6835. auto res = cli_.Get("/streamed-without-length",
  6836. Headers{make_range_header({{0, -1}})});
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. EXPECT_EQ(StatusCode::OK_200, res->status);
  6839. EXPECT_EQ(false, res->has_header("Content-Length"));
  6840. EXPECT_EQ(false, res->has_header("Content-Range"));
  6841. EXPECT_EQ(std::string("abcdefg"), res->body);
  6842. }
  6843. TEST_F(ServerTest, GetStreamedWithRange1) {
  6844. auto res =
  6845. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6848. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6849. EXPECT_EQ(true, res->has_header("Content-Range"));
  6850. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6851. EXPECT_EQ(std::string("def"), res->body);
  6852. }
  6853. TEST_F(ServerTest, GetStreamedWithRange2) {
  6854. auto res =
  6855. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6858. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6859. EXPECT_EQ(true, res->has_header("Content-Range"));
  6860. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6861. EXPECT_EQ(std::string("bcdefg"), res->body);
  6862. }
  6863. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6864. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6866. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6867. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6868. EXPECT_EQ(true, res->has_header("Content-Range"));
  6869. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6870. EXPECT_EQ(std::string("efg"), res->body);
  6871. }
  6872. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6873. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6874. // the entire representation.
  6875. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6876. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6879. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6880. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6881. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6882. }
  6883. }
  6884. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6885. auto res =
  6886. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6889. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6890. EXPECT_EQ(false, res->has_header("Content-Range"));
  6891. EXPECT_EQ(0U, res->body.size());
  6892. }
  6893. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6894. // Only a 206 is served as a partial representation. Under any other status
  6895. // `apply_ranges()` reported the full content length, so the body must match
  6896. // that header, and the content provider must never be asked for an offset
  6897. // outside the representation.
  6898. auto check = [&](int status, const char *range) {
  6899. auto path =
  6900. std::string("/streamed-with-range?status=") + std::to_string(status);
  6901. auto ctx = path + " Range: " + range;
  6902. auto res = cli_.Get(path, Headers{{"Range", range}});
  6903. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6904. EXPECT_EQ(status, res->status) << ctx;
  6905. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6906. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6907. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6908. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6909. };
  6910. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6911. check(403, "bytes=3-5");
  6912. // The offset is far past the representation.
  6913. check(403, "bytes=100000-100200");
  6914. // `first_pos` is still -1 here, and the bounds asserts in
  6915. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6916. check(403, "bytes=-3");
  6917. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6918. // multipart branch would have written one that is empty.
  6919. check(403, "bytes=1-2, 4-5");
  6920. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6921. // covers the whole representation.
  6922. check(200, "bytes=3-5");
  6923. check(200, "bytes=1-2, 4-5");
  6924. }
  6925. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6926. auto res =
  6927. cli_.Get("/streamed-with-range",
  6928. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6929. "92233720368547758079223372036854775807"}});
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6932. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6933. EXPECT_EQ(false, res->has_header("Content-Range"));
  6934. EXPECT_EQ(0U, res->body.size());
  6935. }
  6936. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6937. auto res = cli_.Get(
  6938. "/with-range",
  6939. Headers{{"Range",
  6940. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6941. {"Accept-Encoding", ""}});
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6944. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6945. EXPECT_EQ(true, res->has_header("Content-Range"));
  6946. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6947. EXPECT_EQ(std::string("abcdefg"), res->body);
  6948. }
  6949. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6950. auto res = cli_.Get("/with-range", Headers{
  6951. {"Range", "bytes=0-"},
  6952. {"Accept-Encoding", ""},
  6953. });
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6956. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6957. EXPECT_EQ(true, res->has_header("Content-Range"));
  6958. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6959. EXPECT_EQ(std::string("abcdefg"), res->body);
  6960. }
  6961. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6962. auto res = cli_.Get("/streamed-with-range",
  6963. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6966. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6967. EXPECT_EQ(false, res->has_header("Content-Range"));
  6968. EXPECT_EQ(267U, res->body.size());
  6969. // Check that both range contents are present
  6970. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6971. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6972. // Check that Content-Range headers are present for both ranges
  6973. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6974. std::string::npos);
  6975. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6976. std::string::npos);
  6977. }
  6978. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6979. Ranges ranges;
  6980. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6981. ranges.emplace_back(0, -1);
  6982. }
  6983. auto res = cli_.Get("/streamed-with-range?error",
  6984. Headers{{make_range_header(ranges)}});
  6985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6986. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6987. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6988. EXPECT_EQ(false, res->has_header("Content-Range"));
  6989. EXPECT_EQ(0U, res->body.size());
  6990. }
  6991. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6992. auto res = cli_.Get("/streamed-with-range",
  6993. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6995. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6996. EXPECT_EQ(5U, res->body.size());
  6997. // Check that overlapping ranges are coalesced into a single range
  6998. EXPECT_EQ("bcdef", res->body);
  6999. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7000. // Should be single range, not multipart
  7001. EXPECT_TRUE(res->has_header("Content-Range"));
  7002. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7003. }
  7004. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7005. auto res = cli_.Get("/streamed-with-range",
  7006. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7009. EXPECT_EQ(268U, res->body.size());
  7010. // Check that both range contents are present
  7011. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7012. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7013. // Check that Content-Range headers are present for both ranges
  7014. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7015. std::string::npos);
  7016. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7017. std::string::npos);
  7018. }
  7019. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7020. auto res = cli_.Get("/streamed-with-range",
  7021. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7023. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7024. EXPECT_EQ(269U, res->body.size());
  7025. // Check that both duplicate range contents are present
  7026. size_t first_abc = res->body.find("abc\r\n");
  7027. EXPECT_TRUE(first_abc != std::string::npos);
  7028. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7029. EXPECT_TRUE(second_abc != std::string::npos);
  7030. // Check that Content-Range headers are present for both ranges
  7031. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7032. EXPECT_TRUE(first_range != std::string::npos);
  7033. size_t second_range =
  7034. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7035. EXPECT_TRUE(second_range != std::string::npos);
  7036. }
  7037. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7038. auto res =
  7039. cli_.Get("/streamed-with-range?error",
  7040. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7043. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7044. EXPECT_EQ(false, res->has_header("Content-Range"));
  7045. EXPECT_EQ(0U, res->body.size());
  7046. }
  7047. TEST_F(ServerTest, GetStreamedEndless) {
  7048. uint64_t offset = 0;
  7049. auto res = cli_.Get("/streamed-cancel",
  7050. [&](const char * /*data*/, uint64_t data_length) {
  7051. if (offset < 100) {
  7052. offset += data_length;
  7053. return true;
  7054. }
  7055. return false;
  7056. });
  7057. ASSERT_TRUE(!res);
  7058. EXPECT_EQ(Error::Canceled, res.error());
  7059. }
  7060. TEST_F(ServerTest, ClientStop) {
  7061. std::atomic_size_t count{4};
  7062. std::vector<std::thread> threads;
  7063. for (auto i = count.load(); i != 0; --i) {
  7064. threads.emplace_back([&]() {
  7065. auto res = cli_.Get("/streamed-cancel",
  7066. [&](const char *, uint64_t) { return true; });
  7067. --count;
  7068. ASSERT_TRUE(!res);
  7069. EXPECT_TRUE(res.error() == Error::Canceled ||
  7070. res.error() == Error::Read || res.error() == Error::Write);
  7071. });
  7072. }
  7073. std::this_thread::sleep_for(std::chrono::seconds(2));
  7074. while (count != 0) {
  7075. cli_.stop();
  7076. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7077. }
  7078. for (auto &t : threads) {
  7079. t.join();
  7080. }
  7081. }
  7082. TEST_F(ServerTest, GetWithRange1) {
  7083. auto res = cli_.Get("/with-range", Headers{
  7084. make_range_header({{3, 5}}),
  7085. {"Accept-Encoding", ""},
  7086. });
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7089. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7090. EXPECT_EQ(true, res->has_header("Content-Range"));
  7091. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7092. EXPECT_EQ(std::string("def"), res->body);
  7093. }
  7094. TEST_F(ServerTest, GetWithRange2) {
  7095. auto res = cli_.Get("/with-range", Headers{
  7096. make_range_header({{1, -1}}),
  7097. {"Accept-Encoding", ""},
  7098. });
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7101. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7102. EXPECT_EQ(true, res->has_header("Content-Range"));
  7103. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7104. EXPECT_EQ(std::string("bcdefg"), res->body);
  7105. }
  7106. TEST_F(ServerTest, GetWithRange3) {
  7107. auto res = cli_.Get("/with-range", Headers{
  7108. make_range_header({{0, 0}}),
  7109. {"Accept-Encoding", ""},
  7110. });
  7111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7113. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7114. EXPECT_EQ(true, res->has_header("Content-Range"));
  7115. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7116. EXPECT_EQ(std::string("a"), res->body);
  7117. }
  7118. TEST_F(ServerTest, GetWithRange4) {
  7119. auto res = cli_.Get("/with-range", Headers{
  7120. make_range_header({{-1, 2}}),
  7121. {"Accept-Encoding", ""},
  7122. });
  7123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7124. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7125. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7126. EXPECT_EQ(true, res->has_header("Content-Range"));
  7127. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7128. EXPECT_EQ(std::string("fg"), res->body);
  7129. }
  7130. TEST_F(ServerTest, GetWithRange5) {
  7131. auto res = cli_.Get("/with-range", Headers{
  7132. make_range_header({{0, 5}}),
  7133. {"Accept-Encoding", ""},
  7134. });
  7135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7136. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7137. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7138. EXPECT_EQ(true, res->has_header("Content-Range"));
  7139. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7140. EXPECT_EQ(std::string("abcdef"), res->body);
  7141. }
  7142. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7143. auto res =
  7144. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7146. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7147. }
  7148. TEST_F(ServerTest, GetWithRangeMultipart) {
  7149. auto res =
  7150. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7152. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7153. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7154. EXPECT_EQ(false, res->has_header("Content-Range"));
  7155. EXPECT_EQ(267U, res->body.size());
  7156. }
  7157. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7158. auto res = cli_.Get("/with-range",
  7159. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7162. }
  7163. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7164. auto res = cli_.Get("/with-range-customized-response",
  7165. Headers{{make_range_header({{1, 2}})}});
  7166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7167. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7168. EXPECT_EQ(true, res->has_header("Content-Length"));
  7169. EXPECT_EQ(false, res->has_header("Content-Range"));
  7170. EXPECT_EQ(JSON_DATA, res->body);
  7171. }
  7172. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7173. auto res = cli_.Get("/with-range-customized-response",
  7174. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7177. EXPECT_EQ(true, res->has_header("Content-Length"));
  7178. EXPECT_EQ(false, res->has_header("Content-Range"));
  7179. EXPECT_EQ(JSON_DATA, res->body);
  7180. }
  7181. TEST_F(ServerTest, Issue1772) {
  7182. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7184. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7185. }
  7186. TEST_F(ServerTest, Issue609) {
  7187. auto res = cli_.Delete("/issue609");
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::OK_200, res->status);
  7190. EXPECT_EQ(std::string("ok"), res->body);
  7191. }
  7192. TEST_F(ServerTest, GetStreamedChunked) {
  7193. auto res = cli_.Get("/streamed-chunked");
  7194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7195. EXPECT_EQ(StatusCode::OK_200, res->status);
  7196. EXPECT_EQ(std::string("123456789"), res->body);
  7197. }
  7198. TEST_F(ServerTest, GetStreamedChunked2) {
  7199. auto res = cli_.Get("/streamed-chunked2");
  7200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7201. EXPECT_EQ(StatusCode::OK_200, res->status);
  7202. EXPECT_EQ(std::string("123456789"), res->body);
  7203. }
  7204. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7205. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7207. EXPECT_EQ(StatusCode::OK_200, res->status);
  7208. EXPECT_EQ(std::string("123456789"), res->body);
  7209. EXPECT_TRUE(res->has_header("Trailer"));
  7210. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7211. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7212. // Trailers are now stored separately from headers (security fix)
  7213. EXPECT_EQ(2U, res->trailers.size());
  7214. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7215. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7216. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7217. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7218. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7219. // Verify trailers are NOT in headers (security verification)
  7220. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7221. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7222. }
  7223. TEST_F(ServerTest, LargeChunkedPost) {
  7224. Request req;
  7225. req.method = "POST";
  7226. req.path = "/large-chunked";
  7227. std::string host_and_port;
  7228. host_and_port += HOST;
  7229. host_and_port += ":";
  7230. host_and_port += std::to_string(PORT);
  7231. req.headers.emplace("Host", host_and_port.c_str());
  7232. req.headers.emplace("Accept", "*/*");
  7233. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7234. req.headers.emplace("Content-Type", "text/plain");
  7235. req.headers.emplace("Content-Length", "0");
  7236. req.headers.emplace("Transfer-Encoding", "chunked");
  7237. std::string long_string(30 * 1024u, 'a');
  7238. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7239. // Attempt to make a large enough post to exceed OS buffers, to test that
  7240. // the server handles short reads if the full chunk data isn't available.
  7241. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7242. auto res = std::make_shared<Response>();
  7243. auto error = Error::Success;
  7244. auto ret = cli_.send(req, *res, error);
  7245. ASSERT_TRUE(ret);
  7246. EXPECT_EQ(StatusCode::OK_200, res->status);
  7247. }
  7248. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7249. auto res = cli_.Get("/remote_addr");
  7250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7251. EXPECT_EQ(StatusCode::OK_200, res->status);
  7252. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7253. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7254. }
  7255. TEST_F(ServerTest, GetMethodLocalAddr) {
  7256. auto res = cli_.Get("/local_addr");
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::OK_200, res->status);
  7259. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7260. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7261. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7262. }
  7263. TEST_F(ServerTest, HTTPResponseSplitting) {
  7264. auto res = cli_.Get("/http_response_splitting");
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. EXPECT_EQ(StatusCode::OK_200, res->status);
  7267. }
  7268. TEST_F(ServerTest, SlowRequest) {
  7269. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7270. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7271. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7272. }
  7273. #if 0
  7274. TEST_F(ServerTest, SlowPost) {
  7275. char buffer[64 * 1024];
  7276. memset(buffer, 0x42, sizeof(buffer));
  7277. auto res = cli_.Post(
  7278. "/slowpost", 64 * 1024 * 1024,
  7279. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7280. auto ret = sink.write(buffer, sizeof(buffer));
  7281. EXPECT_TRUE(ret);
  7282. return true;
  7283. },
  7284. "text/plain");
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. EXPECT_EQ(StatusCode::OK_200, res->status);
  7287. }
  7288. TEST_F(ServerTest, SlowPostFail) {
  7289. char buffer[64 * 1024];
  7290. memset(buffer, 0x42, sizeof(buffer));
  7291. cli_.set_write_timeout(std::chrono::seconds(0));
  7292. auto res = cli_.Post(
  7293. "/slowpost", 64 * 1024 * 1024,
  7294. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7295. sink.write(buffer, sizeof(buffer));
  7296. return true;
  7297. },
  7298. "text/plain");
  7299. ASSERT_TRUE(!res);
  7300. EXPECT_EQ(Error::Write, res.error());
  7301. }
  7302. #endif
  7303. TEST_F(ServerTest, Put) {
  7304. auto res = cli_.Put("/put", "PUT", "text/plain");
  7305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7306. EXPECT_EQ(StatusCode::OK_200, res->status);
  7307. EXPECT_EQ("PUT", res->body);
  7308. }
  7309. TEST_F(ServerTest, PutWithContentProvider) {
  7310. auto res = cli_.Put(
  7311. "/put", 3,
  7312. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7313. sink.os << "PUT";
  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. EXPECT_EQ("PUT", res->body);
  7320. }
  7321. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7322. auto res = cli_.Post(
  7323. "/post", 42,
  7324. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7325. return false;
  7326. },
  7327. "text/plain");
  7328. ASSERT_TRUE(!res);
  7329. EXPECT_EQ(Error::Canceled, res.error());
  7330. }
  7331. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7332. auto res = cli_.Put(
  7333. "/put",
  7334. [](size_t /*offset*/, DataSink &sink) {
  7335. sink.os << "PUT";
  7336. sink.done();
  7337. return true;
  7338. },
  7339. "text/plain");
  7340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7341. EXPECT_EQ(StatusCode::OK_200, res->status);
  7342. EXPECT_EQ("PUT", res->body);
  7343. }
  7344. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7345. auto res = cli_.Post(
  7346. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7347. "text/plain");
  7348. ASSERT_TRUE(!res);
  7349. EXPECT_EQ(Error::Canceled, res.error());
  7350. }
  7351. TEST_F(ServerTest, PostLoopBack) {
  7352. std::string body;
  7353. auto res = cli_.Post(
  7354. "/post-loopback", 9,
  7355. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7356. EXPECT_EQ(9u, length);
  7357. sink.write("123", 3);
  7358. sink.write("456", 3);
  7359. sink.write("789", 3);
  7360. return true;
  7361. },
  7362. "text/plain",
  7363. [&body](const char *data, size_t data_length) {
  7364. body.append(data, data_length);
  7365. return true;
  7366. });
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::OK_200, res->status);
  7369. EXPECT_EQ("123456789", body);
  7370. }
  7371. TEST_F(ServerTest, PutLoopBack) {
  7372. std::string body;
  7373. auto res = cli_.Put(
  7374. "/put-loopback", 9,
  7375. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7376. EXPECT_EQ(9u, length);
  7377. sink.write("123", 3);
  7378. sink.write("456", 3);
  7379. sink.write("789", 3);
  7380. return true;
  7381. },
  7382. "text/plain",
  7383. [&body](const char *data, size_t data_length) {
  7384. body.append(data, data_length);
  7385. return true;
  7386. });
  7387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7388. EXPECT_EQ(StatusCode::OK_200, res->status);
  7389. EXPECT_EQ("123456789", body);
  7390. }
  7391. TEST_F(ServerTest, PatchLoopBack) {
  7392. std::string body;
  7393. auto res = cli_.Patch(
  7394. "/patch-loopback", 9,
  7395. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7396. EXPECT_EQ(9u, length);
  7397. sink.write("123", 3);
  7398. sink.write("456", 3);
  7399. sink.write("789", 3);
  7400. return true;
  7401. },
  7402. "text/plain",
  7403. [&body](const char *data, size_t data_length) {
  7404. body.append(data, data_length);
  7405. return true;
  7406. });
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::OK_200, res->status);
  7409. EXPECT_EQ("123456789", body);
  7410. }
  7411. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7412. std::string body;
  7413. auto res = cli_.Post(
  7414. "/post-loopback",
  7415. [](size_t /*offset*/, DataSink &sink) {
  7416. sink.write("123", 3);
  7417. sink.write("456", 3);
  7418. sink.write("789", 3);
  7419. sink.done();
  7420. return true;
  7421. },
  7422. "text/plain",
  7423. [&body](const char *data, size_t data_length) {
  7424. body.append(data, data_length);
  7425. return true;
  7426. });
  7427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7428. EXPECT_EQ(StatusCode::OK_200, res->status);
  7429. EXPECT_EQ("123456789", body);
  7430. }
  7431. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7432. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7433. cli_.set_compress(true);
  7434. auto res = cli_.Put(
  7435. "/put", 3,
  7436. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7437. sink.os << "PUT";
  7438. return true;
  7439. },
  7440. "text/plain");
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_EQ(StatusCode::OK_200, res->status);
  7443. EXPECT_EQ("PUT", res->body);
  7444. }
  7445. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7446. cli_.set_compress(true);
  7447. auto res = cli_.Post(
  7448. "/post", 42,
  7449. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7450. return false;
  7451. },
  7452. "text/plain");
  7453. ASSERT_TRUE(!res);
  7454. EXPECT_EQ(Error::Canceled, res.error());
  7455. }
  7456. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7457. cli_.set_compress(true);
  7458. auto res = cli_.Put(
  7459. "/put",
  7460. [](size_t /*offset*/, DataSink &sink) {
  7461. sink.os << "PUT";
  7462. sink.done();
  7463. return true;
  7464. },
  7465. "text/plain");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. EXPECT_EQ("PUT", res->body);
  7469. }
  7470. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7471. cli_.set_compress(true);
  7472. auto res = cli_.Post(
  7473. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7474. "text/plain");
  7475. ASSERT_TRUE(!res);
  7476. EXPECT_EQ(Error::Canceled, res.error());
  7477. }
  7478. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7479. cli_.set_compress(true);
  7480. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. EXPECT_EQ(LARGE_DATA, res->body);
  7484. }
  7485. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7486. #ifdef CPPHTTPLIB_SSL_ENABLED
  7487. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7488. Client cli(s.c_str());
  7489. cli.enable_server_certificate_verification(false);
  7490. #else
  7491. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7492. Client cli(s.c_str());
  7493. #endif
  7494. cli.set_compress(true);
  7495. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7497. EXPECT_EQ(StatusCode::OK_200, res->status);
  7498. EXPECT_EQ(LARGE_DATA, res->body);
  7499. // The compressed size should be less than a 10th of the original. May vary
  7500. // depending on the zlib library.
  7501. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7502. static_cast<uint64_t>(10 * 1024 * 1024));
  7503. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7504. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7505. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7506. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7507. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7508. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7509. #endif
  7510. }
  7511. TEST_F(ServerTest, PutContentWithDeflate) {
  7512. cli_.set_compress(false);
  7513. Headers headers;
  7514. headers.emplace("Content-Encoding", "deflate");
  7515. // PUT in deflate format:
  7516. auto res = cli_.Put("/put", headers,
  7517. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. EXPECT_EQ("PUT", res->body);
  7521. }
  7522. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7523. Headers headers;
  7524. headers.emplace("Accept-Encoding", "gzip, deflate");
  7525. auto res = cli_.Get("/streamed-chunked", headers);
  7526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7527. EXPECT_EQ(StatusCode::OK_200, res->status);
  7528. EXPECT_EQ(std::string("123456789"), res->body);
  7529. }
  7530. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7531. Headers headers;
  7532. headers.emplace("Accept-Encoding", "gzip, deflate");
  7533. auto res = cli_.Get("/streamed-chunked2", headers);
  7534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7535. EXPECT_EQ(StatusCode::OK_200, res->status);
  7536. EXPECT_EQ(std::string("123456789"), res->body);
  7537. }
  7538. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7539. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::OK_200, res->status);
  7542. }
  7543. TEST(GzipDecompressor, ChunkedDecompression) {
  7544. std::string data;
  7545. for (size_t i = 0; i < 32 * 1024; ++i) {
  7546. data.push_back(static_cast<char>('a' + i % 26));
  7547. }
  7548. std::string compressed_data;
  7549. {
  7550. httplib::detail::gzip_compressor compressor;
  7551. bool result = compressor.compress(
  7552. data.data(), data.size(),
  7553. /*last=*/true,
  7554. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7555. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7556. compressed_data_size);
  7557. return true;
  7558. });
  7559. ASSERT_TRUE(result);
  7560. }
  7561. std::string decompressed_data;
  7562. {
  7563. httplib::detail::gzip_decompressor decompressor;
  7564. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7565. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7566. size_t chunk_size = 130;
  7567. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7568. chunk_begin += chunk_size) {
  7569. size_t current_chunk_size =
  7570. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7571. bool result = decompressor.decompress(
  7572. compressed_data.data() + chunk_begin, current_chunk_size,
  7573. [&](const char *decompressed_data_chunk,
  7574. size_t decompressed_data_chunk_size) {
  7575. decompressed_data.insert(decompressed_data.size(),
  7576. decompressed_data_chunk,
  7577. decompressed_data_chunk_size);
  7578. return true;
  7579. });
  7580. ASSERT_TRUE(result);
  7581. }
  7582. }
  7583. ASSERT_EQ(data, decompressed_data);
  7584. }
  7585. TEST(GzipDecompressor, DeflateDecompression) {
  7586. std::string original_text = "Raw deflate without gzip";
  7587. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7588. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7589. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7590. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7591. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7592. std::string decompressed_data;
  7593. {
  7594. httplib::detail::gzip_decompressor decompressor;
  7595. bool result = decompressor.decompress(
  7596. compressed_data.data(), compressed_data.size(),
  7597. [&](const char *decompressed_data_chunk,
  7598. size_t decompressed_data_chunk_size) {
  7599. decompressed_data.insert(decompressed_data.size(),
  7600. decompressed_data_chunk,
  7601. decompressed_data_chunk_size);
  7602. return true;
  7603. });
  7604. ASSERT_TRUE(result);
  7605. }
  7606. ASSERT_EQ(original_text, decompressed_data);
  7607. }
  7608. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7609. std::string original_text = "Raw deflate without gzip";
  7610. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7611. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7612. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7613. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7614. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7615. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7616. std::string decompressed_data;
  7617. {
  7618. httplib::detail::gzip_decompressor decompressor;
  7619. bool result = decompressor.decompress(
  7620. compressed_data.data(), compressed_data.size(),
  7621. [&](const char *decompressed_data_chunk,
  7622. size_t decompressed_data_chunk_size) {
  7623. decompressed_data.insert(decompressed_data.size(),
  7624. decompressed_data_chunk,
  7625. decompressed_data_chunk_size);
  7626. return true;
  7627. });
  7628. ASSERT_TRUE(result);
  7629. }
  7630. ASSERT_EQ(original_text, decompressed_data);
  7631. }
  7632. #endif
  7633. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7634. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7635. Headers headers;
  7636. headers.emplace("Accept-Encoding", "br");
  7637. auto res = cli_.Get("/streamed-chunked", headers);
  7638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7639. EXPECT_EQ(StatusCode::OK_200, res->status);
  7640. EXPECT_EQ(std::string("123456789"), res->body);
  7641. }
  7642. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7643. Headers headers;
  7644. headers.emplace("Accept-Encoding", "br");
  7645. auto res = cli_.Get("/streamed-chunked2", headers);
  7646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7647. EXPECT_EQ(StatusCode::OK_200, res->status);
  7648. EXPECT_EQ(std::string("123456789"), res->body);
  7649. }
  7650. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7651. cli_.set_compress(true);
  7652. auto res = cli_.Put(
  7653. "/put", 3,
  7654. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7655. sink.os << "PUT";
  7656. return true;
  7657. },
  7658. "text/plain");
  7659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7660. EXPECT_EQ(StatusCode::OK_200, res->status);
  7661. EXPECT_EQ("PUT", res->body);
  7662. }
  7663. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7664. cli_.set_compress(true);
  7665. auto res = cli_.Put(
  7666. "/put",
  7667. [](size_t /*offset*/, DataSink &sink) {
  7668. sink.os << "PUT";
  7669. sink.done();
  7670. return true;
  7671. },
  7672. "text/plain");
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ("PUT", res->body);
  7676. }
  7677. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7678. cli_.set_compress(true);
  7679. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7681. EXPECT_EQ(StatusCode::OK_200, res->status);
  7682. EXPECT_EQ(LARGE_DATA, res->body);
  7683. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7684. }
  7685. #endif
  7686. TEST_F(ServerTest, Patch) {
  7687. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ("PATCH", res->body);
  7691. }
  7692. TEST_F(ServerTest, Delete) {
  7693. auto res = cli_.Delete("/delete");
  7694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7695. EXPECT_EQ(StatusCode::OK_200, res->status);
  7696. EXPECT_EQ("DELETE", res->body);
  7697. }
  7698. TEST_F(ServerTest, DeleteContentReceiver) {
  7699. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7701. EXPECT_EQ(StatusCode::OK_200, res->status);
  7702. EXPECT_EQ("content", res->body);
  7703. }
  7704. TEST_F(ServerTest, Options) {
  7705. auto res = cli_.Options("*");
  7706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7707. EXPECT_EQ(StatusCode::OK_200, res->status);
  7708. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7709. EXPECT_TRUE(res->body.empty());
  7710. }
  7711. TEST_F(ServerTest, URL) {
  7712. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7714. EXPECT_EQ(StatusCode::OK_200, res->status);
  7715. }
  7716. TEST_F(ServerTest, ArrayParam) {
  7717. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7719. EXPECT_EQ(StatusCode::OK_200, res->status);
  7720. }
  7721. TEST_F(ServerTest, ArrayParamValues) {
  7722. auto res =
  7723. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7725. EXPECT_EQ(StatusCode::OK_200, res->status);
  7726. }
  7727. TEST_F(ServerTest, NoMultipleHeaders) {
  7728. Headers headers = {{"Content-Length", "5"}};
  7729. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7730. "text/plain");
  7731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. }
  7734. TEST_F(ServerTest, PostContentReceiver) {
  7735. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. ASSERT_EQ(StatusCode::OK_200, res->status);
  7738. ASSERT_EQ("content", res->body);
  7739. }
  7740. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7741. UploadFormDataItems items = {
  7742. {"text1", "text default", "", ""},
  7743. {"text2", "aωb", "", ""},
  7744. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7745. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7746. {"file3", "", "", "application/octet-stream"},
  7747. };
  7748. auto res = cli_.Post("/content_receiver", items);
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(StatusCode::OK_200, res->status);
  7751. }
  7752. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7753. UploadFormDataItems items = {
  7754. {"text1", "text default", "", ""},
  7755. {"text2", "aωb", "", ""},
  7756. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7757. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7758. {"file3", "", "", "application/octet-stream"},
  7759. };
  7760. auto boundary = std::string("+++++");
  7761. std::string body;
  7762. for (const auto &item : items) {
  7763. body += "--" + boundary + "\r\n";
  7764. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7765. if (!item.filename.empty()) {
  7766. body += "; filename=\"" + item.filename + "\"";
  7767. }
  7768. body += "\r\n";
  7769. if (!item.content_type.empty()) {
  7770. body += "Content-Type: " + item.content_type + "\r\n";
  7771. }
  7772. body += "\r\n";
  7773. body += item.content + "\r\n";
  7774. }
  7775. body += "--" + boundary + "--\r\n";
  7776. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7777. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7779. EXPECT_EQ(StatusCode::OK_200, res->status);
  7780. }
  7781. TEST(MultipartFormDataTest, FieldEscaping) {
  7782. Server svr;
  7783. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7784. const ContentReader &content_reader) {
  7785. ASSERT_TRUE(req.is_multipart_form_data());
  7786. std::vector<FormData> received;
  7787. content_reader(
  7788. [&](const FormData &file) {
  7789. received.push_back(file);
  7790. return true;
  7791. },
  7792. [&](const char *data, size_t data_length) {
  7793. received.back().content.append(data, data_length);
  7794. return true;
  7795. });
  7796. // '"', CR and LF in names and filenames are escaped following the
  7797. // WHATWG HTML standard, so each part still parses as a single part
  7798. // with no injected headers. Content types get CR/LF escaped too,
  7799. // while '"' (legal there, e.g. quoted charset) is preserved.
  7800. ASSERT_EQ(4U, received.size());
  7801. EXPECT_EQ("na%22me", received[0].name);
  7802. EXPECT_EQ("quoted name", received[0].content);
  7803. EXPECT_EQ("file", received[1].name);
  7804. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7805. received[1].filename);
  7806. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7807. EXPECT_EQ("injected", received[1].content);
  7808. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7809. EXPECT_EQ("my%22file.txt", received[2].filename);
  7810. EXPECT_EQ("cr lf name", received[2].content);
  7811. EXPECT_EQ("typed", received[3].name);
  7812. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7813. received[3].content_type);
  7814. EXPECT_EQ("typed content", received[3].content);
  7815. });
  7816. auto port = svr.bind_to_any_port("localhost");
  7817. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7818. auto se = detail::scope_exit([&] {
  7819. svr.stop();
  7820. t.join();
  7821. ASSERT_FALSE(svr.is_running());
  7822. });
  7823. svr.wait_until_ready();
  7824. Client cli("localhost", port);
  7825. UploadFormDataItems items = {
  7826. {"na\"me", "quoted name", "", ""},
  7827. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7828. "application/octet-stream"},
  7829. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7830. {"typed", "typed content", "",
  7831. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7832. };
  7833. auto res = cli.Post("/post", items);
  7834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7835. EXPECT_EQ(StatusCode::OK_200, res->status);
  7836. }
  7837. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7838. const UploadFormDataItems items = {
  7839. {"name1", "Content 1", "", ""},
  7840. {"name2", "Content 2", "file2.txt", "text/plain"},
  7841. };
  7842. Server svr;
  7843. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7844. const ContentReader &content_reader) {
  7845. ASSERT_TRUE(req.is_multipart_form_data());
  7846. std::vector<FormData> received;
  7847. content_reader(
  7848. [&](const FormData &file) {
  7849. received.push_back(file);
  7850. return true;
  7851. },
  7852. [&](const char *data, size_t data_length) {
  7853. received.back().content.append(data, data_length);
  7854. return true;
  7855. });
  7856. ASSERT_EQ(2U, received.size());
  7857. EXPECT_EQ("name1", received[0].name);
  7858. EXPECT_EQ("Content 1", received[0].content);
  7859. EXPECT_EQ("name2", received[1].name);
  7860. EXPECT_EQ("Content 2", received[1].content);
  7861. EXPECT_EQ("file2.txt", received[1].filename);
  7862. EXPECT_EQ("text/plain", received[1].content_type);
  7863. });
  7864. auto port = svr.bind_to_any_port("localhost");
  7865. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7866. auto se = detail::scope_exit([&] {
  7867. svr.stop();
  7868. t.join();
  7869. ASSERT_FALSE(svr.is_running());
  7870. });
  7871. svr.wait_until_ready();
  7872. Client cli("localhost", port);
  7873. // Whole-body serialization with a generated boundary
  7874. {
  7875. MultipartFormDataWriter writer;
  7876. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7877. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7878. writer.content_type());
  7879. auto body = writer.serialize(items);
  7880. EXPECT_EQ(body.size(), writer.content_length(items));
  7881. auto res = cli.Post("/post", body, writer.content_type());
  7882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7883. EXPECT_EQ(StatusCode::OK_200, res->status);
  7884. }
  7885. // Per-part framing with a custom boundary via a content provider
  7886. {
  7887. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7888. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7889. MultipartFormDataWriter writer("custom-boundary_123");
  7890. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7891. std::string body;
  7892. for (const auto &item : items) {
  7893. body += writer.item_begin(item);
  7894. body += item.content;
  7895. body += MultipartFormDataWriter::item_end();
  7896. }
  7897. body += writer.finish();
  7898. EXPECT_EQ(body.size(), writer.content_length(items));
  7899. auto res = cli.Post(
  7900. "/post", body.size(),
  7901. [&](size_t offset, size_t length, DataSink &sink) {
  7902. sink.write(body.data() + offset, length);
  7903. return true;
  7904. },
  7905. writer.content_type());
  7906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7907. EXPECT_EQ(StatusCode::OK_200, res->status);
  7908. }
  7909. }
  7910. TEST_F(ServerTest, PostContentReceiverGzip) {
  7911. cli_.set_compress(true);
  7912. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7914. ASSERT_EQ(StatusCode::OK_200, res->status);
  7915. ASSERT_EQ("content", res->body);
  7916. }
  7917. TEST_F(ServerTest, PutContentReceiver) {
  7918. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. ASSERT_EQ(StatusCode::OK_200, res->status);
  7921. ASSERT_EQ("content", res->body);
  7922. }
  7923. TEST_F(ServerTest, PatchContentReceiver) {
  7924. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7926. ASSERT_EQ(StatusCode::OK_200, res->status);
  7927. ASSERT_EQ("content", res->body);
  7928. }
  7929. template <typename ClientType>
  7930. void TestWithHeadersAndContentReceiver(
  7931. ClientType &cli,
  7932. std::function<Result(ClientType &, const std::string &, const Headers &,
  7933. const std::string &, const std::string &,
  7934. ContentReceiver, DownloadProgress)>
  7935. request_func) {
  7936. Headers headers;
  7937. headers.emplace("X-Custom-Header", "test-value");
  7938. std::string received_body;
  7939. auto res = request_func(
  7940. cli, "/content_receiver", headers, "content", "application/json",
  7941. [&](const char *data, size_t data_length) {
  7942. received_body.append(data, data_length);
  7943. return true;
  7944. },
  7945. nullptr);
  7946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. EXPECT_EQ("content", received_body);
  7949. }
  7950. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7951. #ifdef CPPHTTPLIB_SSL_ENABLED
  7952. using ClientT = SSLClient;
  7953. #else
  7954. using ClientT = Client;
  7955. #endif
  7956. TestWithHeadersAndContentReceiver<ClientT>(
  7957. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7958. const std::string &body, const std::string &content_type,
  7959. ContentReceiver receiver, DownloadProgress progress) {
  7960. return cli.Post(path, headers, body, content_type, receiver, progress);
  7961. });
  7962. }
  7963. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7964. #ifdef CPPHTTPLIB_SSL_ENABLED
  7965. using ClientT = SSLClient;
  7966. #else
  7967. using ClientT = Client;
  7968. #endif
  7969. TestWithHeadersAndContentReceiver<ClientT>(
  7970. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7971. const std::string &body, const std::string &content_type,
  7972. ContentReceiver receiver, DownloadProgress progress) {
  7973. return cli.Put(path, headers, body, content_type, receiver, progress);
  7974. });
  7975. }
  7976. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7977. #ifdef CPPHTTPLIB_SSL_ENABLED
  7978. using ClientT = SSLClient;
  7979. #else
  7980. using ClientT = Client;
  7981. #endif
  7982. TestWithHeadersAndContentReceiver<ClientT>(
  7983. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7984. const std::string &body, const std::string &content_type,
  7985. ContentReceiver receiver, DownloadProgress progress) {
  7986. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7987. });
  7988. }
  7989. template <typename ClientType>
  7990. void TestWithHeadersAndContentReceiverWithProgress(
  7991. ClientType &cli,
  7992. std::function<Result(ClientType &, const std::string &, const Headers &,
  7993. const std::string &, const std::string &,
  7994. ContentReceiver, DownloadProgress)>
  7995. request_func) {
  7996. Headers headers;
  7997. headers.emplace("X-Test-Header", "progress-test");
  7998. std::string received_body;
  7999. auto progress_called = false;
  8000. auto res = request_func(
  8001. cli, "/content_receiver", headers, "content", "text/plain",
  8002. [&](const char *data, size_t data_length) {
  8003. received_body.append(data, data_length);
  8004. return true;
  8005. },
  8006. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8007. progress_called = true;
  8008. return true;
  8009. });
  8010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8011. EXPECT_EQ(StatusCode::OK_200, res->status);
  8012. EXPECT_EQ("content", received_body);
  8013. EXPECT_TRUE(progress_called);
  8014. }
  8015. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8016. #ifdef CPPHTTPLIB_SSL_ENABLED
  8017. using ClientT = SSLClient;
  8018. #else
  8019. using ClientT = Client;
  8020. #endif
  8021. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8022. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8023. const std::string &body, const std::string &content_type,
  8024. ContentReceiver receiver, DownloadProgress progress) {
  8025. return cli.Post(path, headers, body, content_type, receiver, progress);
  8026. });
  8027. }
  8028. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8029. #ifdef CPPHTTPLIB_SSL_ENABLED
  8030. using ClientT = SSLClient;
  8031. #else
  8032. using ClientT = Client;
  8033. #endif
  8034. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8035. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8036. const std::string &body, const std::string &content_type,
  8037. ContentReceiver receiver, DownloadProgress progress) {
  8038. return cli.Put(path, headers, body, content_type, receiver, progress);
  8039. });
  8040. }
  8041. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8042. #ifdef CPPHTTPLIB_SSL_ENABLED
  8043. using ClientT = SSLClient;
  8044. #else
  8045. using ClientT = Client;
  8046. #endif
  8047. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8048. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8049. const std::string &body, const std::string &content_type,
  8050. ContentReceiver receiver, DownloadProgress progress) {
  8051. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8052. });
  8053. }
  8054. template <typename ClientType>
  8055. void TestWithHeadersAndContentReceiverError(
  8056. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8057. const Headers &, const std::string &,
  8058. const std::string &, ContentReceiver)>
  8059. request_func) {
  8060. Headers headers;
  8061. headers.emplace("X-Error-Test", "true");
  8062. std::string received_body;
  8063. auto receiver_failed = false;
  8064. auto res =
  8065. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8066. [&](const char *data, size_t data_length) {
  8067. received_body.append(data, data_length);
  8068. receiver_failed = true;
  8069. return false;
  8070. });
  8071. ASSERT_FALSE(res);
  8072. EXPECT_TRUE(receiver_failed);
  8073. }
  8074. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8075. #ifdef CPPHTTPLIB_SSL_ENABLED
  8076. using ClientT = SSLClient;
  8077. #else
  8078. using ClientT = Client;
  8079. #endif
  8080. TestWithHeadersAndContentReceiverError<ClientT>(
  8081. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8082. const std::string &body, const std::string &content_type,
  8083. ContentReceiver receiver) {
  8084. return cli.Post(path, headers, body, content_type, receiver);
  8085. });
  8086. }
  8087. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8088. #ifdef CPPHTTPLIB_SSL_ENABLED
  8089. using ClientT = SSLClient;
  8090. #else
  8091. using ClientT = Client;
  8092. #endif
  8093. TestWithHeadersAndContentReceiverError<ClientT>(
  8094. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8095. const std::string &body, const std::string &content_type,
  8096. ContentReceiver receiver) {
  8097. return cli.Put(path, headers, body, content_type, receiver);
  8098. });
  8099. }
  8100. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8101. #ifdef CPPHTTPLIB_SSL_ENABLED
  8102. using ClientT = SSLClient;
  8103. #else
  8104. using ClientT = Client;
  8105. #endif
  8106. TestWithHeadersAndContentReceiverError<ClientT>(
  8107. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8108. const std::string &body, const std::string &content_type,
  8109. ContentReceiver receiver) {
  8110. return cli.Patch(path, headers, body, content_type, receiver);
  8111. });
  8112. }
  8113. TEST_F(ServerTest, PostQueryStringAndBody) {
  8114. auto res =
  8115. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8117. ASSERT_EQ(StatusCode::OK_200, res->status);
  8118. }
  8119. TEST_F(ServerTest, HTTP2Magic) {
  8120. Request req;
  8121. req.method = "PRI";
  8122. req.path = "*";
  8123. req.body = "SM";
  8124. auto res = std::make_shared<Response>();
  8125. auto error = Error::Success;
  8126. auto ret = cli_.send(req, *res, error);
  8127. ASSERT_TRUE(ret);
  8128. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8129. }
  8130. TEST_F(ServerTest, KeepAlive) {
  8131. auto res = cli_.Get("/hi");
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8135. EXPECT_EQ("Hello World!", res->body);
  8136. res = cli_.Get("/hi");
  8137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8138. EXPECT_EQ(StatusCode::OK_200, res->status);
  8139. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8140. EXPECT_EQ("Hello World!", res->body);
  8141. res = cli_.Get("/hi");
  8142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8143. EXPECT_EQ(StatusCode::OK_200, res->status);
  8144. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8145. EXPECT_EQ("Hello World!", res->body);
  8146. res = cli_.Get("/not-exist");
  8147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8148. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8149. res = cli_.Post("/empty", "", "text/plain");
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. EXPECT_EQ(StatusCode::OK_200, res->status);
  8152. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8153. EXPECT_EQ("empty", res->body);
  8154. EXPECT_EQ("close", res->get_header_value("Connection"));
  8155. res = cli_.Post(
  8156. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8157. "text/plain");
  8158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8159. EXPECT_EQ(StatusCode::OK_200, res->status);
  8160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8161. EXPECT_EQ("empty", res->body);
  8162. cli_.set_keep_alive(false);
  8163. res = cli_.Get("/last-request");
  8164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. EXPECT_EQ("close", res->get_header_value("Connection"));
  8167. }
  8168. TEST_F(ServerTest, TooManyRedirect) {
  8169. cli_.set_follow_location(true);
  8170. auto res = cli_.Get("/redirect/0");
  8171. ASSERT_TRUE(!res);
  8172. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8173. }
  8174. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8175. Request req;
  8176. req.method = "FOOBAR";
  8177. req.path = "/hi";
  8178. cli_.set_keep_alive(true);
  8179. auto res = cli_.send(req);
  8180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8181. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8182. EXPECT_EQ("close", res->get_header_value("Connection"));
  8183. EXPECT_FALSE(cli_.is_socket_open());
  8184. }
  8185. TEST_F(ServerTest, CustomRouteReadsBody) {
  8186. const std::string xml =
  8187. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8188. Request req;
  8189. req.method = "PROPFIND";
  8190. req.path = "/dav/dir";
  8191. req.set_header("Depth", "1");
  8192. req.body = xml;
  8193. auto res = cli_.send(req);
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8196. EXPECT_EQ(xml, res->body);
  8197. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8198. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8199. }
  8200. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8201. Request req;
  8202. req.method = "PROPFIND";
  8203. req.path = "/dav/42";
  8204. auto res = cli_.send(req);
  8205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8206. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8207. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8208. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8209. }
  8210. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8211. Request req;
  8212. req.method = "PROPFIND";
  8213. req.path = "/dav-re/123";
  8214. auto res = cli_.send(req);
  8215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8216. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8217. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8218. }
  8219. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8220. Request req;
  8221. req.method = "MKCOL";
  8222. req.path = "/dav-mkcol";
  8223. auto res = cli_.send(req);
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ(StatusCode::Created_201, res->status);
  8226. }
  8227. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8228. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8229. Request req;
  8230. req.method = "REPORT";
  8231. req.path = "/dav-report";
  8232. req.body = xml;
  8233. auto res = cli_.send(req);
  8234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8235. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8236. EXPECT_EQ(xml, res->body);
  8237. }
  8238. // A content reader route must fire even when the request carries no body,
  8239. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8240. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8241. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8242. Request req;
  8243. req.method = "REPORT";
  8244. req.path = "/dav-report";
  8245. auto res = cli_.send(req);
  8246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8247. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8248. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8249. }
  8250. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8251. Request req;
  8252. req.method = "PROPFIND";
  8253. req.path = "/not-dav";
  8254. auto res = cli_.send(req);
  8255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8256. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8257. }
  8258. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8259. Request req;
  8260. req.method = "UNLOCK";
  8261. req.path = "/dav/dir";
  8262. cli_.set_keep_alive(true);
  8263. auto res = cli_.send(req);
  8264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8265. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8266. EXPECT_EQ("close", res->get_header_value("Connection"));
  8267. EXPECT_FALSE(cli_.is_socket_open());
  8268. }
  8269. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8270. // The mount point serves this path, but only for GET and HEAD.
  8271. auto get_res = cli_.Get("/dir/index.html");
  8272. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8273. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8274. Request req;
  8275. req.method = "PROPFIND";
  8276. req.path = "/dir/index.html";
  8277. auto res = cli_.send(req);
  8278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8279. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8280. }
  8281. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8282. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8283. cli_.set_keep_alive(true);
  8284. for (auto i = 0; i < 2; i++) {
  8285. Request req;
  8286. req.method = "PROPFIND";
  8287. req.path = "/dav/dir";
  8288. req.body = xml;
  8289. auto res = cli_.send(req);
  8290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8291. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8292. EXPECT_EQ(xml, res->body);
  8293. EXPECT_TRUE(cli_.is_socket_open());
  8294. }
  8295. // A built-in method must still be served on the same connection.
  8296. cli_.set_keep_alive(false);
  8297. auto res = cli_.Get("/hi");
  8298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8299. EXPECT_EQ(StatusCode::OK_200, res->status);
  8300. EXPECT_EQ("close", res->get_header_value("Connection"));
  8301. }
  8302. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8303. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8304. Request req;
  8305. req.method = "PROPFIND";
  8306. req.path = "/dav/dir";
  8307. req.set_header("Expect", "100-continue");
  8308. req.body = xml;
  8309. auto res = cli_.send(req);
  8310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8311. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8312. EXPECT_EQ(xml, res->body);
  8313. }
  8314. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8315. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8316. TEST_F(ServerTest, Gzip) {
  8317. Headers headers;
  8318. headers.emplace("Accept-Encoding", "gzip, deflate");
  8319. auto res = cli_.Get("/compress", headers);
  8320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8321. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8323. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8324. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8325. "7890123456789012345678901234567890",
  8326. res->body);
  8327. EXPECT_EQ(StatusCode::OK_200, res->status);
  8328. }
  8329. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8330. Headers headers;
  8331. headers.emplace("Accept-Encoding", "gzip, deflate");
  8332. auto res = cli_.Get("/compress-with-charset", headers);
  8333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8334. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8335. EXPECT_EQ("application/json; charset=utf-8",
  8336. res->get_header_value("Content-Type"));
  8337. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8338. "7890123456789012345678901234567890",
  8339. res->body);
  8340. EXPECT_EQ(StatusCode::OK_200, res->status);
  8341. }
  8342. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8343. Headers headers;
  8344. headers.emplace("Accept-Encoding", "");
  8345. auto res = cli_.Get("/compress", headers);
  8346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8347. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8348. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8349. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8350. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8351. "7890123456789012345678901234567890",
  8352. res->body);
  8353. EXPECT_EQ(StatusCode::OK_200, res->status);
  8354. }
  8355. TEST_F(ServerTest, GzipWithContentReceiver) {
  8356. Headers headers;
  8357. headers.emplace("Accept-Encoding", "gzip, deflate");
  8358. std::string body;
  8359. auto res = cli_.Get("/compress", headers,
  8360. [&](const char *data, uint64_t data_length) {
  8361. EXPECT_EQ(100U, data_length);
  8362. body.append(data, data_length);
  8363. return true;
  8364. });
  8365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8366. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8368. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8369. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8370. "7890123456789012345678901234567890",
  8371. body);
  8372. EXPECT_EQ(StatusCode::OK_200, res->status);
  8373. }
  8374. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8375. Headers headers;
  8376. headers.emplace("Accept-Encoding", "gzip, deflate");
  8377. cli_.set_decompress(false);
  8378. auto res = cli_.Get("/compress", headers);
  8379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8380. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8381. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8382. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8383. EXPECT_EQ(33U, res->body.size());
  8384. EXPECT_EQ(StatusCode::OK_200, res->status);
  8385. }
  8386. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8387. Headers headers;
  8388. headers.emplace("Accept-Encoding", "");
  8389. std::string body;
  8390. auto res = cli_.Get("/compress", headers,
  8391. [&](const char *data, uint64_t data_length) {
  8392. EXPECT_EQ(100U, data_length);
  8393. body.append(data, data_length);
  8394. return true;
  8395. });
  8396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8397. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8398. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8399. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8400. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8401. "7890123456789012345678901234567890",
  8402. body);
  8403. EXPECT_EQ(StatusCode::OK_200, res->status);
  8404. }
  8405. TEST_F(ServerTest, NoGzip) {
  8406. Headers headers;
  8407. headers.emplace("Accept-Encoding", "gzip, deflate");
  8408. auto res = cli_.Get("/nocompress", headers);
  8409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8410. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8411. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8412. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8413. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8414. "7890123456789012345678901234567890",
  8415. res->body);
  8416. EXPECT_EQ(StatusCode::OK_200, res->status);
  8417. }
  8418. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8419. Headers headers;
  8420. headers.emplace("Accept-Encoding", "gzip, deflate");
  8421. std::string body;
  8422. auto res = cli_.Get("/nocompress", 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_EQ(false, res->has_header("Content-Encoding"));
  8430. EXPECT_EQ("application/octet-stream", 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, MultipartFormDataGzip) {
  8438. UploadFormDataItems items = {
  8439. {"key1", "test", "", ""},
  8440. {"key2", "--abcdefg123", "", ""},
  8441. };
  8442. cli_.set_compress(true);
  8443. auto res = cli_.Post("/compress-multipart", items);
  8444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8445. EXPECT_EQ(StatusCode::OK_200, res->status);
  8446. }
  8447. #endif
  8448. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8449. // Static file compression is opt-in, so these run their own server rather than
  8450. // flipping it on for the shared ServerTest fixture, which would silently
  8451. // rewrite what every other static file test is asserting.
  8452. class StaticFileCompressionTest : public ::testing::Test {
  8453. protected:
  8454. void TearDown() override {
  8455. if (t_.joinable()) {
  8456. svr_.stop();
  8457. t_.join();
  8458. }
  8459. }
  8460. int start(const std::function<void(Server &)> &configure = nullptr) {
  8461. // Serves the same tree as a directory of build-time compressed assets
  8462. // would be served: the mount point names the coding the files are already
  8463. // stored in. Registered before "/" so it is the one that matches.
  8464. svr_.set_mount_point("/pre-encoded", "./www",
  8465. {{"Content-Encoding", "gzip"}});
  8466. svr_.set_mount_point("/", "./www");
  8467. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8468. res.set_file_content("./www/dir/index.html", "text/html");
  8469. });
  8470. svr_.Get("/pre-encoded-file-content",
  8471. [](const Request & /*req*/, Response &res) {
  8472. res.set_header("Content-Encoding", "gzip");
  8473. res.set_file_content("./www/dir/index.html", "text/html");
  8474. });
  8475. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8476. res.set_content_provider(
  8477. 6, "text/plain",
  8478. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8479. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8480. return true;
  8481. });
  8482. });
  8483. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8484. res.set_content_provider(
  8485. 1000, "text/plain",
  8486. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8487. if (offset < 100) {
  8488. std::string data(100, 'A');
  8489. sink.write(data.data(), data.size());
  8490. return true;
  8491. }
  8492. std::this_thread::sleep_for(std::chrono::seconds(2));
  8493. std::string data(900, 'B');
  8494. sink.write(data.data(), data.size());
  8495. return true;
  8496. });
  8497. });
  8498. if (configure) { configure(svr_); }
  8499. auto port = svr_.bind_to_any_port(HOST);
  8500. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8501. svr_.wait_until_ready();
  8502. return port;
  8503. }
  8504. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8505. // Every file under ./www except 1MB.txt is smaller than the default
  8506. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8507. // it out of the way.
  8508. static void enable_without_floor(Server &svr) {
  8509. svr.set_static_file_compression(true);
  8510. svr.set_static_file_compression_min_length(0);
  8511. }
  8512. Server svr_;
  8513. std::thread t_;
  8514. };
  8515. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8516. auto port = start();
  8517. Client cli(HOST, port);
  8518. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8520. EXPECT_EQ(StatusCode::OK_200, res->status);
  8521. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8522. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8523. EXPECT_EQ(1048576U, res->body.size());
  8524. }
  8525. TEST_F(StaticFileCompressionTest, MountPoint) {
  8526. auto port = start(enable);
  8527. Client cli(HOST, port);
  8528. cli.set_decompress(false);
  8529. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8531. EXPECT_EQ(StatusCode::OK_200, res->status);
  8532. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8533. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8534. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8535. // The response stays self-delimiting: a length, not a chunked body.
  8536. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8537. EXPECT_EQ(std::to_string(res->body.size()),
  8538. res->get_header_value("Content-Length"));
  8539. EXPECT_LT(res->body.size(), 1048576U);
  8540. EXPECT_FALSE(res->body.empty());
  8541. }
  8542. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8543. auto port = start(enable);
  8544. Client cli(HOST, port);
  8545. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8547. EXPECT_EQ(StatusCode::OK_200, res->status);
  8548. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8549. EXPECT_EQ(1048576U, res->body.size());
  8550. }
  8551. TEST_F(StaticFileCompressionTest, FileContent) {
  8552. auto port = start(enable_without_floor);
  8553. Client cli(HOST, port);
  8554. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8556. EXPECT_EQ(StatusCode::OK_200, res->status);
  8557. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8558. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8559. EXPECT_EQ(104U, res->body.size());
  8560. }
  8561. // A handler that serves an already-encoded file names the coding itself. The
  8562. // file-backed path decided its coding from Accept-Encoding and the content
  8563. // type alone, so it compressed the stored bytes a second time and appended a
  8564. // second Content-Encoding field line.
  8565. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8566. auto port = start(enable_without_floor);
  8567. Client cli(HOST, port);
  8568. cli.set_decompress(false);
  8569. auto res = cli.Get("/pre-encoded-file-content",
  8570. Headers{{"Accept-Encoding", "gzip"}});
  8571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8572. EXPECT_EQ(StatusCode::OK_200, res->status);
  8573. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8574. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8575. // Vary belongs to a coding the server chose, and it chose none here.
  8576. EXPECT_FALSE(res->has_header("Vary"));
  8577. // The file travels exactly as it is stored on disk.
  8578. EXPECT_EQ(104U, res->body.size());
  8579. }
  8580. // The 1MB file clears the default floor, so this one runs the configuration a
  8581. // deployment would actually have.
  8582. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8583. auto port = start(enable);
  8584. Client cli(HOST, port);
  8585. cli.set_decompress(false);
  8586. auto res =
  8587. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8589. EXPECT_EQ(StatusCode::OK_200, res->status);
  8590. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8591. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8592. EXPECT_FALSE(res->has_header("Vary"));
  8593. EXPECT_EQ(1048576U, res->body.size());
  8594. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8595. }
  8596. TEST_F(StaticFileCompressionTest, Head) {
  8597. auto port = start(enable);
  8598. Client cli(HOST, port);
  8599. cli.set_decompress(false);
  8600. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8601. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8602. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8604. EXPECT_EQ(StatusCode::OK_200, res->status);
  8605. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8606. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8607. // HEAD still reports the size a GET would return.
  8608. EXPECT_EQ(get->get_header_value("Content-Length"),
  8609. res->get_header_value("Content-Length"));
  8610. EXPECT_TRUE(res->body.empty());
  8611. }
  8612. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8613. auto port = start(enable);
  8614. Client cli(HOST, port);
  8615. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8616. {"Accept-Encoding", "gzip"}});
  8617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8618. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8619. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8620. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8621. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8622. EXPECT_EQ("cd", res->body);
  8623. }
  8624. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8625. auto port = start(enable);
  8626. Client cli(HOST, port);
  8627. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8629. EXPECT_EQ(StatusCode::OK_200, res->status);
  8630. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8631. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8632. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8633. }
  8634. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8635. auto port = start(enable);
  8636. Client cli(HOST, port);
  8637. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ(StatusCode::OK_200, res->status);
  8640. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8641. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8642. EXPECT_TRUE(res->body.empty());
  8643. }
  8644. TEST_F(StaticFileCompressionTest, MinLength) {
  8645. auto port = start(enable);
  8646. Client cli(HOST, port);
  8647. // 104 bytes, well under the default floor. Compressing it would add the
  8648. // gzip header and trailer to a body that already fits in one packet.
  8649. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8651. EXPECT_EQ(StatusCode::OK_200, res->status);
  8652. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8653. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8654. }
  8655. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8656. auto port = start([](Server &svr) {
  8657. svr.set_static_file_compression(true);
  8658. svr.set_static_file_compression_min_length(1);
  8659. });
  8660. Client cli(HOST, port);
  8661. cli.set_decompress(false);
  8662. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8664. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8665. // A 9-byte file comes back larger than it went in, because gzip's header and
  8666. // trailer outweigh anything deflate can save. That is the end of the range
  8667. // the floor exists to keep out.
  8668. EXPECT_GT(res->body.size(), 9U);
  8669. }
  8670. TEST_F(StaticFileCompressionTest, MaxLength) {
  8671. auto port = start([](Server &svr) {
  8672. svr.set_static_file_compression(true);
  8673. svr.set_static_file_compression_min_length(0);
  8674. svr.set_static_file_compression_max_length(1024);
  8675. });
  8676. Client cli(HOST, port);
  8677. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8678. // defines `small` as a macro on Windows.
  8679. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8680. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8681. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8682. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8683. // Under it: compressed.
  8684. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8685. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8686. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8687. }
  8688. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8689. auto port = start(enable_without_floor);
  8690. Client cli(HOST, port);
  8691. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8692. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8693. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8694. auto identity_etag = identity->get_header_value("ETag");
  8695. ASSERT_FALSE(identity_etag.empty());
  8696. auto gzipped =
  8697. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8698. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8699. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8700. auto gzip_etag = gzipped->get_header_value("ETag");
  8701. ASSERT_FALSE(gzip_etag.empty());
  8702. // Two representations, two validators.
  8703. EXPECT_NE(identity_etag, gzip_etag);
  8704. // Each one revalidates against the request that would produce it...
  8705. auto fresh =
  8706. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8707. {"If-None-Match", gzip_etag}});
  8708. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8709. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8710. auto fresh_identity =
  8711. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8712. {"If-None-Match", identity_etag}});
  8713. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8714. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8715. // ...and not against the other representation.
  8716. auto crossed =
  8717. cli.Get("/dir/index.html",
  8718. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8719. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8720. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8721. }
  8722. // The opt-in covers responses the server reads off disk itself. A caller's own
  8723. // known-length provider keeps its Content-Length and, more importantly, keeps
  8724. // delivering incrementally: routing it through a compressor would hold every
  8725. // write back until zlib's window filled.
  8726. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8727. auto port = start(enable);
  8728. Client cli(HOST, port);
  8729. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8731. EXPECT_EQ(StatusCode::OK_200, res->status);
  8732. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8733. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8734. EXPECT_EQ("aaabbb", res->body);
  8735. }
  8736. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8737. auto port = start(enable);
  8738. Client cli(HOST, port);
  8739. cli.set_read_timeout(1, 0);
  8740. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8741. Headers{{"Accept-Encoding", "gzip"}});
  8742. ASSERT_TRUE(handle.is_valid());
  8743. // The provider writes 100 bytes and then stalls for longer than the read
  8744. // timeout. Those first bytes have to arrive anyway: run the response through
  8745. // a compressor and zlib holds them until its window fills, so the read would
  8746. // come back empty instead.
  8747. char buf[256];
  8748. auto n = handle.read(buf, sizeof(buf));
  8749. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8750. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8751. }
  8752. #endif
  8753. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8754. TEST_F(ServerTest, Brotli) {
  8755. Headers headers;
  8756. headers.emplace("Accept-Encoding", "br");
  8757. auto res = cli_.Get("/compress", headers);
  8758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8759. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8760. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8761. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8762. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8763. "7890123456789012345678901234567890",
  8764. res->body);
  8765. EXPECT_EQ(StatusCode::OK_200, res->status);
  8766. }
  8767. #endif
  8768. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8769. TEST_F(ServerTest, Zstd) {
  8770. Headers headers;
  8771. headers.emplace("Accept-Encoding", "zstd");
  8772. auto res = cli_.Get("/compress", headers);
  8773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8774. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8775. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8776. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8777. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8778. "7890123456789012345678901234567890",
  8779. res->body);
  8780. EXPECT_EQ(StatusCode::OK_200, res->status);
  8781. }
  8782. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8783. Headers headers;
  8784. headers.emplace("Accept-Encoding", "");
  8785. auto res = cli_.Get("/compress", headers);
  8786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8787. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8788. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8789. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8790. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8791. "7890123456789012345678901234567890",
  8792. res->body);
  8793. EXPECT_EQ(StatusCode::OK_200, res->status);
  8794. }
  8795. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8796. Headers headers;
  8797. headers.emplace("Accept-Encoding", "zstd");
  8798. std::string body;
  8799. auto res = cli_.Get("/compress", headers,
  8800. [&](const char *data, uint64_t data_length) {
  8801. EXPECT_EQ(100U, data_length);
  8802. body.append(data, data_length);
  8803. return true;
  8804. });
  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. body);
  8812. EXPECT_EQ(StatusCode::OK_200, res->status);
  8813. }
  8814. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8815. Headers headers;
  8816. headers.emplace("Accept-Encoding", "zstd");
  8817. cli_.set_decompress(false);
  8818. auto res = cli_.Get("/compress", headers);
  8819. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8820. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8821. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8822. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8826. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8827. EXPECT_EQ(StatusCode::OK_200, res->status);
  8828. ASSERT_EQ(26U, res->body.size());
  8829. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8830. 0);
  8831. }
  8832. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8833. Headers headers;
  8834. headers.emplace("Accept-Encoding", "");
  8835. std::string body;
  8836. auto res = cli_.Get("/compress", headers,
  8837. [&](const char *data, uint64_t data_length) {
  8838. EXPECT_EQ(100U, data_length);
  8839. body.append(data, data_length);
  8840. return true;
  8841. });
  8842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8843. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8844. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8845. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8846. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8847. "7890123456789012345678901234567890",
  8848. body);
  8849. EXPECT_EQ(StatusCode::OK_200, res->status);
  8850. }
  8851. TEST_F(ServerTest, NoZstd) {
  8852. Headers headers;
  8853. headers.emplace("Accept-Encoding", "zstd");
  8854. auto res = cli_.Get("/nocompress", headers);
  8855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8856. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8857. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8858. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8859. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8860. "7890123456789012345678901234567890",
  8861. res->body);
  8862. EXPECT_EQ(StatusCode::OK_200, res->status);
  8863. }
  8864. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8865. Headers headers;
  8866. headers.emplace("Accept-Encoding", "zstd");
  8867. std::string body;
  8868. auto res = cli_.Get("/nocompress", 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_EQ(false, res->has_header("Content-Encoding"));
  8876. EXPECT_EQ("application/octet-stream", 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. // TODO: How to enable zstd ??
  8884. TEST_F(ServerTest, MultipartFormDataZstd) {
  8885. UploadFormDataItems items = {
  8886. {"key1", "test", "", ""},
  8887. {"key2", "--abcdefg123", "", ""},
  8888. };
  8889. Headers headers;
  8890. headers.emplace("Accept-Encoding", "zstd");
  8891. cli_.set_compress(true);
  8892. auto res = cli_.Post("/compress-multipart", headers, items);
  8893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8894. EXPECT_EQ(StatusCode::OK_200, res->status);
  8895. }
  8896. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8897. Headers headers;
  8898. headers.emplace("Accept-Encoding", "zstd");
  8899. cli_.set_compress(true);
  8900. auto res = cli_.Put(
  8901. "/put", headers, 3,
  8902. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8903. sink.os << "PUT";
  8904. return true;
  8905. },
  8906. "text/plain");
  8907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8908. EXPECT_EQ(StatusCode::OK_200, res->status);
  8909. EXPECT_EQ("PUT", res->body);
  8910. }
  8911. // Pre-compression logging tests
  8912. TEST_F(ServerTest, PreCompressionLogging) {
  8913. // Test data for compression (matches the actual /compress endpoint content)
  8914. const std::string test_content =
  8915. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8916. "3456789012345678901234567890";
  8917. // Variables to capture logging data
  8918. std::string pre_compression_body;
  8919. std::string pre_compression_content_type;
  8920. std::string pre_compression_content_encoding;
  8921. std::string post_compression_body;
  8922. std::string post_compression_content_type;
  8923. std::string post_compression_content_encoding;
  8924. // Set up pre-compression logger
  8925. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8926. const Response &res) {
  8927. pre_compression_body = res.body;
  8928. pre_compression_content_type = res.get_header_value("Content-Type");
  8929. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8930. });
  8931. // Set up post-compression logger
  8932. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8933. post_compression_body = res.body;
  8934. post_compression_content_type = res.get_header_value("Content-Type");
  8935. post_compression_content_encoding =
  8936. res.get_header_value("Content-Encoding");
  8937. });
  8938. // Test with gzip compression
  8939. Headers headers;
  8940. headers.emplace("Accept-Encoding", "gzip");
  8941. auto res = cli_.Get("/compress", headers);
  8942. // Verify response was compressed
  8943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8944. EXPECT_EQ(StatusCode::OK_200, res->status);
  8945. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8946. // Verify pre-compression logger captured uncompressed content
  8947. EXPECT_EQ(test_content, pre_compression_body);
  8948. EXPECT_EQ("text/plain", pre_compression_content_type);
  8949. EXPECT_TRUE(pre_compression_content_encoding
  8950. .empty()); // No encoding header before compression
  8951. // Verify post-compression logger captured compressed content
  8952. EXPECT_NE(test_content,
  8953. post_compression_body); // Should be different after compression
  8954. EXPECT_EQ("text/plain", post_compression_content_type);
  8955. EXPECT_EQ("gzip", post_compression_content_encoding);
  8956. // Verify compressed content is smaller
  8957. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8958. }
  8959. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8960. const std::string test_content =
  8961. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8962. "3456789012345678901234567890";
  8963. std::string pre_compression_body;
  8964. std::string post_compression_body;
  8965. svr_.set_pre_compression_logger(
  8966. [&](const Request & /*req*/, const Response &res) {
  8967. pre_compression_body = res.body;
  8968. });
  8969. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8970. post_compression_body = res.body;
  8971. });
  8972. Headers headers;
  8973. headers.emplace("Accept-Encoding", "br");
  8974. auto res = cli_.Get("/compress", headers);
  8975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8976. EXPECT_EQ(StatusCode::OK_200, res->status);
  8977. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8978. // Verify pre-compression content is uncompressed
  8979. EXPECT_EQ(test_content, pre_compression_body);
  8980. // Verify post-compression content is compressed
  8981. EXPECT_NE(test_content, post_compression_body);
  8982. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8983. }
  8984. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8985. const std::string test_content =
  8986. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8987. "3456789012345678901234567890";
  8988. std::string pre_compression_body;
  8989. std::string post_compression_body;
  8990. svr_.set_pre_compression_logger(
  8991. [&](const Request & /*req*/, const Response &res) {
  8992. pre_compression_body = res.body;
  8993. });
  8994. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8995. post_compression_body = res.body;
  8996. });
  8997. // Request without compression (use /nocompress endpoint)
  8998. Headers headers;
  8999. auto res = cli_.Get("/nocompress", headers);
  9000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9001. EXPECT_EQ(StatusCode::OK_200, res->status);
  9002. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9003. // Pre-compression logger should not be called when no compression is applied
  9004. EXPECT_TRUE(
  9005. pre_compression_body.empty()); // Pre-compression logger not called
  9006. EXPECT_EQ(
  9007. test_content,
  9008. post_compression_body); // Post-compression logger captures final content
  9009. }
  9010. TEST_F(ServerTest, LoggerSeesContentLength) {
  9011. size_t logged_content_length = 0;
  9012. std::string logged_content_length_header;
  9013. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9014. logged_content_length = res.content_length_;
  9015. logged_content_length_header = res.get_header_value("Content-Length");
  9016. });
  9017. auto res = cli_.Get("/nocompress");
  9018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9019. EXPECT_EQ(StatusCode::OK_200, res->status);
  9020. EXPECT_EQ(res->body.size(), logged_content_length);
  9021. EXPECT_EQ(std::to_string(logged_content_length),
  9022. logged_content_length_header);
  9023. }
  9024. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9025. const std::string test_content =
  9026. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9027. "3456789012345678901234567890";
  9028. std::string pre_compression_body;
  9029. bool pre_logger_called = false;
  9030. // Set only pre-compression logger
  9031. svr_.set_pre_compression_logger(
  9032. [&](const Request & /*req*/, const Response &res) {
  9033. pre_compression_body = res.body;
  9034. pre_logger_called = true;
  9035. });
  9036. Headers headers;
  9037. headers.emplace("Accept-Encoding", "gzip");
  9038. auto res = cli_.Get("/compress", headers);
  9039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9040. EXPECT_EQ(StatusCode::OK_200, res->status);
  9041. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9042. // Verify pre-compression logger was called
  9043. EXPECT_TRUE(pre_logger_called);
  9044. EXPECT_EQ(test_content, pre_compression_body);
  9045. }
  9046. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9047. {
  9048. // Test with Expect: 100-continue header - success case
  9049. // Server returns 100 Continue, client sends body, server returns 200 OK
  9050. Request req;
  9051. req.method = "POST";
  9052. req.path = "/post-large";
  9053. req.set_header("Expect", "100-continue");
  9054. req.body = LARGE_DATA;
  9055. Response res;
  9056. auto error = Error::Success;
  9057. cli_.set_keep_alive(true);
  9058. auto ret = cli_.send(req, res, error);
  9059. EXPECT_TRUE(ret);
  9060. EXPECT_EQ(StatusCode::OK_200, res.status);
  9061. EXPECT_EQ(LARGE_DATA, res.body);
  9062. }
  9063. {
  9064. // Test with Expect: 100-continue header - error case
  9065. // Client should not send the body when server returns an error
  9066. Request req;
  9067. req.method = "POST";
  9068. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9069. req.set_header("Expect", "100-continue");
  9070. req.body = LARGE_DATA;
  9071. Response res;
  9072. auto error = Error::Success;
  9073. auto start = std::chrono::high_resolution_clock::now();
  9074. cli_.set_keep_alive(true);
  9075. auto ret = cli_.send(req, res, error);
  9076. auto end = std::chrono::high_resolution_clock::now();
  9077. auto elapsed =
  9078. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9079. .count();
  9080. // With Expect: 100-continue, request completes successfully but with error
  9081. EXPECT_TRUE(ret);
  9082. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9083. EXPECT_EQ("close", res.get_header_value("Connection"));
  9084. EXPECT_FALSE(cli_.is_socket_open());
  9085. EXPECT_LE(elapsed, 2000);
  9086. }
  9087. {
  9088. // Send an extra GET request to ensure error recovery without hanging
  9089. Request req;
  9090. req.method = "GET";
  9091. req.path = "/hi";
  9092. auto start = std::chrono::high_resolution_clock::now();
  9093. auto res = cli_.send(req);
  9094. auto end = std::chrono::high_resolution_clock::now();
  9095. auto elapsed =
  9096. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9097. .count();
  9098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9099. EXPECT_EQ(StatusCode::OK_200, res->status);
  9100. EXPECT_EQ("Hello World!", res->body);
  9101. EXPECT_LE(elapsed, 500);
  9102. }
  9103. }
  9104. TEST(ZstdDecompressor, ChunkedDecompression) {
  9105. std::string data;
  9106. for (size_t i = 0; i < 32 * 1024; ++i) {
  9107. data.push_back(static_cast<char>('a' + i % 26));
  9108. }
  9109. std::string compressed_data;
  9110. {
  9111. httplib::detail::zstd_compressor compressor;
  9112. bool result = compressor.compress(
  9113. data.data(), data.size(),
  9114. /*last=*/true,
  9115. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9116. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9117. compressed_data_size);
  9118. return true;
  9119. });
  9120. ASSERT_TRUE(result);
  9121. }
  9122. std::string decompressed_data;
  9123. {
  9124. httplib::detail::zstd_decompressor decompressor;
  9125. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9126. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9127. size_t chunk_size = 130;
  9128. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9129. chunk_begin += chunk_size) {
  9130. size_t current_chunk_size =
  9131. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9132. bool result = decompressor.decompress(
  9133. compressed_data.data() + chunk_begin, current_chunk_size,
  9134. [&](const char *decompressed_data_chunk,
  9135. size_t decompressed_data_chunk_size) {
  9136. decompressed_data.insert(decompressed_data.size(),
  9137. decompressed_data_chunk,
  9138. decompressed_data_chunk_size);
  9139. return true;
  9140. });
  9141. ASSERT_TRUE(result);
  9142. }
  9143. }
  9144. ASSERT_EQ(data, decompressed_data);
  9145. }
  9146. TEST(ZstdDecompressor, Decompress) {
  9147. std::string original_text = "Compressed with ZSTD";
  9148. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9149. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9150. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9151. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9152. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9153. std::string decompressed_data;
  9154. {
  9155. httplib::detail::zstd_decompressor decompressor;
  9156. bool result = decompressor.decompress(
  9157. compressed_data.data(), compressed_data.size(),
  9158. [&](const char *decompressed_data_chunk,
  9159. size_t decompressed_data_chunk_size) {
  9160. decompressed_data.insert(decompressed_data.size(),
  9161. decompressed_data_chunk,
  9162. decompressed_data_chunk_size);
  9163. return true;
  9164. });
  9165. ASSERT_TRUE(result);
  9166. }
  9167. ASSERT_EQ(original_text, decompressed_data);
  9168. }
  9169. #endif
  9170. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9171. // separate chunks so that the server sees each part in its own read(). Used to
  9172. // place a read boundary at a specific offset of a request body.
  9173. static bool send_request_in_parts(time_t read_timeout_sec,
  9174. const std::vector<std::string> &parts,
  9175. std::string *resp = nullptr,
  9176. int port = PORT) {
  9177. auto error = Error::Success;
  9178. auto client_sock = detail::create_client_socket(
  9179. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9180. /*connection_timeout_sec=*/5, 0,
  9181. /*read_timeout_sec=*/5, 0,
  9182. /*write_timeout_sec=*/5, 0, std::string(), error);
  9183. if (client_sock == INVALID_SOCKET) { return false; }
  9184. auto ret = detail::process_client_socket(
  9185. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9186. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9187. for (size_t i = 0; i < parts.size(); i++) {
  9188. const auto &part = parts[i];
  9189. if (part.size() !=
  9190. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9191. return false;
  9192. }
  9193. if (i + 1 < parts.size()) {
  9194. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9195. }
  9196. }
  9197. char buf[512];
  9198. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9199. while (line_reader.getline()) {
  9200. if (resp) { *resp += line_reader.ptr(); }
  9201. }
  9202. return true;
  9203. });
  9204. detail::close_socket(client_sock);
  9205. return ret;
  9206. }
  9207. // Sends a raw request to a server listening at HOST:PORT.
  9208. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9209. std::string *resp = nullptr, int port = PORT) {
  9210. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9211. }
  9212. #ifdef CPPHTTPLIB_SSL_ENABLED
  9213. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9214. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9215. ASSERT_TRUE(svr.is_valid());
  9216. svr.set_read_timeout(1, 0);
  9217. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9218. auto se = detail::scope_exit([&] {
  9219. svr.stop();
  9220. t.join();
  9221. ASSERT_FALSE(svr.is_running());
  9222. });
  9223. svr.wait_until_ready();
  9224. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9225. // keeps each wait well within the read timeout. The server gives up a
  9226. // second in, so the bytes sent after that fail.
  9227. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9228. parts.resize(26, std::string(1, '\0'));
  9229. EXPECT_FALSE(send_request_in_parts(5, parts));
  9230. }
  9231. #endif
  9232. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9233. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9234. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9235. const std::vector<std::string> &parts,
  9236. std::string *resp = nullptr,
  9237. int port = PORT) {
  9238. auto error = Error::Success;
  9239. auto sock = detail::create_client_socket(
  9240. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9241. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9242. /*write_timeout_sec=*/5, 0, std::string(), error);
  9243. if (sock == INVALID_SOCKET) { return false; }
  9244. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9245. auto ctx = SSL_CTX_new(TLS_client_method());
  9246. auto ssl = SSL_new(ctx);
  9247. auto ssl_se = detail::scope_exit([&] {
  9248. SSL_free(ssl);
  9249. SSL_CTX_free(ctx);
  9250. });
  9251. SSL_set_fd(ssl, static_cast<int>(sock));
  9252. if (SSL_connect(ssl) != 1) { return false; }
  9253. for (size_t i = 0; i < parts.size(); i++) {
  9254. const auto &part = parts[i];
  9255. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9256. static_cast<int>(part.size())) {
  9257. return false;
  9258. }
  9259. if (i + 1 < parts.size()) {
  9260. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9261. }
  9262. }
  9263. char buf[512];
  9264. int n;
  9265. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9266. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9267. }
  9268. return true;
  9269. }
  9270. #endif
  9271. // The request line, then a header value a byte at a time.
  9272. static std::vector<std::string> slow_request_head_parts() {
  9273. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9274. parts.resize(26, "a");
  9275. parts.emplace_back("\r\n\r\n");
  9276. return parts;
  9277. }
  9278. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9279. // within the one-second read timeout. The server gives up a second in, before
  9280. // the head is complete.
  9281. static void
  9282. expect_slow_request_head_dropped(Server &svr,
  9283. const std::function<std::string()> &send) {
  9284. std::atomic<bool> handled(false);
  9285. svr.Get("/", [&](const Request &, Response &res) {
  9286. handled = true;
  9287. res.set_content("ok", "text/plain");
  9288. });
  9289. svr.set_read_timeout(1, 0);
  9290. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9291. auto se = detail::scope_exit([&] {
  9292. svr.stop();
  9293. t.join();
  9294. ASSERT_FALSE(svr.is_running());
  9295. });
  9296. svr.wait_until_ready();
  9297. auto resp = send();
  9298. EXPECT_FALSE(handled);
  9299. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9300. }
  9301. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9302. Server svr;
  9303. expect_slow_request_head_dropped(svr, [] {
  9304. std::string resp;
  9305. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9306. return resp;
  9307. });
  9308. }
  9309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9310. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9312. ASSERT_TRUE(svr.is_valid());
  9313. expect_slow_request_head_dropped(svr, [] {
  9314. std::string resp;
  9315. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9316. return resp;
  9317. });
  9318. }
  9319. #endif
  9320. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9321. Server svr;
  9322. std::string header_value;
  9323. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9324. header_value = req.get_header_value("foo");
  9325. res.set_content("ok", "text/plain");
  9326. });
  9327. thread t = thread([&] { svr.listen(HOST, PORT); });
  9328. auto se = detail::scope_exit([&] {
  9329. svr.stop();
  9330. t.join();
  9331. ASSERT_FALSE(svr.is_running());
  9332. });
  9333. svr.wait_until_ready();
  9334. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9335. // like characters are not treated the same - use vertical tab and escape.
  9336. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9337. "foo: \t \v bar \x1B\t \r\n"
  9338. "Connection: close\r\n"
  9339. "\r\n";
  9340. std::string res;
  9341. ASSERT_TRUE(send_request(5, req, &res));
  9342. EXPECT_EQ(header_value, "");
  9343. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9344. }
  9345. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9346. Server svr;
  9347. std::string received;
  9348. svr.Get("/order", [&](const Request &req, Response &res) {
  9349. received = entries_to_string(req.headers);
  9350. res.set_content("ok", "text/plain");
  9351. });
  9352. auto port = svr.bind_to_any_port(HOST);
  9353. thread t = thread([&] { svr.listen_after_bind(); });
  9354. auto se = detail::scope_exit([&] {
  9355. svr.stop();
  9356. t.join();
  9357. ASSERT_FALSE(svr.is_running());
  9358. });
  9359. svr.wait_until_ready();
  9360. const std::string req = "GET /order HTTP/1.1\r\n"
  9361. "Host: localhost\r\n"
  9362. "X-First: 1\r\n"
  9363. "X-Dup: a\r\n"
  9364. "X-Second: 2\r\n"
  9365. "X-Dup: b\r\n"
  9366. "Connection: close\r\n"
  9367. "\r\n";
  9368. std::string res;
  9369. ASSERT_TRUE(send_request(5, req, &res, port));
  9370. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9371. EXPECT_EQ(
  9372. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9373. received);
  9374. }
  9375. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9376. Server svr;
  9377. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9378. res.set_header("Set-Cookie", "first=1");
  9379. res.set_header("X-Between", "y");
  9380. res.set_header("Set-Cookie", "second=2");
  9381. res.set_content("ok", "text/plain");
  9382. });
  9383. auto port = svr.bind_to_any_port(HOST);
  9384. thread t = thread([&] { svr.listen_after_bind(); });
  9385. auto se = detail::scope_exit([&] {
  9386. svr.stop();
  9387. t.join();
  9388. ASSERT_FALSE(svr.is_running());
  9389. });
  9390. svr.wait_until_ready();
  9391. Client cli(HOST, port);
  9392. auto res = cli.Get("/cookies");
  9393. ASSERT_TRUE(res);
  9394. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9395. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9396. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9397. }
  9398. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9399. Server svr;
  9400. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9401. auto i = new int(0);
  9402. res.set_header("Trailer", "X-Safe, X-Reflected");
  9403. res.set_chunked_content_provider(
  9404. "text/plain",
  9405. [i](size_t /*offset*/, DataSink &sink) {
  9406. if (*i == 0) {
  9407. sink.os << "body";
  9408. } else {
  9409. Headers trailer;
  9410. // A valid trailer that must survive.
  9411. trailer.emplace("X-Safe", "safe");
  9412. // Attacker-controlled value carrying CR/LF (response splitting).
  9413. trailer.emplace("X-Reflected",
  9414. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9415. // Attacker-controlled name carrying CR/LF.
  9416. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9417. sink.done_with_trailer(trailer);
  9418. }
  9419. (*i)++;
  9420. return true;
  9421. },
  9422. [i](bool /*success*/) { delete i; });
  9423. });
  9424. thread t = thread([&] { svr.listen(HOST, PORT); });
  9425. auto se = detail::scope_exit([&] {
  9426. svr.stop();
  9427. t.join();
  9428. ASSERT_FALSE(svr.is_running());
  9429. });
  9430. svr.wait_until_ready();
  9431. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9432. "Host: " + HOST +
  9433. "\r\n"
  9434. "Connection: close\r\n"
  9435. "\r\n";
  9436. std::string res;
  9437. ASSERT_TRUE(send_request(5, req, &res));
  9438. // The injected fields must not appear anywhere in the raw response.
  9439. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9440. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9441. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9442. // Invalid trailers are dropped entirely, matching set_header().
  9443. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9444. // The valid trailer still passes through.
  9445. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9446. }
  9447. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9448. Server svr;
  9449. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9450. // res.headers is a public field an application can populate directly,
  9451. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9452. // A valid header that must survive.
  9453. res.headers.emplace("X-Safe", "safe");
  9454. // Attacker-controlled value carrying CR/LF (response splitting).
  9455. res.headers.emplace("X-Reflected",
  9456. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9457. // Attacker-controlled name carrying CR/LF.
  9458. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9459. res.set_content("body", "text/plain");
  9460. });
  9461. thread t = thread([&] { svr.listen(HOST, PORT); });
  9462. auto se = detail::scope_exit([&] {
  9463. svr.stop();
  9464. t.join();
  9465. ASSERT_FALSE(svr.is_running());
  9466. });
  9467. svr.wait_until_ready();
  9468. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9469. "Host: " + HOST +
  9470. "\r\n"
  9471. "Connection: close\r\n"
  9472. "\r\n";
  9473. std::string res;
  9474. ASSERT_TRUE(send_request(5, req, &res));
  9475. // The injected fields must not appear anywhere in the raw response.
  9476. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9477. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9478. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9479. // Invalid headers are dropped entirely, matching set_header().
  9480. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9481. // The valid header still passes through.
  9482. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9483. }
  9484. // Forward declaration: in split builds split.py strips `inline` and moves the
  9485. // definition into httplib.cc, so detail::write_request_line is not visible from
  9486. // the public httplib.h. Re-declaring it here lets the tests link against the
  9487. // symbol in both header-only and split builds.
  9488. namespace httplib {
  9489. namespace detail {
  9490. ssize_t write_request_line(Stream &strm, const std::string &method,
  9491. const std::string &path);
  9492. } // namespace detail
  9493. } // namespace httplib
  9494. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9495. // A well-formed target is written verbatim.
  9496. {
  9497. detail::BufferStream strm;
  9498. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9499. EXPECT_GT(n, 0);
  9500. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9501. }
  9502. // A target carrying CR/LF, SP or other control octets must be rejected
  9503. // before anything reaches the wire, otherwise it splits the request line and
  9504. // injects a header or a whole request.
  9505. const std::string evil_targets[] = {
  9506. "/a\r\nInjected: pwned",
  9507. "/a\rInjected",
  9508. "/a\nInjected",
  9509. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9510. "/a b",
  9511. "/a\tb",
  9512. "/a\x7f",
  9513. };
  9514. for (const auto &evil : evil_targets) {
  9515. detail::BufferStream strm;
  9516. auto n = detail::write_request_line(strm, "GET", evil);
  9517. EXPECT_LT(n, 0);
  9518. EXPECT_TRUE(strm.get_buffer().empty());
  9519. }
  9520. }
  9521. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9522. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9523. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9524. // target reaches write_request. The client must fail cleanly with
  9525. // Error::Write instead of putting a request-line-less, header-injecting
  9526. // request on the wire.
  9527. Server svr;
  9528. svr.Get("/a", [](const Request &, Response &res) {
  9529. res.set_content("ok", "text/plain");
  9530. });
  9531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9532. auto se = detail::scope_exit([&] {
  9533. svr.stop();
  9534. thread.join();
  9535. ASSERT_FALSE(svr.is_running());
  9536. });
  9537. svr.wait_until_ready();
  9538. {
  9539. Client cli(HOST, PORT);
  9540. cli.set_path_encode(false);
  9541. // The request is rejected before anything is written, so the connection
  9542. // stays silent and the subsequent response read would otherwise block for
  9543. // the full default read timeout. Shorten it -- the assertion is on the
  9544. // error, not the timeout.
  9545. cli.set_read_timeout(1, 0);
  9546. auto res = cli.Get("/a\r\nInjected: pwned");
  9547. EXPECT_FALSE(res);
  9548. EXPECT_EQ(Error::Write, res.error());
  9549. }
  9550. }
  9551. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9552. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9553. // including extension methods.
  9554. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9555. for (const auto &method : good_methods) {
  9556. detail::BufferStream strm;
  9557. auto n = detail::write_request_line(strm, method, "/");
  9558. EXPECT_GT(n, 0);
  9559. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9560. }
  9561. // A method carrying CR/LF would split the request line and smuggle a whole
  9562. // request ahead of the real one. A space or an empty method corrupts the
  9563. // request line. All must be rejected before anything reaches the wire.
  9564. const std::string evil_methods[] = {
  9565. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9566. "GET\r\nInjected: pwned",
  9567. "GET\r",
  9568. "GET\n",
  9569. "GE T",
  9570. "",
  9571. };
  9572. for (const auto &evil : evil_methods) {
  9573. detail::BufferStream strm;
  9574. auto n = detail::write_request_line(strm, evil, "/");
  9575. EXPECT_LT(n, 0);
  9576. EXPECT_TRUE(strm.get_buffer().empty());
  9577. }
  9578. }
  9579. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9580. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9581. // through Client::send must fail with Error::Write and no request, neither
  9582. // the smuggled one nor the real one, may reach the server.
  9583. Server svr;
  9584. std::atomic<int> request_count(0);
  9585. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9586. request_count++;
  9587. res.status = StatusCode::OK_200;
  9588. return Server::HandlerResponse::Handled;
  9589. });
  9590. auto port = svr.bind_to_any_port(HOST);
  9591. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9592. auto se = detail::scope_exit([&] {
  9593. svr.stop();
  9594. thread.join();
  9595. ASSERT_FALSE(svr.is_running());
  9596. });
  9597. svr.wait_until_ready();
  9598. {
  9599. Client cli(HOST, port);
  9600. const std::string evil_methods[] = {
  9601. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9602. "GE T",
  9603. "",
  9604. };
  9605. for (const auto &evil : evil_methods) {
  9606. Request req;
  9607. req.method = evil;
  9608. req.path = "/";
  9609. auto res = cli.send(req);
  9610. EXPECT_FALSE(res);
  9611. EXPECT_EQ(Error::Write, res.error());
  9612. }
  9613. auto handle =
  9614. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9615. EXPECT_FALSE(handle.is_valid());
  9616. EXPECT_EQ(Error::Write, handle.error);
  9617. // A valid request on the same client still goes through.
  9618. auto res = cli.Get("/");
  9619. ASSERT_TRUE(res);
  9620. EXPECT_EQ(StatusCode::OK_200, res->status);
  9621. }
  9622. EXPECT_EQ(1, request_count.load());
  9623. }
  9624. // Sends a raw request and verifies that there isn't a crash or exception.
  9625. static void test_raw_request(const std::string &req,
  9626. std::string *out = nullptr) {
  9627. Server svr;
  9628. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9629. res.set_content("ok", "text/plain");
  9630. });
  9631. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9632. res.set_content("ok", "text/plain");
  9633. });
  9634. svr.Get("/header_field_value_check",
  9635. [&](const Request & /*req*/, Response &res) {
  9636. res.set_content("ok", "text/plain");
  9637. });
  9638. svr.CustomRoute("PROPFIND", "/dav",
  9639. [&](const Request & /*req*/, Response &res) {
  9640. res.status = StatusCode::MultiStatus_207;
  9641. });
  9642. // Server read timeout must be longer than the client read timeout for the
  9643. // bug to reproduce, probably to force the server to process a request
  9644. // without a trailing blank line.
  9645. const time_t client_read_timeout_sec = 1;
  9646. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9647. bool listen_thread_ok = false;
  9648. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9649. auto se = detail::scope_exit([&] {
  9650. svr.stop();
  9651. t.join();
  9652. ASSERT_FALSE(svr.is_running());
  9653. EXPECT_TRUE(listen_thread_ok);
  9654. });
  9655. svr.wait_until_ready();
  9656. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9657. }
  9658. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9659. // A certain header line causes an exception if the header property is parsed
  9660. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9661. test_raw_request(
  9662. "GET /hi HTTP/1.1\r\n"
  9663. " : "
  9664. " "
  9665. " ");
  9666. }
  9667. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9668. // A certain header line causes an exception if the header property *name* is
  9669. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9670. // greedy matcher and requires backtracking when there are a lot of ":"
  9671. // characters.
  9672. // This occurs with libc++ but not libstdc++.
  9673. test_raw_request(
  9674. "GET /hi HTTP/1.1\r\n"
  9675. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9676. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9677. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9678. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9679. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9680. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9681. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9682. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9683. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9684. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9685. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9686. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9687. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9688. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9689. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9690. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9691. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9692. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9693. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9694. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9695. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9696. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9697. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9698. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9699. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9700. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9701. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9702. "&&&%%%");
  9703. }
  9704. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9705. // Make sure this doesn't crash the server.
  9706. // In a previous version of the header line regex, the "\r" rendered the line
  9707. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9708. // a new position where the leading white space ended and the field value
  9709. // began.
  9710. // The crash occurs with libc++ but not libstdc++.
  9711. test_raw_request("GET /hi HTTP/1.1\r\n"
  9712. "a:" +
  9713. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9714. "\r\n"
  9715. "\r\n");
  9716. }
  9717. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9718. const char *rejected[] = {
  9719. // RFC 9112 §3: one SP between the parts, and nothing else
  9720. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9721. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9722. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9723. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9724. // A request-target has no fragment
  9725. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9726. // An HTTP/1.1 request needs a Host
  9727. "GET /hi HTTP/1.1\r\n\r\n",
  9728. };
  9729. for (auto request : rejected) {
  9730. std::string out;
  9731. test_raw_request(request, &out);
  9732. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9733. }
  9734. std::string out;
  9735. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9736. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9737. }
  9738. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9739. // RFC 9112 §6.1
  9740. const char *requests[] = {
  9741. "PUT /put_hi HTTP/1.1\r\n"
  9742. "Host: localhost\r\n"
  9743. "Content-Length: 0\r\n"
  9744. "Transfer-Encoding: chunked\r\n"
  9745. "\r\n"
  9746. "0\r\n\r\n",
  9747. "PUT /put_hi HTTP/1.0\r\n"
  9748. "Connection: keep-alive\r\n"
  9749. "Transfer-Encoding: chunked\r\n"
  9750. "\r\n"
  9751. "0\r\n\r\n",
  9752. };
  9753. for (auto request : requests) {
  9754. std::string out;
  9755. test_raw_request(request, &out);
  9756. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9757. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9758. }
  9759. }
  9760. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9761. std::string out;
  9762. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9763. "Content-Type: text/plain\r\n"
  9764. "Transfer-Encoding: chunked\r\n"
  9765. "\r\n"
  9766. "nothex\r\n",
  9767. &out);
  9768. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9769. }
  9770. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9771. std::string out;
  9772. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9773. "Content-Type: text/plain\r\n"
  9774. "Transfer-Encoding: chunked\r\n"
  9775. "\r\n"
  9776. "3\r\n"
  9777. "xyz\r\n"
  9778. "NaN\r\n",
  9779. &out);
  9780. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9781. }
  9782. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9783. std::string out;
  9784. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9785. "Content-Type: text/plain\r\n"
  9786. "Transfer-Encoding: chunked\r\n"
  9787. "\r\n"
  9788. // Length is too large for 64 bits.
  9789. "1ffffffffffffffff\r\n"
  9790. "xyz\r\n",
  9791. &out);
  9792. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9793. }
  9794. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9795. test_raw_request("GET /hi HTTP/1.1\r\n"
  9796. "Content-Type: text/plain\r\n\r");
  9797. }
  9798. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9799. std::string out;
  9800. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9801. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9802. }
  9803. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9804. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9805. std::string out;
  9806. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9807. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9808. }
  9809. }
  9810. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9811. std::string out;
  9812. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9813. "Host: localhost\r\n"
  9814. "Connection: close\r\n\r\n",
  9815. &out);
  9816. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9817. }
  9818. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9819. Server svr;
  9820. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9821. EXPECT_TRUE(!req.remote_addr.empty());
  9822. });
  9823. thread t = thread([&] { svr.listen(HOST, PORT); });
  9824. auto se = detail::scope_exit([&] {
  9825. svr.stop();
  9826. t.join();
  9827. ASSERT_FALSE(svr.is_running());
  9828. });
  9829. svr.wait_until_ready();
  9830. // Send an invalid request line to trigger Bad Request
  9831. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9832. std::string out;
  9833. ASSERT_TRUE(send_request(5, bad_req, &out));
  9834. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9835. }
  9836. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9837. // answered right away rather than blocking on a read that waits for EOF.
  9838. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9839. std::string out;
  9840. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9841. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9842. }
  9843. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9844. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9845. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9846. for (const auto *method : methods) {
  9847. Server svr;
  9848. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9849. EXPECT_FALSE(svr.is_valid()) << method;
  9850. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9851. }
  9852. }
  9853. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9854. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9855. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9856. for (const auto *method : methods) {
  9857. Server svr;
  9858. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9859. EXPECT_FALSE(svr.is_valid()) << method;
  9860. }
  9861. }
  9862. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9863. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9864. "COPY", "MOVE", "LOCK",
  9865. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9866. Server svr;
  9867. for (const auto *method : methods) {
  9868. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9869. }
  9870. EXPECT_TRUE(svr.is_valid());
  9871. }
  9872. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9873. Server svr;
  9874. svr.CustomRoute("POST", "/x",
  9875. [](const Request &, Response &, const ContentReader &) {});
  9876. EXPECT_FALSE(svr.is_valid());
  9877. }
  9878. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9879. Server svr;
  9880. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9881. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9882. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9883. EXPECT_FALSE(svr.is_valid());
  9884. }
  9885. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9886. Server svr;
  9887. auto captured = Error::Success;
  9888. svr.set_error_logger(
  9889. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9890. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9891. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9892. }
  9893. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9894. std::string out;
  9895. std::string request(
  9896. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9897. test_raw_request(request, &out);
  9898. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9899. }
  9900. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9901. std::string out;
  9902. std::string request(
  9903. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9904. test_raw_request(request, &out);
  9905. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9906. }
  9907. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9908. std::string out;
  9909. std::string request(
  9910. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9911. test_raw_request(request, &out);
  9912. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9913. }
  9914. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9915. std::string out;
  9916. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9917. "Host: localhost\r\n"
  9918. "Test: \r\n\r\n",
  9919. &out);
  9920. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9921. }
  9922. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9923. Server svr;
  9924. std::string x_custom;
  9925. std::string cookie;
  9926. std::string xff;
  9927. std::string x_unicode;
  9928. std::string x_iis;
  9929. svr.Get("/check", [&](const Request &req, Response &res) {
  9930. x_custom = req.get_header_value("X-Custom");
  9931. cookie = req.get_header_value("Cookie");
  9932. xff = req.get_header_value("X-Forwarded-For");
  9933. x_unicode = req.get_header_value("X-Unicode");
  9934. x_iis = req.get_header_value("X-IIS");
  9935. res.set_content("ok", "text/plain");
  9936. });
  9937. thread t = thread([&] { svr.listen(HOST, PORT); });
  9938. auto se = detail::scope_exit([&] {
  9939. svr.stop();
  9940. t.join();
  9941. ASSERT_FALSE(svr.is_running());
  9942. });
  9943. svr.wait_until_ready();
  9944. const std::string req = "GET /check HTTP/1.1\r\n"
  9945. "Host: localhost\r\n"
  9946. "X-Custom: a%0D%0AInjected: b\r\n"
  9947. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9948. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9949. "X-Unicode: %E3%81%82\r\n"
  9950. "X-IIS: %u00E9\r\n"
  9951. "Connection: close\r\n"
  9952. "\r\n";
  9953. std::string res;
  9954. ASSERT_TRUE(send_request(5, req, &res));
  9955. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9956. // Every value must be returned verbatim (wire form), with no decoding.
  9957. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9958. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9959. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9960. EXPECT_EQ("%E3%81%82", x_unicode);
  9961. EXPECT_EQ("%u00E9", x_iis);
  9962. }
  9963. // Applications that previously relied on automatic percent-decoding can
  9964. // reproduce the old behavior by explicitly calling decode_path_component()
  9965. // or, for RFC 3986 conformance, decode_uri_component().
  9966. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9967. Server svr;
  9968. std::string decoded;
  9969. svr.Get("/check", [&](const Request &req, Response &res) {
  9970. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9971. res.set_content("ok", "text/plain");
  9972. });
  9973. thread t = thread([&] { svr.listen(HOST, PORT); });
  9974. auto se = detail::scope_exit([&] {
  9975. svr.stop();
  9976. t.join();
  9977. ASSERT_FALSE(svr.is_running());
  9978. });
  9979. svr.wait_until_ready();
  9980. const std::string req = "GET /check HTTP/1.1\r\n"
  9981. "Host: localhost\r\n"
  9982. "X-Custom: hello%20world\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. EXPECT_EQ("hello world", decoded);
  9989. }
  9990. // Regression test for #2033. Browsers send Referer values that include
  9991. // percent-encoded characters such as %0A inside the URL. Decoding the
  9992. // header value would either trip the post-decode CR/LF/NUL guard (the
  9993. // original bug, returning 400) or, after that guard was relaxed, silently
  9994. // store a literal LF — both unacceptable. The wire form must round-trip.
  9995. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9996. Server svr;
  9997. std::string referer;
  9998. svr.Get("/check", [&](const Request &req, Response &res) {
  9999. referer = req.get_header_value("Referer");
  10000. res.set_content("ok", "text/plain");
  10001. });
  10002. thread t = thread([&] { svr.listen(HOST, PORT); });
  10003. auto se = detail::scope_exit([&] {
  10004. svr.stop();
  10005. t.join();
  10006. ASSERT_FALSE(svr.is_running());
  10007. });
  10008. svr.wait_until_ready();
  10009. const std::string req = "GET /check HTTP/1.1\r\n"
  10010. "Host: localhost\r\n"
  10011. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10012. "Connection: close\r\n"
  10013. "\r\n";
  10014. std::string res;
  10015. ASSERT_TRUE(send_request(5, req, &res));
  10016. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10017. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10018. }
  10019. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10020. Server svr;
  10021. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10022. res.set_header("Cache-Control", "no-cache");
  10023. res.set_chunked_content_provider(
  10024. "text/event-stream", [](size_t offset, DataSink &sink) {
  10025. std::string s = "data:";
  10026. s += std::to_string(offset);
  10027. s += "\n\n";
  10028. auto ret = sink.write(s.data(), s.size());
  10029. EXPECT_TRUE(ret);
  10030. std::this_thread::sleep_for(std::chrono::seconds(1));
  10031. return true;
  10032. });
  10033. });
  10034. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10035. svr.wait_until_ready();
  10036. Client client(HOST, PORT);
  10037. const Headers headers = {{"Accept", "text/event-stream"}};
  10038. auto get_thread = std::thread([&client, &headers]() {
  10039. auto res = client.Get(
  10040. "/events", headers,
  10041. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10042. });
  10043. auto se = detail::scope_exit([&] {
  10044. svr.stop();
  10045. get_thread.join();
  10046. listen_thread.join();
  10047. ASSERT_FALSE(svr.is_running());
  10048. });
  10049. // Give GET time to get a few messages.
  10050. std::this_thread::sleep_for(std::chrono::seconds(2));
  10051. }
  10052. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10053. httplib::Server svr;
  10054. svr.Post("/hi",
  10055. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10056. res.status = StatusCode::OK_200;
  10057. });
  10058. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10059. svr.wait_until_ready();
  10060. Client cli(HOST, PORT);
  10061. auto res = cli.Post("/hi", "data", "text/plain");
  10062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10063. EXPECT_EQ(StatusCode::OK_200, res->status);
  10064. svr.stop();
  10065. thread.join();
  10066. ASSERT_FALSE(svr.is_running());
  10067. res = cli.Post("/hi", "data", "text/plain");
  10068. ASSERT_FALSE(res);
  10069. }
  10070. TEST(ServerStopTest, ListenFailure) {
  10071. Server svr;
  10072. auto t = thread([&]() {
  10073. auto ret = svr.listen("????", PORT);
  10074. EXPECT_FALSE(ret);
  10075. });
  10076. svr.wait_until_ready();
  10077. svr.stop();
  10078. t.join();
  10079. }
  10080. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10081. TEST(ServerStopTest, Decommision) {
  10082. Server svr;
  10083. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10084. for (int i = 0; i < 4; i++) {
  10085. auto is_even = !(i % 2);
  10086. std::thread t{[&] {
  10087. try {
  10088. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10089. if (is_even) {
  10090. throw std::runtime_error("Some thing that happens to go wrong.");
  10091. }
  10092. svr.listen(HOST, PORT);
  10093. } catch (...) { svr.decommission(); }
  10094. }};
  10095. svr.wait_until_ready();
  10096. // Server is up
  10097. {
  10098. Client cli(HOST, PORT);
  10099. auto res = cli.Get("/hi");
  10100. if (is_even) {
  10101. EXPECT_FALSE(res);
  10102. } else {
  10103. EXPECT_TRUE(res);
  10104. EXPECT_EQ("hi...", res->body);
  10105. }
  10106. }
  10107. svr.stop();
  10108. t.join();
  10109. // Server is down...
  10110. {
  10111. Client cli(HOST, PORT);
  10112. auto res = cli.Get("/hi");
  10113. EXPECT_FALSE(res);
  10114. }
  10115. }
  10116. }
  10117. #endif
  10118. // Helper function for string body upload progress tests
  10119. template <typename SetupHandler, typename ClientCall>
  10120. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10121. ClientCall &&client_call,
  10122. const string &body) {
  10123. Server svr;
  10124. setup_handler(svr);
  10125. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10126. auto se = detail::scope_exit([&] {
  10127. svr.stop();
  10128. t.join();
  10129. });
  10130. svr.wait_until_ready();
  10131. Client cli(HOST, PORT);
  10132. vector<uint64_t> progress_values;
  10133. bool progress_called = false;
  10134. auto res =
  10135. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10136. progress_values.push_back(current);
  10137. progress_called = true;
  10138. return true;
  10139. });
  10140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10141. EXPECT_EQ(200, res->status);
  10142. EXPECT_TRUE(progress_called);
  10143. }
  10144. TEST(UploadProgressTest, PostStringBodyBasic) {
  10145. TestStringBodyUploadProgress(
  10146. [](Server &svr) {
  10147. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10148. res.set_content("received", "text/plain");
  10149. });
  10150. },
  10151. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10152. return cli.Post("/test", body, "text/plain", progress_callback);
  10153. },
  10154. "test data for upload progress");
  10155. }
  10156. TEST(UploadProgressTest, PutStringBodyBasic) {
  10157. TestStringBodyUploadProgress(
  10158. [](Server &svr) {
  10159. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10160. res.set_content("put received", "text/plain");
  10161. });
  10162. },
  10163. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10164. return cli.Put("/test", body, "text/plain", progress_callback);
  10165. },
  10166. "put test data for upload progress");
  10167. }
  10168. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10169. TestStringBodyUploadProgress(
  10170. [](Server &svr) {
  10171. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10172. res.set_content("patch received", "text/plain");
  10173. });
  10174. },
  10175. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10176. return cli.Patch("/test", body, "text/plain", progress_callback);
  10177. },
  10178. "patch test data for upload progress");
  10179. }
  10180. // Helper function for content provider upload progress tests
  10181. template <typename SetupHandler, typename ClientCall>
  10182. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10183. ClientCall &&client_call) {
  10184. Server svr;
  10185. setup_handler(svr);
  10186. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10187. auto se = detail::scope_exit([&] {
  10188. svr.stop();
  10189. t.join();
  10190. });
  10191. svr.wait_until_ready();
  10192. Client cli(HOST, PORT);
  10193. vector<uint64_t> progress_values;
  10194. auto res =
  10195. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10196. progress_values.push_back(current);
  10197. return true;
  10198. });
  10199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10200. EXPECT_EQ(200, res->status);
  10201. EXPECT_FALSE(progress_values.empty());
  10202. }
  10203. TEST(UploadProgressTest, PostContentProviderProgress) {
  10204. TestContentProviderUploadProgress(
  10205. [](Server &svr) {
  10206. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10207. res.set_content("provider received", "text/plain");
  10208. });
  10209. },
  10210. [](Client &cli, UploadProgress progress_callback) {
  10211. return cli.Post(
  10212. "/test", 9,
  10213. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10214. sink.os << "test data";
  10215. return true;
  10216. },
  10217. "text/plain", progress_callback);
  10218. });
  10219. }
  10220. // Helper function for multipart upload progress tests
  10221. template <typename SetupHandler, typename ClientCall>
  10222. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10223. ClientCall &&client_call,
  10224. const string &endpoint) {
  10225. Server svr;
  10226. setup_handler(svr);
  10227. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10228. auto se = detail::scope_exit([&] {
  10229. svr.stop();
  10230. t.join();
  10231. });
  10232. svr.wait_until_ready();
  10233. Client cli(HOST, PORT);
  10234. vector<uint64_t> progress_values;
  10235. UploadFormDataItems items = {
  10236. {"field1", "value1", "", ""},
  10237. {"field2", "longer value for progress tracking test", "", ""},
  10238. {"file1", "file content data for upload progress", "test.txt",
  10239. "text/plain"}};
  10240. auto res = client_call(cli, endpoint, items,
  10241. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10242. progress_values.push_back(current);
  10243. return true;
  10244. });
  10245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10246. EXPECT_EQ(200, res->status);
  10247. EXPECT_FALSE(progress_values.empty());
  10248. }
  10249. TEST(UploadProgressTest, PostMultipartProgress) {
  10250. TestMultipartUploadProgress(
  10251. [](Server &svr) {
  10252. svr.Post("/multipart", [](const Request &req, Response &res) {
  10253. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10254. res.set_content("multipart received", "text/plain");
  10255. });
  10256. },
  10257. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10258. UploadProgress progress_callback) {
  10259. return cli.Post(endpoint, items, progress_callback);
  10260. },
  10261. "/multipart");
  10262. }
  10263. // Helper function for basic download progress tests
  10264. template <typename SetupHandler, typename ClientCall>
  10265. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10266. ClientCall &&client_call, const string &endpoint,
  10267. size_t expected_content_size) {
  10268. Server svr;
  10269. setup_handler(svr);
  10270. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10271. auto se = detail::scope_exit([&] {
  10272. svr.stop();
  10273. t.join();
  10274. });
  10275. svr.wait_until_ready();
  10276. Client cli(HOST, PORT);
  10277. vector<uint64_t> progress_values;
  10278. auto res = client_call(cli, endpoint,
  10279. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10280. progress_values.push_back(current);
  10281. return true;
  10282. });
  10283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10284. EXPECT_EQ(200, res->status);
  10285. EXPECT_FALSE(progress_values.empty());
  10286. EXPECT_EQ(expected_content_size, res->body.size());
  10287. }
  10288. TEST(DownloadProgressTest, GetBasic) {
  10289. TestBasicDownloadProgress(
  10290. [](Server &svr) {
  10291. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10292. string content(1000, 'D');
  10293. res.set_content(content, "text/plain");
  10294. });
  10295. },
  10296. [](Client &cli, const string &endpoint,
  10297. DownloadProgress progress_callback) {
  10298. return cli.Get(endpoint, progress_callback);
  10299. },
  10300. "/download", 1000u);
  10301. }
  10302. // Helper function for content receiver download progress tests
  10303. template <typename SetupHandler, typename ClientCall>
  10304. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10305. ClientCall &&client_call,
  10306. const string &endpoint,
  10307. size_t expected_content_size) {
  10308. Server svr;
  10309. setup_handler(svr);
  10310. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10311. auto se = detail::scope_exit([&] {
  10312. svr.stop();
  10313. t.join();
  10314. });
  10315. svr.wait_until_ready();
  10316. Client cli(HOST, PORT);
  10317. vector<uint64_t> progress_values;
  10318. string received_body;
  10319. auto res = client_call(
  10320. cli, endpoint,
  10321. [&](const char *data, size_t data_length) -> bool {
  10322. received_body.append(data, data_length);
  10323. return true;
  10324. },
  10325. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10326. progress_values.push_back(current);
  10327. return true;
  10328. });
  10329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10330. EXPECT_EQ(200, res->status);
  10331. EXPECT_FALSE(progress_values.empty());
  10332. EXPECT_EQ(expected_content_size, received_body.size());
  10333. EXPECT_TRUE(res->body.empty());
  10334. }
  10335. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10336. TestContentReceiverDownloadProgress(
  10337. [](Server &svr) {
  10338. svr.Get("/download-receiver",
  10339. [](const Request & /*req*/, Response &res) {
  10340. string content(2000, 'R');
  10341. res.set_content(content, "text/plain");
  10342. });
  10343. },
  10344. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10345. DownloadProgress progress_callback) {
  10346. return cli.Get(endpoint, content_receiver, progress_callback);
  10347. },
  10348. "/download-receiver", 2000u);
  10349. }
  10350. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10351. // A provider reaching a pass with nothing to hand over - an empty buffer
  10352. // popped off a queue, say - must not be taken to mean the body is finished.
  10353. // It used to end the loop with the terminating chunk unwritten while the
  10354. // server still considered the response complete, so the peer waited for an
  10355. // end that never arrived.
  10356. Server svr;
  10357. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10358. auto step = std::make_shared<int>(0);
  10359. res.set_chunked_content_provider("text/plain",
  10360. [step](size_t /*offset*/, DataSink &sink) {
  10361. switch ((*step)++) {
  10362. case 0: sink.write("", 0); break;
  10363. case 1: sink.write("hello", 5); break;
  10364. default: sink.done(); break;
  10365. }
  10366. return true;
  10367. });
  10368. });
  10369. auto port = svr.bind_to_any_port(HOST);
  10370. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10371. auto listen_se = detail::scope_exit([&] {
  10372. svr.stop();
  10373. listen_thread.join();
  10374. ASSERT_FALSE(svr.is_running());
  10375. });
  10376. svr.wait_until_ready();
  10377. Client cli(HOST, port);
  10378. // Without the fix the body is never terminated, so bound the wait rather
  10379. // than letting the test hang on the default read timeout.
  10380. cli.set_read_timeout(5, 0);
  10381. auto res = cli.Get("/stream");
  10382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10383. EXPECT_EQ(StatusCode::OK_200, res->status);
  10384. EXPECT_EQ("hello", res->body);
  10385. }
  10386. TEST(StreamingTest, NoContentLengthStreaming) {
  10387. Server svr;
  10388. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10389. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10390. if (offset < 6) {
  10391. sink.os << (offset < 3 ? "a" : "b");
  10392. } else {
  10393. sink.done();
  10394. }
  10395. return true;
  10396. });
  10397. });
  10398. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10399. auto listen_se = detail::scope_exit([&] {
  10400. svr.stop();
  10401. listen_thread.join();
  10402. ASSERT_FALSE(svr.is_running());
  10403. });
  10404. svr.wait_until_ready();
  10405. Client client(HOST, PORT);
  10406. auto get_thread = std::thread([&client]() {
  10407. std::string s;
  10408. auto res =
  10409. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10410. s += std::string(data, len);
  10411. return true;
  10412. });
  10413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10414. EXPECT_EQ(StatusCode::OK_200, res->status);
  10415. EXPECT_EQ("aaabbb", s);
  10416. });
  10417. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10418. // Give GET time to get a few messages.
  10419. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10420. }
  10421. TEST(MountTest, Unmount) {
  10422. Server svr;
  10423. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10424. auto se = detail::scope_exit([&] {
  10425. svr.stop();
  10426. listen_thread.join();
  10427. ASSERT_FALSE(svr.is_running());
  10428. });
  10429. svr.wait_until_ready();
  10430. Client cli("localhost", PORT);
  10431. svr.set_mount_point("/mount2", "./www2");
  10432. auto res = cli.Get("/");
  10433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10434. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10435. res = cli.Get("/mount2/dir/test.html");
  10436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10437. EXPECT_EQ(StatusCode::OK_200, res->status);
  10438. svr.set_mount_point("/", "./www");
  10439. res = cli.Get("/dir/");
  10440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10441. EXPECT_EQ(StatusCode::OK_200, res->status);
  10442. svr.remove_mount_point("/");
  10443. res = cli.Get("/dir/");
  10444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10446. svr.remove_mount_point("/mount2");
  10447. res = cli.Get("/mount2/dir/test.html");
  10448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10450. }
  10451. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10452. Server svr;
  10453. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10454. svr.Get("/api/hello", [](const Request &, Response &res) {
  10455. res.set_content("api", "text/plain");
  10456. });
  10457. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10458. auto se = detail::scope_exit([&] {
  10459. svr.stop();
  10460. listen_thread.join();
  10461. ASSERT_FALSE(svr.is_running());
  10462. });
  10463. svr.wait_until_ready();
  10464. Client cli(HOST, PORT);
  10465. auto res = cli.Get("/dir/test.html");
  10466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10467. EXPECT_EQ(StatusCode::OK_200, res->status);
  10468. res = cli.Get("/api/hello");
  10469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10470. EXPECT_EQ(StatusCode::OK_200, res->status);
  10471. EXPECT_EQ("api", res->body);
  10472. }
  10473. TEST(MountTest, PathSegmentBoundary) {
  10474. Server svr;
  10475. svr.set_mount_point("/mount2", "./www2");
  10476. svr.set_mount_point("/", "./www");
  10477. auto port = svr.bind_to_any_port(HOST);
  10478. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10479. auto se = detail::scope_exit([&] {
  10480. svr.stop();
  10481. listen_thread.join();
  10482. ASSERT_FALSE(svr.is_running());
  10483. });
  10484. svr.wait_until_ready();
  10485. Client cli(HOST, port);
  10486. auto res = cli.Get("/mount2/dir/test.html");
  10487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10488. EXPECT_EQ(StatusCode::OK_200, res->status);
  10489. // "/mount2" must not match part-way through a path segment.
  10490. res = cli.Get("/mount2dir/test.html");
  10491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10492. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10493. // A mount point ending in '/' keeps matching every path below it.
  10494. res = cli.Get("/dir/test.html");
  10495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10496. EXPECT_EQ(StatusCode::OK_200, res->status);
  10497. }
  10498. TEST(MountTest, Redicect) {
  10499. Server svr;
  10500. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10501. auto se = detail::scope_exit([&] {
  10502. svr.stop();
  10503. listen_thread.join();
  10504. ASSERT_FALSE(svr.is_running());
  10505. });
  10506. svr.set_mount_point("/", "./www");
  10507. svr.wait_until_ready();
  10508. Client cli("localhost", PORT);
  10509. auto res = cli.Get("/dir/");
  10510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10511. EXPECT_EQ(StatusCode::OK_200, res->status);
  10512. res = cli.Get("/dir");
  10513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10514. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10515. res = cli.Get("/file");
  10516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10517. EXPECT_EQ(StatusCode::OK_200, res->status);
  10518. res = cli.Get("/file/");
  10519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10520. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10521. cli.set_follow_location(true);
  10522. res = cli.Get("/dir");
  10523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10524. EXPECT_EQ(StatusCode::OK_200, res->status);
  10525. }
  10526. TEST(MountTest, MultibytesPathName) {
  10527. Server svr;
  10528. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10529. auto se = detail::scope_exit([&] {
  10530. svr.stop();
  10531. listen_thread.join();
  10532. ASSERT_FALSE(svr.is_running());
  10533. });
  10534. svr.set_mount_point("/", "./www");
  10535. svr.wait_until_ready();
  10536. Client cli("localhost", PORT);
  10537. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10539. EXPECT_EQ(StatusCode::OK_200, res->status);
  10540. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10541. }
  10542. #ifdef _WIN32
  10543. // Issue #2435: mmap::open() must succeed even when another handle holds
  10544. // the file open for writing (e.g. an active log file).
  10545. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10546. const char *path = "mmap_concurrent_writer_test.txt";
  10547. const char *content = "hello";
  10548. {
  10549. std::ofstream f(path, std::ios::binary);
  10550. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10551. }
  10552. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10553. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10554. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10555. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10556. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10557. detail::mmap m(path);
  10558. ASSERT_TRUE(m.is_open());
  10559. EXPECT_EQ(strlen(content), m.size());
  10560. char buf[8];
  10561. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10562. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10563. }
  10564. #endif
  10565. #ifndef _WIN32
  10566. // A directory or a device has no size to serve.
  10567. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10568. const char *path = "./mmap_not_regular_test_dir";
  10569. ASSERT_EQ(0, ::mkdir(path, 0755));
  10570. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10571. for (auto p : {path, "/dev/null"}) {
  10572. detail::mmap m(p);
  10573. EXPECT_FALSE(m.is_open()) << p;
  10574. EXPECT_EQ(0U, m.size()) << p;
  10575. }
  10576. Server svr;
  10577. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10578. res.set_file_content("/dev/null");
  10579. });
  10580. auto port = svr.bind_to_any_port(HOST);
  10581. thread t = thread([&] { svr.listen_after_bind(); });
  10582. auto se = detail::scope_exit([&] {
  10583. svr.stop();
  10584. t.join();
  10585. });
  10586. svr.wait_until_ready();
  10587. auto res = Client(HOST, port).Get("/null");
  10588. ASSERT_TRUE(res);
  10589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10590. }
  10591. #endif
  10592. #ifdef __linux__
  10593. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10594. TEST(MmapTest, FileIsNotMapped) {
  10595. const char *path = "mmap_not_mapped_test.txt";
  10596. {
  10597. std::ofstream f(path, std::ios::binary);
  10598. f << "hello";
  10599. }
  10600. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10601. detail::mmap m(path);
  10602. ASSERT_TRUE(m.is_open());
  10603. std::ifstream maps("/proc/self/maps");
  10604. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10605. std::istreambuf_iterator<char>());
  10606. EXPECT_EQ(std::string::npos, mappings.find(path));
  10607. }
  10608. #endif
  10609. TEST(KeepAliveTest, ReadTimeout) {
  10610. Server svr;
  10611. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10612. std::this_thread::sleep_for(std::chrono::seconds(2));
  10613. res.set_content("a", "text/plain");
  10614. });
  10615. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10616. res.set_content("b", "text/plain");
  10617. });
  10618. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10619. auto se = detail::scope_exit([&] {
  10620. svr.stop();
  10621. listen_thread.join();
  10622. ASSERT_FALSE(svr.is_running());
  10623. });
  10624. svr.wait_until_ready();
  10625. Client cli("localhost", PORT);
  10626. cli.set_keep_alive(true);
  10627. cli.set_read_timeout(std::chrono::seconds(1));
  10628. auto resa = cli.Get("/a");
  10629. ASSERT_FALSE(resa);
  10630. EXPECT_EQ(Error::Read, resa.error());
  10631. auto resb = cli.Get("/b");
  10632. ASSERT_TRUE(resb);
  10633. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10634. EXPECT_EQ("b", resb->body);
  10635. }
  10636. TEST(KeepAliveTest, MaxCount) {
  10637. size_t keep_alive_max_count = 3;
  10638. Server svr;
  10639. svr.set_keep_alive_max_count(keep_alive_max_count);
  10640. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10641. res.set_content("Hello World!", "text/plain");
  10642. });
  10643. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10644. auto se = detail::scope_exit([&] {
  10645. svr.stop();
  10646. listen_thread.join();
  10647. ASSERT_FALSE(svr.is_running());
  10648. });
  10649. svr.wait_until_ready();
  10650. Client cli(HOST, PORT);
  10651. cli.set_keep_alive(true);
  10652. for (size_t i = 0; i < 5; i++) {
  10653. auto result = cli.Get("/hi");
  10654. ASSERT_TRUE(result);
  10655. EXPECT_EQ(StatusCode::OK_200, result->status);
  10656. if (i == keep_alive_max_count - 1) {
  10657. EXPECT_EQ("close", result->get_header_value("Connection"));
  10658. } else {
  10659. EXPECT_FALSE(result->has_header("Connection"));
  10660. }
  10661. }
  10662. }
  10663. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10664. // can pull the next one into the server's buffer. The server must serve it
  10665. // without waiting for the socket to become readable again. The keep-alive
  10666. // timeout outlasts the client's read timeout, so a request left waiting for it
  10667. // shows up as a missing response.
  10668. static void serve_pipelining_routes(Server &svr,
  10669. const std::function<void(int)> &client) {
  10670. svr.set_keep_alive_timeout(5);
  10671. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10672. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10673. });
  10674. svr.Post("/echo", [](const Request &req, Response &res) {
  10675. res.set_content("echo " + req.body, "text/plain");
  10676. });
  10677. auto port = svr.bind_to_any_port(HOST);
  10678. thread t = thread([&] { svr.listen_after_bind(); });
  10679. auto se = detail::scope_exit([&] {
  10680. svr.stop();
  10681. t.join();
  10682. });
  10683. svr.wait_until_ready();
  10684. client(port);
  10685. }
  10686. static std::string
  10687. send_pipelined_requests(const std::vector<std::string> &parts) {
  10688. Server svr;
  10689. std::string res;
  10690. serve_pipelining_routes(svr, [&](int port) {
  10691. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10692. });
  10693. return res;
  10694. }
  10695. static void expect_in_order(const std::string &res,
  10696. const std::vector<std::string> &bodies) {
  10697. size_t pos = 0;
  10698. for (const auto &body : bodies) {
  10699. pos = res.find(body, pos);
  10700. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10701. pos += body.size();
  10702. }
  10703. }
  10704. TEST(KeepAliveTest, PipelinedRequests) {
  10705. auto res = send_pipelined_requests(
  10706. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10707. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10708. "Content-Length: 4\r\n\r\nbody"
  10709. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10710. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10711. }
  10712. // The second request starts in the server's buffer and ends on the socket.
  10713. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10714. auto res =
  10715. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10716. "GET /hi/2 HTTP/1.1\r\nHo",
  10717. "st: localhost\r\nConnection: close\r\n\r\n"});
  10718. expect_in_order(res, {"hi 1", "hi 2"});
  10719. }
  10720. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10721. // CRLF after a body does not turn into a 400 for the next request.
  10722. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10723. auto res = send_pipelined_requests(
  10724. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10725. "Content-Length: 4\r\n\r\nbody\r\n"
  10726. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10727. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10728. expect_in_order(res, {"echo body", "hi 2"});
  10729. }
  10730. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10731. // must not be served as the next request.
  10732. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10733. auto res = send_pipelined_requests(
  10734. {"INVALID REQUEST LINE\r\n\r\n"
  10735. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10736. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10737. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10738. }
  10739. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10740. // Over TLS, the next request is held by the TLS library as already decrypted
  10741. // data rather than on the socket.
  10742. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10743. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10744. std::string res;
  10745. serve_pipelining_routes(svr, [&](int port) {
  10746. // One part, so all three requests arrive in one TLS record
  10747. EXPECT_TRUE(send_ssl_request_in_parts(
  10748. 2,
  10749. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10750. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10751. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10752. &res, port));
  10753. });
  10754. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10755. }
  10756. #endif
  10757. TEST(KeepAliveTest, Issue1041) {
  10758. Server svr;
  10759. svr.set_keep_alive_timeout(3);
  10760. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10761. res.set_content("Hello World!", "text/plain");
  10762. });
  10763. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10764. auto se = detail::scope_exit([&] {
  10765. svr.stop();
  10766. listen_thread.join();
  10767. ASSERT_FALSE(svr.is_running());
  10768. });
  10769. svr.wait_until_ready();
  10770. Client cli(HOST, PORT);
  10771. cli.set_keep_alive(true);
  10772. auto result = cli.Get("/hi");
  10773. ASSERT_TRUE(result);
  10774. EXPECT_EQ(StatusCode::OK_200, result->status);
  10775. std::this_thread::sleep_for(std::chrono::seconds(5));
  10776. result = cli.Get("/hi");
  10777. ASSERT_TRUE(result);
  10778. EXPECT_EQ(StatusCode::OK_200, result->status);
  10779. }
  10780. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10781. Server svr;
  10782. svr.set_keep_alive_max_count(0);
  10783. std::set<int> remote_ports;
  10784. svr.Get("/hi", [&](const Request &req, Response &res) {
  10785. remote_ports.insert(req.remote_port);
  10786. res.set_content("hi", "text/plain");
  10787. });
  10788. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10789. auto se = detail::scope_exit([&] {
  10790. svr.stop();
  10791. listen_thread.join();
  10792. ASSERT_FALSE(svr.is_running());
  10793. });
  10794. svr.wait_until_ready();
  10795. Client cli(HOST, PORT);
  10796. cli.set_keep_alive(true);
  10797. for (int i = 0; i < 3; i++) {
  10798. auto res = cli.Get("/hi");
  10799. ASSERT_TRUE(res);
  10800. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10801. }
  10802. // All three over one connection
  10803. EXPECT_EQ(1u, remote_ports.size());
  10804. }
  10805. TEST(KeepAliveTest, Issue1959) {
  10806. Server svr;
  10807. svr.set_keep_alive_timeout(5);
  10808. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10809. res.set_content("a", "text/plain");
  10810. });
  10811. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10812. auto se = detail::scope_exit([&] {
  10813. if (!svr.is_running()) return;
  10814. svr.stop();
  10815. listen_thread.join();
  10816. ASSERT_FALSE(svr.is_running());
  10817. });
  10818. svr.wait_until_ready();
  10819. Client cli("localhost", PORT);
  10820. cli.set_keep_alive(true);
  10821. using namespace std::chrono;
  10822. auto start = steady_clock::now();
  10823. cli.Get("/a");
  10824. svr.stop();
  10825. listen_thread.join();
  10826. auto end = steady_clock::now();
  10827. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10828. EXPECT_LT(elapsed, 5000);
  10829. }
  10830. #ifdef CPPHTTPLIB_SSL_ENABLED
  10831. TEST(KeepAliveTest, SSLClientReconnection) {
  10832. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10833. ASSERT_TRUE(svr.is_valid());
  10834. svr.set_keep_alive_timeout(1);
  10835. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10836. res.set_content("Hello World!", "text/plain");
  10837. });
  10838. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10839. auto se = detail::scope_exit([&] {
  10840. svr.stop();
  10841. listen_thread.join();
  10842. ASSERT_FALSE(svr.is_running());
  10843. });
  10844. svr.wait_until_ready();
  10845. SSLClient cli(HOST, PORT);
  10846. cli.enable_server_certificate_verification(false);
  10847. cli.set_keep_alive(true);
  10848. auto result = cli.Get("/hi");
  10849. ASSERT_TRUE(result);
  10850. EXPECT_EQ(StatusCode::OK_200, result->status);
  10851. result = cli.Get("/hi");
  10852. ASSERT_TRUE(result);
  10853. EXPECT_EQ(StatusCode::OK_200, result->status);
  10854. std::this_thread::sleep_for(std::chrono::seconds(2));
  10855. // Recoonect
  10856. result = cli.Get("/hi");
  10857. ASSERT_TRUE(result);
  10858. EXPECT_EQ(StatusCode::OK_200, result->status);
  10859. result = cli.Get("/hi");
  10860. ASSERT_TRUE(result);
  10861. EXPECT_EQ(StatusCode::OK_200, result->status);
  10862. }
  10863. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10865. ASSERT_TRUE(svr.is_valid());
  10866. svr.set_keep_alive_timeout(1);
  10867. std::string content = "reconnect";
  10868. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10869. res.set_content("Hello World!", "text/plain");
  10870. });
  10871. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10872. auto se = detail::scope_exit([&] {
  10873. svr.stop();
  10874. listen_thread.join();
  10875. ASSERT_FALSE(svr.is_running());
  10876. });
  10877. svr.wait_until_ready();
  10878. SSLClient cli(HOST, PORT);
  10879. cli.enable_server_certificate_verification(false);
  10880. cli.set_keep_alive(true);
  10881. auto result = cli.Post(
  10882. "/hi", content.size(),
  10883. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10884. sink.write(content.c_str(), content.size());
  10885. return true;
  10886. },
  10887. "text/plain");
  10888. ASSERT_TRUE(result);
  10889. EXPECT_EQ(200, result->status);
  10890. std::this_thread::sleep_for(std::chrono::seconds(2));
  10891. // Recoonect
  10892. result = cli.Post(
  10893. "/hi", content.size(),
  10894. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10895. sink.write(content.c_str(), content.size());
  10896. return true;
  10897. },
  10898. "text/plain");
  10899. ASSERT_TRUE(result);
  10900. EXPECT_EQ(200, result->status);
  10901. result = cli.Post(
  10902. "/hi", content.size(),
  10903. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10904. sink.write(content.c_str(), content.size());
  10905. return true;
  10906. },
  10907. "text/plain");
  10908. ASSERT_TRUE(result);
  10909. EXPECT_EQ(200, result->status);
  10910. }
  10911. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10912. using namespace httplib::tls;
  10913. {
  10914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10915. ASSERT_TRUE(svr.is_valid());
  10916. svr.Get("/sni", [&](const Request &req, Response &res) {
  10917. std::string expected = req.sni();
  10918. EXPECT_EQ(expected, req.get_param_value("expected"));
  10919. res.set_content("ok", "text/plain");
  10920. });
  10921. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10922. auto se = detail::scope_exit([&] {
  10923. svr.stop();
  10924. listen_thread.join();
  10925. ASSERT_FALSE(svr.is_running());
  10926. });
  10927. svr.wait_until_ready();
  10928. {
  10929. SSLClient cli("localhost", PORT);
  10930. cli.enable_server_certificate_verification(false);
  10931. auto res = cli.Get("/sni?expected=localhost");
  10932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10933. }
  10934. {
  10935. SSLClient cli("::1", PORT);
  10936. cli.enable_server_certificate_verification(false);
  10937. auto res = cli.Get("/sni?expected=");
  10938. // NOTE: This may fail if the server is listening on IPv4 only
  10939. // (e.g., when localhost resolves to 127.0.0.1 only)
  10940. if (res) {
  10941. EXPECT_EQ(StatusCode::OK_200, res->status);
  10942. } else {
  10943. EXPECT_EQ(Error::Connection, res.error());
  10944. }
  10945. }
  10946. }
  10947. }
  10948. #endif
  10949. TEST(ClientProblemDetectionTest, ContentProvider) {
  10950. Server svr;
  10951. size_t content_length = 1024 * 1024;
  10952. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10953. res.set_content_provider(
  10954. content_length, "text/plain",
  10955. [&](size_t offset, size_t length, DataSink &sink) {
  10956. auto out_len = std::min(length, static_cast<size_t>(1024));
  10957. std::string out(out_len, '@');
  10958. sink.write(out.data(), out_len);
  10959. return offset < 4096;
  10960. },
  10961. [](bool success) { ASSERT_FALSE(success); });
  10962. });
  10963. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10964. res.set_content_provider(
  10965. 0, "text/plain",
  10966. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10967. EXPECT_TRUE(false);
  10968. return true;
  10969. },
  10970. [](bool success) { ASSERT_FALSE(success); });
  10971. });
  10972. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10973. auto se = detail::scope_exit([&] {
  10974. svr.stop();
  10975. listen_thread.join();
  10976. ASSERT_FALSE(svr.is_running());
  10977. });
  10978. svr.wait_until_ready();
  10979. Client cli("localhost", PORT);
  10980. {
  10981. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10982. size_t /*data_length*/) { return false; });
  10983. ASSERT_FALSE(res);
  10984. }
  10985. {
  10986. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10987. size_t /*data_length*/) { return false; });
  10988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10989. }
  10990. }
  10991. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10992. // A provider that reports success without writing anything and without
  10993. // calling done() used to be handed the same offset and length again on every
  10994. // pass, so it spun for as long as the peer stayed connected.
  10995. Server svr;
  10996. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10997. res.set_content("ok", "text/plain");
  10998. });
  10999. auto port = svr.bind_to_any_port(HOST);
  11000. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11001. auto se = detail::scope_exit([&] {
  11002. svr.stop();
  11003. listen_thread.join();
  11004. ASSERT_FALSE(svr.is_running());
  11005. });
  11006. svr.wait_until_ready();
  11007. std::atomic<int> call_count{0};
  11008. Client cli(HOST, port);
  11009. auto res = cli.Post(
  11010. "/", 1024,
  11011. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11012. // Give up after enough passes to show the spin, so that losing the
  11013. // check below fails this test instead of hanging it.
  11014. return ++call_count < 100;
  11015. },
  11016. "text/plain");
  11017. ASSERT_FALSE(res);
  11018. EXPECT_EQ(Error::Write, res.error());
  11019. EXPECT_EQ(1, call_count.load());
  11020. }
  11021. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11022. // A writer only has to assign `write`. The other three used to be left as
  11023. // empty std::functions, so a provider calling one threw
  11024. // std::bad_function_call out of the thread running it and took the whole
  11025. // process down.
  11026. DataSink sink;
  11027. std::string written;
  11028. sink.write = [&](const char *data, size_t data_len) {
  11029. written.append(data, data_len);
  11030. return true;
  11031. };
  11032. EXPECT_TRUE(sink.is_writable());
  11033. sink.done();
  11034. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11035. EXPECT_TRUE(written.empty());
  11036. }
  11037. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11038. // A sink that cannot carry trailers still has to finish.
  11039. DataSink sink;
  11040. auto done_count = 0;
  11041. sink.done = [&]() { done_count++; };
  11042. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11043. EXPECT_EQ(1, done_count);
  11044. }
  11045. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11046. Server svr;
  11047. const std::string body(4096, 'x');
  11048. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11049. res.set_content_provider(body.size(), "text/plain",
  11050. [&](size_t offset, size_t length, DataSink &sink) {
  11051. sink.write(body.data() + offset, length);
  11052. sink.done();
  11053. return true;
  11054. });
  11055. });
  11056. auto port = svr.bind_to_any_port(HOST);
  11057. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11058. auto se = detail::scope_exit([&] {
  11059. svr.stop();
  11060. listen_thread.join();
  11061. ASSERT_FALSE(svr.is_running());
  11062. });
  11063. svr.wait_until_ready();
  11064. Client cli(HOST, port);
  11065. auto res = cli.Get("/");
  11066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11067. EXPECT_EQ(StatusCode::OK_200, res->status);
  11068. EXPECT_EQ(body, res->body);
  11069. }
  11070. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11071. Server svr;
  11072. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11073. res.set_content_provider(
  11074. 1024, "text/plain",
  11075. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11076. sink.write("hello", 5);
  11077. sink.done(); // short of the 1024 bytes the response promised
  11078. return true;
  11079. });
  11080. });
  11081. auto port = svr.bind_to_any_port(HOST);
  11082. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11083. auto se = detail::scope_exit([&] {
  11084. svr.stop();
  11085. listen_thread.join();
  11086. ASSERT_FALSE(svr.is_running());
  11087. });
  11088. svr.wait_until_ready();
  11089. Client cli(HOST, port);
  11090. cli.set_read_timeout(5, 0);
  11091. // The response is short of its Content-Length, so the client cannot read a
  11092. // complete body. What matters is that this returns at all: a no-op done()
  11093. // would leave the writer looping over a provider that never makes progress.
  11094. auto res = cli.Get("/");
  11095. EXPECT_FALSE(res);
  11096. }
  11097. // Read as the next response by a peer that sees it after a framed body.
  11098. static const std::string smuggled_response =
  11099. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11100. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11101. Server svr;
  11102. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11103. res.set_content_provider(
  11104. 5, "text/plain",
  11105. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11106. auto data = "AAAAA" + smuggled_response;
  11107. sink.write(data.data(), data.size());
  11108. return true;
  11109. });
  11110. });
  11111. thread t = thread([&] { svr.listen(HOST, PORT); });
  11112. auto se = detail::scope_exit([&] {
  11113. svr.stop();
  11114. t.join();
  11115. ASSERT_FALSE(svr.is_running());
  11116. });
  11117. svr.wait_until_ready();
  11118. std::string resp;
  11119. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11120. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11121. resp.clear();
  11122. ASSERT_TRUE(send_request(
  11123. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11124. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11125. }
  11126. TEST(NoContentTest, BodyIsNotSent) {
  11127. Server svr;
  11128. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11129. res.status = StatusCode::NoContent_204;
  11130. res.set_content(smuggled_response, "text/plain");
  11131. });
  11132. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11133. res.status = StatusCode::NotModified_304;
  11134. res.set_chunked_content_provider(
  11135. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11136. sink.write(smuggled_response.data(), smuggled_response.size());
  11137. sink.done();
  11138. return true;
  11139. });
  11140. });
  11141. thread t = thread([&] { svr.listen(HOST, PORT); });
  11142. auto se = detail::scope_exit([&] {
  11143. svr.stop();
  11144. t.join();
  11145. ASSERT_FALSE(svr.is_running());
  11146. });
  11147. svr.wait_until_ready();
  11148. for (auto path : {"/204", "/304"}) {
  11149. std::string resp;
  11150. ASSERT_TRUE(send_request(
  11151. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11152. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11153. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11154. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11155. }
  11156. }
  11157. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11158. Server svr;
  11159. std::atomic<bool> smuggled(false);
  11160. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11161. res.set_content("ok", "text/plain");
  11162. });
  11163. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11164. smuggled = true;
  11165. });
  11166. auto port = svr.bind_to_any_port(HOST);
  11167. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11168. auto se = detail::scope_exit([&] {
  11169. svr.stop();
  11170. listen_thread.join();
  11171. ASSERT_FALSE(svr.is_running());
  11172. });
  11173. svr.wait_until_ready();
  11174. // What follows the body would be read as the next request.
  11175. Client cli(HOST, port);
  11176. auto res = cli.Post(
  11177. "/", 5,
  11178. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11179. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11180. sink.write(data.data(), data.size());
  11181. return true;
  11182. },
  11183. "text/plain");
  11184. ASSERT_FALSE(res);
  11185. EXPECT_EQ(Error::Write, res.error());
  11186. EXPECT_FALSE(smuggled);
  11187. }
  11188. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11189. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11190. // The compressed path builds the whole body before connecting, so this
  11191. // fails client-side and never reaches a server.
  11192. Client cli(HOST, PORT);
  11193. cli.set_compress(true);
  11194. auto res = cli.Post(
  11195. "/", 1024,
  11196. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11197. sink.write("hello", 5);
  11198. sink.done(); // short of the 1024 bytes the request announced
  11199. return true;
  11200. },
  11201. "text/plain");
  11202. ASSERT_FALSE(res);
  11203. EXPECT_EQ(Error::Write, res.error());
  11204. }
  11205. #endif
  11206. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11207. Server svr;
  11208. svr.set_error_handler([](Request const &, Response &res) -> void {
  11209. res.set_chunked_content_provider(
  11210. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11211. sink.os << "hello";
  11212. sink.os << "world";
  11213. sink.done();
  11214. return true;
  11215. });
  11216. });
  11217. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11218. auto se = detail::scope_exit([&] {
  11219. svr.stop();
  11220. listen_thread.join();
  11221. ASSERT_FALSE(svr.is_running());
  11222. });
  11223. svr.wait_until_ready();
  11224. Client cli("localhost", PORT);
  11225. auto res = cli.Get("/");
  11226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11227. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11228. EXPECT_EQ("helloworld", res->body);
  11229. }
  11230. // A body set after a content provider must replace it, not be sent through it.
  11231. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11232. Server svr;
  11233. svr.set_mount_point("/", "./www");
  11234. svr.set_file_request_handler([](const Request &req, Response &res) {
  11235. if (req.path == "/dir/test.html") {
  11236. res.status = StatusCode::Forbidden_403;
  11237. res.set_content(std::string(5000, 'D'), "text/plain");
  11238. } else if (req.path == "/file") {
  11239. res.status = StatusCode::Forbidden_403;
  11240. res.body = "Denied";
  11241. }
  11242. });
  11243. auto port = svr.bind_to_any_port(HOST);
  11244. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11245. auto se = detail::scope_exit([&] {
  11246. svr.stop();
  11247. t.join();
  11248. ASSERT_FALSE(svr.is_running());
  11249. });
  11250. svr.wait_until_ready();
  11251. Client cli(HOST, port);
  11252. {
  11253. auto res = cli.Get("/dir/test.html");
  11254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11255. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11256. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11257. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11258. }
  11259. {
  11260. auto res = cli.Get("/file");
  11261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11262. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11263. EXPECT_EQ("Denied", res->body);
  11264. }
  11265. {
  11266. auto res = cli.Get("/dir/index.html");
  11267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11268. EXPECT_EQ(StatusCode::OK_200, res->status);
  11269. EXPECT_EQ(0U, res->body.find("<html>"));
  11270. }
  11271. }
  11272. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11273. Server svr;
  11274. std::vector<bool> released;
  11275. std::mutex released_mutex;
  11276. auto releaser = [&](bool success) {
  11277. std::lock_guard<std::mutex> guard(released_mutex);
  11278. released.push_back(success);
  11279. };
  11280. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11281. return sink.write(&"hello"[offset], length);
  11282. };
  11283. svr.Get("/sized", [&](const Request &, Response &res) {
  11284. res.status = StatusCode::NotFound_404;
  11285. res.set_content_provider(5, "text/plain", provider, releaser);
  11286. });
  11287. svr.Get("/chunked", [&](const Request &, Response &res) {
  11288. res.status = StatusCode::ServiceUnavailable_503;
  11289. res.set_chunked_content_provider(
  11290. "text/plain",
  11291. [](size_t, DataSink &sink) {
  11292. sink.os << "chunk";
  11293. sink.done();
  11294. return true;
  11295. },
  11296. releaser);
  11297. });
  11298. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11299. res.set_content_provider(5, "text/plain", provider, releaser);
  11300. throw std::runtime_error("after the provider");
  11301. });
  11302. svr.set_error_handler([](const Request &req, Response &res) {
  11303. // Leave the exception handler's content to it.
  11304. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11305. res.set_content(std::string(1000, 'E'), "text/html");
  11306. return Server::HandlerResponse::Handled;
  11307. });
  11308. svr.set_exception_handler(
  11309. [](const Request &, Response &res, std::exception_ptr) {
  11310. res.status = StatusCode::InternalServerError_500;
  11311. res.set_content(std::string(1000, 'X'), "text/html");
  11312. });
  11313. auto port = svr.bind_to_any_port(HOST);
  11314. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11315. auto se = detail::scope_exit([&] {
  11316. svr.stop();
  11317. t.join();
  11318. ASSERT_FALSE(svr.is_running());
  11319. });
  11320. svr.wait_until_ready();
  11321. Client cli(HOST, port);
  11322. {
  11323. auto res = cli.Get("/sized");
  11324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11326. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11327. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11328. }
  11329. {
  11330. auto res = cli.Get("/chunked");
  11331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11332. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11333. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11334. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11335. }
  11336. {
  11337. auto res = cli.Get("/throw");
  11338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11339. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11340. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11341. }
  11342. std::lock_guard<std::mutex> guard(released_mutex);
  11343. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11344. }
  11345. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11346. Server svr;
  11347. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11348. return sink.write(&"abc"[offset], length);
  11349. };
  11350. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11351. res.set_file_content("./www/dir/test.html");
  11352. res.set_content("body", "text/plain");
  11353. });
  11354. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11355. res.set_content(std::string(100, 'B'), "text/plain");
  11356. res.set_file_content("./www/dir/test.html");
  11357. });
  11358. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11359. res.set_content(std::string(100, 'B'), "text/plain");
  11360. res.set_content_provider(3, "text/plain", abc);
  11361. });
  11362. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11363. res.set_content_provider(3, "text/plain", abc);
  11364. res.set_content(std::string(100, 'B'), "text/plain");
  11365. });
  11366. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11367. res.set_content_provider(3, "text/plain", abc);
  11368. res.body = "direct";
  11369. });
  11370. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11371. res.set_file_content("./www/dir/test.html");
  11372. res.body = "direct";
  11373. });
  11374. auto port = svr.bind_to_any_port(HOST);
  11375. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11376. auto se = detail::scope_exit([&] {
  11377. svr.stop();
  11378. t.join();
  11379. ASSERT_FALSE(svr.is_running());
  11380. });
  11381. svr.wait_until_ready();
  11382. Client cli(HOST, port);
  11383. auto expect_body = [&](const char *path, const std::string &body) {
  11384. // Uncompressed, so Content-Length can be compared with the body.
  11385. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11386. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11387. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11388. EXPECT_EQ(body, res->body) << path;
  11389. EXPECT_EQ(std::to_string(body.size()),
  11390. res->get_header_value("Content-Length"))
  11391. << path;
  11392. };
  11393. expect_body("/file-then-body", "body");
  11394. expect_body("/body-then-file", "test.html");
  11395. expect_body("/body-then-provider", "abc");
  11396. expect_body("/provider-then-body", std::string(100, 'B'));
  11397. expect_body("/provider-then-direct-body", "direct");
  11398. expect_body("/file-then-direct-body", "direct");
  11399. // Ranges are checked against the body, not the dropped provider.
  11400. {
  11401. auto res = cli.Get("/provider-then-direct-body",
  11402. Headers{{make_range_header({{1, 2}})}});
  11403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11405. EXPECT_EQ("ir", res->body);
  11406. }
  11407. {
  11408. auto res = cli.Get("/file-then-direct-body",
  11409. Headers{{make_range_header({{7, 8}})}});
  11410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11411. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11412. }
  11413. }
  11414. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11415. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11416. const char *path = "./truncated_while_served.txt";
  11417. const size_t size = 32 * 1024 * 1024;
  11418. {
  11419. std::ofstream f(path, std::ios::binary);
  11420. f << std::string(size, 'x');
  11421. }
  11422. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11423. // Over TLS, where the bytes are encrypted in this process rather than
  11424. // copied by send().
  11425. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11426. svr.Get("/file", [&](const Request &, Response &res) {
  11427. res.set_file_content(path, "text/plain");
  11428. });
  11429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11430. auto se = detail::scope_exit([&] {
  11431. svr.stop();
  11432. thread.join();
  11433. ASSERT_FALSE(svr.is_running());
  11434. });
  11435. svr.wait_until_ready();
  11436. // The file shrinks once the first bytes are in, as a rewrite in place
  11437. // would, and reading the mapping past its new end used to raise SIGBUS.
  11438. SSLClient cli(HOST, PORT);
  11439. cli.enable_server_certificate_verification(false);
  11440. size_t received = 0;
  11441. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11442. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11443. received += len;
  11444. return true;
  11445. });
  11446. EXPECT_FALSE(res);
  11447. EXPECT_LT(received, size);
  11448. }
  11449. #endif
  11450. // Forward declaration (see the base64_encode note).
  11451. namespace httplib {
  11452. namespace detail {
  11453. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11454. const std::string &content_type,
  11455. EncodingType encoding);
  11456. } // namespace detail
  11457. } // namespace httplib
  11458. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11459. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11460. ASSERT_TRUE(mm->is_open());
  11461. Response res;
  11462. detail::set_file_content_provider(res, mm, "text/html",
  11463. detail::EncodingType::None);
  11464. std::string out;
  11465. DataSink sink;
  11466. sink.write = [&](const char *d, size_t l) {
  11467. out.append(d, l);
  11468. return true;
  11469. };
  11470. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11471. EXPECT_EQ("test.html", out);
  11472. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11473. EXPECT_EQ("test.html", out);
  11474. }
  11475. TEST(LongPollingTest, ClientCloseDetection) {
  11476. Server svr;
  11477. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11478. res.set_chunked_content_provider(
  11479. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11480. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11481. sink.os << "hello";
  11482. auto count = 10;
  11483. while (count > 0 && sink.is_writable()) {
  11484. this_thread::sleep_for(chrono::milliseconds(10));
  11485. count--;
  11486. }
  11487. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11488. return true;
  11489. });
  11490. });
  11491. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11492. auto se = detail::scope_exit([&] {
  11493. svr.stop();
  11494. listen_thread.join();
  11495. ASSERT_FALSE(svr.is_running());
  11496. });
  11497. svr.wait_until_ready();
  11498. Client cli("localhost", PORT);
  11499. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11500. EXPECT_EQ("hello", string(data, data_length));
  11501. return false; // close the socket immediately.
  11502. });
  11503. ASSERT_FALSE(res);
  11504. }
  11505. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11506. Server svr;
  11507. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11508. res.set_chunked_content_provider(
  11509. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11510. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11511. sink.os << "hello";
  11512. EXPECT_TRUE(sink.os.good());
  11513. // Wait for the client to close the connection
  11514. auto count = 10;
  11515. while (count > 0 && sink.is_writable()) {
  11516. this_thread::sleep_for(chrono::milliseconds(10));
  11517. count--;
  11518. }
  11519. // After client disconnect, write repeatedly until the socket
  11520. // write actually fails (small writes may be absorbed by the
  11521. // kernel buffer)
  11522. std::string chunk(1024, 'x');
  11523. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11524. sink.os << chunk;
  11525. }
  11526. EXPECT_TRUE(sink.os.fail());
  11527. return true;
  11528. });
  11529. });
  11530. auto port = svr.bind_to_any_port("localhost");
  11531. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11532. auto se = detail::scope_exit([&] {
  11533. svr.stop();
  11534. listen_thread.join();
  11535. ASSERT_FALSE(svr.is_running());
  11536. });
  11537. svr.wait_until_ready();
  11538. Client cli("localhost", port);
  11539. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11540. EXPECT_EQ("hello", string(data, data_length));
  11541. return false; // close the socket immediately.
  11542. });
  11543. ASSERT_FALSE(res);
  11544. }
  11545. TEST(GetWithParametersTest, GetWithParameters) {
  11546. Server svr;
  11547. svr.Get("/", [&](const Request &req, Response &) {
  11548. EXPECT_EQ("world", req.get_param_value("hello"));
  11549. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11550. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11551. });
  11552. svr.Get("/params", [&](const Request &req, Response &) {
  11553. EXPECT_EQ("world", req.get_param_value("hello"));
  11554. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11555. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11556. });
  11557. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11558. EXPECT_EQ("resource-id", req.matches[1]);
  11559. EXPECT_EQ("foo", req.get_param_value("param1"));
  11560. EXPECT_EQ("bar", req.get_param_value("param2"));
  11561. });
  11562. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11563. EXPECT_EQ("user-id", req.path_params.at("id"));
  11564. EXPECT_EQ("foo", req.get_param_value("param1"));
  11565. EXPECT_EQ("bar", req.get_param_value("param2"));
  11566. });
  11567. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11568. auto se = detail::scope_exit([&] {
  11569. svr.stop();
  11570. listen_thread.join();
  11571. ASSERT_FALSE(svr.is_running());
  11572. });
  11573. svr.wait_until_ready();
  11574. {
  11575. Client cli(HOST, PORT);
  11576. Params params;
  11577. params.emplace("hello", "world");
  11578. params.emplace("hello2", "world2");
  11579. params.emplace("hello3", "world3");
  11580. auto res = cli.Get("/", params, Headers{});
  11581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11582. EXPECT_EQ(StatusCode::OK_200, res->status);
  11583. }
  11584. {
  11585. Client cli(HOST, PORT);
  11586. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11588. EXPECT_EQ(StatusCode::OK_200, res->status);
  11589. }
  11590. {
  11591. Client cli(HOST, PORT);
  11592. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11594. EXPECT_EQ(StatusCode::OK_200, res->status);
  11595. }
  11596. {
  11597. Client cli(HOST, PORT);
  11598. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11600. EXPECT_EQ(StatusCode::OK_200, res->status);
  11601. }
  11602. }
  11603. TEST(GetWithParametersTest, GetWithParameters2) {
  11604. Server svr;
  11605. svr.Get("/", [&](const Request &req, Response &res) {
  11606. auto text = req.get_param_value("hello");
  11607. res.set_content(text, "text/plain");
  11608. });
  11609. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11610. auto se = detail::scope_exit([&] {
  11611. svr.stop();
  11612. listen_thread.join();
  11613. ASSERT_FALSE(svr.is_running());
  11614. });
  11615. svr.wait_until_ready();
  11616. Client cli("localhost", PORT);
  11617. Params params;
  11618. params.emplace("hello", "world");
  11619. std::string body;
  11620. auto res = cli.Get("/", params, Headers{},
  11621. [&](const char *data, size_t data_length) {
  11622. body.append(data, data_length);
  11623. return true;
  11624. });
  11625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11626. EXPECT_EQ(StatusCode::OK_200, res->status);
  11627. EXPECT_EQ("world", body);
  11628. }
  11629. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11630. Server svr;
  11631. svr.Get("/search", [&](const Request &req, Response &res) {
  11632. auto q = req.get_param_value("q");
  11633. res.set_content(q, "text/plain");
  11634. });
  11635. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11636. auto se = detail::scope_exit([&] {
  11637. svr.stop();
  11638. listen_thread.join();
  11639. ASSERT_FALSE(svr.is_running());
  11640. });
  11641. svr.wait_until_ready();
  11642. Client cli("localhost", PORT);
  11643. // Verify that Get(path, params) works without requiring Headers argument
  11644. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11646. EXPECT_EQ(StatusCode::OK_200, res->status);
  11647. EXPECT_EQ("cpp-httplib", res->body);
  11648. }
  11649. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11650. auto host = "httpbingo.org";
  11651. auto path = std::string{"/range/32"};
  11652. #ifdef CPPHTTPLIB_SSL_ENABLED
  11653. SSLClient cli(host);
  11654. #else
  11655. Client cli(host);
  11656. #endif
  11657. cli.set_default_headers({make_range_header({{1, 10}})});
  11658. cli.set_connection_timeout(5);
  11659. {
  11660. auto res = cli.Get(path);
  11661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11662. EXPECT_EQ("bcdefghijk", res->body);
  11663. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11664. }
  11665. {
  11666. auto res = cli.Get(path);
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. EXPECT_EQ("bcdefghijk", res->body);
  11669. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11670. }
  11671. }
  11672. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11673. Server svr;
  11674. svr.set_default_headers({{"Hello", "World"}});
  11675. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11676. res.set_content("ok", "text/plain");
  11677. });
  11678. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11679. auto se = detail::scope_exit([&] {
  11680. svr.stop();
  11681. listen_thread.join();
  11682. ASSERT_FALSE(svr.is_running());
  11683. });
  11684. svr.wait_until_ready();
  11685. Client cli("localhost", PORT);
  11686. auto res = cli.Get("/");
  11687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11688. EXPECT_EQ(StatusCode::OK_200, res->status);
  11689. EXPECT_EQ("ok", res->body);
  11690. EXPECT_EQ("World", res->get_header_value("Hello"));
  11691. }
  11692. #ifdef CPPHTTPLIB_SSL_ENABLED
  11693. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11695. ASSERT_TRUE(svr.is_valid());
  11696. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11697. std::this_thread::sleep_for(std::chrono::seconds(2));
  11698. res.set_content("a", "text/plain");
  11699. });
  11700. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11701. res.set_content("b", "text/plain");
  11702. });
  11703. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11704. auto se = detail::scope_exit([&] {
  11705. svr.stop();
  11706. listen_thread.join();
  11707. ASSERT_FALSE(svr.is_running());
  11708. });
  11709. svr.wait_until_ready();
  11710. SSLClient cli("localhost", PORT);
  11711. cli.enable_server_certificate_verification(false);
  11712. cli.set_keep_alive(true);
  11713. cli.set_read_timeout(std::chrono::seconds(1));
  11714. auto resa = cli.Get("/a");
  11715. ASSERT_TRUE(!resa);
  11716. EXPECT_EQ(Error::Read, resa.error());
  11717. auto resb = cli.Get("/b");
  11718. ASSERT_TRUE(resb);
  11719. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11720. EXPECT_EQ("b", resb->body);
  11721. }
  11722. // Closing an idle keep-alive connection sends close_notify and returns. The
  11723. // server must not wait for the client's close_notify: an idle client never
  11724. // sends one, so the worker would be held until the read timeout expires, and
  11725. // stop() would wait for it.
  11726. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11727. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11728. ASSERT_TRUE(svr.is_valid());
  11729. svr.set_keep_alive_timeout(1);
  11730. svr.set_read_timeout(10, 0);
  11731. svr.Get("/", [](const Request &, Response &res) {
  11732. res.set_content("ok", "text/plain");
  11733. });
  11734. auto port = svr.bind_to_any_port(HOST);
  11735. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11736. auto se = detail::scope_exit([&] {
  11737. if (listen_thread.joinable()) {
  11738. svr.stop();
  11739. listen_thread.join();
  11740. }
  11741. });
  11742. svr.wait_until_ready();
  11743. SSLClient cli(HOST, port);
  11744. cli.enable_server_certificate_verification(false);
  11745. cli.set_keep_alive(true);
  11746. auto res = cli.Get("/");
  11747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11748. EXPECT_EQ(StatusCode::OK_200, res->status);
  11749. // Stay idle past the keep-alive timeout so the server closes the connection.
  11750. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11751. auto start = std::chrono::steady_clock::now();
  11752. svr.stop();
  11753. listen_thread.join();
  11754. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11755. std::chrono::steady_clock::now() - start)
  11756. .count();
  11757. EXPECT_LT(elapsed, 3000);
  11758. }
  11759. #endif
  11760. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11761. protected:
  11762. ServerTestWithAI_PASSIVE()
  11763. : cli_(HOST, PORT)
  11764. #ifdef CPPHTTPLIB_SSL_ENABLED
  11765. ,
  11766. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11767. #endif
  11768. {
  11769. #ifdef CPPHTTPLIB_SSL_ENABLED
  11770. cli_.enable_server_certificate_verification(false);
  11771. #endif
  11772. }
  11773. virtual void SetUp() {
  11774. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11775. res.set_content("Hello World!", "text/plain");
  11776. });
  11777. t_ = thread(
  11778. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11779. svr_.wait_until_ready();
  11780. }
  11781. virtual void TearDown() {
  11782. svr_.stop();
  11783. t_.join();
  11784. }
  11785. #ifdef CPPHTTPLIB_SSL_ENABLED
  11786. SSLClient cli_;
  11787. SSLServer svr_;
  11788. #else
  11789. Client cli_;
  11790. Server svr_;
  11791. #endif
  11792. thread t_;
  11793. };
  11794. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11795. auto res = cli_.Get("/hi");
  11796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11797. EXPECT_EQ(StatusCode::OK_200, res->status);
  11798. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11799. EXPECT_EQ("Hello World!", res->body);
  11800. }
  11801. class ServerUpDownTest : public ::testing::Test {
  11802. protected:
  11803. ServerUpDownTest() : cli_(HOST, PORT) {}
  11804. virtual void SetUp() {
  11805. t_ = thread([&]() {
  11806. svr_.bind_to_any_port(HOST);
  11807. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11808. ASSERT_TRUE(svr_.listen_after_bind());
  11809. });
  11810. svr_.wait_until_ready();
  11811. }
  11812. virtual void TearDown() {
  11813. svr_.stop();
  11814. t_.join();
  11815. }
  11816. Client cli_;
  11817. Server svr_;
  11818. thread t_;
  11819. };
  11820. TEST_F(ServerUpDownTest, QuickStartStop) {
  11821. // Should not crash, especially when run with
  11822. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11823. }
  11824. class PayloadMaxLengthTest : public ::testing::Test {
  11825. protected:
  11826. PayloadMaxLengthTest()
  11827. : cli_(HOST, PORT)
  11828. #ifdef CPPHTTPLIB_SSL_ENABLED
  11829. ,
  11830. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11831. #endif
  11832. {
  11833. #ifdef CPPHTTPLIB_SSL_ENABLED
  11834. cli_.enable_server_certificate_verification(false);
  11835. #endif
  11836. }
  11837. virtual void SetUp() {
  11838. svr_.set_payload_max_length(8);
  11839. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11840. res.set_content("test", "text/plain");
  11841. });
  11842. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11843. svr_.wait_until_ready();
  11844. }
  11845. virtual void TearDown() {
  11846. svr_.stop();
  11847. t_.join();
  11848. }
  11849. #ifdef CPPHTTPLIB_SSL_ENABLED
  11850. SSLClient cli_;
  11851. SSLServer svr_;
  11852. #else
  11853. Client cli_;
  11854. Server svr_;
  11855. #endif
  11856. thread t_;
  11857. };
  11858. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11859. auto res = cli_.Post("/test", "123456789", "text/plain");
  11860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11861. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11862. res = cli_.Post("/test", "12345678", "text/plain");
  11863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11864. EXPECT_EQ(StatusCode::OK_200, res->status);
  11865. }
  11866. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11867. // Test chunked encoding with payload exceeding the 8-byte limit
  11868. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11869. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11871. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11872. }
  11873. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11874. // Test chunked encoding with payload within the 8-byte limit
  11875. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11876. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11878. EXPECT_EQ(StatusCode::OK_200, res->status);
  11879. }
  11880. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11881. // Test using send_request to send chunked data exceeding payload limit
  11882. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11883. "Host: " +
  11884. std::string(HOST) + ":" + std::to_string(PORT) +
  11885. "\r\n"
  11886. "Transfer-Encoding: chunked\r\n"
  11887. "Connection: close\r\n"
  11888. "\r\n"
  11889. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11890. "0123456789\r\n"
  11891. "0\r\n" // End chunk
  11892. "\r\n";
  11893. std::string response;
  11894. bool result = send_request(1, chunked_request, &response);
  11895. if (!result) {
  11896. // If send_request fails, it might be because the server closed the
  11897. // connection due to payload limit enforcement, which is acceptable
  11898. SUCCEED()
  11899. << "Server rejected oversized chunked request (connection closed)";
  11900. } else {
  11901. // If we got a response, check if it's an error response or connection was
  11902. // closed early Short response length indicates connection was closed due to
  11903. // payload limit
  11904. if (response.length() <= 10) {
  11905. SUCCEED() << "Server closed connection for oversized chunked request";
  11906. } else {
  11907. // Check for error status codes
  11908. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11909. response.find("Payload Too Large") != std::string::npos ||
  11910. response.find("400") != std::string::npos);
  11911. }
  11912. }
  11913. }
  11914. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11915. // Test request without Content-Length header exceeding payload limit
  11916. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11917. "Host: " +
  11918. std::string(HOST) + ":" +
  11919. std::to_string(PORT) +
  11920. "\r\n"
  11921. "Connection: close\r\n"
  11922. "\r\n";
  11923. // Add payload exceeding the 8-byte limit
  11924. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11925. request_without_content_length += large_payload;
  11926. std::string response;
  11927. bool result = send_request(1, request_without_content_length, &response);
  11928. if (!result) {
  11929. // If send_request fails, server likely closed connection due to payload
  11930. // limit
  11931. SUCCEED() << "Server rejected oversized request without Content-Length "
  11932. "(connection closed)";
  11933. } else {
  11934. // Check if server responded with error or closed connection early
  11935. if (response.length() <= 10) {
  11936. SUCCEED() << "Server closed connection for oversized request without "
  11937. "Content-Length";
  11938. } else {
  11939. // Check for error status codes
  11940. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11941. response.find("Payload Too Large") != std::string::npos ||
  11942. response.find("400") != std::string::npos);
  11943. }
  11944. }
  11945. }
  11946. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11947. // Test request without Content-Length header within payload limit
  11948. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11949. "Host: " +
  11950. std::string(HOST) + ":" +
  11951. std::to_string(PORT) +
  11952. "\r\n"
  11953. "Connection: close\r\n"
  11954. "\r\n";
  11955. // Add payload within the 8-byte limit
  11956. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11957. request_without_content_length += small_payload;
  11958. std::string response;
  11959. bool result = send_request(1, request_without_content_length, &response);
  11960. // For requests without Content-Length, the server may have different behavior
  11961. // The key is that it should not reject due to payload limit for small
  11962. // payloads
  11963. if (result) {
  11964. // Check for any HTTP response (success or error, but not connection closed)
  11965. if (response.length() > 10) {
  11966. SUCCEED()
  11967. << "Server processed request without Content-Length within limit";
  11968. } else {
  11969. // Short response might indicate connection closed, which is acceptable
  11970. SUCCEED() << "Server closed connection for request without "
  11971. "Content-Length (acceptable behavior)";
  11972. }
  11973. } else {
  11974. // Connection failure might be due to protocol requirements
  11975. SUCCEED() << "Connection issue with request without Content-Length "
  11976. "(environment-specific)";
  11977. }
  11978. }
  11979. class LargePayloadMaxLengthTest : public ::testing::Test {
  11980. protected:
  11981. LargePayloadMaxLengthTest()
  11982. : cli_(HOST, PORT)
  11983. #ifdef CPPHTTPLIB_SSL_ENABLED
  11984. ,
  11985. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11986. #endif
  11987. {
  11988. #ifdef CPPHTTPLIB_SSL_ENABLED
  11989. cli_.enable_server_certificate_verification(false);
  11990. #endif
  11991. }
  11992. virtual void SetUp() {
  11993. // Set 10MB payload limit
  11994. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11995. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11996. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11997. res.set_content("Large payload test", "text/plain");
  11998. });
  11999. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12000. svr_.wait_until_ready();
  12001. }
  12002. virtual void TearDown() {
  12003. svr_.stop();
  12004. t_.join();
  12005. }
  12006. #ifdef CPPHTTPLIB_SSL_ENABLED
  12007. SSLClient cli_;
  12008. SSLServer svr_;
  12009. #else
  12010. Client cli_;
  12011. Server svr_;
  12012. #endif
  12013. thread t_;
  12014. };
  12015. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12016. // Test chunked encoding with payload within 10MB limit
  12017. std::string medium_payload(5 * 1024 * 1024,
  12018. 'A'); // 5MB payload, within 10MB limit
  12019. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12021. EXPECT_EQ(StatusCode::OK_200, res->status);
  12022. }
  12023. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12024. // Test chunked encoding with payload exceeding 10MB limit
  12025. std::string large_payload(12 * 1024 * 1024,
  12026. 'B'); // 12MB payload, exceeds 10MB limit
  12027. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12028. // Server may either return 413 or close the connection
  12029. if (res) {
  12030. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12031. } else {
  12032. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12033. }
  12034. }
  12035. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12036. // Test request without Content-Length header within 10MB limit
  12037. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12038. "Host: " +
  12039. std::string(HOST) + ":" +
  12040. std::to_string(PORT) +
  12041. "\r\n"
  12042. "Connection: close\r\n"
  12043. "\r\n";
  12044. // Add 1MB payload (within 10MB limit)
  12045. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12046. request_without_content_length += medium_payload;
  12047. std::string response;
  12048. bool result = send_request(5, request_without_content_length, &response);
  12049. if (result) {
  12050. // Should get a proper HTTP response for payloads within limit
  12051. if (response.length() > 10) {
  12052. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12053. "10MB limit";
  12054. } else {
  12055. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12056. "Content-Length)";
  12057. }
  12058. } else {
  12059. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12060. }
  12061. }
  12062. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12063. // Test request without Content-Length header exceeding 10MB limit
  12064. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12065. "Host: " +
  12066. std::string(HOST) + ":" +
  12067. std::to_string(PORT) +
  12068. "\r\n"
  12069. "Connection: close\r\n"
  12070. "\r\n";
  12071. // Add 12MB payload (exceeds 10MB limit)
  12072. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12073. request_without_content_length += large_payload;
  12074. std::string response;
  12075. bool result = send_request(10, request_without_content_length, &response);
  12076. if (!result) {
  12077. // Server should close connection due to payload limit
  12078. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12079. "(connection closed)";
  12080. } else {
  12081. // Check for error response
  12082. if (response.length() <= 10) {
  12083. SUCCEED()
  12084. << "Server closed connection for 12MB request exceeding 10MB limit";
  12085. } else {
  12086. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12087. response.find("Payload Too Large") != std::string::npos ||
  12088. response.find("400") != std::string::npos);
  12089. }
  12090. }
  12091. }
  12092. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12093. Server svr;
  12094. svr.Get("/", [](const Request &, Response &res) {
  12095. // Claims far more than it sends, then drops the connection.
  12096. res.set_content_provider(size_t(1) << 41, "text/plain",
  12097. [](size_t, size_t, DataSink &sink) {
  12098. sink.write("abc", 3);
  12099. return false;
  12100. });
  12101. });
  12102. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12103. auto se = detail::scope_exit([&] {
  12104. svr.stop();
  12105. thread.join();
  12106. ASSERT_FALSE(svr.is_running());
  12107. });
  12108. svr.wait_until_ready();
  12109. Client cli(HOST, PORT);
  12110. cli.set_payload_max_length(0);
  12111. EXPECT_FALSE(cli.Get("/"));
  12112. }
  12113. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12114. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12115. // path.
  12116. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12117. Server svr;
  12118. const size_t LIMIT = 64 * 1024; // 64KB
  12119. svr.set_payload_max_length(LIMIT);
  12120. size_t total = 0;
  12121. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12122. const ContentReader &content_reader) {
  12123. content_reader([&](const char * /*data*/, size_t len) {
  12124. total += len;
  12125. return true;
  12126. });
  12127. res.status = 200;
  12128. res.set_content("stream_ok", "text/plain");
  12129. });
  12130. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12131. auto se = detail::scope_exit([&] {
  12132. svr.stop();
  12133. thread.join();
  12134. ASSERT_FALSE(svr.is_running());
  12135. });
  12136. svr.wait_until_ready();
  12137. // Prepare 256KB raw data and gzip-compress it
  12138. std::string raw(256 * 1024, 'A');
  12139. std::string gz;
  12140. {
  12141. z_stream zs{};
  12142. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12143. Z_DEFAULT_STRATEGY);
  12144. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12145. zs.avail_in = static_cast<uInt>(raw.size());
  12146. char outbuf[4096];
  12147. int ret;
  12148. do {
  12149. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12150. zs.avail_out = sizeof(outbuf);
  12151. ret = deflate(&zs, Z_FINISH);
  12152. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12153. } while (ret != Z_STREAM_END);
  12154. deflateEnd(&zs);
  12155. }
  12156. Client cli(HOST, PORT);
  12157. cli.set_connection_timeout(std::chrono::seconds(5));
  12158. Headers headers = {{"Content-Encoding", "gzip"}};
  12159. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12160. "application/octet-stream");
  12161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12162. // Server must reject oversized decompressed payloads with 413.
  12163. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12164. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12165. EXPECT_LE(total, LIMIT);
  12166. }
  12167. #ifndef CPPHTTPLIB_SSL_ENABLED
  12168. // For a request with neither Content-Length nor Transfer-Encoding, the
  12169. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12170. // compressed wire bytes straight to the ContentReader without ever routing
  12171. // them through the decompressor, so payload_max_length_ only bounded the
  12172. // compressed size on the wire, not the decompressed size.
  12173. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12174. Server svr;
  12175. const size_t LIMIT = 64 * 1024; // 64KB
  12176. svr.set_payload_max_length(LIMIT);
  12177. size_t total = 0;
  12178. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12179. const ContentReader &content_reader) {
  12180. content_reader([&](const char * /*data*/, size_t len) {
  12181. total += len;
  12182. return true;
  12183. });
  12184. res.status = 200;
  12185. res.set_content("stream_ok", "text/plain");
  12186. });
  12187. auto port = svr.bind_to_any_port(HOST);
  12188. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12189. auto se = detail::scope_exit([&] {
  12190. svr.stop();
  12191. thread.join();
  12192. ASSERT_FALSE(svr.is_running());
  12193. });
  12194. svr.wait_until_ready();
  12195. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12196. // StreamingGzipDecompression test above.
  12197. std::string raw(256 * 1024, 'A');
  12198. std::string gz;
  12199. {
  12200. httplib::detail::gzip_compressor compressor;
  12201. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12202. [&](const char *chunk, size_t len) {
  12203. gz.append(chunk, len);
  12204. return true;
  12205. });
  12206. ASSERT_TRUE(result);
  12207. }
  12208. // Send the gzip body over raw TCP with neither Content-Length nor
  12209. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12210. // kicks in.
  12211. std::string req = "POST /stream HTTP/1.1\r\n"
  12212. "Host: " +
  12213. std::string(HOST) + ":" + std::to_string(port) +
  12214. "\r\n"
  12215. "Content-Encoding: gzip\r\n"
  12216. "Connection: close\r\n"
  12217. "\r\n" +
  12218. gz;
  12219. std::string response;
  12220. ASSERT_TRUE(send_request(5, req, &response, port));
  12221. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12222. EXPECT_LE(total, LIMIT);
  12223. }
  12224. #endif
  12225. #endif
  12226. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12227. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12228. // the payload must be passed through untouched instead of being rejected.
  12229. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12230. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12231. Server svr;
  12232. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12233. res.set_content(body, "image/jpeg");
  12234. res.set_header("Content-Encoding", "UTF-8");
  12235. });
  12236. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12237. res.set_content(body, "image/jpeg");
  12238. res.set_header("Content-Encoding", "identity");
  12239. });
  12240. svr.Post("/echo", [](const Request &req, Response &res) {
  12241. res.set_content(req.body, "image/jpeg");
  12242. });
  12243. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12244. auto se = detail::scope_exit([&] {
  12245. svr.stop();
  12246. t.join();
  12247. ASSERT_FALSE(svr.is_running());
  12248. });
  12249. svr.wait_until_ready();
  12250. Client cli(HOST, PORT);
  12251. {
  12252. auto res = cli.Get("/image");
  12253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12254. EXPECT_EQ(StatusCode::OK_200, res->status);
  12255. EXPECT_EQ(body, res->body);
  12256. }
  12257. {
  12258. auto res = cli.Get("/identity");
  12259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12260. EXPECT_EQ(StatusCode::OK_200, res->status);
  12261. EXPECT_EQ(body, res->body);
  12262. }
  12263. {
  12264. // The same applies to a request body reaching the server.
  12265. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12266. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12268. EXPECT_EQ(StatusCode::OK_200, res->status);
  12269. EXPECT_EQ(body, res->body);
  12270. }
  12271. }
  12272. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12273. // gzip-encoded response even when the build has no zlib support.
  12274. static const char GZIPPED_HELLO_WORLD[] = {
  12275. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12276. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12277. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12278. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12279. // A content coding is a whole token, not something the field value merely
  12280. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12281. // as "fibre" look like Brotli, and turned a multi-coding value like
  12282. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12283. // it was never meant to see.
  12284. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12285. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12286. Server svr;
  12287. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12288. res.set_content(body, "image/jpeg");
  12289. res.set_header("Content-Encoding", "fibre");
  12290. });
  12291. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12292. res.set_content(body, "image/jpeg");
  12293. res.set_header("Content-Encoding", "gzip, br");
  12294. });
  12295. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12296. res.set_content(body, "image/jpeg");
  12297. res.set_header("Content-Encoding", "x-zstd-ish");
  12298. });
  12299. auto port = svr.bind_to_any_port(HOST);
  12300. thread t = thread([&]() { svr.listen_after_bind(); });
  12301. auto se = detail::scope_exit([&] {
  12302. svr.stop();
  12303. t.join();
  12304. ASSERT_FALSE(svr.is_running());
  12305. });
  12306. svr.wait_until_ready();
  12307. Client cli(HOST, port);
  12308. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12309. auto res = cli.Get(path);
  12310. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12311. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12312. // Not a coding we recognize, so the payload comes back untouched
  12313. EXPECT_EQ(body, res->body) << path;
  12314. }
  12315. }
  12316. // A content coding cpp-httplib recognizes but was not built with must be
  12317. // reported as such. Handing the still-compressed payload back to the caller
  12318. // would silently corrupt it.
  12319. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12320. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12321. Server svr;
  12322. // "image/jpeg" keeps the server from applying a content coding of its own,
  12323. // so the hand-crafted Content-Encoding below survives.
  12324. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12325. res.set_content(gzipped, "image/jpeg");
  12326. res.set_header("Content-Encoding", "gzip");
  12327. });
  12328. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12329. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12330. res.set_content(gzipped, "image/jpeg");
  12331. res.set_header("Content-Encoding", "GZIP");
  12332. });
  12333. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12334. auto se = detail::scope_exit([&] {
  12335. svr.stop();
  12336. t.join();
  12337. ASSERT_FALSE(svr.is_running());
  12338. });
  12339. svr.wait_until_ready();
  12340. Client cli(HOST, PORT);
  12341. {
  12342. auto res = cli.Get("/gzipped");
  12343. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12345. EXPECT_EQ("Hello World!", res->body);
  12346. #else
  12347. ASSERT_FALSE(res);
  12348. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12349. #endif
  12350. }
  12351. {
  12352. // open_stream() must behave the same way.
  12353. auto handle = cli.open_stream("GET", "/gzipped");
  12354. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12355. ASSERT_TRUE(handle.is_valid());
  12356. std::string received;
  12357. char buf[256];
  12358. ssize_t n;
  12359. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12360. received.append(buf, static_cast<size_t>(n));
  12361. }
  12362. EXPECT_EQ("Hello World!", received);
  12363. #else
  12364. EXPECT_FALSE(handle.is_valid());
  12365. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12366. #endif
  12367. }
  12368. {
  12369. // A differently-cased coding must not be mistaken for an unknown one, or
  12370. // the body would be handed back still compressed.
  12371. auto res = cli.Get("/gzipped-uppercase");
  12372. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12374. EXPECT_EQ("Hello World!", res->body);
  12375. #else
  12376. ASSERT_FALSE(res);
  12377. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12378. #endif
  12379. }
  12380. }
  12381. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12382. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12383. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12384. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12385. // body a second time and appending a second Content-Encoding field line, so
  12386. // clients that decode one coding per listed value handed back raw gzip bytes.
  12387. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12388. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12389. Server svr;
  12390. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12391. // keeps the server from applying a coding of its own.
  12392. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12393. res.set_content(gzipped, "text/plain");
  12394. res.set_header("Content-Encoding", "gzip");
  12395. });
  12396. auto port = svr.bind_to_any_port(HOST);
  12397. thread t = thread([&]() { svr.listen_after_bind(); });
  12398. auto se = detail::scope_exit([&] {
  12399. svr.stop();
  12400. t.join();
  12401. ASSERT_FALSE(svr.is_running());
  12402. });
  12403. svr.wait_until_ready();
  12404. Client cli(HOST, port);
  12405. Headers headers = {{"Accept-Encoding", "gzip"}};
  12406. auto res = cli.Get("/pre-gzipped", headers);
  12407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12408. EXPECT_EQ(StatusCode::OK_200, res->status);
  12409. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12410. EXPECT_EQ("Hello World!", res->body);
  12411. }
  12412. // A chunked provider settles its coding where the headers are written and
  12413. // reuses it at write time. Both ends of that have to hold: a handler's own
  12414. // Content-Encoding suppresses the coding, and a response without one is still
  12415. // compressed as it always was.
  12416. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12417. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12418. const std::string plain = "Hello World! Hello World! Hello World!";
  12419. Server svr;
  12420. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12421. res.set_header("Content-Encoding", "gzip");
  12422. res.set_chunked_content_provider(
  12423. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12424. sink.write(gzipped.data(), gzipped.size());
  12425. sink.done();
  12426. return true;
  12427. });
  12428. });
  12429. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12430. res.set_chunked_content_provider(
  12431. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12432. sink.write(plain.data(), plain.size());
  12433. sink.done();
  12434. return true;
  12435. });
  12436. });
  12437. auto port = svr.bind_to_any_port(HOST);
  12438. thread t = thread([&]() { svr.listen_after_bind(); });
  12439. auto se = detail::scope_exit([&] {
  12440. svr.stop();
  12441. t.join();
  12442. ASSERT_FALSE(svr.is_running());
  12443. });
  12444. svr.wait_until_ready();
  12445. Client cli(HOST, port);
  12446. Headers headers = {{"Accept-Encoding", "gzip"}};
  12447. {
  12448. auto res = cli.Get("/pre-gzipped", headers);
  12449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12450. EXPECT_EQ(StatusCode::OK_200, res->status);
  12451. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12452. EXPECT_EQ("Hello World!", res->body);
  12453. }
  12454. {
  12455. auto res = cli.Get("/negotiated", headers);
  12456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12457. EXPECT_EQ(StatusCode::OK_200, res->status);
  12458. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12459. EXPECT_EQ(plain, res->body);
  12460. }
  12461. }
  12462. #endif
  12463. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12464. // the same message as the comma-joined one, so both have to be read the same
  12465. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12466. // single gzip coding, and a body the sender says was encoded twice was handed
  12467. // back after one pass, still compressed but presented as decoded.
  12468. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12469. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12470. Server svr;
  12471. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12472. res.set_content(body, "image/jpeg");
  12473. res.headers.emplace("Content-Encoding", "gzip");
  12474. res.headers.emplace("Content-Encoding", "gzip");
  12475. });
  12476. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12477. res.set_content(body, "image/jpeg");
  12478. res.set_header("Content-Encoding", "gzip, gzip");
  12479. });
  12480. auto port = svr.bind_to_any_port(HOST);
  12481. thread t = thread([&]() { svr.listen_after_bind(); });
  12482. auto se = detail::scope_exit([&] {
  12483. svr.stop();
  12484. t.join();
  12485. ASSERT_FALSE(svr.is_running());
  12486. });
  12487. svr.wait_until_ready();
  12488. Client cli(HOST, port);
  12489. // Two codings is not something cpp-httplib decodes, so both representations
  12490. // take the pass-through path rather than one of them being gunzipped once.
  12491. for (const char *path : {"/split", "/joined"}) {
  12492. auto res = cli.Get(path);
  12493. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12494. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12495. EXPECT_EQ(body, res->body) << path;
  12496. }
  12497. }
  12498. // Regression test for DoS vulnerability: a malicious server sending a response
  12499. // without Content-Length header must not cause unbounded memory consumption on
  12500. // the client side. The client should stop reading after a reasonable limit,
  12501. // similar to the server-side set_payload_max_length protection.
  12502. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12503. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12504. #ifndef _WIN32
  12505. signal(SIGPIPE, SIG_IGN);
  12506. #endif
  12507. auto server_thread = std::thread([] {
  12508. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12509. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12510. default_socket_options(srv);
  12511. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12512. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12513. sockaddr_in addr{};
  12514. addr.sin_family = AF_INET;
  12515. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12516. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12517. int opt = 1;
  12518. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12519. #ifdef _WIN32
  12520. reinterpret_cast<const char *>(&opt),
  12521. #else
  12522. &opt,
  12523. #endif
  12524. sizeof(opt));
  12525. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12526. ::listen(srv, 1);
  12527. sockaddr_in cli_addr{};
  12528. socklen_t cli_len = sizeof(cli_addr);
  12529. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12530. if (cli != INVALID_SOCKET) {
  12531. char buf[4096];
  12532. ::recv(cli, buf, sizeof(buf), 0);
  12533. // Malicious response: no Content-Length, no chunked encoding
  12534. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12535. "Connection: close\r\n"
  12536. "\r\n";
  12537. ::send(cli,
  12538. #ifdef _WIN32
  12539. static_cast<const char *>(response_header.c_str()),
  12540. static_cast<int>(response_header.size()),
  12541. #else
  12542. response_header.c_str(), response_header.size(),
  12543. #endif
  12544. 0);
  12545. // Send 10MB of data
  12546. std::string chunk(64 * 1024, 'A');
  12547. size_t total_sent = 0;
  12548. while (total_sent < MALICIOUS_DATA_SIZE) {
  12549. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12550. auto sent = ::send(cli,
  12551. #ifdef _WIN32
  12552. static_cast<const char *>(chunk.c_str()),
  12553. static_cast<int>(to_send),
  12554. #else
  12555. chunk.c_str(), to_send,
  12556. #endif
  12557. 0);
  12558. if (sent <= 0) break;
  12559. total_sent += static_cast<size_t>(sent);
  12560. }
  12561. detail::close_socket(cli);
  12562. }
  12563. detail::close_socket(srv);
  12564. });
  12565. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12566. size_t total_read = 0;
  12567. {
  12568. Client cli("127.0.0.1", PORT + 2);
  12569. cli.set_read_timeout(5, 0);
  12570. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12571. auto stream = cli.open_stream("GET", "/malicious");
  12572. ASSERT_TRUE(stream.is_valid());
  12573. char buffer[64 * 1024];
  12574. ssize_t n;
  12575. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12576. total_read += static_cast<size_t>(n);
  12577. }
  12578. } // StreamHandle and Client destroyed here, closing the socket
  12579. server_thread.join();
  12580. // With set_payload_max_length, the client must stop reading before consuming
  12581. // all 10MB. The read loop should be cut off at or near the configured limit.
  12582. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12583. << "Client read " << total_read << " bytes, exceeding the configured "
  12584. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12585. }
  12586. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12587. // the entire response body without truncation.
  12588. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12589. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12590. #ifndef _WIN32
  12591. signal(SIGPIPE, SIG_IGN);
  12592. #endif
  12593. auto server_thread = std::thread([] {
  12594. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12595. default_socket_options(srv);
  12596. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12597. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12598. sockaddr_in addr{};
  12599. addr.sin_family = AF_INET;
  12600. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12601. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12602. int opt = 1;
  12603. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12604. #ifdef _WIN32
  12605. reinterpret_cast<const char *>(&opt),
  12606. #else
  12607. &opt,
  12608. #endif
  12609. sizeof(opt));
  12610. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12611. ::listen(srv, 1);
  12612. sockaddr_in cli_addr{};
  12613. socklen_t cli_len = sizeof(cli_addr);
  12614. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12615. if (cli != INVALID_SOCKET) {
  12616. char buf[4096];
  12617. ::recv(cli, buf, sizeof(buf), 0);
  12618. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12619. "Connection: close\r\n"
  12620. "\r\n";
  12621. ::send(cli,
  12622. #ifdef _WIN32
  12623. static_cast<const char *>(response_header.c_str()),
  12624. static_cast<int>(response_header.size()),
  12625. #else
  12626. response_header.c_str(), response_header.size(),
  12627. #endif
  12628. 0);
  12629. std::string chunk(64 * 1024, 'A');
  12630. size_t total_sent = 0;
  12631. while (total_sent < DATA_SIZE) {
  12632. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12633. auto sent = ::send(cli,
  12634. #ifdef _WIN32
  12635. static_cast<const char *>(chunk.c_str()),
  12636. static_cast<int>(to_send),
  12637. #else
  12638. chunk.c_str(), to_send,
  12639. #endif
  12640. 0);
  12641. if (sent <= 0) break;
  12642. total_sent += static_cast<size_t>(sent);
  12643. }
  12644. #ifdef _WIN32
  12645. ::shutdown(cli, SD_SEND);
  12646. #else
  12647. ::shutdown(cli, SHUT_WR);
  12648. #endif
  12649. // Drain until the client closes its end, ensuring all data is delivered
  12650. char drain[1024];
  12651. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12652. detail::close_socket(cli);
  12653. }
  12654. detail::close_socket(srv);
  12655. });
  12656. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12657. size_t total_read = 0;
  12658. {
  12659. Client cli("127.0.0.1", PORT + 2);
  12660. cli.set_read_timeout(5, 0);
  12661. cli.set_payload_max_length(0); // 0 means no limit
  12662. auto stream = cli.open_stream("GET", "/data");
  12663. ASSERT_TRUE(stream.is_valid());
  12664. char buffer[64 * 1024];
  12665. ssize_t n;
  12666. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12667. total_read += static_cast<size_t>(n);
  12668. }
  12669. }
  12670. server_thread.join();
  12671. EXPECT_EQ(total_read, DATA_SIZE)
  12672. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12673. << " bytes without truncation, but only read " << total_read << " bytes.";
  12674. }
  12675. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12676. // enormous Content-Length must not cause the client to pre-allocate a huge
  12677. // response body buffer. The reservation is capped at payload_max_length_, and
  12678. // the read itself fails when the body exceeds the limit.
  12679. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12680. #ifndef _WIN32
  12681. signal(SIGPIPE, SIG_IGN);
  12682. #endif
  12683. auto server_thread = std::thread([] {
  12684. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12685. default_socket_options(srv);
  12686. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12687. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12688. sockaddr_in addr{};
  12689. addr.sin_family = AF_INET;
  12690. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12691. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12692. int opt = 1;
  12693. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12694. #ifdef _WIN32
  12695. reinterpret_cast<const char *>(&opt),
  12696. #else
  12697. &opt,
  12698. #endif
  12699. sizeof(opt));
  12700. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12701. ::listen(srv, 1);
  12702. sockaddr_in cli_addr{};
  12703. socklen_t cli_len = sizeof(cli_addr);
  12704. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12705. if (cli != INVALID_SOCKET) {
  12706. char buf[4096];
  12707. ::recv(cli, buf, sizeof(buf), 0);
  12708. // Malicious response: claim a 20GB body but send only a tiny payload.
  12709. std::string response = "HTTP/1.1 200 OK\r\n"
  12710. "Content-Length: 20000000000\r\n"
  12711. "\r\n"
  12712. "abc";
  12713. ::send(cli,
  12714. #ifdef _WIN32
  12715. static_cast<const char *>(response.c_str()),
  12716. static_cast<int>(response.size()),
  12717. #else
  12718. response.c_str(), response.size(),
  12719. #endif
  12720. 0);
  12721. detail::close_socket(cli);
  12722. }
  12723. detail::close_socket(srv);
  12724. });
  12725. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12726. {
  12727. Client cli("127.0.0.1", PORT + 2);
  12728. cli.set_read_timeout(5, 0);
  12729. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12730. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12731. // (server claims more bytes than payload_max_length permits), but it must
  12732. // not exhaust memory before getting there.
  12733. auto res = cli.Get("/malicious");
  12734. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12735. }
  12736. server_thread.join();
  12737. }
  12738. // Verify that content_receiver bypasses the default payload_max_length,
  12739. // allowing streaming downloads larger than 100MB without requiring an explicit
  12740. // set_payload_max_length call.
  12741. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12742. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12743. #ifndef _WIN32
  12744. signal(SIGPIPE, SIG_IGN);
  12745. #endif
  12746. auto server_thread = std::thread([] {
  12747. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12748. default_socket_options(srv);
  12749. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12750. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12751. sockaddr_in addr{};
  12752. addr.sin_family = AF_INET;
  12753. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12754. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12755. int opt = 1;
  12756. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12757. #ifdef _WIN32
  12758. reinterpret_cast<const char *>(&opt),
  12759. #else
  12760. &opt,
  12761. #endif
  12762. sizeof(opt));
  12763. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12764. ::listen(srv, 1);
  12765. sockaddr_in cli_addr{};
  12766. socklen_t cli_len = sizeof(cli_addr);
  12767. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12768. if (cli != INVALID_SOCKET) {
  12769. char buf[4096];
  12770. ::recv(cli, buf, sizeof(buf), 0);
  12771. // Response with Content-Length larger than default 100MB limit
  12772. auto content_length = std::to_string(DATA_SIZE);
  12773. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12774. "Content-Length: " +
  12775. content_length +
  12776. "\r\n"
  12777. "Connection: close\r\n"
  12778. "\r\n";
  12779. ::send(cli,
  12780. #ifdef _WIN32
  12781. static_cast<const char *>(response_header.c_str()),
  12782. static_cast<int>(response_header.size()),
  12783. #else
  12784. response_header.c_str(), response_header.size(),
  12785. #endif
  12786. 0);
  12787. std::string chunk(64 * 1024, 'A');
  12788. size_t total_sent = 0;
  12789. while (total_sent < DATA_SIZE) {
  12790. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12791. auto sent = ::send(cli,
  12792. #ifdef _WIN32
  12793. static_cast<const char *>(chunk.c_str()),
  12794. static_cast<int>(to_send),
  12795. #else
  12796. chunk.c_str(), to_send,
  12797. #endif
  12798. 0);
  12799. if (sent <= 0) break;
  12800. total_sent += static_cast<size_t>(sent);
  12801. }
  12802. detail::close_socket(cli);
  12803. }
  12804. detail::close_socket(srv);
  12805. });
  12806. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12807. size_t total_received = 0;
  12808. {
  12809. Client cli("127.0.0.1", PORT + 2);
  12810. cli.set_read_timeout(10, 0);
  12811. // Do NOT call set_payload_max_length — use the default 100MB limit
  12812. auto res =
  12813. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12814. total_received += data_length;
  12815. return true;
  12816. });
  12817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12818. EXPECT_EQ(StatusCode::OK_200, res->status);
  12819. }
  12820. server_thread.join();
  12821. EXPECT_EQ(total_received, DATA_SIZE)
  12822. << "With content_receiver, the client should read all " << DATA_SIZE
  12823. << " bytes despite the default 100MB payload_max_length, but only read "
  12824. << total_received << " bytes.";
  12825. }
  12826. // Verify that an explicit set_payload_max_length smaller than the response is
  12827. // enforced even when a content_receiver is used.
  12828. TEST(ClientVulnerabilityTest,
  12829. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12830. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12831. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12832. #ifndef _WIN32
  12833. signal(SIGPIPE, SIG_IGN);
  12834. #endif
  12835. auto server_thread = std::thread([] {
  12836. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12837. default_socket_options(srv);
  12838. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12839. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12840. sockaddr_in addr{};
  12841. addr.sin_family = AF_INET;
  12842. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12843. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12844. int opt = 1;
  12845. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12846. #ifdef _WIN32
  12847. reinterpret_cast<const char *>(&opt),
  12848. #else
  12849. &opt,
  12850. #endif
  12851. sizeof(opt));
  12852. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12853. ::listen(srv, 1);
  12854. sockaddr_in cli_addr{};
  12855. socklen_t cli_len = sizeof(cli_addr);
  12856. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12857. if (cli != INVALID_SOCKET) {
  12858. char buf[4096];
  12859. ::recv(cli, buf, sizeof(buf), 0);
  12860. auto content_length = std::to_string(DATA_SIZE);
  12861. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12862. "Content-Length: " +
  12863. content_length +
  12864. "\r\n"
  12865. "Connection: close\r\n"
  12866. "\r\n";
  12867. ::send(cli,
  12868. #ifdef _WIN32
  12869. static_cast<const char *>(response_header.c_str()),
  12870. static_cast<int>(response_header.size()),
  12871. #else
  12872. response_header.c_str(), response_header.size(),
  12873. #endif
  12874. 0);
  12875. std::string chunk(64 * 1024, 'A');
  12876. size_t total_sent = 0;
  12877. while (total_sent < DATA_SIZE) {
  12878. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12879. auto sent = ::send(cli,
  12880. #ifdef _WIN32
  12881. static_cast<const char *>(chunk.c_str()),
  12882. static_cast<int>(to_send),
  12883. #else
  12884. chunk.c_str(), to_send,
  12885. #endif
  12886. 0);
  12887. if (sent <= 0) break;
  12888. total_sent += static_cast<size_t>(sent);
  12889. }
  12890. detail::close_socket(cli);
  12891. }
  12892. detail::close_socket(srv);
  12893. });
  12894. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12895. size_t total_received = 0;
  12896. {
  12897. Client cli("127.0.0.1", PORT + 2);
  12898. cli.set_read_timeout(10, 0);
  12899. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12900. auto res =
  12901. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12902. total_received += data_length;
  12903. return true;
  12904. });
  12905. // Should fail because 200MB exceeds the explicit 150MB limit
  12906. EXPECT_FALSE(res);
  12907. }
  12908. server_thread.join();
  12909. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12910. << "Client with content_receiver should respect the explicit "
  12911. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12912. << total_received << " bytes.";
  12913. }
  12914. // Verify that an explicit set_payload_max_length larger than the response
  12915. // allows the content_receiver to read all data successfully.
  12916. TEST(ClientVulnerabilityTest,
  12917. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12918. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12919. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12920. #ifndef _WIN32
  12921. signal(SIGPIPE, SIG_IGN);
  12922. #endif
  12923. auto server_thread = std::thread([] {
  12924. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12925. default_socket_options(srv);
  12926. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12927. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12928. sockaddr_in addr{};
  12929. addr.sin_family = AF_INET;
  12930. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12931. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12932. int opt = 1;
  12933. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12934. #ifdef _WIN32
  12935. reinterpret_cast<const char *>(&opt),
  12936. #else
  12937. &opt,
  12938. #endif
  12939. sizeof(opt));
  12940. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12941. ::listen(srv, 1);
  12942. sockaddr_in cli_addr{};
  12943. socklen_t cli_len = sizeof(cli_addr);
  12944. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12945. if (cli != INVALID_SOCKET) {
  12946. char buf[4096];
  12947. ::recv(cli, buf, sizeof(buf), 0);
  12948. auto content_length = std::to_string(DATA_SIZE);
  12949. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12950. "Content-Length: " +
  12951. content_length +
  12952. "\r\n"
  12953. "Connection: close\r\n"
  12954. "\r\n";
  12955. ::send(cli,
  12956. #ifdef _WIN32
  12957. static_cast<const char *>(response_header.c_str()),
  12958. static_cast<int>(response_header.size()),
  12959. #else
  12960. response_header.c_str(), response_header.size(),
  12961. #endif
  12962. 0);
  12963. std::string chunk(64 * 1024, 'A');
  12964. size_t total_sent = 0;
  12965. while (total_sent < DATA_SIZE) {
  12966. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12967. auto sent = ::send(cli,
  12968. #ifdef _WIN32
  12969. static_cast<const char *>(chunk.c_str()),
  12970. static_cast<int>(to_send),
  12971. #else
  12972. chunk.c_str(), to_send,
  12973. #endif
  12974. 0);
  12975. if (sent <= 0) break;
  12976. total_sent += static_cast<size_t>(sent);
  12977. }
  12978. #ifdef _WIN32
  12979. ::shutdown(cli, SD_SEND);
  12980. #else
  12981. ::shutdown(cli, SHUT_WR);
  12982. #endif
  12983. char drain[1024];
  12984. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12985. detail::close_socket(cli);
  12986. }
  12987. detail::close_socket(srv);
  12988. });
  12989. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12990. size_t total_received = 0;
  12991. {
  12992. Client cli("127.0.0.1", PORT + 2);
  12993. cli.set_read_timeout(10, 0);
  12994. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12995. auto res =
  12996. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12997. total_received += data_length;
  12998. return true;
  12999. });
  13000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13001. EXPECT_EQ(StatusCode::OK_200, res->status);
  13002. }
  13003. server_thread.join();
  13004. EXPECT_EQ(total_received, DATA_SIZE)
  13005. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13006. << " bytes (larger than " << DATA_SIZE
  13007. << " bytes response), content_receiver should read all data, but only "
  13008. "read "
  13009. << total_received << " bytes.";
  13010. }
  13011. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13012. // Regression test for "zip bomb" attack on the client side: a malicious server
  13013. // sends a small gzip-compressed response that decompresses to a huge payload.
  13014. // The client must enforce payload_max_length on the decompressed size.
  13015. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13016. constexpr size_t DECOMPRESSED_SIZE =
  13017. 10 * 1024 * 1024; // 10MB after decompression
  13018. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13019. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13020. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13021. std::string compressed;
  13022. {
  13023. httplib::detail::gzip_compressor compressor;
  13024. bool ok =
  13025. compressor.compress(uncompressed.data(), uncompressed.size(),
  13026. /*last=*/true, [&](const char *buf, size_t len) {
  13027. compressed.append(buf, len);
  13028. return true;
  13029. });
  13030. ASSERT_TRUE(ok);
  13031. }
  13032. // Sanity: compressed data should be much smaller than the decompressed size
  13033. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13034. #ifndef _WIN32
  13035. signal(SIGPIPE, SIG_IGN);
  13036. #endif
  13037. // Set up the listening socket in the main thread so the server is guaranteed
  13038. // to be ready before the client connects (eliminates race condition).
  13039. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13040. default_socket_options(srv);
  13041. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13042. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13043. sockaddr_in addr{};
  13044. addr.sin_family = AF_INET;
  13045. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13046. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13047. int opt = 1;
  13048. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13049. #ifdef _WIN32
  13050. reinterpret_cast<const char *>(&opt),
  13051. #else
  13052. &opt,
  13053. #endif
  13054. sizeof(opt));
  13055. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13056. ASSERT_EQ(0, ::listen(srv, 1));
  13057. auto server_thread = std::thread([&compressed, srv] {
  13058. sockaddr_in cli_addr{};
  13059. socklen_t cli_len = sizeof(cli_addr);
  13060. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13061. if (cli != INVALID_SOCKET) {
  13062. // Read the full HTTP request (until \r\n\r\n)
  13063. char buf[4096];
  13064. size_t total = 0;
  13065. while (total < sizeof(buf)) {
  13066. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13067. if (n <= 0) break;
  13068. total += static_cast<size_t>(n);
  13069. // Check for end of headers
  13070. if (total >= 4) {
  13071. std::string req(buf, total);
  13072. if (req.find("\r\n\r\n") != std::string::npos) break;
  13073. }
  13074. }
  13075. // Malicious response: gzip-compressed body, no Content-Length
  13076. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13077. "Content-Encoding: gzip\r\n"
  13078. "Connection: close\r\n"
  13079. "\r\n";
  13080. ::send(cli,
  13081. #ifdef _WIN32
  13082. static_cast<const char *>(response_header.c_str()),
  13083. static_cast<int>(response_header.size()),
  13084. #else
  13085. response_header.c_str(), response_header.size(),
  13086. #endif
  13087. 0);
  13088. // Send the compressed payload (small on the wire, huge when decompressed)
  13089. size_t total_sent = 0;
  13090. while (total_sent < compressed.size()) {
  13091. auto to_send = std::min(compressed.size() - total_sent,
  13092. static_cast<size_t>(64 * 1024));
  13093. auto sent =
  13094. ::send(cli,
  13095. #ifdef _WIN32
  13096. static_cast<const char *>(compressed.c_str() + total_sent),
  13097. static_cast<int>(to_send),
  13098. #else
  13099. compressed.c_str() + total_sent, to_send,
  13100. #endif
  13101. 0);
  13102. if (sent <= 0) break;
  13103. total_sent += static_cast<size_t>(sent);
  13104. }
  13105. detail::close_socket(cli);
  13106. }
  13107. });
  13108. auto se = detail::scope_exit([&] {
  13109. detail::close_socket(srv);
  13110. server_thread.join();
  13111. });
  13112. size_t total_decompressed = 0;
  13113. {
  13114. Client cli("127.0.0.1", PORT + 3);
  13115. cli.set_read_timeout(5, 0);
  13116. cli.set_decompress(true);
  13117. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13118. auto stream = cli.open_stream("GET", "/zipbomb");
  13119. ASSERT_TRUE(stream.is_valid());
  13120. char buffer[64 * 1024];
  13121. ssize_t n;
  13122. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13123. total_decompressed += static_cast<size_t>(n);
  13124. }
  13125. }
  13126. // The decompressed size must be capped by payload_max_length. Without
  13127. // protection, the client would decompress the full 10MB from a tiny
  13128. // compressed payload, enabling a zip bomb DoS attack.
  13129. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13130. << "Client decompressed " << total_decompressed
  13131. << " bytes from a gzip response. The decompressed size should be "
  13132. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13133. }
  13134. #endif
  13135. TEST(HostAndPortPropertiesTest, NoSSL) {
  13136. httplib::Client cli("www.google.com", 1234);
  13137. ASSERT_EQ("www.google.com", cli.host());
  13138. ASSERT_EQ(1234, cli.port());
  13139. }
  13140. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13141. httplib::Client cli("www.google.com:1234");
  13142. ASSERT_EQ("www.google.com", cli.host());
  13143. ASSERT_EQ(1234, cli.port());
  13144. }
  13145. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13146. // Port number that overflows int — should not crash, client becomes invalid
  13147. httplib::Client cli("http://www.google.com:99999999999999999999");
  13148. ASSERT_FALSE(cli.is_valid());
  13149. }
  13150. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13151. // Port 99999 exceeds valid range (1-65535) — should not crash
  13152. httplib::Client cli("http://www.google.com:99999");
  13153. ASSERT_FALSE(cli.is_valid());
  13154. auto res = cli.Get("/");
  13155. EXPECT_FALSE(res);
  13156. EXPECT_EQ(Error::Connection, res.error());
  13157. }
  13158. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13159. httplib::Client cli("http://user:pass@localhost:1234");
  13160. ASSERT_FALSE(cli.is_valid());
  13161. EXPECT_FALSE(cli.Get("/"));
  13162. }
  13163. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13164. httplib::Client cli("http://www.google.com:80abc");
  13165. ASSERT_FALSE(cli.is_valid());
  13166. }
  13167. #ifdef CPPHTTPLIB_SSL_ENABLED
  13168. TEST(HostAndPortPropertiesTest, SSL) {
  13169. httplib::SSLClient cli("www.google.com");
  13170. ASSERT_EQ("www.google.com", cli.host());
  13171. ASSERT_EQ(443, cli.port());
  13172. }
  13173. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13174. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13175. std::string cert;
  13176. read_file(CA_CERT_FILE, cert);
  13177. httplib::SSLClient httplib_client("www.google.com");
  13178. // Load CA store first time
  13179. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13180. // Load CA store second time (update)
  13181. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13182. // Verify client is still valid and can make connections
  13183. httplib_client.enable_server_certificate_verification(true);
  13184. auto res = httplib_client.Get("/");
  13185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13186. // Google may return 200 or 301 depending on various factors
  13187. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13188. res->status == StatusCode::MovedPermanently_301);
  13189. }
  13190. TEST(SSLClientTest, ServerNameIndication_Online) {
  13191. auto host = "httpbingo.org";
  13192. auto path = std::string{"/get"};
  13193. SSLClient cli(host, 443);
  13194. auto res = cli.Get(path);
  13195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13196. ASSERT_EQ(StatusCode::OK_200, res->status);
  13197. }
  13198. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13199. // Use a site that will cause SSL verification failure due to self-signed cert
  13200. SSLClient cli("self-signed.badssl.com", 443);
  13201. cli.enable_server_certificate_verification(true);
  13202. auto res = cli.Get("/");
  13203. ASSERT_TRUE(!res);
  13204. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13205. // Verify backend error is captured for SSLServerVerification
  13206. // This occurs when certificate verification fails
  13207. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13208. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13209. EXPECT_NE(0UL, res.ssl_backend_error());
  13210. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13211. // For OpenSSL, ssl_error is 0 for verification errors
  13212. EXPECT_EQ(0, res.ssl_error());
  13213. #if !defined(_WIN32) || \
  13214. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13215. // On non-Windows or when Windows Schannel is disabled, the error comes
  13216. // from OpenSSL's verification
  13217. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13218. res.ssl_backend_error());
  13219. #endif
  13220. #endif
  13221. }
  13222. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13223. // Use a site where hostname doesn't match the certificate
  13224. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13225. SSLClient cli("wrong.host.badssl.com", 443);
  13226. cli.enable_server_certificate_verification(true);
  13227. cli.enable_server_hostname_verification(true);
  13228. auto res = cli.Get("/");
  13229. ASSERT_TRUE(!res);
  13230. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13231. // Verify backend error is captured for hostname verification failure
  13232. EXPECT_NE(0UL, res.ssl_backend_error());
  13233. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13234. // For OpenSSL, ssl_error is 0 for verification errors
  13235. EXPECT_EQ(0, res.ssl_error());
  13236. #if !defined(_WIN32) || \
  13237. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13238. // On non-Windows or when Windows Schannel is disabled, the error comes
  13239. // from OpenSSL's hostname verification
  13240. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13241. res.ssl_backend_error());
  13242. #endif
  13243. #endif
  13244. }
  13245. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13246. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13247. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13248. SSLClient cli("www.google.com", 443);
  13249. cli.enable_server_certificate_verification(true);
  13250. auto res = cli.Get("/");
  13251. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13252. }
  13253. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13254. SSLClient cli("www.google.com", 443);
  13255. cli.enable_server_certificate_verification(true);
  13256. cli.enable_windows_certificate_verification(false);
  13257. auto res = cli.Get("/");
  13258. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13259. }
  13260. // The server sends an intermediate cross-signed by a root Windows trusts,
  13261. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13262. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13263. SSLClient cli("accounts.spotify.com", 443);
  13264. auto res = cli.Get("/");
  13265. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13266. << " ssl_backend_error=" << res.ssl_backend_error();
  13267. }
  13268. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13269. // policy status, which no backend reports for a self-signed certificate.
  13270. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13271. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13272. ASSERT_TRUE(svr.is_valid());
  13273. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13274. auto se = detail::scope_exit([&] {
  13275. svr.stop();
  13276. t.join();
  13277. ASSERT_FALSE(svr.is_running());
  13278. });
  13279. svr.wait_until_ready();
  13280. SSLClient cli("127.0.0.1", PORT);
  13281. cli.set_connection_timeout(30);
  13282. auto res = cli.Get("/");
  13283. ASSERT_FALSE(res);
  13284. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13285. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13286. }
  13287. #endif
  13288. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13289. Client cli("https://google.com");
  13290. auto res = cli.Get("/");
  13291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13292. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13293. }
  13294. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13295. SSLClient cli("google.com");
  13296. cli.set_ca_cert_path(CA_CERT_FILE);
  13297. auto res = cli.Get("/");
  13298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13299. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13300. }
  13301. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13302. SSLClient cli("google.com");
  13303. cli.enable_server_certificate_verification(true);
  13304. cli.set_ca_cert_path("hello");
  13305. auto res = cli.Get("/");
  13306. ASSERT_TRUE(!res);
  13307. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13308. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13309. // should be set
  13310. EXPECT_EQ(0, res.ssl_error());
  13311. // Verify backend error is captured for SSLLoadingCerts
  13312. // This error occurs when loading CA certificates fails
  13313. EXPECT_NE(0UL, res.ssl_backend_error());
  13314. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13315. // OpenSSL specific error codes:
  13316. // > openssl errstr 0x80000002
  13317. // error:80000002:system library::No such file or directory
  13318. // > openssl errstr 0xA000126
  13319. // error:0A000126:SSL routines::unexpected eof while reading
  13320. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13321. res.ssl_backend_error() == 0xA000126);
  13322. #endif
  13323. }
  13324. TEST(SSLClientTest, ServerCertificateVerification4) {
  13325. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13326. ASSERT_TRUE(svr.is_valid());
  13327. svr.Get("/test", [&](const Request &, Response &res) {
  13328. res.set_content("test", "text/plain");
  13329. svr.stop();
  13330. ASSERT_TRUE(true);
  13331. });
  13332. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13333. auto se = detail::scope_exit([&] {
  13334. t.join();
  13335. ASSERT_FALSE(svr.is_running());
  13336. });
  13337. svr.wait_until_ready();
  13338. SSLClient cli("127.0.0.1", PORT);
  13339. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13340. cli.enable_server_certificate_verification(true);
  13341. cli.set_connection_timeout(30);
  13342. auto res = cli.Get("/test");
  13343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13344. ASSERT_EQ(StatusCode::OK_200, res->status);
  13345. }
  13346. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13347. std::string cert;
  13348. read_file(CA_CERT_FILE, cert);
  13349. SSLClient cli("google.com");
  13350. cli.load_ca_cert_store(cert.data(), cert.size());
  13351. const auto res = cli.Get("/");
  13352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13353. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13354. }
  13355. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13356. // clang-format off
  13357. static constexpr char cert[] =
  13358. "GlobalSign Root CA\n"
  13359. "==================\n"
  13360. "-----BEGIN CERTIFICATE-----\n"
  13361. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13362. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13363. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13364. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13365. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13366. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13367. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13368. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13369. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13370. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13371. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13372. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13373. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13374. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13375. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13376. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13377. "-----END CERTIFICATE-----\n";
  13378. // clang-format on
  13379. SSLClient cli("google.com");
  13380. cli.load_ca_cert_store(cert, sizeof(cert));
  13381. const auto res = cli.Get("/");
  13382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13383. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13384. }
  13385. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13386. SSLClient cli("www.youtube.com");
  13387. cli.set_ca_cert_path(CA_CERT_FILE);
  13388. cli.enable_server_certificate_verification(true);
  13389. cli.set_follow_location(true);
  13390. auto res = cli.Get("/");
  13391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13392. ASSERT_EQ(StatusCode::OK_200, res->status);
  13393. }
  13394. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13395. SSLClient cli("wWw.YouTube.Com");
  13396. cli.set_ca_cert_path(CA_CERT_FILE);
  13397. cli.enable_server_certificate_verification(true);
  13398. cli.enable_server_hostname_verification(true);
  13399. cli.set_follow_location(true);
  13400. auto res = cli.Get("/");
  13401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13402. ASSERT_EQ(StatusCode::OK_200, res->status);
  13403. }
  13404. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13405. SSLClient cli("gOoGlE.COm");
  13406. cli.enable_server_certificate_verification(true);
  13407. cli.enable_server_hostname_verification(true);
  13408. cli.set_follow_location(true);
  13409. auto res = cli.Get("/");
  13410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13411. ASSERT_EQ(StatusCode::OK_200, res->status);
  13412. }
  13413. TEST(SSLClientTest, Issue2004_Online) {
  13414. Client client("https://google.com");
  13415. client.set_follow_location(true);
  13416. auto res = client.Get("/");
  13417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13418. ASSERT_EQ(StatusCode::OK_200, res->status);
  13419. auto body = res->body;
  13420. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13421. }
  13422. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13423. // Create SSLClient with invalid cert/key to make is_valid() return false
  13424. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13425. "nonexistent_key.pem");
  13426. // is_valid() should be false due to cert loading failure
  13427. ASSERT_FALSE(cli.is_valid());
  13428. auto res = cli.Get("/");
  13429. ASSERT_FALSE(res);
  13430. EXPECT_EQ(Error::SSLConnection, res.error());
  13431. }
  13432. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13433. // Test for Issue #2251: SSL error not properly reported when client cert
  13434. // and key paths are swapped or mismatched
  13435. // This simulates the scenario where user accidentally swaps the cert and key
  13436. // files
  13437. // Using client cert file as private key and vice versa (completely wrong)
  13438. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13439. // Should fail validation due to cert/key mismatch
  13440. ASSERT_FALSE(cli.is_valid());
  13441. // Attempt to make a request should fail with proper error
  13442. auto res = cli.Get("/");
  13443. ASSERT_FALSE(res);
  13444. EXPECT_EQ(Error::SSLConnection, res.error());
  13445. // SSL error should be recorded in the Result object (this is the key fix for
  13446. // Issue #2251)
  13447. auto backend_error = res.ssl_backend_error();
  13448. EXPECT_NE(0u, backend_error);
  13449. }
  13450. // Tests cert/key mismatch detection at the TLS context level
  13451. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13452. // Test that using mismatched cert/key causes connection failure.
  13453. // We verify this at the SSLClient level rather than through internal
  13454. // TLS API functions.
  13455. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13456. cli.enable_server_certificate_verification(false);
  13457. cli.set_connection_timeout(2);
  13458. // The mismatch should cause a connection or handshake error
  13459. auto res = cli.Get("/test");
  13460. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13461. // Either way, the request should fail
  13462. EXPECT_FALSE(res);
  13463. }
  13464. #endif
  13465. #if 0
  13466. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13467. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13468. ASSERT_TRUE(cli != nullptr);
  13469. cli->set_address_family(AF_INET6);
  13470. cli->set_interface("en0");
  13471. auto res = cli->Get("/get");
  13472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13473. ASSERT_EQ(StatusCode::OK_200, res->status);
  13474. }
  13475. #endif
  13476. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13477. #ifdef CPPHTTPLIB_SSL_ENABLED
  13478. void ClientCertPresent(
  13479. const std::string &client_cert_file,
  13480. const std::string &client_private_key_file,
  13481. const std::string &client_encrypted_private_key_pass = std::string()) {
  13482. using namespace httplib::tls;
  13483. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13484. CLIENT_CA_CERT_DIR);
  13485. ASSERT_TRUE(svr.is_valid());
  13486. svr.Get("/test", [&](const Request &req, Response &res) {
  13487. res.set_content("test", "text/plain");
  13488. auto cert = req.peer_cert();
  13489. ASSERT_TRUE(static_cast<bool>(cert));
  13490. std::string common_name = cert.subject_cn();
  13491. EXPECT_EQ("Common Name", common_name);
  13492. });
  13493. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13494. auto se = detail::scope_exit([&] {
  13495. svr.stop();
  13496. t.join();
  13497. ASSERT_FALSE(svr.is_running());
  13498. });
  13499. svr.wait_until_ready();
  13500. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13501. client_encrypted_private_key_pass);
  13502. cli.enable_server_certificate_verification(false);
  13503. cli.set_connection_timeout(30);
  13504. auto res = cli.Get("/test");
  13505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13506. ASSERT_EQ(StatusCode::OK_200, res->status);
  13507. }
  13508. TEST(SSLClientServerTest, ClientCertPresent) {
  13509. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13510. }
  13511. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13512. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13513. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13514. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13515. }
  13516. // PEM memory-based constructor tests (works with all TLS backends)
  13517. void PemMemoryClientCertPresent(
  13518. const std::string &client_cert_file,
  13519. const std::string &client_private_key_file,
  13520. const std::string &client_encrypted_private_key_pass = std::string()) {
  13521. // Read PEM files into memory
  13522. std::string server_cert_pem, server_key_pem;
  13523. std::string client_ca_pem;
  13524. std::string client_cert_pem, client_key_pem;
  13525. read_file(SERVER_CERT_FILE, server_cert_pem);
  13526. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13527. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13528. read_file(client_cert_file, client_cert_pem);
  13529. read_file(client_private_key_file, client_key_pem);
  13530. // Create server with PEM memory
  13531. SSLServer::PemMemory server_pem = {
  13532. server_cert_pem.c_str(),
  13533. server_cert_pem.size(),
  13534. server_key_pem.c_str(),
  13535. server_key_pem.size(),
  13536. client_ca_pem.c_str(),
  13537. client_ca_pem.size(),
  13538. nullptr // no password for server key
  13539. };
  13540. SSLServer svr(server_pem);
  13541. ASSERT_TRUE(svr.is_valid());
  13542. svr.Get("/test", [&](const Request &, Response &res) {
  13543. res.set_content("test", "text/plain");
  13544. });
  13545. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13546. auto se = detail::scope_exit([&] {
  13547. svr.stop();
  13548. t.join();
  13549. ASSERT_FALSE(svr.is_running());
  13550. });
  13551. svr.wait_until_ready();
  13552. // Create client with PEM memory
  13553. const char *password = client_encrypted_private_key_pass.empty()
  13554. ? nullptr
  13555. : client_encrypted_private_key_pass.c_str();
  13556. SSLClient::PemMemory client_pem = {
  13557. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13558. client_key_pem.size(), password};
  13559. SSLClient cli(HOST, PORT, client_pem);
  13560. cli.enable_server_certificate_verification(false);
  13561. cli.set_connection_timeout(30);
  13562. auto res = cli.Get("/test");
  13563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13564. ASSERT_EQ(StatusCode::OK_200, res->status);
  13565. }
  13566. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13567. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13568. }
  13569. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13570. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13571. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13572. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13573. }
  13574. TEST(SSLClientServerTest, ClientCertMissing) {
  13575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13576. CLIENT_CA_CERT_DIR);
  13577. ASSERT_TRUE(svr.is_valid());
  13578. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13580. auto se = detail::scope_exit([&] {
  13581. svr.stop();
  13582. t.join();
  13583. ASSERT_FALSE(svr.is_running());
  13584. });
  13585. svr.wait_until_ready();
  13586. SSLClient cli(HOST, PORT);
  13587. cli.set_connection_timeout(30);
  13588. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13589. // the chain check on Windows, so the result does not depend on the order.
  13590. cli.enable_server_hostname_verification(false);
  13591. auto res = cli.Get("/test");
  13592. ASSERT_TRUE(!res);
  13593. // When client cert is missing and server requires it, connection fails
  13594. // Error type depends on backend implementation
  13595. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13596. res.error() == Error::SSLConnection);
  13597. // Verify backend error is captured
  13598. // Note: This test may have different error codes depending on the exact
  13599. // verification failure
  13600. EXPECT_NE(0UL, res.ssl_backend_error());
  13601. }
  13602. TEST(SSLClientServerTest, TrustDirOptional) {
  13603. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13604. ASSERT_TRUE(svr.is_valid());
  13605. svr.Get("/test", [&](const Request &, Response &res) {
  13606. res.set_content("test", "text/plain");
  13607. });
  13608. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13609. auto se = detail::scope_exit([&] {
  13610. svr.stop();
  13611. t.join();
  13612. ASSERT_FALSE(svr.is_running());
  13613. });
  13614. svr.wait_until_ready();
  13615. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13616. cli.enable_server_certificate_verification(false);
  13617. cli.set_connection_timeout(30);
  13618. auto res = cli.Get("/test");
  13619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13620. ASSERT_EQ(StatusCode::OK_200, res->status);
  13621. }
  13622. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13623. class NoListenSSLServer : public SSLServer {
  13624. public:
  13625. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13626. const char *client_ca_cert_file_path,
  13627. const char *client_ca_cert_dir_path = nullptr)
  13628. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13629. client_ca_cert_dir_path),
  13630. stop_(false) {}
  13631. std::atomic_bool stop_;
  13632. private:
  13633. bool process_and_close_socket(socket_t /*sock*/) override {
  13634. // Don't create SSL context
  13635. while (!stop_.load()) {
  13636. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13637. }
  13638. return true;
  13639. }
  13640. };
  13641. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13642. CLIENT_CA_CERT_FILE);
  13643. ASSERT_TRUE(svr.is_valid());
  13644. svr.Get("/test", [&](const Request &, Response &res) {
  13645. res.set_content("test", "text/plain");
  13646. });
  13647. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13648. auto se = detail::scope_exit([&] {
  13649. svr.stop_ = true;
  13650. svr.stop();
  13651. t.join();
  13652. ASSERT_FALSE(svr.is_running());
  13653. });
  13654. svr.wait_until_ready();
  13655. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13656. cli.enable_server_certificate_verification(false);
  13657. cli.set_connection_timeout(1);
  13658. auto res = cli.Get("/test");
  13659. ASSERT_TRUE(!res);
  13660. EXPECT_EQ(Error::SSLConnection, res.error());
  13661. // Timeout results in WantRead error code (maps to backend-specific value)
  13662. EXPECT_NE(0, res.ssl_error());
  13663. }
  13664. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13665. // Test SSLServer with client certificate verification using the standard
  13666. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13667. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13668. CLIENT_CA_CERT_DIR);
  13669. ASSERT_TRUE(svr.is_valid());
  13670. svr.Get("/test", [&](const Request &req, Response &res) {
  13671. res.set_content("test", "text/plain");
  13672. auto cert = req.peer_cert();
  13673. ASSERT_TRUE(static_cast<bool>(cert));
  13674. auto common_name = cert.subject_cn();
  13675. EXPECT_EQ("Common Name", common_name);
  13676. });
  13677. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13678. auto se = detail::scope_exit([&] {
  13679. svr.stop();
  13680. t.join();
  13681. ASSERT_FALSE(svr.is_running());
  13682. });
  13683. svr.wait_until_ready();
  13684. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13685. cli.enable_server_certificate_verification(false);
  13686. cli.set_connection_timeout(30);
  13687. auto res = cli.Get("/test");
  13688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13689. ASSERT_EQ(StatusCode::OK_200, res->status);
  13690. }
  13691. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13692. // Verifies that wildcard matching and exact matching work consistently
  13693. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13694. using namespace httplib::tls;
  13695. // We need a running server to test against
  13696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13697. ASSERT_TRUE(svr.is_valid());
  13698. svr.Get("/test", [](const Request &, Response &res) {
  13699. res.set_content("ok", "text/plain");
  13700. });
  13701. thread t([&]() { svr.listen(HOST, PORT); });
  13702. auto se = detail::scope_exit([&] {
  13703. svr.stop();
  13704. t.join();
  13705. });
  13706. svr.wait_until_ready();
  13707. bool verify_callback_called = false;
  13708. bool verify_result_wrong = false;
  13709. SSLClient cli(HOST, PORT);
  13710. cli.enable_server_certificate_verification(true);
  13711. cli.set_ca_cert_path(CA_CERT_FILE);
  13712. cli.set_connection_timeout(5);
  13713. // Note: Test certificate has CN="Common Name", not "localhost"
  13714. bool verify_result_cn = false;
  13715. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13716. verify_callback_called = true;
  13717. if (!ctx.cert) return false;
  13718. // Test 1: "Common Name" should match (our test server cert CN)
  13719. verify_result_cn = ctx.check_hostname("Common Name");
  13720. // Test 2: wrong hostname should not match
  13721. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13722. return true; // Accept for the purpose of this test
  13723. });
  13724. auto res = cli.Get("/test");
  13725. // The request may succeed or fail depending on cert configuration
  13726. // but the callback should have been called
  13727. ASSERT_TRUE(verify_callback_called)
  13728. << "Verify callback should have been called";
  13729. // CN="Common Name" should match our test certificate
  13730. //
  13731. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13732. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13733. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13734. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13735. // <openssl/base.h>, which is included transitively when
  13736. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13737. #if defined(OPENSSL_IS_BORINGSSL)
  13738. EXPECT_FALSE(verify_result_cn)
  13739. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13740. #else
  13741. EXPECT_TRUE(verify_result_cn)
  13742. << "verify_hostname should match 'Common Name' (certificate CN)";
  13743. #endif
  13744. // Wrong hostname should not match
  13745. EXPECT_FALSE(verify_result_wrong)
  13746. << "verify_hostname should not match 'wronghost.example.com'";
  13747. }
  13748. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13749. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13750. // X509_check_ip behavior and must hold for every backend.
  13751. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13752. using namespace httplib::tls;
  13753. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13754. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13755. ASSERT_TRUE(svr.is_valid());
  13756. svr.Get("/test", [](const Request &, Response &res) {
  13757. res.set_content("ok", "text/plain");
  13758. });
  13759. thread t([&]() { svr.listen(HOST, PORT); });
  13760. auto se = detail::scope_exit([&] {
  13761. svr.stop();
  13762. t.join();
  13763. });
  13764. svr.wait_until_ready();
  13765. bool verify_callback_called = false;
  13766. bool ip_matched_via_cn = true;
  13767. SSLClient cli(HOST, PORT);
  13768. cli.enable_server_certificate_verification(true);
  13769. cli.set_ca_cert_path(CA_CERT_FILE);
  13770. cli.set_connection_timeout(5);
  13771. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13772. verify_callback_called = true;
  13773. if (!ctx.cert) return false;
  13774. // The IP appears only in the CN, so it must NOT be accepted.
  13775. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13776. return true; // Accept for the purpose of this test
  13777. });
  13778. cli.Get("/test");
  13779. ASSERT_TRUE(verify_callback_called)
  13780. << "Verify callback should have been called";
  13781. EXPECT_FALSE(ip_matched_via_cn)
  13782. << "An IP host must not be authenticated via the certificate CN";
  13783. }
  13784. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13785. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13786. using namespace httplib::tls;
  13787. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13788. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13789. ASSERT_TRUE(svr.is_valid());
  13790. svr.Get("/test", [](const Request &, Response &res) {
  13791. res.set_content("ok", "text/plain");
  13792. });
  13793. thread t([&]() { svr.listen(HOST, PORT); });
  13794. auto se = detail::scope_exit([&] {
  13795. svr.stop();
  13796. t.join();
  13797. });
  13798. svr.wait_until_ready();
  13799. bool verify_callback_called = false;
  13800. bool san_matched = false;
  13801. bool wrong_ipv6_matched = true;
  13802. bool cn_ipv6_matched = true;
  13803. SSLClient cli(HOST, PORT);
  13804. cli.enable_server_certificate_verification(true);
  13805. cli.set_ca_cert_path(CA_CERT_FILE);
  13806. cli.set_connection_timeout(5);
  13807. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13808. verify_callback_called = true;
  13809. if (!ctx.cert) return false;
  13810. // Matches the IPv6 iPAddress SAN.
  13811. san_matched = ctx.check_hostname("2001:db8::1");
  13812. // A different IPv6 address must not match.
  13813. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13814. // "::1" lives only in the CN, so it must not be accepted.
  13815. cn_ipv6_matched = ctx.check_hostname("::1");
  13816. return true; // Accept for the purpose of this test
  13817. });
  13818. cli.Get("/test");
  13819. ASSERT_TRUE(verify_callback_called)
  13820. << "Verify callback should have been called";
  13821. EXPECT_TRUE(san_matched)
  13822. << "verify_hostname should match an IPv6 iPAddress SAN";
  13823. EXPECT_FALSE(wrong_ipv6_matched)
  13824. << "verify_hostname should not match a non-matching IPv6 address";
  13825. EXPECT_FALSE(cn_ipv6_matched)
  13826. << "An IPv6 host must not be authenticated via the certificate CN";
  13827. }
  13828. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13829. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13830. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13831. using namespace httplib::tls;
  13832. // SANs: DNS:a.zz, IP:42.46.122.122
  13833. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13834. ASSERT_TRUE(svr.is_valid());
  13835. svr.Get("/test", [](const Request &, Response &res) {
  13836. res.set_content("ok", "text/plain");
  13837. });
  13838. auto port = svr.bind_to_any_port(HOST);
  13839. thread t([&]() { svr.listen_after_bind(); });
  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 dns_san_matched = false;
  13847. bool ip_san_matched = false;
  13848. bool ip_matched_via_dns_san = true;
  13849. bool dns_matched_via_ip_san = true;
  13850. bool cn_matched_next_to_dns_san = true;
  13851. SSLClient cli(HOST, port);
  13852. cli.enable_server_certificate_verification(true);
  13853. cli.set_ca_cert_path(CA_CERT_FILE);
  13854. cli.set_connection_timeout(5);
  13855. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13856. verify_callback_called = true;
  13857. if (!ctx.cert) return false;
  13858. dns_san_matched = ctx.check_hostname("a.zz");
  13859. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13860. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13861. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13862. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  13863. return true; // Accept for the purpose of this test
  13864. });
  13865. cli.Get("/test");
  13866. ASSERT_TRUE(verify_callback_called)
  13867. << "Verify callback should have been called";
  13868. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13869. EXPECT_TRUE(ip_san_matched)
  13870. << "verify_hostname should match an iPAddress SAN";
  13871. EXPECT_FALSE(ip_matched_via_dns_san)
  13872. << "An IP host must not be authenticated via a dNSName SAN";
  13873. EXPECT_FALSE(dns_matched_via_ip_san)
  13874. << "A DNS host must not be authenticated via an iPAddress SAN";
  13875. EXPECT_FALSE(cn_matched_next_to_dns_san)
  13876. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  13877. }
  13878. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13879. // "www.*.example.test" names one host and not every host under example.test.
  13880. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13881. using namespace httplib::tls;
  13882. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13883. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13884. ASSERT_TRUE(svr.is_valid());
  13885. svr.Get("/test", [](const Request &, Response &res) {
  13886. res.set_content("ok", "text/plain");
  13887. });
  13888. auto port = svr.bind_to_any_port(HOST);
  13889. thread t([&]() { svr.listen_after_bind(); });
  13890. auto se = detail::scope_exit([&] {
  13891. svr.stop();
  13892. t.join();
  13893. });
  13894. svr.wait_until_ready();
  13895. bool verify_callback_called = false;
  13896. bool leftmost_wildcard_matched = false;
  13897. bool wildcard_spanned_labels = true;
  13898. bool inner_wildcard_matched = true;
  13899. SSLClient cli(HOST, port);
  13900. cli.enable_server_certificate_verification(true);
  13901. cli.set_ca_cert_path(CA_CERT_FILE);
  13902. cli.set_connection_timeout(5);
  13903. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13904. verify_callback_called = true;
  13905. if (!ctx.cert) return false;
  13906. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13907. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13908. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  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(leftmost_wildcard_matched)
  13915. << "A leftmost wildcard should match a single label";
  13916. EXPECT_FALSE(wildcard_spanned_labels)
  13917. << "A wildcard label must not match more than one label";
  13918. EXPECT_FALSE(inner_wildcard_matched)
  13919. << "A wildcard outside the leftmost label must not be honoured";
  13920. }
  13921. // sans() must report each SAN entry under its own type.
  13922. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13923. using namespace httplib::tls;
  13924. // SANs: DNS:a.zz, IP:42.46.122.122
  13925. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13926. ASSERT_TRUE(svr.is_valid());
  13927. svr.Get("/test", [](const Request &, Response &res) {
  13928. res.set_content("ok", "text/plain");
  13929. });
  13930. auto port = svr.bind_to_any_port(HOST);
  13931. thread t([&]() { svr.listen_after_bind(); });
  13932. auto se = detail::scope_exit([&] {
  13933. svr.stop();
  13934. t.join();
  13935. });
  13936. svr.wait_until_ready();
  13937. bool verify_callback_called = false;
  13938. std::vector<SanEntry> sans;
  13939. SSLClient cli(HOST, port);
  13940. cli.enable_server_certificate_verification(true);
  13941. cli.set_ca_cert_path(CA_CERT_FILE);
  13942. cli.set_connection_timeout(5);
  13943. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13944. verify_callback_called = true;
  13945. if (!ctx.cert) return false;
  13946. sans = ctx.sans();
  13947. return true; // Accept for the purpose of this test
  13948. });
  13949. cli.Get("/test");
  13950. ASSERT_TRUE(verify_callback_called)
  13951. << "Verify callback should have been called";
  13952. auto has_san = [&](SanType type, const std::string &value) {
  13953. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13954. return san.type == type && san.value == value;
  13955. });
  13956. };
  13957. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13958. << "sans() should report the dNSName SAN";
  13959. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13960. << "sans() should report the iPAddress SAN";
  13961. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13962. << "sans() must not report the dNSName SAN as an address";
  13963. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13964. << "sans() must not report the iPAddress SAN as a DNS name";
  13965. }
  13966. #endif
  13967. // mbedTLS-specific callback constructor test
  13968. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13969. #ifdef CPPHTTPLIB_SSL_ENABLED
  13970. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13971. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13972. ASSERT_TRUE(svr.is_valid());
  13973. // Set up a handler to verify client certificate is present
  13974. bool client_cert_verified = false;
  13975. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13976. // Verify that client certificate was provided
  13977. client_cert_verified = true;
  13978. res.set_content("success", "text/plain");
  13979. });
  13980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13981. auto se = detail::scope_exit([&] {
  13982. svr.stop();
  13983. t.join();
  13984. ASSERT_FALSE(svr.is_running());
  13985. });
  13986. svr.wait_until_ready();
  13987. // Client with certificate
  13988. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13989. cli.enable_server_certificate_verification(false);
  13990. cli.set_connection_timeout(30);
  13991. auto res = cli.Get("/test");
  13992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13993. ASSERT_EQ(StatusCode::OK_200, res->status);
  13994. ASSERT_TRUE(client_cert_verified);
  13995. EXPECT_EQ("success", res->body);
  13996. }
  13997. #endif
  13998. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13999. // backends
  14000. #ifdef CPPHTTPLIB_SSL_ENABLED
  14001. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14002. using namespace httplib::tls;
  14003. // Test that when client CA cert file is provided,
  14004. // the server properly requests and validates client certificates
  14005. // Create a server with client authentication
  14006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14007. ASSERT_TRUE(svr.is_valid());
  14008. bool handler_called = false;
  14009. svr.Get("/test", [&](const Request &req, Response &res) {
  14010. handler_called = true;
  14011. // Verify that a client certificate was provided
  14012. auto cert = req.peer_cert();
  14013. ASSERT_TRUE(static_cast<bool>(cert));
  14014. // Get the issuer name
  14015. std::string issuer_str = cert.issuer_name();
  14016. ASSERT_FALSE(issuer_str.empty());
  14017. // The client certificate should be issued by our test CA
  14018. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14019. res.set_content("authenticated", "text/plain");
  14020. });
  14021. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14022. auto se = detail::scope_exit([&] {
  14023. svr.stop();
  14024. t.join();
  14025. ASSERT_FALSE(svr.is_running());
  14026. });
  14027. svr.wait_until_ready();
  14028. // Connect with a client certificate issued by the CA
  14029. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14030. cli.enable_server_certificate_verification(false);
  14031. cli.set_connection_timeout(30);
  14032. auto res = cli.Get("/test");
  14033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14034. ASSERT_EQ(StatusCode::OK_200, res->status);
  14035. ASSERT_TRUE(handler_called);
  14036. EXPECT_EQ("authenticated", res->body);
  14037. }
  14038. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14039. using namespace httplib::tls;
  14040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14041. ASSERT_TRUE(svr.is_valid());
  14042. svr.Get("/test", [](const Request &, Response &res) {
  14043. res.set_content("ok", "text/plain");
  14044. });
  14045. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14046. auto se = detail::scope_exit([&] {
  14047. svr.stop();
  14048. t.join();
  14049. });
  14050. svr.wait_until_ready();
  14051. SSLClient cli(HOST, PORT);
  14052. cli.enable_server_certificate_verification(false);
  14053. cli.set_connection_timeout(30);
  14054. bool cert_checked = false;
  14055. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14056. if (ctx.cert) {
  14057. auto sans = ctx.sans();
  14058. // Test certificate may or may not have SANs - just verify the API
  14059. // works If SANs exist, verify the types are valid
  14060. for (const auto &san : sans) {
  14061. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14062. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14063. san.type == SanType::OTHER);
  14064. EXPECT_FALSE(san.value.empty());
  14065. }
  14066. cert_checked = true;
  14067. }
  14068. return true;
  14069. });
  14070. auto res = cli.Get("/test");
  14071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14072. EXPECT_TRUE(cert_checked);
  14073. }
  14074. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14075. using namespace httplib::tls;
  14076. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14077. ASSERT_TRUE(svr.is_valid());
  14078. svr.Get("/test", [](const Request &, Response &res) {
  14079. res.set_content("ok", "text/plain");
  14080. });
  14081. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14082. auto se = detail::scope_exit([&] {
  14083. svr.stop();
  14084. t.join();
  14085. });
  14086. svr.wait_until_ready();
  14087. SSLClient cli(HOST, PORT);
  14088. cli.enable_server_certificate_verification(false);
  14089. cli.set_connection_timeout(30);
  14090. bool validity_checked = false;
  14091. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14092. if (ctx.cert) {
  14093. time_t not_before = 0, not_after = 0;
  14094. bool result = ctx.validity(not_before, not_after);
  14095. EXPECT_TRUE(result);
  14096. // Verify that not_before < now < not_after for a valid cert
  14097. time_t now = time(nullptr);
  14098. EXPECT_LT(not_before, now);
  14099. EXPECT_GT(not_after, now);
  14100. validity_checked = true;
  14101. }
  14102. return true;
  14103. });
  14104. auto res = cli.Get("/test");
  14105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14106. EXPECT_TRUE(validity_checked);
  14107. }
  14108. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14109. using namespace httplib::tls;
  14110. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14111. ASSERT_TRUE(svr.is_valid());
  14112. svr.Get("/test", [](const Request &, Response &res) {
  14113. res.set_content("ok", "text/plain");
  14114. });
  14115. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14116. auto se = detail::scope_exit([&] {
  14117. svr.stop();
  14118. t.join();
  14119. });
  14120. svr.wait_until_ready();
  14121. SSLClient cli(HOST, PORT);
  14122. cli.enable_server_certificate_verification(false);
  14123. cli.set_connection_timeout(30);
  14124. bool serial_checked = false;
  14125. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14126. if (ctx.cert) {
  14127. std::string serial = ctx.serial();
  14128. EXPECT_FALSE(serial.empty());
  14129. // Serial should be a hex string
  14130. for (char c : serial) {
  14131. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14132. (c >= 'a' && c <= 'f'));
  14133. }
  14134. serial_checked = true;
  14135. }
  14136. return true;
  14137. });
  14138. auto res = cli.Get("/test");
  14139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14140. EXPECT_TRUE(serial_checked);
  14141. }
  14142. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14143. // Test 1: Valid CA file - no error should be recorded
  14144. {
  14145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14146. CLIENT_CA_CERT_FILE);
  14147. ASSERT_TRUE(svr.is_valid());
  14148. // With valid setup, last_ssl_error should be 0
  14149. EXPECT_EQ(0, svr.ssl_last_error());
  14150. }
  14151. // Test 2: Invalid CA file content
  14152. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14153. {
  14154. // Create a temporary file with completely invalid content
  14155. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14156. {
  14157. std::ofstream ofs(temp_invalid_ca);
  14158. ofs << "This is not a certificate file at all\n";
  14159. ofs << "Just plain text content\n";
  14160. }
  14161. // Create server with invalid CA file
  14162. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14163. // Clean up temporary file
  14164. std::remove(temp_invalid_ca);
  14165. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14166. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14167. // Note: SSL_CTX_load_verify_locations typically fails first,
  14168. // but our error handling code path is still exercised
  14169. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14170. }
  14171. }
  14172. TEST(VerifyCallbackTest, VerifyContextFields) {
  14173. using namespace httplib::tls;
  14174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14175. ASSERT_TRUE(svr.is_valid());
  14176. svr.Get("/test", [](const Request &, Response &res) {
  14177. res.set_content("ok", "text/plain");
  14178. });
  14179. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14180. auto se = detail::scope_exit([&] {
  14181. svr.stop();
  14182. t.join();
  14183. });
  14184. svr.wait_until_ready();
  14185. SSLClient cli(HOST, PORT);
  14186. cli.enable_server_certificate_verification(false);
  14187. cli.set_connection_timeout(30);
  14188. int callback_count = 0;
  14189. bool saw_leaf_cert = false;
  14190. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14191. if (ctx.cert) {
  14192. callback_count++;
  14193. // We should see at least one certificate (the leaf)
  14194. std::string cn = ctx.subject_cn();
  14195. if (!cn.empty()) { saw_leaf_cert = true; }
  14196. // Verify context fields are populated
  14197. EXPECT_NE(ctx.session, nullptr);
  14198. EXPECT_GE(ctx.depth, 0);
  14199. }
  14200. return true;
  14201. });
  14202. auto res = cli.Get("/test");
  14203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14204. EXPECT_GT(callback_count, 0);
  14205. EXPECT_TRUE(saw_leaf_cert);
  14206. }
  14207. // A verifier belongs to the client that set it, not to the thread that set it.
  14208. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14209. using namespace httplib::tls;
  14210. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14211. ASSERT_TRUE(svr.is_valid());
  14212. svr.Get("/test", [](const Request &, Response &res) {
  14213. res.set_content("ok", "text/plain");
  14214. });
  14215. auto port = svr.bind_to_any_port(HOST);
  14216. thread t([&]() { svr.listen_after_bind(); });
  14217. auto se = detail::scope_exit([&] {
  14218. svr.stop();
  14219. t.join();
  14220. });
  14221. svr.wait_until_ready();
  14222. auto rejecting_calls = 0;
  14223. SSLClient rejecting(HOST, port);
  14224. rejecting.enable_server_certificate_verification(false);
  14225. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14226. rejecting_calls++;
  14227. return false;
  14228. });
  14229. auto accepting_calls = 0;
  14230. SSLClient accepting(HOST, port);
  14231. accepting.enable_server_certificate_verification(false);
  14232. // Set on another thread than the requests below.
  14233. thread([&]() {
  14234. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14235. accepting_calls++;
  14236. return true;
  14237. });
  14238. }).join();
  14239. // Requested on another thread than the verifier was set on.
  14240. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14241. EXPECT_GT(rejecting_calls, 0);
  14242. auto res = accepting.Get("/test");
  14243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14244. EXPECT_GT(accepting_calls, 0);
  14245. }
  14246. // A verifier replaced while a handshake runs it lives until it returns.
  14247. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14248. using namespace httplib::tls;
  14249. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14250. ASSERT_TRUE(svr.is_valid());
  14251. svr.Get("/test", [](const Request &, Response &res) {
  14252. res.set_content("ok", "text/plain");
  14253. });
  14254. auto port = svr.bind_to_any_port(HOST);
  14255. thread t([&]() { svr.listen_after_bind(); });
  14256. auto se = detail::scope_exit([&] {
  14257. svr.stop();
  14258. t.join();
  14259. });
  14260. svr.wait_until_ready();
  14261. SSLClient cli(HOST, port);
  14262. cli.enable_server_certificate_verification(false);
  14263. std::promise<void> entered;
  14264. std::promise<void> replaced;
  14265. auto replaced_future = replaced.get_future();
  14266. auto first_call = true;
  14267. // Long enough to live on the heap
  14268. std::string expected(64, 'v');
  14269. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14270. if (first_call) {
  14271. first_call = false;
  14272. entered.set_value();
  14273. replaced_future.wait();
  14274. }
  14275. return expected == std::string(64, 'v');
  14276. });
  14277. thread request([&]() {
  14278. auto res = cli.Get("/test");
  14279. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14280. });
  14281. entered.get_future().wait();
  14282. cli.set_server_certificate_verifier(
  14283. [](const VerifyContext &) { return true; });
  14284. replaced.set_value();
  14285. request.join();
  14286. }
  14287. // VerifyContext::session is the same handle the other tls:: functions take.
  14288. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14289. using namespace httplib::tls;
  14290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14291. ASSERT_TRUE(svr.is_valid());
  14292. svr.Get("/test", [](const Request &, Response &res) {
  14293. res.set_content("ok", "text/plain");
  14294. });
  14295. auto port = svr.bind_to_any_port(HOST);
  14296. thread t([&]() { svr.listen_after_bind(); });
  14297. auto se = detail::scope_exit([&] {
  14298. svr.stop();
  14299. t.join();
  14300. });
  14301. svr.wait_until_ready();
  14302. SSLClient cli(HOST, port);
  14303. cli.enable_server_certificate_verification(false);
  14304. session_t verifier_session = nullptr;
  14305. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14306. verifier_session = ctx.session;
  14307. return true;
  14308. });
  14309. session_t session_verifier_session = nullptr;
  14310. cli.set_session_verifier([&](session_t session) {
  14311. session_verifier_session = session;
  14312. return SSLVerifierResponse::NoDecisionMade;
  14313. });
  14314. auto res = cli.Get("/test");
  14315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14316. EXPECT_NE(nullptr, verifier_session);
  14317. EXPECT_EQ(session_verifier_session, verifier_session);
  14318. }
  14319. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14320. using httplib::tls::TlsError;
  14321. // Test that verify_error_to_string returns empty for success
  14322. std::string success_str = TlsError::verify_error_to_string(0);
  14323. EXPECT_TRUE(success_str.empty());
  14324. // Test that verify_error_to_string returns non-empty for error codes
  14325. // Using a common error code (certificate expired)
  14326. std::string error_str =
  14327. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14328. EXPECT_FALSE(error_str.empty());
  14329. }
  14330. TEST(SessionVerifierTest, CertificateAccepted) {
  14331. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14332. ASSERT_TRUE(svr.is_valid());
  14333. svr.Get("/test", [](const Request &, Response &res) {
  14334. res.set_content("ok", "text/plain");
  14335. });
  14336. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14337. auto se = detail::scope_exit([&] {
  14338. svr.stop();
  14339. t.join();
  14340. });
  14341. svr.wait_until_ready();
  14342. SSLClient cli(HOST, PORT);
  14343. cli.enable_server_certificate_verification(false);
  14344. cli.set_connection_timeout(30);
  14345. bool callback_called = false;
  14346. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14347. EXPECT_NE(session, nullptr);
  14348. callback_called = true;
  14349. return SSLVerifierResponse::CertificateAccepted;
  14350. });
  14351. auto res = cli.Get("/test");
  14352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14353. EXPECT_EQ(200, res->status);
  14354. EXPECT_TRUE(callback_called);
  14355. }
  14356. TEST(SessionVerifierTest, CertificateRejected) {
  14357. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14358. ASSERT_TRUE(svr.is_valid());
  14359. svr.Get("/test", [](const Request &, Response &res) {
  14360. res.set_content("ok", "text/plain");
  14361. });
  14362. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14363. auto se = detail::scope_exit([&] {
  14364. svr.stop();
  14365. t.join();
  14366. });
  14367. svr.wait_until_ready();
  14368. SSLClient cli(HOST, PORT);
  14369. cli.enable_server_certificate_verification(false);
  14370. cli.set_connection_timeout(30);
  14371. bool callback_called = false;
  14372. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14373. EXPECT_NE(session, nullptr);
  14374. callback_called = true;
  14375. return SSLVerifierResponse::CertificateRejected;
  14376. });
  14377. auto res = cli.Get("/test");
  14378. EXPECT_FALSE(res);
  14379. EXPECT_TRUE(callback_called);
  14380. }
  14381. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14382. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14383. ASSERT_TRUE(svr.is_valid());
  14384. svr.Get("/test", [](const Request &, Response &res) {
  14385. res.set_content("ok", "text/plain");
  14386. });
  14387. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14388. auto se = detail::scope_exit([&] {
  14389. svr.stop();
  14390. t.join();
  14391. });
  14392. svr.wait_until_ready();
  14393. // NoDecisionMade with verification disabled should succeed (no default check)
  14394. SSLClient cli(HOST, PORT);
  14395. cli.enable_server_certificate_verification(false);
  14396. cli.set_connection_timeout(30);
  14397. bool callback_called = false;
  14398. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14399. EXPECT_NE(session, nullptr);
  14400. callback_called = true;
  14401. return SSLVerifierResponse::NoDecisionMade;
  14402. });
  14403. auto res = cli.Get("/test");
  14404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14405. EXPECT_EQ(200, res->status);
  14406. EXPECT_TRUE(callback_called);
  14407. }
  14408. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14410. ASSERT_TRUE(svr.is_valid());
  14411. svr.Get("/test", [](const Request &, Response &res) {
  14412. res.set_content("ok", "text/plain");
  14413. });
  14414. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14415. auto se = detail::scope_exit([&] {
  14416. svr.stop();
  14417. t.join();
  14418. });
  14419. svr.wait_until_ready();
  14420. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14421. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14422. // so we only check that the request fails, not whether the callback was
  14423. // called.
  14424. SSLClient cli(HOST, PORT);
  14425. cli.enable_server_certificate_verification(true);
  14426. cli.set_connection_timeout(30);
  14427. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14428. EXPECT_NE(session, nullptr);
  14429. return SSLVerifierResponse::NoDecisionMade;
  14430. });
  14431. auto res = cli.Get("/test");
  14432. EXPECT_FALSE(res);
  14433. }
  14434. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14435. // Test SSL server using PemMemory constructor with client CA certificates
  14436. // Read PEM files
  14437. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14438. read_file(SERVER_CERT_FILE, server_cert_pem);
  14439. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14440. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14441. // Create SSLServer with PemMemory constructor including client CA
  14442. SSLServer::PemMemory server_pem = {
  14443. server_cert_pem.c_str(),
  14444. server_cert_pem.size(),
  14445. server_key_pem.c_str(),
  14446. server_key_pem.size(),
  14447. client_ca_pem.c_str(),
  14448. client_ca_pem.size(),
  14449. nullptr // no password for server key
  14450. };
  14451. SSLServer svr(server_pem);
  14452. ASSERT_TRUE(svr.is_valid());
  14453. // No SSL error should be recorded for valid setup
  14454. EXPECT_EQ(0, svr.ssl_last_error());
  14455. // Set up server endpoints
  14456. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14457. res.set_content("ok", "text/plain");
  14458. });
  14459. // Start server in a thread
  14460. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14461. svr.wait_until_ready();
  14462. // Connect with client certificate (using constructor with paths)
  14463. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14464. cli.enable_server_certificate_verification(false);
  14465. auto res = cli.Get("/test-pem-ca");
  14466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14467. EXPECT_EQ(200, res->status);
  14468. EXPECT_EQ("ok", res->body);
  14469. svr.stop();
  14470. server_thread.join();
  14471. }
  14472. #endif
  14473. #ifdef _WIN32
  14474. TEST(CleanupTest, WSACleanup) {
  14475. int ret = WSACleanup();
  14476. ASSERT_EQ(0, ret);
  14477. }
  14478. #endif
  14479. #ifndef CPPHTTPLIB_SSL_ENABLED
  14480. TEST(NoSSLSupport, SimpleInterface) {
  14481. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14482. }
  14483. #endif
  14484. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14485. TEST(InvalidScheme, SimpleInterface) {
  14486. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14487. }
  14488. #endif
  14489. TEST(NoScheme, SimpleInterface) {
  14490. Client cli("yahoo.com:80");
  14491. ASSERT_TRUE(cli.is_valid());
  14492. }
  14493. TEST(SendAPI, SimpleInterface_Online) {
  14494. Client cli("http://yahoo.com");
  14495. Request req;
  14496. req.method = "GET";
  14497. req.path = "/";
  14498. auto res = cli.send(req);
  14499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14500. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14501. }
  14502. TEST(SendAPI, WithParamsInRequest) {
  14503. Server svr;
  14504. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14505. EXPECT_TRUE(req.has_param("test"));
  14506. EXPECT_EQ("test_value", req.get_param_value("test"));
  14507. });
  14508. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14509. auto se = detail::scope_exit([&] {
  14510. svr.stop();
  14511. t.join();
  14512. ASSERT_FALSE(svr.is_running());
  14513. });
  14514. svr.wait_until_ready();
  14515. Client cli(HOST, PORT);
  14516. {
  14517. Request req;
  14518. req.method = "GET";
  14519. req.path = "/";
  14520. req.params.emplace("test", "test_value");
  14521. auto res = cli.send(req);
  14522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14523. }
  14524. {
  14525. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14527. }
  14528. }
  14529. TEST(ClientImplMethods, GetSocketTest) {
  14530. httplib::Server svr;
  14531. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14532. res.status = StatusCode::OK_200;
  14533. });
  14534. auto port = svr.bind_to_any_port("127.0.0.1");
  14535. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14536. auto se = detail::scope_exit([&] {
  14537. svr.stop();
  14538. thread.join();
  14539. ASSERT_FALSE(svr.is_running());
  14540. });
  14541. svr.wait_until_ready();
  14542. {
  14543. httplib::Client cli("127.0.0.1", port);
  14544. cli.set_keep_alive(true);
  14545. // Use the behavior of cpp-httplib of opening the connection
  14546. // only when the first request happens. If that changes,
  14547. // this test would be obsolete.
  14548. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14549. // This also implicitly tests the server. But other tests would fail much
  14550. // earlier than this one to be considered.
  14551. auto res = cli.Get("/");
  14552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14553. EXPECT_EQ(StatusCode::OK_200, res->status);
  14554. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14555. }
  14556. }
  14557. #ifdef CPPHTTPLIB_SSL_ENABLED
  14558. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14559. Client cli("http://yahoo.com");
  14560. auto res = cli.Get("/");
  14561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14562. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14563. cli.set_follow_location(true);
  14564. res = cli.Get("/");
  14565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14566. EXPECT_EQ(StatusCode::OK_200, res->status);
  14567. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14568. }
  14569. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14570. Client cli("https://yahoo.com");
  14571. auto res = cli.Get("/");
  14572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14573. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14574. cli.set_follow_location(true);
  14575. res = cli.Get("/");
  14576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14577. EXPECT_EQ(StatusCode::OK_200, res->status);
  14578. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14579. }
  14580. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14581. Client cli("https://yahoo.com");
  14582. auto res = cli.Get("/");
  14583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14584. ASSERT_FALSE(!res);
  14585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14586. ASSERT_FALSE(res == nullptr);
  14587. ASSERT_TRUE(res != nullptr);
  14588. EXPECT_EQ(Error::Success, res.error());
  14589. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14590. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14591. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14592. cli.set_follow_location(true);
  14593. res = cli.Get("/");
  14594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14595. EXPECT_EQ(Error::Success, res.error());
  14596. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14597. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14598. EXPECT_EQ(StatusCode::OK_200, res->status);
  14599. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14600. }
  14601. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14602. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14603. Client cli("https://cdnjs.cloudflare.com");
  14604. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14605. Headers{{"Accept-Encoding", "br"}});
  14606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14607. EXPECT_EQ(StatusCode::OK_200, res->status);
  14608. EXPECT_EQ(287630U, res->body.size());
  14609. EXPECT_EQ("application/javascript; charset=utf-8",
  14610. res->get_header_value("Content-Type"));
  14611. }
  14612. #endif
  14613. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14614. #undef REDIR_HOST // Silence compiler warning
  14615. #define REDIR_HOST "https://httpbingo.org"
  14616. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14617. Client cli(REDIR_HOST);
  14618. cli.set_follow_location(true);
  14619. auto res =
  14620. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14622. EXPECT_EQ(StatusCode::OK_200, res->status);
  14623. }
  14624. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14625. Client cli(REDIR_HOST);
  14626. cli.set_follow_location(true);
  14627. Params params;
  14628. params.emplace("url", "http://example.com");
  14629. params.emplace("status_code", "302");
  14630. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14632. EXPECT_EQ(StatusCode::OK_200, res->status);
  14633. }
  14634. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14635. Client cli(REDIR_HOST);
  14636. cli.set_follow_location(true);
  14637. Params params;
  14638. params.emplace("url", "http://example.com");
  14639. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14641. EXPECT_EQ(StatusCode::OK_200, res->status);
  14642. }
  14643. TEST(HttpToHttpsRedirectTest, CertFile) {
  14644. auto ssl_port = PORT + 1;
  14645. Server svr;
  14646. ASSERT_TRUE(svr.is_valid());
  14647. svr.Get("/index", [&](const Request &, Response &res) {
  14648. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14649. "/index");
  14650. svr.stop();
  14651. });
  14652. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14653. ASSERT_TRUE(ssl_svr.is_valid());
  14654. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14655. res.set_content("test", "text/plain");
  14656. ssl_svr.stop();
  14657. });
  14658. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14659. thread t2 =
  14660. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14661. auto se = detail::scope_exit([&] {
  14662. t2.join();
  14663. t.join();
  14664. ASSERT_FALSE(svr.is_running());
  14665. });
  14666. svr.wait_until_ready();
  14667. ssl_svr.wait_until_ready();
  14668. Client cli("127.0.0.1", PORT);
  14669. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14670. cli.enable_server_certificate_verification(true);
  14671. cli.set_follow_location(true);
  14672. cli.set_connection_timeout(30);
  14673. auto res = cli.Get("/index");
  14674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14675. ASSERT_EQ(StatusCode::OK_200, res->status);
  14676. }
  14677. TEST(SSLClientRedirectTest, CertFile) {
  14678. auto ssl_port = PORT + 1;
  14679. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14680. ASSERT_TRUE(ssl_svr1.is_valid());
  14681. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14682. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14683. "/index");
  14684. ssl_svr1.stop();
  14685. });
  14686. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14687. ASSERT_TRUE(ssl_svr2.is_valid());
  14688. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14689. res.set_content("test", "text/plain");
  14690. ssl_svr2.stop();
  14691. });
  14692. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14693. thread t2 =
  14694. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14695. auto se = detail::scope_exit([&] {
  14696. t2.join();
  14697. t.join();
  14698. ASSERT_FALSE(ssl_svr1.is_running());
  14699. });
  14700. ssl_svr1.wait_until_ready();
  14701. ssl_svr2.wait_until_ready();
  14702. SSLClient cli("127.0.0.1", PORT);
  14703. std::string cert;
  14704. read_file(SERVER_CERT2_FILE, cert);
  14705. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14706. cli.enable_server_certificate_verification(true);
  14707. cli.set_follow_location(true);
  14708. cli.set_connection_timeout(30);
  14709. auto res = cli.Get("/index");
  14710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14711. ASSERT_EQ(StatusCode::OK_200, res->status);
  14712. }
  14713. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14714. // another port, so the client follows it with a new client.
  14715. static Result GetThroughTlsRedirectToDifferentPort(
  14716. const std::function<void(SSLClient &)> &setup,
  14717. const char *target_cert = SERVER_CERT2_FILE,
  14718. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14719. auto ssl_port = PORT + 1;
  14720. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14721. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14722. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14723. "/index");
  14724. });
  14725. SSLServer ssl_svr2(target_cert, target_key);
  14726. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14727. res.set_content("test", "text/plain");
  14728. });
  14729. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14730. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14731. auto se = detail::scope_exit([&] {
  14732. ssl_svr2.stop();
  14733. ssl_svr1.stop();
  14734. t2.join();
  14735. t.join();
  14736. });
  14737. ssl_svr1.wait_until_ready();
  14738. ssl_svr2.wait_until_ready();
  14739. SSLClient cli("127.0.0.1", PORT);
  14740. cli.set_follow_location(true);
  14741. cli.set_connection_timeout(30);
  14742. setup(cli);
  14743. return cli.Get("/index");
  14744. }
  14745. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14746. auto calls = 0;
  14747. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14748. cli.enable_server_certificate_verification(false);
  14749. // Accept the first server only.
  14750. cli.set_session_verifier([&](tls::session_t) {
  14751. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14752. : SSLVerifierResponse::CertificateRejected;
  14753. });
  14754. });
  14755. EXPECT_FALSE(res);
  14756. EXPECT_EQ(2, calls);
  14757. }
  14758. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14759. std::string pinned;
  14760. auto res = GetThroughTlsRedirectToDifferentPort(
  14761. [&](SSLClient &cli) {
  14762. cli.enable_server_certificate_verification(false);
  14763. // Pin the first certificate seen.
  14764. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14765. if (pinned.empty()) { pinned = ctx.serial(); }
  14766. return ctx.serial() == pinned;
  14767. });
  14768. },
  14769. // A certificate other than the first server's.
  14770. SERVER_CERT_FILE);
  14771. EXPECT_FALSE(res);
  14772. EXPECT_FALSE(pinned.empty());
  14773. }
  14774. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14775. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14776. std::string cert;
  14777. read_file(SERVER_CERT2_FILE, cert);
  14778. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14779. });
  14780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14781. EXPECT_EQ(StatusCode::OK_200, res->status);
  14782. }
  14783. // The target's certificate is signed by the root CA, which the first server's
  14784. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14785. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14786. auto res = GetThroughTlsRedirectToDifferentPort(
  14787. [](SSLClient &cli) {
  14788. std::string root_ca, cert;
  14789. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14790. read_file(SERVER_CERT2_FILE, cert);
  14791. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14792. cli.load_ca_cert_store(cert.data(), cert.size());
  14793. cli.enable_server_hostname_verification(false);
  14794. },
  14795. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14797. EXPECT_EQ(StatusCode::OK_200, res->status);
  14798. }
  14799. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14800. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14801. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14802. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14803. auto res = GetThroughTlsRedirectToDifferentPort(
  14804. [](SSLClient &cli) {
  14805. std::string root_ca, cert;
  14806. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14807. read_file(SERVER_CERT2_FILE, cert);
  14808. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14809. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14810. cli.enable_server_hostname_verification(false);
  14811. },
  14812. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14813. ASSERT_FALSE(res);
  14814. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14815. }
  14816. #endif
  14817. #endif
  14818. #ifdef CPPHTTPLIB_SSL_ENABLED
  14819. // Test that set_ca_cert_store() skips system certs (consistent with
  14820. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14821. // should be trusted - system certs should NOT be loaded.
  14822. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14823. // Load a specific cert that is NOT a system CA cert
  14824. std::string cert;
  14825. read_file(SERVER_CERT2_FILE, cert);
  14826. SSLClient cli("google.com");
  14827. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14828. cli.enable_server_certificate_verification(true);
  14829. // This should FAIL because:
  14830. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14831. // 2. System certs should NOT be loaded when custom store is set
  14832. // If system certs WERE loaded, this would succeed
  14833. auto res = cli.Get("/");
  14834. ASSERT_FALSE(res);
  14835. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14836. }
  14837. // Same as above, but through the native store handle path. Regression test:
  14838. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14839. // merged system certs into the user-provided store.
  14840. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14841. std::string cert;
  14842. read_file(SERVER_CERT2_FILE, cert);
  14843. SSLClient cli("google.com");
  14844. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14845. cli.enable_server_certificate_verification(true);
  14846. auto res = cli.Get("/");
  14847. ASSERT_FALSE(res);
  14848. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14849. }
  14850. // A custom store set via the native handle must still verify a server whose
  14851. // cert it does contain.
  14852. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14853. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14854. ASSERT_TRUE(svr.is_valid());
  14855. svr.Get("/test", [&](const Request &, Response &res) {
  14856. res.set_content("test", "text/plain");
  14857. });
  14858. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14859. auto se = detail::scope_exit([&] {
  14860. svr.stop();
  14861. t.join();
  14862. ASSERT_FALSE(svr.is_running());
  14863. });
  14864. svr.wait_until_ready();
  14865. SSLClient cli("127.0.0.1", PORT);
  14866. std::string cert;
  14867. read_file(SERVER_CERT2_FILE, cert);
  14868. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14869. cli.enable_server_certificate_verification(true);
  14870. cli.set_connection_timeout(30);
  14871. auto res = cli.Get("/test");
  14872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14873. ASSERT_EQ(StatusCode::OK_200, res->status);
  14874. }
  14875. // CA certs loaded through the universal Client must be transferred to the
  14876. // client created internally for following an HTTPS redirect. Regression test:
  14877. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14878. // the CA data for redirect transfer.
  14879. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14880. auto ssl_port = PORT + 1;
  14881. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14882. ASSERT_TRUE(ssl_svr1.is_valid());
  14883. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14884. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14885. "/index");
  14886. });
  14887. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14888. ASSERT_TRUE(ssl_svr2.is_valid());
  14889. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14890. res.set_content("test", "text/plain");
  14891. });
  14892. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14893. thread t2 =
  14894. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14895. auto se = detail::scope_exit([&] {
  14896. ssl_svr2.stop();
  14897. ssl_svr1.stop();
  14898. t2.join();
  14899. t.join();
  14900. ASSERT_FALSE(ssl_svr1.is_running());
  14901. });
  14902. ssl_svr1.wait_until_ready();
  14903. ssl_svr2.wait_until_ready();
  14904. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14905. std::string cert;
  14906. read_file(SERVER_CERT2_FILE, cert);
  14907. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14908. cli.enable_server_certificate_verification(true);
  14909. cli.set_follow_location(true);
  14910. cli.set_connection_timeout(30);
  14911. auto res = cli.Get("/index");
  14912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14913. ASSERT_EQ(StatusCode::OK_200, res->status);
  14914. }
  14915. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14916. // so a host signed by a system CA verifies even though a custom CA is set
  14917. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14918. std::string cert;
  14919. read_file(SERVER_CERT2_FILE, cert);
  14920. SSLClient cli("google.com");
  14921. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14922. cli.enable_system_ca(true);
  14923. cli.enable_server_certificate_verification(true);
  14924. auto res = cli.Get("/");
  14925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14926. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14927. }
  14928. // The custom CA remains effective when combined with the system CA
  14929. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14930. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14931. ASSERT_TRUE(svr.is_valid());
  14932. svr.Get("/test", [&](const Request &, Response &res) {
  14933. res.set_content("test", "text/plain");
  14934. });
  14935. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14936. auto se = detail::scope_exit([&] {
  14937. svr.stop();
  14938. t.join();
  14939. ASSERT_FALSE(svr.is_running());
  14940. });
  14941. svr.wait_until_ready();
  14942. SSLClient cli("127.0.0.1", PORT);
  14943. std::string cert;
  14944. read_file(SERVER_CERT2_FILE, cert);
  14945. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14946. cli.enable_system_ca(true);
  14947. cli.enable_server_certificate_verification(true);
  14948. cli.set_connection_timeout(30);
  14949. auto res = cli.Get("/test");
  14950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14951. ASSERT_EQ(StatusCode::OK_200, res->status);
  14952. }
  14953. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14954. // skip chain verification entirely (only the certificate identity was
  14955. // checked), so a server presenting an untrusted certificate with a matching
  14956. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14957. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14958. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14959. ASSERT_TRUE(svr.is_valid());
  14960. svr.Get("/test", [&](const Request &, Response &res) {
  14961. res.set_content("test", "text/plain");
  14962. });
  14963. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14964. auto se = detail::scope_exit([&] {
  14965. svr.stop();
  14966. t.join();
  14967. ASSERT_FALSE(svr.is_running());
  14968. });
  14969. svr.wait_until_ready();
  14970. SSLClient cli("127.0.0.1", PORT);
  14971. std::string cert;
  14972. // A trusted CA that did not sign the server certificate. The server cert
  14973. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14974. // this connection.
  14975. read_file(CLIENT_CA_CERT_FILE, cert);
  14976. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14977. cli.enable_server_certificate_verification(true);
  14978. cli.set_connection_timeout(30);
  14979. auto res = cli.Get("/test");
  14980. ASSERT_FALSE(res);
  14981. }
  14982. // enable_system_ca(false) prevents system CA loading entirely
  14983. TEST(SSLClientTest, DisableSystemCa_Online) {
  14984. SSLClient cli("google.com");
  14985. cli.enable_system_ca(false);
  14986. cli.enable_server_certificate_verification(true);
  14987. auto res = cli.Get("/");
  14988. ASSERT_FALSE(res);
  14989. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14990. // itself when the CA chain is empty
  14991. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14992. res.error() == Error::SSLConnection);
  14993. }
  14994. // The universal Client forwards enable_system_ca()
  14995. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14996. std::string cert;
  14997. read_file(SERVER_CERT2_FILE, cert);
  14998. Client cli("https://google.com");
  14999. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15000. cli.enable_system_ca(true);
  15001. cli.enable_server_certificate_verification(true);
  15002. auto res = cli.Get("/");
  15003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15004. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15005. }
  15006. // The system CA policy must carry over to the client created internally for
  15007. // following a cross-host HTTPS redirect
  15008. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15009. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15010. ASSERT_TRUE(svr.is_valid());
  15011. svr.Get("/index", [&](const Request &, Response &res) {
  15012. res.set_redirect("https://www.google.com/");
  15013. });
  15014. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15015. auto se = detail::scope_exit([&] {
  15016. svr.stop();
  15017. t.join();
  15018. ASSERT_FALSE(svr.is_running());
  15019. });
  15020. svr.wait_until_ready();
  15021. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15022. std::string cert;
  15023. read_file(SERVER_CERT2_FILE, cert);
  15024. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15025. cli.enable_system_ca(true);
  15026. cli.enable_server_certificate_verification(true);
  15027. cli.set_follow_location(true);
  15028. cli.set_connection_timeout(30);
  15029. // Receiving any response proves the redirect client completed the TLS
  15030. // handshake with a system-CA-signed host
  15031. auto res = cli.Get("/index");
  15032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15033. }
  15034. TEST(MultipartFormDataTest, LargeData) {
  15035. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15036. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15037. const ContentReader &content_reader) {
  15038. if (req.is_multipart_form_data()) {
  15039. std::vector<FormData> items;
  15040. content_reader(
  15041. [&](const FormData &file) {
  15042. items.push_back(file);
  15043. return true;
  15044. },
  15045. [&](const char *data, size_t data_length) {
  15046. items.back().content.append(data, data_length);
  15047. return true;
  15048. });
  15049. EXPECT_TRUE(std::string(items[0].name) == "document");
  15050. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15051. EXPECT_TRUE(items[0].filename == "2MB_data");
  15052. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15053. EXPECT_TRUE(items[1].name == "hello");
  15054. EXPECT_TRUE(items[1].content == "world");
  15055. EXPECT_TRUE(items[1].filename == "");
  15056. EXPECT_TRUE(items[1].content_type == "");
  15057. } else {
  15058. std::string body;
  15059. content_reader([&](const char *data, size_t data_length) {
  15060. body.append(data, data_length);
  15061. return true;
  15062. });
  15063. }
  15064. });
  15065. auto port = svr.bind_to_any_port(HOST);
  15066. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15067. auto se = detail::scope_exit([&] {
  15068. svr.stop();
  15069. t.join();
  15070. ASSERT_FALSE(svr.is_running());
  15071. });
  15072. svr.wait_until_ready();
  15073. {
  15074. std::string data(1024 * 1024 * 2, '.');
  15075. std::stringstream buffer;
  15076. buffer << data;
  15077. SSLClient cli(HOST, port);
  15078. cli.enable_server_certificate_verification(false);
  15079. UploadFormDataItems items{
  15080. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15081. {"hello", "world", "", ""},
  15082. };
  15083. auto res = cli.Post("/post", items);
  15084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15085. ASSERT_EQ(StatusCode::OK_200, res->status);
  15086. }
  15087. }
  15088. TEST(MultipartFormDataTest, DataProviderItems) {
  15089. std::random_device seed_gen;
  15090. std::mt19937 random(seed_gen());
  15091. std::string rand1;
  15092. rand1.resize(1000);
  15093. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15094. std::string rand2;
  15095. rand2.resize(3000);
  15096. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15098. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15099. const ContentReader &content_reader) {
  15100. ASSERT_FALSE(req.is_multipart_form_data());
  15101. std::string body;
  15102. content_reader([&](const char *data, size_t data_length) {
  15103. body.append(data, data_length);
  15104. return true;
  15105. });
  15106. EXPECT_EQ(body, "");
  15107. });
  15108. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15109. const ContentReader &content_reader) {
  15110. ASSERT_TRUE(req.is_multipart_form_data());
  15111. std::vector<FormData> items;
  15112. content_reader(
  15113. [&](const FormData &file) {
  15114. items.push_back(file);
  15115. return true;
  15116. },
  15117. [&](const char *data, size_t data_length) {
  15118. items.back().content.append(data, data_length);
  15119. return true;
  15120. });
  15121. ASSERT_TRUE(items.size() == 2);
  15122. EXPECT_EQ(std::string(items[0].name), "name1");
  15123. EXPECT_EQ(items[0].content, "Testing123");
  15124. EXPECT_EQ(items[0].filename, "filename1");
  15125. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15126. EXPECT_EQ(items[1].name, "name2");
  15127. EXPECT_EQ(items[1].content, "Testing456");
  15128. EXPECT_EQ(items[1].filename, "");
  15129. EXPECT_EQ(items[1].content_type, "");
  15130. });
  15131. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15132. const ContentReader &content_reader) {
  15133. ASSERT_TRUE(req.is_multipart_form_data());
  15134. std::vector<FormData> items;
  15135. content_reader(
  15136. [&](const FormData &file) {
  15137. items.push_back(file);
  15138. return true;
  15139. },
  15140. [&](const char *data, size_t data_length) {
  15141. items.back().content.append(data, data_length);
  15142. return true;
  15143. });
  15144. ASSERT_TRUE(items.size() == 2);
  15145. EXPECT_EQ(items[0].name, "name3");
  15146. EXPECT_EQ(items[0].content, rand1);
  15147. EXPECT_EQ(items[0].filename, "filename3");
  15148. EXPECT_EQ(items[0].content_type, "");
  15149. EXPECT_EQ(items[1].name, "name4");
  15150. EXPECT_EQ(items[1].content, rand2);
  15151. EXPECT_EQ(items[1].filename, "filename4");
  15152. EXPECT_EQ(items[1].content_type, "");
  15153. });
  15154. svr.Post("/post-both", [&](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() == 4);
  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. EXPECT_EQ(items[2].name, "name3");
  15177. EXPECT_EQ(items[2].content, rand1);
  15178. EXPECT_EQ(items[2].filename, "filename3");
  15179. EXPECT_EQ(items[2].content_type, "");
  15180. EXPECT_EQ(items[3].name, "name4");
  15181. EXPECT_EQ(items[3].content, rand2);
  15182. EXPECT_EQ(items[3].filename, "filename4");
  15183. EXPECT_EQ(items[3].content_type, "");
  15184. });
  15185. auto port = svr.bind_to_any_port("localhost");
  15186. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15187. auto se = detail::scope_exit([&] {
  15188. svr.stop();
  15189. t.join();
  15190. ASSERT_FALSE(svr.is_running());
  15191. });
  15192. svr.wait_until_ready();
  15193. {
  15194. SSLClient cli("localhost", port);
  15195. cli.enable_server_certificate_verification(false);
  15196. UploadFormDataItems items{
  15197. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15198. {"name2", "Testing456", "", ""}, // not a file
  15199. };
  15200. {
  15201. auto res = cli.Post("/post-none", {}, {}, {});
  15202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15203. ASSERT_EQ(StatusCode::OK_200, res->status);
  15204. }
  15205. FormDataProviderItems providers;
  15206. {
  15207. auto res =
  15208. cli.Post("/post-items", {}, items, providers); // empty providers
  15209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15210. ASSERT_EQ(StatusCode::OK_200, res->status);
  15211. }
  15212. providers.push_back({"name3",
  15213. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15214. // test the offset is given correctly at each step
  15215. if (!offset)
  15216. sink.os.write(rand1.data(), 30);
  15217. else if (offset == 30)
  15218. sink.os.write(rand1.data() + 30, 300);
  15219. else if (offset == 330)
  15220. sink.os.write(rand1.data() + 330, 670);
  15221. else if (offset == rand1.size())
  15222. sink.done();
  15223. return true;
  15224. },
  15225. "filename3",
  15226. {}});
  15227. providers.push_back({"name4",
  15228. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15229. // test the offset is given correctly at each step
  15230. if (!offset)
  15231. sink.os.write(rand2.data(), 2000);
  15232. else if (offset == 2000)
  15233. sink.os.write(rand2.data() + 2000, 1);
  15234. else if (offset == 2001)
  15235. sink.os.write(rand2.data() + 2001, 999);
  15236. else if (offset == rand2.size())
  15237. sink.done();
  15238. return true;
  15239. },
  15240. "filename4",
  15241. {}});
  15242. {
  15243. auto res = cli.Post("/post-providers", {}, {}, providers);
  15244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15245. ASSERT_EQ(StatusCode::OK_200, res->status);
  15246. }
  15247. {
  15248. auto res = cli.Post("/post-both", {}, items, providers);
  15249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15250. ASSERT_EQ(StatusCode::OK_200, res->status);
  15251. }
  15252. }
  15253. }
  15254. TEST(MultipartFormDataTest, BadHeader) {
  15255. Server svr;
  15256. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15257. res.set_content("ok", "text/plain");
  15258. });
  15259. thread t = thread([&] { svr.listen(HOST, PORT); });
  15260. auto se = detail::scope_exit([&] {
  15261. svr.stop();
  15262. t.join();
  15263. ASSERT_FALSE(svr.is_running());
  15264. });
  15265. svr.wait_until_ready();
  15266. const std::string body =
  15267. "This is the preamble. It is to be ignored, though it\r\n"
  15268. "is a handy place for composition agents to include an\r\n"
  15269. "explanatory note to non-MIME conformant readers.\r\n"
  15270. "\r\n"
  15271. "\r\n"
  15272. "--simple boundary\r\n"
  15273. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15274. ": BAD...\r\n"
  15275. "\r\n"
  15276. "value1\r\n"
  15277. "--simple boundary\r\n"
  15278. "Content-Disposition: form-data; name=\"field2\"; "
  15279. "filename=\"example.txt\"\r\n"
  15280. "\r\n"
  15281. "value2\r\n"
  15282. "--simple boundary--\r\n"
  15283. "This is the epilogue. It is also to be ignored.\r\n";
  15284. std::string content_type =
  15285. R"(multipart/form-data; boundary="simple boundary")";
  15286. Client cli(HOST, PORT);
  15287. auto res = cli.Post("/post", body, content_type.c_str());
  15288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15289. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15290. }
  15291. TEST(MultipartFormDataTest, WithPreamble) {
  15292. Server svr;
  15293. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15294. res.set_content("ok", "text/plain");
  15295. });
  15296. thread t = thread([&] { svr.listen(HOST, PORT); });
  15297. auto se = detail::scope_exit([&] {
  15298. svr.stop();
  15299. t.join();
  15300. ASSERT_FALSE(svr.is_running());
  15301. });
  15302. svr.wait_until_ready();
  15303. const std::string body =
  15304. "This is the preamble. It is to be ignored, though it\r\n"
  15305. "is a handy place for composition agents to include an\r\n"
  15306. "explanatory note to non-MIME conformant readers.\r\n"
  15307. "\r\n"
  15308. "\r\n"
  15309. "--simple boundary\r\n"
  15310. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15311. "\r\n"
  15312. "value1\r\n"
  15313. "--simple boundary\r\n"
  15314. "Content-Disposition: form-data; name=\"field2\"; "
  15315. "filename=\"example.txt\"\r\n"
  15316. "\r\n"
  15317. "value2\r\n"
  15318. "--simple boundary--\r\n"
  15319. "This is the epilogue. It is also to be ignored.\r\n";
  15320. std::string content_type =
  15321. R"(multipart/form-data; boundary="simple boundary")";
  15322. Client cli(HOST, PORT);
  15323. auto res = cli.Post("/post", body, content_type.c_str());
  15324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15325. EXPECT_EQ(StatusCode::OK_200, res->status);
  15326. }
  15327. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15328. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15329. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15330. const ContentReader &content_reader) {
  15331. if (req.is_multipart_form_data()) {
  15332. std::vector<FormData> items;
  15333. content_reader(
  15334. [&](const FormData &file) {
  15335. items.push_back(file);
  15336. return true;
  15337. },
  15338. [&](const char *data, size_t data_length) {
  15339. items.back().content.append(data, data_length);
  15340. return true;
  15341. });
  15342. EXPECT_TRUE(std::string(items[0].name) == "document");
  15343. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15344. EXPECT_TRUE(items[0].filename == "2MB_data");
  15345. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15346. EXPECT_TRUE(items[1].name == "hello");
  15347. EXPECT_TRUE(items[1].content == "world");
  15348. EXPECT_TRUE(items[1].filename == "");
  15349. EXPECT_TRUE(items[1].content_type == "");
  15350. } else {
  15351. std::string body;
  15352. content_reader([&](const char *data, size_t data_length) {
  15353. body.append(data, data_length);
  15354. return true;
  15355. });
  15356. }
  15357. });
  15358. auto port = svr.bind_to_any_port("localhost");
  15359. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15360. auto se = detail::scope_exit([&] {
  15361. svr.stop();
  15362. t.join();
  15363. ASSERT_FALSE(svr.is_running());
  15364. });
  15365. svr.wait_until_ready();
  15366. {
  15367. std::string data(1024 * 1024 * 2, '.');
  15368. std::stringstream buffer;
  15369. buffer << data;
  15370. SSLClient cli("localhost", port);
  15371. cli.enable_server_certificate_verification(false);
  15372. UploadFormDataItems items{
  15373. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15374. {"hello", "world", "", ""},
  15375. };
  15376. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15378. ASSERT_EQ(StatusCode::OK_200, res->status);
  15379. }
  15380. }
  15381. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15382. std::string data(1024 * 1024 * 2, '&');
  15383. std::stringstream buffer;
  15384. buffer << data;
  15385. Client cli("https://localhost:8080");
  15386. UploadFormDataItems items{
  15387. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15388. {"hello", "world", "", ""},
  15389. };
  15390. for (const char &c : " \t\r\n") {
  15391. auto res =
  15392. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15393. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15394. ASSERT_FALSE(res);
  15395. }
  15396. }
  15397. TEST(MultipartFormDataTest, PutFormData) {
  15398. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15399. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15400. const ContentReader &content_reader) {
  15401. if (req.is_multipart_form_data()) {
  15402. std::vector<FormData> items;
  15403. content_reader(
  15404. [&](const FormData &file) {
  15405. items.push_back(file);
  15406. return true;
  15407. },
  15408. [&](const char *data, size_t data_length) {
  15409. items.back().content.append(data, data_length);
  15410. return true;
  15411. });
  15412. EXPECT_TRUE(std::string(items[0].name) == "document");
  15413. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15414. EXPECT_TRUE(items[0].filename == "2MB_data");
  15415. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15416. EXPECT_TRUE(items[1].name == "hello");
  15417. EXPECT_TRUE(items[1].content == "world");
  15418. EXPECT_TRUE(items[1].filename == "");
  15419. EXPECT_TRUE(items[1].content_type == "");
  15420. } else {
  15421. std::string body;
  15422. content_reader([&](const char *data, size_t data_length) {
  15423. body.append(data, data_length);
  15424. return true;
  15425. });
  15426. }
  15427. });
  15428. auto port = svr.bind_to_any_port("localhost");
  15429. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15430. auto se = detail::scope_exit([&] {
  15431. svr.stop();
  15432. t.join();
  15433. ASSERT_FALSE(svr.is_running());
  15434. });
  15435. svr.wait_until_ready();
  15436. {
  15437. std::string data(1024 * 1024 * 2, '&');
  15438. std::stringstream buffer;
  15439. buffer << data;
  15440. SSLClient cli("localhost", port);
  15441. cli.enable_server_certificate_verification(false);
  15442. UploadFormDataItems items{
  15443. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15444. {"hello", "world", "", ""},
  15445. };
  15446. auto res = cli.Put("/put", items);
  15447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15448. ASSERT_EQ(StatusCode::OK_200, res->status);
  15449. }
  15450. }
  15451. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15452. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15453. svr.Put("/put_customboundary",
  15454. [&](const Request &req, const Response & /*res*/,
  15455. const ContentReader &content_reader) {
  15456. if (req.is_multipart_form_data()) {
  15457. std::vector<FormData> items;
  15458. content_reader(
  15459. [&](const FormData &file) {
  15460. items.push_back(file);
  15461. return true;
  15462. },
  15463. [&](const char *data, size_t data_length) {
  15464. items.back().content.append(data, data_length);
  15465. return true;
  15466. });
  15467. EXPECT_TRUE(std::string(items[0].name) == "document");
  15468. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15469. EXPECT_TRUE(items[0].filename == "2MB_data");
  15470. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15471. EXPECT_TRUE(items[1].name == "hello");
  15472. EXPECT_TRUE(items[1].content == "world");
  15473. EXPECT_TRUE(items[1].filename == "");
  15474. EXPECT_TRUE(items[1].content_type == "");
  15475. } else {
  15476. std::string body;
  15477. content_reader([&](const char *data, size_t data_length) {
  15478. body.append(data, data_length);
  15479. return true;
  15480. });
  15481. }
  15482. });
  15483. auto port = svr.bind_to_any_port("localhost");
  15484. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15485. auto se = detail::scope_exit([&] {
  15486. svr.stop();
  15487. t.join();
  15488. ASSERT_FALSE(svr.is_running());
  15489. });
  15490. svr.wait_until_ready();
  15491. {
  15492. std::string data(1024 * 1024 * 2, '&');
  15493. std::stringstream buffer;
  15494. buffer << data;
  15495. SSLClient cli("localhost", port);
  15496. cli.enable_server_certificate_verification(false);
  15497. UploadFormDataItems items{
  15498. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15499. {"hello", "world", "", ""},
  15500. };
  15501. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15503. ASSERT_EQ(StatusCode::OK_200, res->status);
  15504. }
  15505. }
  15506. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15507. std::string data(1024 * 1024 * 2, '&');
  15508. std::stringstream buffer;
  15509. buffer << data;
  15510. Client cli("https://localhost:8080");
  15511. cli.enable_server_certificate_verification(false);
  15512. UploadFormDataItems items{
  15513. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15514. {"hello", "world", "", ""},
  15515. };
  15516. for (const char &c : " \t\r\n") {
  15517. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15518. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15519. ASSERT_FALSE(res);
  15520. }
  15521. }
  15522. TEST(MultipartFormDataTest, AlternateFilename) {
  15523. auto handled = false;
  15524. Server svr;
  15525. svr.Post("/test", [&](const Request &req, Response &res) {
  15526. ASSERT_EQ(2u, req.form.files.size());
  15527. ASSERT_EQ(1u, req.form.fields.size());
  15528. // Test files
  15529. const auto &file1 = req.form.get_file("file1");
  15530. ASSERT_EQ("file1", file1.name);
  15531. ASSERT_EQ("A.txt", file1.filename);
  15532. ASSERT_EQ("text/plain", file1.content_type);
  15533. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15534. const auto &file2 = req.form.get_file("file2");
  15535. ASSERT_EQ("file2", file2.name);
  15536. ASSERT_EQ("a.html", file2.filename);
  15537. ASSERT_EQ("text/html", file2.content_type);
  15538. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15539. file2.content);
  15540. // Test text field
  15541. const auto &text = req.form.get_field("text");
  15542. ASSERT_EQ("text default", text);
  15543. res.set_content("ok", "text/plain");
  15544. handled = true;
  15545. });
  15546. thread t = thread([&] { svr.listen(HOST, PORT); });
  15547. auto se = detail::scope_exit([&] {
  15548. svr.stop();
  15549. t.join();
  15550. ASSERT_FALSE(svr.is_running());
  15551. ASSERT_TRUE(handled);
  15552. });
  15553. svr.wait_until_ready();
  15554. auto req = "POST /test HTTP/1.1\r\n"
  15555. "Host: localhost\r\n"
  15556. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15557. "Content-Length: 399\r\n"
  15558. "\r\n"
  15559. "----------\r\n"
  15560. "Content-Disposition: form-data; name=\"text\"\r\n"
  15561. "\r\n"
  15562. "text default\r\n"
  15563. "----------\r\n"
  15564. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15565. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15566. "Content-Type: text/plain\r\n"
  15567. "\r\n"
  15568. "Content of a.txt.\r\n"
  15569. "\r\n"
  15570. "----------\r\n"
  15571. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15572. "\"a.html\"\r\n"
  15573. "Content-Type: text/html\r\n"
  15574. "\r\n"
  15575. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15576. "\r\n"
  15577. "------------\r\n";
  15578. ASSERT_TRUE(send_request(1, req));
  15579. }
  15580. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15581. auto handled = false;
  15582. Server svr;
  15583. svr.Post("/test", [&](const Request &req, Response &res) {
  15584. // Case-insensitive "utf-8''" prefix with a long value
  15585. const auto &file = req.form.get_file("file1");
  15586. ASSERT_EQ("file1", file.name);
  15587. // 8000 chars exercises both the Content-Disposition parser and the
  15588. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15589. // Prior to the fix, std::regex_match on this header would cause O(N)
  15590. // stack recursion in libstdc++, leading to SIGSEGV.
  15591. std::string expected_filename(8000, 'A');
  15592. ASSERT_EQ(expected_filename, file.filename);
  15593. res.set_content("ok", "text/plain");
  15594. handled = true;
  15595. });
  15596. thread t = thread([&] { svr.listen(HOST, PORT); });
  15597. auto se = detail::scope_exit([&] {
  15598. svr.stop();
  15599. t.join();
  15600. ASSERT_FALSE(svr.is_running());
  15601. ASSERT_TRUE(handled);
  15602. });
  15603. svr.wait_until_ready();
  15604. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15605. // Regression test for GHSA-qq6v-r583-3h69
  15606. std::string long_filename(8000, 'A');
  15607. std::string body = "----------\r\n"
  15608. "Content-Disposition: form-data; name=\"file1\"; "
  15609. "filename*=\"Utf-8''" +
  15610. long_filename +
  15611. "\"\r\n"
  15612. "\r\n"
  15613. "hello\r\n"
  15614. "------------\r\n";
  15615. auto req = "POST /test HTTP/1.1\r\n"
  15616. "Host: localhost\r\n"
  15617. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15618. "Content-Length: " +
  15619. std::to_string(body.size()) + "\r\n\r\n" + body;
  15620. ASSERT_TRUE(send_request(1, req));
  15621. }
  15622. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15623. auto handled = false;
  15624. Server svr;
  15625. svr.Post("/test", [&](const Request &req, Response &) {
  15626. ASSERT_EQ(2u, req.form.fields.size());
  15627. const auto &text1 = req.form.get_field("text1");
  15628. ASSERT_EQ("text1", text1);
  15629. const auto &text2 = req.form.get_field("text2");
  15630. ASSERT_EQ("text2", text2);
  15631. handled = true;
  15632. });
  15633. thread t = thread([&] { svr.listen(HOST, PORT); });
  15634. auto se = detail::scope_exit([&] {
  15635. svr.stop();
  15636. t.join();
  15637. ASSERT_FALSE(svr.is_running());
  15638. ASSERT_TRUE(handled);
  15639. });
  15640. svr.wait_until_ready();
  15641. auto req = "POST /test HTTP/1.1\r\n"
  15642. "Host: localhost\r\n"
  15643. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15644. "Content-Length: 146\r\n"
  15645. "\r\n----------\r\n"
  15646. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15647. "\r\n"
  15648. "text1"
  15649. "\r\n----------\r\n"
  15650. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15651. "\r\n"
  15652. "text2"
  15653. "\r\n------------";
  15654. std::string response;
  15655. ASSERT_TRUE(send_request(1, req, &response));
  15656. ASSERT_EQ("200", response.substr(9, 3));
  15657. }
  15658. TEST(MultipartFormDataTest, ContentLength) {
  15659. auto handled = false;
  15660. Server svr;
  15661. svr.Post("/test", [&](const Request &req, Response &) {
  15662. ASSERT_EQ(2u, req.form.fields.size());
  15663. const auto &text1 = req.form.get_field("text1");
  15664. ASSERT_EQ("text1", text1);
  15665. const auto &text2 = req.form.get_field("text2");
  15666. ASSERT_EQ("text2", text2);
  15667. handled = true;
  15668. });
  15669. thread t = thread([&] { svr.listen(HOST, PORT); });
  15670. auto se = detail::scope_exit([&] {
  15671. svr.stop();
  15672. t.join();
  15673. ASSERT_FALSE(svr.is_running());
  15674. ASSERT_TRUE(handled);
  15675. });
  15676. svr.wait_until_ready();
  15677. auto req = "POST /test HTTP/1.1\r\n"
  15678. "Host: localhost\r\n"
  15679. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15680. "Content-Length: 167\r\n"
  15681. "\r\n----------\r\n"
  15682. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15683. "Content-Length: 5\r\n"
  15684. "\r\n"
  15685. "text1"
  15686. "\r\n----------\r\n"
  15687. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15688. "\r\n"
  15689. "text2"
  15690. "\r\n------------\r\n";
  15691. std::string response;
  15692. ASSERT_TRUE(send_request(1, req, &response));
  15693. ASSERT_EQ("200", response.substr(9, 3));
  15694. }
  15695. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15696. auto handled = false;
  15697. Server svr;
  15698. svr.Post("/test", [&](const Request &req, Response &) {
  15699. ASSERT_EQ(2u, req.form.fields.size());
  15700. const auto &text1 = req.form.get_field("text1");
  15701. ASSERT_EQ("text1", text1);
  15702. // TODO: Add header access for text fields if needed
  15703. const auto &text2 = req.form.get_field("text2");
  15704. ASSERT_EQ("text2", text2);
  15705. // TODO: Header access for text fields needs to be implemented
  15706. // auto &headers = it->second.headers;
  15707. // ASSERT_EQ(3U, headers.size());
  15708. // auto custom_header = headers.find("x-whatever");
  15709. // ASSERT_TRUE(custom_header != headers.end());
  15710. // ASSERT_NE("customvalue", custom_header->second);
  15711. // ASSERT_EQ("CustomValue", custom_header->second);
  15712. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  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: 232\r\n"
  15727. "\r\n----------\r\n"
  15728. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15729. "Content-Length: 5\r\n"
  15730. "X-Test: 1\r\n"
  15731. "\r\n"
  15732. "text1"
  15733. "\r\n----------\r\n"
  15734. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15735. "Content-Type: text/plain\r\n"
  15736. "X-Whatever: CustomValue\r\n"
  15737. "\r\n"
  15738. "text2"
  15739. "\r\n------------\r\n"
  15740. "That should be disregarded. Not even read";
  15741. std::string response;
  15742. ASSERT_TRUE(send_request(1, req, &response));
  15743. ASSERT_EQ("200", response.substr(9, 3));
  15744. }
  15745. TEST(MultipartFormDataTest, LargeHeader) {
  15746. auto handled = false;
  15747. Server svr;
  15748. svr.Post("/test", [&](const Request &req, Response &) {
  15749. ASSERT_EQ(1u, req.form.fields.size());
  15750. const auto &text = req.form.get_field("name1");
  15751. ASSERT_EQ("text1", text);
  15752. handled = true;
  15753. });
  15754. thread t = thread([&] { svr.listen(HOST, PORT); });
  15755. auto se = detail::scope_exit([&] {
  15756. svr.stop();
  15757. t.join();
  15758. ASSERT_FALSE(svr.is_running());
  15759. ASSERT_TRUE(handled);
  15760. });
  15761. svr.wait_until_ready();
  15762. auto boundary = std::string("cpp-httplib-multipart-data");
  15763. std::string content = "--" + boundary +
  15764. "\r\n"
  15765. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15766. "\r\n"
  15767. "text1\r\n"
  15768. "--" +
  15769. boundary + "--\r\n";
  15770. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15771. "Host: localhost\r\n"
  15772. "Content-Type: multipart/form-data;boundary=" +
  15773. boundary +
  15774. "\r\n"
  15775. "Content-Length: " +
  15776. std::to_string(content.size()) +
  15777. "\r\n"
  15778. "Dummy-Header: ";
  15779. std::string header_suffix = "\r\n"
  15780. "\r\n";
  15781. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15782. size_t header_dummy_size =
  15783. read_buff_size -
  15784. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15785. auto header_dummy = std::string(header_dummy_size, '@');
  15786. auto req = header_prefix + header_dummy + header_suffix + content;
  15787. std::string response;
  15788. ASSERT_TRUE(send_request(1, req, &response));
  15789. ASSERT_EQ("200", response.substr(9, 3));
  15790. }
  15791. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15792. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15793. // (not chunked Transfer-Encoding) after the streaming refactor.
  15794. auto handled = false;
  15795. Server svr;
  15796. svr.Post("/upload", [&](const Request &req, Response &res) {
  15797. auto cl_it = req.headers.find("Content-Length");
  15798. EXPECT_TRUE(cl_it != req.headers.end());
  15799. auto te_it = req.headers.find("Transfer-Encoding");
  15800. EXPECT_TRUE(te_it == req.headers.end());
  15801. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15802. res.set_content("ok", "text/plain");
  15803. handled = true;
  15804. });
  15805. auto port = svr.bind_to_any_port(HOST);
  15806. auto t = thread([&] { svr.listen_after_bind(); });
  15807. auto se = detail::scope_exit([&] {
  15808. svr.stop();
  15809. t.join();
  15810. ASSERT_FALSE(svr.is_running());
  15811. ASSERT_TRUE(handled);
  15812. });
  15813. svr.wait_until_ready();
  15814. UploadFormDataItems items = {
  15815. {"field1", "hello", "", "text/plain"},
  15816. {"file1", "world", "test.txt", "application/octet-stream"},
  15817. };
  15818. Client cli(HOST, port);
  15819. auto res = cli.Post("/upload", {}, items);
  15820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15821. EXPECT_EQ(StatusCode::OK_200, res->status);
  15822. }
  15823. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15824. // Verify that make_multipart_content_provider coalesces many small segments
  15825. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15826. constexpr size_t kItemCount = 1000;
  15827. UploadFormDataItems items;
  15828. items.reserve(kItemCount);
  15829. for (size_t i = 0; i < kItemCount; i++) {
  15830. items.push_back(
  15831. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15832. }
  15833. const std::string boundary = "----test-boundary";
  15834. auto content_length = detail::get_multipart_content_length(items, boundary);
  15835. auto provider = detail::make_multipart_content_provider(items, boundary);
  15836. // Drive the provider the same way write_content_with_progress does
  15837. size_t write_count = 0;
  15838. size_t total_bytes = 0;
  15839. DataSink sink;
  15840. size_t offset = 0;
  15841. sink.write = [&](const char *d, size_t l) -> bool {
  15842. (void)d;
  15843. write_count++;
  15844. total_bytes += l;
  15845. offset += l;
  15846. return true;
  15847. };
  15848. sink.is_writable = []() -> bool { return true; };
  15849. while (offset < content_length) {
  15850. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15851. }
  15852. EXPECT_EQ(content_length, total_bytes);
  15853. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15854. // With buffering into 64KB blocks, write_count should be much smaller.
  15855. auto segment_count = 3 * kItemCount + 1;
  15856. EXPECT_LT(write_count, segment_count / 10);
  15857. }
  15858. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15859. // Integration test: send many UploadFormDataItems and verify the server
  15860. // receives all of them correctly (#2410).
  15861. constexpr size_t kItemCount = 500;
  15862. auto handled = false;
  15863. Server svr;
  15864. svr.Post("/upload", [&](const Request &req, Response &res) {
  15865. EXPECT_EQ(kItemCount, req.form.fields.size());
  15866. for (size_t i = 0; i < kItemCount; i++) {
  15867. auto key = "field" + std::to_string(i);
  15868. auto val = "value" + std::to_string(i);
  15869. auto it = req.form.fields.find(key);
  15870. if (it != req.form.fields.end()) {
  15871. EXPECT_EQ(val, it->second.content);
  15872. } else {
  15873. ADD_FAILURE() << "Missing field: " << key;
  15874. }
  15875. }
  15876. res.set_content("ok", "text/plain");
  15877. handled = true;
  15878. });
  15879. auto port = svr.bind_to_any_port(HOST);
  15880. auto t = thread([&] { svr.listen_after_bind(); });
  15881. auto se = detail::scope_exit([&] {
  15882. svr.stop();
  15883. t.join();
  15884. ASSERT_FALSE(svr.is_running());
  15885. ASSERT_TRUE(handled);
  15886. });
  15887. svr.wait_until_ready();
  15888. UploadFormDataItems items;
  15889. items.reserve(kItemCount);
  15890. for (size_t i = 0; i < kItemCount; i++) {
  15891. items.push_back(
  15892. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15893. }
  15894. Client cli(HOST, port);
  15895. auto res = cli.Post("/upload", items);
  15896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15897. EXPECT_EQ(StatusCode::OK_200, res->status);
  15898. }
  15899. TEST(MultipartFormDataTest, MakeFileProvider) {
  15900. // Verify make_file_provider sends a file's contents correctly.
  15901. const std::string file_content(4096, 'Z');
  15902. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15903. {
  15904. std::ofstream ofs(tmp_path, std::ios::binary);
  15905. ofs.write(file_content.data(),
  15906. static_cast<std::streamsize>(file_content.size()));
  15907. }
  15908. auto handled = false;
  15909. Server svr;
  15910. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15911. const ContentReader &content_reader) {
  15912. ASSERT_TRUE(req.is_multipart_form_data());
  15913. std::vector<FormData> items;
  15914. content_reader(
  15915. [&](const FormData &file) {
  15916. items.push_back(file);
  15917. return true;
  15918. },
  15919. [&](const char *data, size_t data_length) {
  15920. items.back().content.append(data, data_length);
  15921. return true;
  15922. });
  15923. ASSERT_EQ(1u, items.size());
  15924. EXPECT_EQ("myfile", items[0].name);
  15925. EXPECT_EQ("data.bin", items[0].filename);
  15926. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15927. EXPECT_EQ(file_content, items[0].content);
  15928. handled = true;
  15929. });
  15930. auto port = svr.bind_to_any_port(HOST);
  15931. auto t = thread([&] { svr.listen_after_bind(); });
  15932. auto se = detail::scope_exit([&] {
  15933. svr.stop();
  15934. t.join();
  15935. ASSERT_FALSE(svr.is_running());
  15936. ASSERT_TRUE(handled);
  15937. std::remove(tmp_path.c_str());
  15938. });
  15939. svr.wait_until_ready();
  15940. FormDataProviderItems providers;
  15941. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15942. "application/octet-stream"));
  15943. Client cli(HOST, port);
  15944. auto res = cli.Post("/upload", {}, {}, providers);
  15945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15946. EXPECT_EQ(StatusCode::OK_200, res->status);
  15947. }
  15948. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15949. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15950. // (100) headers is rejected with a 400 Bad Request response.
  15951. Server svr;
  15952. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15953. res.set_content("ok", "text/plain");
  15954. });
  15955. thread t = thread([&] { svr.listen(HOST, PORT); });
  15956. auto se = detail::scope_exit([&] {
  15957. svr.stop();
  15958. t.join();
  15959. ASSERT_FALSE(svr.is_running());
  15960. });
  15961. svr.wait_until_ready();
  15962. // Build a multipart part with 101 custom headers (exceeding
  15963. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15964. std::stringstream body;
  15965. body << "--simpleboundary\r\n"
  15966. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15967. for (int i = 0; i < 101; i++) {
  15968. body << "X-Custom-Header-" << i << ": value\r\n";
  15969. }
  15970. body << "\r\n"
  15971. << "value1\r\n"
  15972. << "--simpleboundary--\r\n";
  15973. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15974. Client cli(HOST, PORT);
  15975. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15977. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15978. }
  15979. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15980. // A body that never contains the declared boundary must not be accumulated
  15981. // while the parser waits for it. Buffering it would also make every read
  15982. // rescan everything seen so far, which is quadratic in the body size.
  15983. Server svr;
  15984. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15985. res.set_content("ok", "text/plain");
  15986. });
  15987. auto port = svr.bind_to_any_port(HOST);
  15988. thread t = thread([&] { svr.listen_after_bind(); });
  15989. auto se = detail::scope_exit([&] {
  15990. svr.stop();
  15991. t.join();
  15992. ASSERT_FALSE(svr.is_running());
  15993. });
  15994. svr.wait_until_ready();
  15995. Client cli(HOST, port);
  15996. cli.set_read_timeout(60, 0);
  15997. cli.set_write_timeout(60, 0);
  15998. // '-' is the worst case: it matches the first character of the boundary, so
  15999. // every position has to be checked against it.
  16000. auto post_dashes = [&](size_t size) {
  16001. const std::string body(size, '-');
  16002. auto start = std::chrono::steady_clock::now();
  16003. auto res =
  16004. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16005. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16006. std::chrono::steady_clock::now() - start)
  16007. .count();
  16008. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16009. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16010. return ms;
  16011. };
  16012. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16013. // Windows.
  16014. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16015. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16016. // Comparing the two sizes rather than checking an absolute duration keeps
  16017. // this meaningful across build types and CI load, both of which move the
  16018. // absolute numbers by more than an order of magnitude. Four times the bytes
  16019. // costs about four times the time when parsing is linear, and about sixteen
  16020. // times when the body is buffered and rescanned.
  16021. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16022. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16023. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16024. << "ms, which suggests the body is being buffered and rescanned";
  16025. }
  16026. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16027. // A boundary can only be followed by CRLF or by "--", so anything else is
  16028. // malformed no matter what comes next. The parser must say so right away
  16029. // instead of buffering the rest of the declared body.
  16030. Server svr;
  16031. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16032. res.set_content("ok", "text/plain");
  16033. });
  16034. auto port = svr.bind_to_any_port(HOST);
  16035. thread t = thread([&] { svr.listen_after_bind(); });
  16036. auto se = detail::scope_exit([&] {
  16037. svr.stop();
  16038. t.join();
  16039. ASSERT_FALSE(svr.is_running());
  16040. });
  16041. svr.wait_until_ready();
  16042. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16043. // buffers instead of failing would still be waiting for the remaining bytes.
  16044. const std::string body = "--zzzz\r\n"
  16045. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16046. "\r\n"
  16047. "text1"
  16048. "\r\n--zzzzXX";
  16049. const std::string req = "POST /post HTTP/1.1\r\n"
  16050. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16051. "Content-Length: 1048576\r\n"
  16052. "\r\n" +
  16053. body;
  16054. std::string response;
  16055. ASSERT_TRUE(send_request(3, req, &response, port));
  16056. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16057. EXPECT_EQ("400", response.substr(9, 3));
  16058. }
  16059. // Posts a multipart body split into two writes, so that the server sees the
  16060. // split at whatever offset the caller chose, and expects the single "text1"
  16061. // field to come through.
  16062. static void expect_split_multipart_ok(const std::string &body1,
  16063. const std::string &body2) {
  16064. auto handled = false;
  16065. Server svr;
  16066. svr.Post("/post", [&](const Request &req, Response &) {
  16067. EXPECT_EQ(1u, req.form.fields.size());
  16068. EXPECT_EQ("text1", req.form.get_field("text1"));
  16069. handled = true;
  16070. });
  16071. auto port = svr.bind_to_any_port(HOST);
  16072. thread t = thread([&] { svr.listen_after_bind(); });
  16073. auto se = detail::scope_exit([&] {
  16074. svr.stop();
  16075. t.join();
  16076. ASSERT_FALSE(svr.is_running());
  16077. ASSERT_TRUE(handled);
  16078. });
  16079. svr.wait_until_ready();
  16080. // "Connection: close" makes the server close once it has answered, so the
  16081. // response drain ends immediately instead of idling until the read timeout.
  16082. const std::string head =
  16083. "POST /post HTTP/1.1\r\n"
  16084. "Host: localhost\r\n"
  16085. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16086. "Connection: close\r\n"
  16087. "Content-Length: " +
  16088. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16089. std::string response;
  16090. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16091. ASSERT_GE(response.size(), 12u) << "no response";
  16092. EXPECT_EQ("200", response.substr(9, 3));
  16093. }
  16094. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16095. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16096. // ignored, including when it does not arrive in the same read as the
  16097. // close-delimiter itself.
  16098. expect_split_multipart_ok("--zzzz\r\n"
  16099. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16100. "\r\n"
  16101. "text1"
  16102. "\r\n--zzzz--",
  16103. "\r\nthis epilogue must be ignored\r\n");
  16104. }
  16105. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16106. // The initial boundary may be preceded by a preamble of any length and may
  16107. // straddle a read boundary. Discarding data while waiting for it must not
  16108. // throw away a partial boundary sitting at the end of the buffer.
  16109. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16110. "zz\r\n"
  16111. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16112. "\r\n"
  16113. "text1"
  16114. "\r\n--zzzz--\r\n");
  16115. }
  16116. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16117. // The received boundary was only checked for being non-empty, so it could be
  16118. // as long as a header is allowed to be. The parser scans the body for
  16119. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16120. // costs a nearly full comparison at nearly every position, making the
  16121. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16122. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16123. Server svr;
  16124. svr.Post("/post", [](const Request &req, Response &res) {
  16125. EXPECT_EQ(1u, req.form.fields.size());
  16126. EXPECT_EQ("text1", req.form.get_field("text1"));
  16127. res.set_content("ok", "text/plain");
  16128. });
  16129. auto port = svr.bind_to_any_port(HOST);
  16130. thread t = thread([&] { svr.listen_after_bind(); });
  16131. auto se = detail::scope_exit([&] {
  16132. svr.stop();
  16133. t.join();
  16134. ASSERT_FALSE(svr.is_running());
  16135. });
  16136. svr.wait_until_ready();
  16137. Client cli(HOST, port);
  16138. auto post_with_boundary_of_length = [&](size_t len) {
  16139. const std::string boundary(len, 'a');
  16140. const std::string body =
  16141. "--" + boundary +
  16142. "\r\n"
  16143. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16144. "\r\n"
  16145. "text1"
  16146. "\r\n--" +
  16147. boundary + "--\r\n";
  16148. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16149. };
  16150. auto res = post_with_boundary_of_length(70);
  16151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16152. EXPECT_EQ(StatusCode::OK_200, res->status);
  16153. res = post_with_boundary_of_length(71);
  16154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16155. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16156. }
  16157. TEST(MakeFileBodyTest, Basic) {
  16158. const std::string file_content(4096, 'Z');
  16159. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16160. {
  16161. std::ofstream ofs(tmp_path, std::ios::binary);
  16162. ofs.write(file_content.data(),
  16163. static_cast<std::streamsize>(file_content.size()));
  16164. }
  16165. auto handled = false;
  16166. Server svr;
  16167. svr.Post("/upload", [&](const Request &req, Response &res) {
  16168. EXPECT_EQ(file_content, req.body);
  16169. handled = true;
  16170. res.status = StatusCode::OK_200;
  16171. });
  16172. auto port = svr.bind_to_any_port(HOST);
  16173. auto t = thread([&] { svr.listen_after_bind(); });
  16174. auto se = detail::scope_exit([&] {
  16175. svr.stop();
  16176. t.join();
  16177. ASSERT_FALSE(svr.is_running());
  16178. ASSERT_TRUE(handled);
  16179. std::remove(tmp_path.c_str());
  16180. });
  16181. svr.wait_until_ready();
  16182. auto fb = make_file_body(tmp_path);
  16183. ASSERT_GT(fb.first, 0u);
  16184. Client cli(HOST, port);
  16185. auto res =
  16186. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16188. EXPECT_EQ(StatusCode::OK_200, res->status);
  16189. }
  16190. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16191. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16192. {
  16193. std::ofstream ofs(path, std::ios::binary);
  16194. const std::string content(100, 'A');
  16195. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16196. }
  16197. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16198. auto body = make_file_body(path);
  16199. ASSERT_EQ(100u, body.first);
  16200. ASSERT_TRUE(static_cast<bool>(body.second));
  16201. // Rewritten shorter after its length was measured - and, on a server, after
  16202. // that length has already gone out as Content-Length.
  16203. {
  16204. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16205. const std::string content(10, 'A');
  16206. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16207. }
  16208. std::string written;
  16209. DataSink sink;
  16210. sink.write = [&](const char *d, size_t l) {
  16211. written.append(d, l);
  16212. return true;
  16213. };
  16214. // The provider has to report failure. write_content_with_progress() advances
  16215. // its offset only by what was written, so a provider that returns true
  16216. // without completing the length it promised is called again straight away,
  16217. // and again.
  16218. EXPECT_FALSE(body.second(0, body.first, sink));
  16219. EXPECT_EQ(std::string(10, 'A'), written);
  16220. }
  16221. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16222. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16223. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16224. {
  16225. std::ofstream ofs(path, std::ios::binary);
  16226. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16227. }
  16228. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16229. auto body = make_file_body(path);
  16230. ASSERT_EQ(content.size(), body.first);
  16231. ASSERT_TRUE(static_cast<bool>(body.second));
  16232. std::string written;
  16233. DataSink sink;
  16234. sink.write = [&](const char *d, size_t l) {
  16235. written.append(d, l);
  16236. return true;
  16237. };
  16238. EXPECT_TRUE(body.second(0, body.first, sink));
  16239. EXPECT_EQ(content, written);
  16240. }
  16241. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16242. static constexpr unsigned int number_of_tasks{1000000};
  16243. std::atomic_uint count{0};
  16244. std::unique_ptr<TaskQueue> task_queue{
  16245. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16246. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16247. auto queued = task_queue->enqueue(
  16248. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16249. EXPECT_TRUE(queued);
  16250. }
  16251. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16252. task_queue->shutdown();
  16253. #else
  16254. EXPECT_NO_THROW(task_queue->shutdown());
  16255. #endif
  16256. EXPECT_EQ(number_of_tasks, count.load());
  16257. }
  16258. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16259. static constexpr unsigned int number_of_tasks{1000000};
  16260. static constexpr unsigned int qlimit{2};
  16261. unsigned int queued_count{0};
  16262. std::atomic_uint count{0};
  16263. std::unique_ptr<TaskQueue> task_queue{
  16264. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16265. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16266. if (task_queue->enqueue(
  16267. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16268. queued_count++;
  16269. }
  16270. }
  16271. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16272. task_queue->shutdown();
  16273. #else
  16274. EXPECT_NO_THROW(task_queue->shutdown());
  16275. #endif
  16276. EXPECT_EQ(queued_count, count.load());
  16277. EXPECT_TRUE(queued_count <= number_of_tasks);
  16278. EXPECT_TRUE(queued_count >= qlimit);
  16279. }
  16280. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16281. // Use a short idle timeout so a dynamic thread spawns, times out and
  16282. // exits during the test, and the pool keeps working afterwards.
  16283. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16284. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16285. /*idle_timeout_sec=*/1}};
  16286. std::atomic_uint count{0};
  16287. std::condition_variable cv;
  16288. std::mutex mtx;
  16289. bool release = false;
  16290. // Block the base thread so the second task spawns a dynamic thread.
  16291. EXPECT_TRUE(task_queue->enqueue([&] {
  16292. std::unique_lock<std::mutex> lock(mtx);
  16293. while (!release) {
  16294. cv.wait(lock);
  16295. }
  16296. count++;
  16297. }));
  16298. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16299. // Let the dynamic thread finish its task and exceed the idle timeout.
  16300. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16301. {
  16302. std::unique_lock<std::mutex> lock(mtx);
  16303. release = true;
  16304. }
  16305. cv.notify_all();
  16306. // The pool must still accept and run tasks after the dynamic thread exited.
  16307. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16308. task_queue->shutdown();
  16309. EXPECT_EQ(3u, count.load());
  16310. }
  16311. TEST(TaskQueueTest, MaxQueuedRequests) {
  16312. static constexpr unsigned int qlimit{3};
  16313. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16314. std::condition_variable sem_cv;
  16315. std::mutex sem_mtx;
  16316. int credits = 0;
  16317. bool queued;
  16318. /* Fill up the queue with tasks that will block until we give them credits to
  16319. * complete. */
  16320. for (unsigned int n = 0; n <= qlimit;) {
  16321. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16322. std::unique_lock<std::mutex> lock(sem_mtx);
  16323. while (credits <= 0) {
  16324. sem_cv.wait(lock);
  16325. }
  16326. /* Consume the credit and signal the test code if they are all gone. */
  16327. if (--credits == 0) { sem_cv.notify_one(); }
  16328. });
  16329. if (n < qlimit) {
  16330. /* The first qlimit enqueues must succeed. */
  16331. EXPECT_TRUE(queued);
  16332. } else {
  16333. /* The last one will succeed only when the worker thread
  16334. * starts and dequeues the first blocking task. Although
  16335. * not necessary for the correctness of this test, we sleep for
  16336. * a short while to avoid busy waiting. */
  16337. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16338. }
  16339. if (queued) { n++; }
  16340. }
  16341. /* Further enqueues must fail since the queue is full. */
  16342. for (auto i = 0; i < 4; i++) {
  16343. queued = task_queue->enqueue([] {});
  16344. EXPECT_FALSE(queued);
  16345. }
  16346. /* Give the credits to allow the previous tasks to complete. */
  16347. {
  16348. std::unique_lock<std::mutex> lock(sem_mtx);
  16349. credits += qlimit + 1;
  16350. }
  16351. sem_cv.notify_all();
  16352. /* Wait for all the credits to be consumed. */
  16353. {
  16354. std::unique_lock<std::mutex> lock(sem_mtx);
  16355. while (credits > 0) {
  16356. sem_cv.wait(lock);
  16357. }
  16358. }
  16359. /* Check that we are able again to enqueue at least qlimit tasks. */
  16360. for (unsigned int i = 0; i < qlimit; i++) {
  16361. queued = task_queue->enqueue([] {});
  16362. EXPECT_TRUE(queued);
  16363. }
  16364. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16365. task_queue->shutdown();
  16366. #else
  16367. EXPECT_NO_THROW(task_queue->shutdown());
  16368. #endif
  16369. }
  16370. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16371. Server svr;
  16372. std::string method;
  16373. std::string body;
  16374. auto has_content_length = false;
  16375. auto has_transfer_encoding = false;
  16376. std::atomic<int> bad_requests{0};
  16377. // Leftover body bytes get parsed as a malformed request and answered with
  16378. // 400
  16379. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16380. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16381. });
  16382. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16383. res.set_redirect("/down", StatusCode::SeeOther_303);
  16384. });
  16385. svr.Get("/down", [&](const Request &req, Response &res) {
  16386. method = req.method;
  16387. body = req.body;
  16388. has_content_length = req.has_header("Content-Length");
  16389. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16390. res.set_content("ok", "text/plain");
  16391. });
  16392. auto port = svr.bind_to_any_port(HOST);
  16393. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16394. auto se = detail::scope_exit([&] {
  16395. svr.stop();
  16396. thread.join();
  16397. ASSERT_FALSE(svr.is_running());
  16398. });
  16399. svr.wait_until_ready();
  16400. const std::string payload = "SECRET-BODY";
  16401. auto check = [&](Client &cli, const Result &res) {
  16402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16403. EXPECT_EQ(StatusCode::OK_200, res->status);
  16404. EXPECT_EQ("ok", res->body);
  16405. EXPECT_EQ("GET", method);
  16406. EXPECT_TRUE(body.empty());
  16407. EXPECT_FALSE(has_content_length);
  16408. EXPECT_FALSE(has_transfer_encoding);
  16409. // Nothing of the original body may be left on the connection
  16410. auto res2 = cli.Get("/down");
  16411. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16412. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16413. EXPECT_EQ("ok", res2->body);
  16414. EXPECT_EQ(0, bad_requests);
  16415. };
  16416. // With content length
  16417. {
  16418. Client cli(HOST, port);
  16419. cli.set_keep_alive(true);
  16420. cli.set_follow_location(true);
  16421. auto res = cli.Post(
  16422. "/up", payload.size(),
  16423. [&](size_t offset, size_t length, DataSink &sink) {
  16424. return sink.write(payload.data() + offset, length);
  16425. },
  16426. "text/plain");
  16427. check(cli, res);
  16428. }
  16429. // Without content length (chunked)
  16430. {
  16431. Client cli(HOST, port);
  16432. cli.set_keep_alive(true);
  16433. cli.set_follow_location(true);
  16434. auto res = cli.Post(
  16435. "/up",
  16436. [&](size_t /*offset*/, DataSink &sink) {
  16437. sink.write(payload.data(), payload.size());
  16438. sink.done();
  16439. return true;
  16440. },
  16441. "text/plain");
  16442. check(cli, res);
  16443. }
  16444. }
  16445. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16446. Server svr;
  16447. std::string target;
  16448. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16449. // Echo the still-encoded name back in the Location
  16450. const std::string prefix = "/start/";
  16451. res.status = StatusCode::Found_302;
  16452. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16453. });
  16454. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16455. target = req.target;
  16456. res.set_content("ok", "text/plain");
  16457. });
  16458. auto port = svr.bind_to_any_port(HOST);
  16459. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16460. auto se = detail::scope_exit([&] {
  16461. svr.stop();
  16462. thread.join();
  16463. ASSERT_FALSE(svr.is_running());
  16464. });
  16465. svr.wait_until_ready();
  16466. // Decoding the Location path would turn the first four into a path
  16467. // separator, a query delimiter, a fragment delimiter and a different
  16468. // percent-encoded octet. The rest must keep reaching the server as they are.
  16469. const std::vector<std::string> names = {
  16470. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16471. };
  16472. for (auto path_encode : {true, false}) {
  16473. Client cli(HOST, port);
  16474. cli.set_follow_location(true);
  16475. cli.set_path_encode(path_encode);
  16476. for (const auto &name : names) {
  16477. target.clear();
  16478. auto res = cli.Get("/start/" + name);
  16479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16480. EXPECT_EQ(StatusCode::OK_200, res->status);
  16481. EXPECT_EQ("/dest/" + name, target);
  16482. }
  16483. }
  16484. }
  16485. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16486. Server svr;
  16487. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16488. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16489. });
  16490. svr.Get("/hello", [](const Request &req, Response &res) {
  16491. res.set_content(req.get_param_value("key"), "text/plain");
  16492. });
  16493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16494. auto se = detail::scope_exit([&] {
  16495. svr.stop();
  16496. thread.join();
  16497. ASSERT_FALSE(svr.is_running());
  16498. });
  16499. svr.wait_until_ready();
  16500. {
  16501. Client cli(HOST, PORT);
  16502. cli.set_follow_location(true);
  16503. auto res = cli.Get("/");
  16504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16505. EXPECT_EQ(StatusCode::OK_200, res->status);
  16506. EXPECT_EQ("val&key2=val2", res->body);
  16507. }
  16508. }
  16509. #endif
  16510. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16511. Server svr;
  16512. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16513. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16514. });
  16515. svr.Get("/hello", [](const Request &req, Response &res) {
  16516. res.set_content(req.get_param_value("key"), "text/plain");
  16517. });
  16518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16519. auto se = detail::scope_exit([&] {
  16520. svr.stop();
  16521. thread.join();
  16522. ASSERT_FALSE(svr.is_running());
  16523. });
  16524. svr.wait_until_ready();
  16525. {
  16526. Client cli(HOST, PORT);
  16527. cli.set_follow_location(true);
  16528. auto res = cli.Get("/");
  16529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16530. EXPECT_EQ(StatusCode::OK_200, res->status);
  16531. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16532. }
  16533. }
  16534. TEST(RedirectTest, RedirectWithPlusInPath) {
  16535. Server svr;
  16536. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16537. res.set_redirect("/a+b");
  16538. });
  16539. // Route pattern uses regex; escape + as \\+
  16540. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16541. res.set_content(req.path, "text/plain");
  16542. });
  16543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16544. auto se = detail::scope_exit([&] {
  16545. svr.stop();
  16546. thread.join();
  16547. ASSERT_FALSE(svr.is_running());
  16548. });
  16549. svr.wait_until_ready();
  16550. {
  16551. Client cli(HOST, PORT);
  16552. cli.set_follow_location(true);
  16553. auto res = cli.Get("/");
  16554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16555. EXPECT_EQ(StatusCode::OK_200, res->status);
  16556. EXPECT_EQ("/a+b", res->body);
  16557. }
  16558. }
  16559. TEST(RedirectTest, ResolveRelativeLocation) {
  16560. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16561. const std::vector<std::pair<std::string, std::string>> cases = {
  16562. {"g", "/b/c/g"},
  16563. {"./g", "/b/c/g"},
  16564. {"g/", "/b/c/g/"},
  16565. {"?y", "/b/c/d;p?y"},
  16566. {"g?y", "/b/c/g?y"},
  16567. {"#s", "/b/c/d;p?q#s"},
  16568. {"g#s", "/b/c/g#s"},
  16569. {"g?y#s", "/b/c/g?y#s"},
  16570. {";x", "/b/c/;x"},
  16571. {"g;x", "/b/c/g;x"},
  16572. {".", "/b/c/"},
  16573. {"./", "/b/c/"},
  16574. {"..", "/b/"},
  16575. {"../", "/b/"},
  16576. {"../g", "/b/g"},
  16577. {"../..", "/"},
  16578. {"../../", "/"},
  16579. {"../../g", "/g"},
  16580. {"../../../g", "/g"},
  16581. {"g.", "/b/c/g."},
  16582. {".g", "/b/c/.g"},
  16583. {"g..", "/b/c/g.."},
  16584. {"..g", "/b/c/..g"},
  16585. {"./../g", "/b/g"},
  16586. {"./g/.", "/b/c/g/"},
  16587. {"g/./h", "/b/c/g/h"},
  16588. {"g/../h", "/b/c/h"},
  16589. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16590. {"g;x=1/../y", "/b/c/y"},
  16591. {"g?y/./x", "/b/c/g?y/./x"},
  16592. {"g#s/../x", "/b/c/g#s/../x"},
  16593. // Not relative-path references, so left for parse_url.
  16594. {"/g", "/g"},
  16595. {"//g", "//g"},
  16596. {"http://g/x", "http://g/x"},
  16597. {"g:h", "g:h"},
  16598. };
  16599. for (const auto &c : cases) {
  16600. EXPECT_EQ(c.second,
  16601. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16602. << c.first;
  16603. }
  16604. }
  16605. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16606. Server svr;
  16607. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16608. res.set_redirect(req.get_param_value("to"));
  16609. });
  16610. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16611. res.set_content(req.target, "text/plain");
  16612. });
  16613. svr.Get("/other", [](const Request &req, Response &res) {
  16614. res.set_content(req.target, "text/plain");
  16615. });
  16616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16617. auto se = detail::scope_exit([&] {
  16618. svr.stop();
  16619. thread.join();
  16620. ASSERT_FALSE(svr.is_running());
  16621. });
  16622. svr.wait_until_ready();
  16623. const std::vector<std::pair<std::string, std::string>> cases = {
  16624. {"next", "/dir/next"},
  16625. {"./next?x=1", "/dir/next?x=1"},
  16626. {"../other", "/other"},
  16627. };
  16628. for (const auto &c : cases) {
  16629. Client cli(HOST, PORT);
  16630. cli.set_follow_location(true);
  16631. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16632. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16633. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16634. EXPECT_EQ(c.second, res->body) << c.first;
  16635. }
  16636. }
  16637. #ifdef CPPHTTPLIB_SSL_ENABLED
  16638. TEST(RedirectTest, Issue2185_Online) {
  16639. SSLClient client("github.com");
  16640. client.set_follow_location(true);
  16641. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16642. "Coollab-Windows.zip");
  16643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16644. EXPECT_EQ(StatusCode::OK_200, res->status);
  16645. EXPECT_EQ(9920427U, res->body.size());
  16646. }
  16647. #endif
  16648. TEST(VulnerabilityTest, CRLFInjection) {
  16649. Server svr;
  16650. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16651. res.set_content("Hello 1", "text/plain");
  16652. });
  16653. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16654. res.set_content("Hello 2", "text/plain");
  16655. });
  16656. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16657. res.set_content("Hello 3", "text/plain");
  16658. });
  16659. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16660. res.set_content("Hello 4", "text/plain");
  16661. });
  16662. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16663. for (const auto &x : req.headers) {
  16664. auto key = x.first;
  16665. EXPECT_STRNE("evil", key.c_str());
  16666. }
  16667. });
  16668. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16669. auto se = detail::scope_exit([&] {
  16670. svr.stop();
  16671. thread.join();
  16672. ASSERT_FALSE(svr.is_running());
  16673. });
  16674. svr.wait_until_ready();
  16675. {
  16676. Client cli(HOST, PORT);
  16677. cli.Post("/test1", "A=B",
  16678. "application/x-www-form-urlencoded\r\nevil: hello1");
  16679. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16680. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16681. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16682. }
  16683. }
  16684. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16685. auto server_thread = std::thread([] {
  16686. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16687. default_socket_options(srv);
  16688. sockaddr_in addr{};
  16689. addr.sin_family = AF_INET;
  16690. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16691. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16692. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16693. ::listen(srv, 1);
  16694. sockaddr_in cli_addr{};
  16695. socklen_t cli_len = sizeof(cli_addr);
  16696. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16697. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16698. std::string buf_all;
  16699. char buf[2048];
  16700. ssize_t n;
  16701. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16702. buf_all.append(buf, static_cast<size_t>(n));
  16703. size_t pos;
  16704. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16705. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16706. auto e = request_block.find("\r\n");
  16707. if (e != std::string::npos) {
  16708. auto request_line = request_block.substr(0, e);
  16709. std::string msg =
  16710. "CRLF injection detected in request line: '" + request_line + "'";
  16711. EXPECT_FALSE(true) << msg;
  16712. }
  16713. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16714. ::send(cli,
  16715. #ifdef _WIN32
  16716. static_cast<const char *>(resp.c_str()),
  16717. static_cast<int>(resp.size()),
  16718. #else
  16719. resp.c_str(), resp.size(),
  16720. #endif
  16721. 0);
  16722. buf_all.erase(0, pos + 4);
  16723. }
  16724. }
  16725. detail::close_socket(cli);
  16726. detail::close_socket(srv);
  16727. });
  16728. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16729. auto cli = Client("127.0.0.1", PORT + 1);
  16730. auto headers = Headers{
  16731. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16732. {"Connection", "keep-alive"}};
  16733. auto res = cli.Get("/hi", headers);
  16734. EXPECT_FALSE(res);
  16735. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16736. server_thread.join();
  16737. }
  16738. // A request rejected before any byte reaches the socket must fail right away
  16739. // instead of waiting for a response the server will never send.
  16740. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16741. // The kernel completes the TCP handshake from the listen backlog, so the
  16742. // client connects, but nothing ever reads, responds or closes.
  16743. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16744. default_socket_options(srv);
  16745. sockaddr_in addr{};
  16746. addr.sin_family = AF_INET;
  16747. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16748. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16749. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16750. ASSERT_EQ(0, ::listen(srv, 8));
  16751. auto cli = Client("127.0.0.1", PORT + 1);
  16752. cli.set_read_timeout(10, 0);
  16753. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16754. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16755. std::chrono::steady_clock::now() - start)
  16756. .count();
  16757. };
  16758. {
  16759. Request req;
  16760. req.method = "GE T";
  16761. req.path = "/";
  16762. auto start = std::chrono::steady_clock::now();
  16763. auto res = cli.send(req);
  16764. EXPECT_FALSE(res);
  16765. EXPECT_EQ(Error::Write, res.error());
  16766. EXPECT_LT(elapsed_ms(start), 1000);
  16767. }
  16768. {
  16769. auto start = std::chrono::steady_clock::now();
  16770. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16771. EXPECT_FALSE(res);
  16772. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16773. EXPECT_LT(elapsed_ms(start), 1000);
  16774. }
  16775. EXPECT_FALSE(cli.is_socket_open());
  16776. detail::close_socket(srv);
  16777. }
  16778. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16779. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16780. default_socket_options(srv);
  16781. sockaddr_in addr{};
  16782. addr.sin_family = AF_INET;
  16783. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16784. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16785. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16786. ASSERT_EQ(0, ::listen(srv, 1));
  16787. std::string received;
  16788. auto server_thread = std::thread([&] {
  16789. auto sock = ::accept(srv, nullptr, nullptr);
  16790. if (sock == INVALID_SOCKET) { return; }
  16791. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16792. char buf[2048];
  16793. ssize_t n;
  16794. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16795. received.append(buf, static_cast<size_t>(n));
  16796. }
  16797. detail::close_socket(sock);
  16798. });
  16799. {
  16800. auto cli = Client("127.0.0.1", PORT + 1);
  16801. // "Z" sorts after the default headers, so writing straight to the socket
  16802. // would have sent the request line and those headers before the rejection.
  16803. auto handle =
  16804. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16805. EXPECT_FALSE(handle.is_valid());
  16806. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16807. }
  16808. server_thread.join();
  16809. detail::close_socket(srv);
  16810. EXPECT_TRUE(received.empty()) << received;
  16811. }
  16812. TEST(PathParamsTest, StaticMatch) {
  16813. const auto pattern = "/users/all";
  16814. detail::PathParamsMatcher matcher(pattern);
  16815. Request request;
  16816. request.path = "/users/all";
  16817. ASSERT_TRUE(matcher.match(request));
  16818. std::unordered_map<std::string, std::string> expected_params = {};
  16819. EXPECT_EQ(request.path_params, expected_params);
  16820. }
  16821. TEST(PathParamsTest, StaticMismatch) {
  16822. const auto pattern = "/users/all";
  16823. detail::PathParamsMatcher matcher(pattern);
  16824. Request request;
  16825. request.path = "/users/1";
  16826. ASSERT_FALSE(matcher.match(request));
  16827. }
  16828. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16829. const auto pattern = "/users/:id/subscriptions";
  16830. detail::PathParamsMatcher matcher(pattern);
  16831. Request request;
  16832. request.path = "/users/42/subscriptions";
  16833. ASSERT_TRUE(matcher.match(request));
  16834. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16835. EXPECT_EQ(request.path_params, expected_params);
  16836. }
  16837. TEST(PathParamsTest, SingleParamInTheEnd) {
  16838. const auto pattern = "/users/:id";
  16839. detail::PathParamsMatcher matcher(pattern);
  16840. Request request;
  16841. request.path = "/users/24";
  16842. ASSERT_TRUE(matcher.match(request));
  16843. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16844. EXPECT_EQ(request.path_params, expected_params);
  16845. }
  16846. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16847. const auto pattern = "/users/:id/";
  16848. detail::PathParamsMatcher matcher(pattern);
  16849. Request request;
  16850. request.path = "/users/42/";
  16851. ASSERT_TRUE(matcher.match(request));
  16852. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16853. EXPECT_EQ(request.path_params, expected_params);
  16854. }
  16855. TEST(PathParamsTest, EmptyParam) {
  16856. const auto pattern = "/users/:id/";
  16857. detail::PathParamsMatcher matcher(pattern);
  16858. Request request;
  16859. request.path = "/users//";
  16860. ASSERT_TRUE(matcher.match(request));
  16861. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16862. EXPECT_EQ(request.path_params, expected_params);
  16863. }
  16864. TEST(PathParamsTest, FragmentMismatch) {
  16865. const auto pattern = "/users/:id/";
  16866. detail::PathParamsMatcher matcher(pattern);
  16867. Request request;
  16868. request.path = "/admins/24/";
  16869. ASSERT_FALSE(matcher.match(request));
  16870. }
  16871. TEST(PathParamsTest, ExtraFragments) {
  16872. const auto pattern = "/users/:id";
  16873. detail::PathParamsMatcher matcher(pattern);
  16874. Request request;
  16875. request.path = "/users/42/subscriptions";
  16876. ASSERT_FALSE(matcher.match(request));
  16877. }
  16878. TEST(PathParamsTest, MissingTrailingParam) {
  16879. const auto pattern = "/users/:id";
  16880. detail::PathParamsMatcher matcher(pattern);
  16881. Request request;
  16882. request.path = "/users";
  16883. ASSERT_FALSE(matcher.match(request));
  16884. }
  16885. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16886. const auto pattern = "/users/:id/subscriptions";
  16887. detail::PathParamsMatcher matcher(pattern);
  16888. Request request;
  16889. request.path = "/users/subscriptions";
  16890. ASSERT_FALSE(matcher.match(request));
  16891. }
  16892. TEST(PathParamsTest, MultipleParams) {
  16893. const auto pattern = "/users/:userid/subscriptions/:subid";
  16894. detail::PathParamsMatcher matcher(pattern);
  16895. Request request;
  16896. request.path = "/users/42/subscriptions/2";
  16897. ASSERT_TRUE(matcher.match(request));
  16898. std::unordered_map<std::string, std::string> expected_params = {
  16899. {"userid", "42"}, {"subid", "2"}};
  16900. EXPECT_EQ(request.path_params, expected_params);
  16901. }
  16902. TEST(PathParamsTest, SequenceOfParams) {
  16903. const auto pattern = "/values/:x/:y/:z";
  16904. detail::PathParamsMatcher matcher(pattern);
  16905. Request request;
  16906. request.path = "/values/1/2/3";
  16907. ASSERT_TRUE(matcher.match(request));
  16908. std::unordered_map<std::string, std::string> expected_params = {
  16909. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16910. EXPECT_EQ(request.path_params, expected_params);
  16911. }
  16912. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16913. const auto pattern = "/prefix:suffix";
  16914. detail::PathParamsMatcher matcher(pattern);
  16915. Request request;
  16916. request.path = "/prefix:suffix";
  16917. ASSERT_TRUE(matcher.match(request));
  16918. const std::unordered_map<std::string, std::string> expected_params = {};
  16919. EXPECT_EQ(request.path_params, expected_params);
  16920. }
  16921. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16922. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16923. // calling thread's stack on a long enough path for a quantified pattern;
  16924. // RegexMatcher must refuse to run regex matching on paths beyond
  16925. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16926. detail::RegexMatcher matcher("/files/(.*)");
  16927. Request within_limit;
  16928. within_limit.path = "/files/" + std::string(10, 'A');
  16929. EXPECT_TRUE(matcher.match(within_limit));
  16930. Request over_limit;
  16931. over_limit.path =
  16932. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16933. EXPECT_FALSE(matcher.match(over_limit));
  16934. }
  16935. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16936. Server svr;
  16937. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16938. res.set_content("ok", "text/plain");
  16939. });
  16940. auto port = svr.bind_to_any_port(HOST);
  16941. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16942. auto se = detail::scope_exit([&] {
  16943. svr.stop();
  16944. thread.join();
  16945. ASSERT_FALSE(svr.is_running());
  16946. });
  16947. svr.wait_until_ready();
  16948. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16949. // request URI limit; this used to be able to crash the process.
  16950. std::string path =
  16951. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16952. std::string req = "GET " + path +
  16953. " HTTP/1.1\r\n"
  16954. "Host: " +
  16955. std::string(HOST) + ":" + std::to_string(port) +
  16956. "\r\n"
  16957. "Connection: close\r\n"
  16958. "\r\n";
  16959. std::string response;
  16960. ASSERT_TRUE(send_request(5, req, &response, port));
  16961. EXPECT_NE(std::string::npos, response.find("404"));
  16962. }
  16963. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16964. Server svr;
  16965. auto handler = [](const Request & /*req*/, Response &res) {
  16966. res.set_content("hit", "text/plain");
  16967. };
  16968. // No regex metacharacter, so this one is compared literally
  16969. svr.Get("/literal/route", handler);
  16970. // '.' is a regex metacharacter, so this one must keep regex semantics
  16971. svr.Get("/a.c", handler);
  16972. auto port = svr.bind_to_any_port(HOST);
  16973. std::thread t([&]() { svr.listen_after_bind(); });
  16974. auto se = detail::scope_exit([&] {
  16975. svr.stop();
  16976. t.join();
  16977. ASSERT_FALSE(svr.is_running());
  16978. });
  16979. svr.wait_until_ready();
  16980. Client cli(HOST, port);
  16981. struct {
  16982. const char *path;
  16983. int status;
  16984. } cases[] = {
  16985. {"/literal/route", StatusCode::OK_200},
  16986. {"/literal/routes", StatusCode::NotFound_404},
  16987. {"/literal/rout", StatusCode::NotFound_404},
  16988. {"/abc", StatusCode::OK_200},
  16989. {"/a.c", StatusCode::OK_200},
  16990. };
  16991. for (const auto &x : cases) {
  16992. auto res = cli.Get(x.path);
  16993. ASSERT_TRUE(res) << x.path;
  16994. EXPECT_EQ(x.status, res->status) << x.path;
  16995. }
  16996. }
  16997. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16998. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16999. // from exhausting the stack, so it must only constrain routes that actually
  17000. // run a regular expression. A literal route is matched by comparison and
  17001. // stays usable at any length.
  17002. Server svr;
  17003. const std::string pattern =
  17004. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17005. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17006. res.set_content("hit", "text/plain");
  17007. });
  17008. auto port = svr.bind_to_any_port(HOST);
  17009. std::thread t([&]() { svr.listen_after_bind(); });
  17010. auto se = detail::scope_exit([&] {
  17011. svr.stop();
  17012. t.join();
  17013. ASSERT_FALSE(svr.is_running());
  17014. });
  17015. svr.wait_until_ready();
  17016. Client cli(HOST, port);
  17017. auto res = cli.Get(pattern);
  17018. ASSERT_TRUE(res);
  17019. EXPECT_EQ(StatusCode::OK_200, res->status);
  17020. }
  17021. TEST(ParseUrlTest, VariousPatterns) {
  17022. {
  17023. detail::UrlComponents uc;
  17024. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17025. EXPECT_EQ("http", uc.scheme);
  17026. EXPECT_EQ("example.com", uc.host);
  17027. EXPECT_EQ("8080", uc.port);
  17028. EXPECT_EQ("/path", uc.path);
  17029. EXPECT_EQ("?q=1", uc.query);
  17030. }
  17031. {
  17032. detail::UrlComponents uc;
  17033. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17034. EXPECT_EQ("https", uc.scheme);
  17035. EXPECT_EQ("example.com", uc.host);
  17036. EXPECT_TRUE(uc.port.empty());
  17037. EXPECT_EQ("/path", uc.path);
  17038. }
  17039. {
  17040. detail::UrlComponents uc;
  17041. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17042. EXPECT_EQ("::1", uc.host);
  17043. EXPECT_EQ("8080", uc.port);
  17044. EXPECT_EQ("/path", uc.path);
  17045. }
  17046. {
  17047. detail::UrlComponents uc;
  17048. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17049. }
  17050. {
  17051. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17052. // the path while the connection still targets the bracketed host.
  17053. detail::UrlComponents uc;
  17054. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17055. }
  17056. {
  17057. detail::UrlComponents uc;
  17058. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17059. }
  17060. {
  17061. detail::UrlComponents uc;
  17062. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17063. EXPECT_EQ("::1", uc.host);
  17064. EXPECT_TRUE(uc.port.empty());
  17065. EXPECT_EQ("/path", uc.path);
  17066. }
  17067. {
  17068. detail::UrlComponents uc;
  17069. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17070. EXPECT_TRUE(uc.scheme.empty());
  17071. EXPECT_EQ("example.com", uc.host);
  17072. EXPECT_EQ("/path", uc.path);
  17073. EXPECT_EQ("?q=1", uc.query);
  17074. }
  17075. {
  17076. detail::UrlComponents uc;
  17077. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17078. EXPECT_TRUE(uc.host.empty());
  17079. EXPECT_EQ("/path", uc.path);
  17080. EXPECT_EQ("?q=1", uc.query);
  17081. }
  17082. {
  17083. detail::UrlComponents uc;
  17084. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17085. EXPECT_EQ("example.com", uc.host);
  17086. EXPECT_EQ("8080", uc.port);
  17087. }
  17088. {
  17089. // Unix socket path — must not be parsed as host
  17090. detail::UrlComponents uc;
  17091. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17092. EXPECT_TRUE(uc.host.empty());
  17093. }
  17094. {
  17095. detail::UrlComponents uc;
  17096. ASSERT_TRUE(detail::parse_url("", uc));
  17097. EXPECT_TRUE(uc.host.empty());
  17098. EXPECT_TRUE(uc.path.empty());
  17099. }
  17100. {
  17101. detail::UrlComponents uc;
  17102. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17103. }
  17104. {
  17105. detail::UrlComponents uc;
  17106. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17107. }
  17108. {
  17109. // Accepted by parse_url; callers restrict to http/https
  17110. detail::UrlComponents uc;
  17111. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17112. EXPECT_EQ("ftp", uc.scheme);
  17113. }
  17114. {
  17115. detail::UrlComponents uc;
  17116. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17117. }
  17118. {
  17119. detail::UrlComponents uc;
  17120. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17121. }
  17122. }
  17123. TEST(ParseUrlTest, FragmentHandling) {
  17124. {
  17125. detail::UrlComponents uc;
  17126. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17127. EXPECT_EQ("/path", uc.path);
  17128. EXPECT_TRUE(uc.query.empty());
  17129. }
  17130. {
  17131. detail::UrlComponents uc;
  17132. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17133. EXPECT_TRUE(uc.path.empty());
  17134. EXPECT_TRUE(uc.query.empty());
  17135. }
  17136. }
  17137. TEST(ParseUrlTest, UserinfoHandling) {
  17138. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17139. // parsers would see evil.com as the host.
  17140. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17141. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17142. for (auto url : urls) {
  17143. detail::UrlComponents uc;
  17144. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17145. }
  17146. }
  17147. TEST(ParseUrlTest, IPv6EdgeCases) {
  17148. {
  17149. detail::UrlComponents uc;
  17150. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17151. EXPECT_TRUE(uc.scheme.empty());
  17152. EXPECT_EQ("::1", uc.host);
  17153. EXPECT_EQ("8080", uc.port);
  17154. }
  17155. {
  17156. // Zone ID '%25' is not in [a-fA-F0-9:]
  17157. detail::UrlComponents uc;
  17158. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17159. }
  17160. }
  17161. TEST(ParseUrlTest, SchemeEdgeCases) {
  17162. {
  17163. detail::UrlComponents uc;
  17164. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17165. }
  17166. {
  17167. detail::UrlComponents uc;
  17168. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17169. }
  17170. {
  17171. detail::UrlComponents uc;
  17172. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17173. }
  17174. }
  17175. TEST(ParseUrlTest, PortEdgeCases) {
  17176. {
  17177. detail::UrlComponents uc;
  17178. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17179. EXPECT_TRUE(uc.port.empty());
  17180. EXPECT_EQ("/path", uc.path);
  17181. }
  17182. {
  17183. // parse_url accepts any port string; validation is done by parse_port
  17184. detail::UrlComponents uc;
  17185. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17186. EXPECT_EQ("abc", uc.port);
  17187. }
  17188. }
  17189. TEST(ParseUrlTest, WebSocketPatterns) {
  17190. {
  17191. detail::UrlComponents uc;
  17192. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17193. EXPECT_EQ("ws", uc.scheme);
  17194. EXPECT_EQ("echo.example.com", uc.host);
  17195. EXPECT_EQ("8080", uc.port);
  17196. EXPECT_EQ("/ws", uc.path);
  17197. }
  17198. {
  17199. detail::UrlComponents uc;
  17200. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17201. EXPECT_EQ("wss", uc.scheme);
  17202. EXPECT_EQ("echo.example.com", uc.host);
  17203. EXPECT_TRUE(uc.port.empty());
  17204. EXPECT_EQ("/ws", uc.path);
  17205. }
  17206. }
  17207. TEST(ParseUrlTest, QueryOnly) {
  17208. detail::UrlComponents uc;
  17209. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17210. EXPECT_TRUE(uc.host.empty());
  17211. EXPECT_TRUE(uc.path.empty());
  17212. EXPECT_EQ("?q=1&r=2", uc.query);
  17213. }
  17214. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17215. detail::UrlComponents uc;
  17216. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17217. EXPECT_TRUE(uc.scheme.empty());
  17218. EXPECT_EQ("example.com", uc.host);
  17219. EXPECT_EQ("443", uc.port);
  17220. EXPECT_EQ("/path", uc.path);
  17221. }
  17222. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17223. // If ipv6 regex working, regex match codepath is taken.
  17224. // else port will default to 80 in Client impl
  17225. int clientImplMagicPort = 80;
  17226. int port = 4321;
  17227. // above ports must be different to avoid false negative
  17228. EXPECT_NE(clientImplMagicPort, port);
  17229. std::string ipV6TestURL = "http://[ff06::c3]";
  17230. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17231. CLIENT_PRIVATE_KEY_FILE);
  17232. EXPECT_EQ(cli.port(), port);
  17233. }
  17234. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17235. auto file_path = "./www/dir/index.html";
  17236. auto dir_path = "./www/dir";
  17237. detail::FileStat stat_file(file_path);
  17238. EXPECT_TRUE(stat_file.is_file());
  17239. EXPECT_FALSE(stat_file.is_dir());
  17240. detail::FileStat stat_dir(dir_path);
  17241. EXPECT_FALSE(stat_dir.is_file());
  17242. EXPECT_TRUE(stat_dir.is_dir());
  17243. }
  17244. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17245. // IPv4 with default HTTP port (80)
  17246. EXPECT_EQ("example.com",
  17247. detail::make_host_and_port_string("example.com", 80, false));
  17248. // IPv4 with default HTTPS port (443)
  17249. EXPECT_EQ("example.com",
  17250. detail::make_host_and_port_string("example.com", 443, true));
  17251. // IPv4 with non-default HTTP port
  17252. EXPECT_EQ("example.com:8080",
  17253. detail::make_host_and_port_string("example.com", 8080, false));
  17254. // IPv4 with non-default HTTPS port
  17255. EXPECT_EQ("example.com:8443",
  17256. detail::make_host_and_port_string("example.com", 8443, true));
  17257. // IPv6 with default HTTP port (80)
  17258. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17259. // IPv6 with default HTTPS port (443)
  17260. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17261. // IPv6 with non-default HTTP port
  17262. EXPECT_EQ("[::1]:8080",
  17263. detail::make_host_and_port_string("::1", 8080, false));
  17264. // IPv6 with non-default HTTPS port
  17265. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17266. // IPv6 full address with default port
  17267. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17268. detail::make_host_and_port_string(
  17269. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17270. // IPv6 full address with non-default port
  17271. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17272. detail::make_host_and_port_string(
  17273. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17274. // IPv6 localhost with non-default port
  17275. EXPECT_EQ("[::1]:3000",
  17276. detail::make_host_and_port_string("::1", 3000, false));
  17277. // IPv6 with zone ID (link-local address) with default port
  17278. EXPECT_EQ("[fe80::1%eth0]",
  17279. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17280. // IPv6 with zone ID (link-local address) with non-default port
  17281. EXPECT_EQ("[fe80::1%eth0]:8080",
  17282. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17283. // Edge case: Port 443 with is_ssl=false (should add port)
  17284. EXPECT_EQ("example.com:443",
  17285. detail::make_host_and_port_string("example.com", 443, false));
  17286. // Edge case: Port 80 with is_ssl=true (should add port)
  17287. EXPECT_EQ("example.com:80",
  17288. detail::make_host_and_port_string("example.com", 80, true));
  17289. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17290. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17291. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17292. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17293. // Security fix: Already bracketed IPv6 should not get double brackets
  17294. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17295. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17296. EXPECT_EQ("[::1]:8080",
  17297. detail::make_host_and_port_string("[::1]", 8080, false));
  17298. EXPECT_EQ("[2001:db8::1]:8080",
  17299. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17300. EXPECT_EQ("[fe80::1%eth0]",
  17301. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17302. EXPECT_EQ("[fe80::1%eth0]:8080",
  17303. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17304. // Edge case: Empty host (should return as-is)
  17305. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17306. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17307. // This is a known limitation but shouldn't crash
  17308. EXPECT_EQ("[host:name]",
  17309. detail::make_host_and_port_string("host:name", 80, false));
  17310. // Port number edge cases (no validation, but should not crash)
  17311. EXPECT_EQ("example.com:0",
  17312. detail::make_host_and_port_string("example.com", 0, false));
  17313. EXPECT_EQ("example.com:-1",
  17314. detail::make_host_and_port_string("example.com", -1, false));
  17315. EXPECT_EQ("example.com:65535",
  17316. detail::make_host_and_port_string("example.com", 65535, false));
  17317. EXPECT_EQ("example.com:65536",
  17318. detail::make_host_and_port_string("example.com", 65536, false));
  17319. }
  17320. #ifdef CPPHTTPLIB_SSL_ENABLED
  17321. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17322. httplib::SSLClient cli("roblox.com", 443);
  17323. cli.set_follow_location(true);
  17324. auto res = cli.Get("/");
  17325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17326. EXPECT_EQ(StatusCode::OK_200, res->status);
  17327. }
  17328. #endif
  17329. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17330. Server svr;
  17331. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17332. EXPECT_EQ(res.status, 400);
  17333. });
  17334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17335. auto se = detail::scope_exit([&] {
  17336. svr.stop();
  17337. thread.join();
  17338. ASSERT_FALSE(svr.is_running());
  17339. });
  17340. svr.wait_until_ready();
  17341. Client cli(HOST, PORT);
  17342. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17343. }
  17344. TEST(InvalidHeaderCharsTest, is_field_name) {
  17345. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17346. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17347. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17348. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17349. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17350. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17351. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17352. EXPECT_FALSE(detail::fields::is_field_name(""));
  17353. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17354. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17355. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17356. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17357. }
  17358. TEST(InvalidHeaderCharsTest, is_field_value) {
  17359. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17360. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17361. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17362. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17363. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17364. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17365. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17366. EXPECT_TRUE(detail::fields::is_field_value(""));
  17367. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17368. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17369. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17370. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17371. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17372. }
  17373. TEST(InvalidHeaderCharsTest, OnServer) {
  17374. Server svr;
  17375. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17376. std::string header = "Not Set";
  17377. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17378. res.set_header(header, "value");
  17379. res.set_content("Page Content Page Content", "text/plain");
  17380. });
  17381. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17382. std::string header = "Not Set";
  17383. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17384. res.set_header("X-Test", header);
  17385. res.set_content("Page Content Page Content", "text/plain");
  17386. });
  17387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17388. auto se = detail::scope_exit([&] {
  17389. svr.stop();
  17390. thread.join();
  17391. ASSERT_FALSE(svr.is_running());
  17392. });
  17393. svr.wait_until_ready();
  17394. Client cli(HOST, PORT);
  17395. {
  17396. auto res = cli.Get(
  17397. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17399. EXPECT_EQ("Page Content Page Content", res->body);
  17400. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17401. }
  17402. {
  17403. auto res = cli.Get(
  17404. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17406. EXPECT_EQ("Page Content Page Content", res->body);
  17407. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17408. }
  17409. }
  17410. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17411. auto handled = false;
  17412. Server svr;
  17413. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17414. thread t = thread([&] { svr.listen(HOST, PORT); });
  17415. auto se = detail::scope_exit([&] {
  17416. svr.stop();
  17417. t.join();
  17418. ASSERT_FALSE(svr.is_running());
  17419. ASSERT_FALSE(handled);
  17420. });
  17421. svr.wait_until_ready();
  17422. auto req = "POST /test HTTP/1.1\r\n"
  17423. "Content-Length: x\r\n"
  17424. "\r\n";
  17425. std::string response;
  17426. ASSERT_TRUE(send_request(1, req, &response));
  17427. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17428. response.substr(0, response.find("\r\n")));
  17429. }
  17430. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17431. // case-insensitive, and a server that receives a 100-continue expectation in
  17432. // an HTTP/1.0 request MUST ignore it.
  17433. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17434. std::string response;
  17435. ASSERT_TRUE(send_request(1, req, &response, port));
  17436. *got_100 = response.find("100 Continue") != std::string::npos;
  17437. }
  17438. class ExpectTokenTest : public ::testing::Test {
  17439. protected:
  17440. void SetUp() override {
  17441. svr_.Post("/p", [](const Request &, Response &res) {
  17442. res.set_content("ok", "text/plain");
  17443. });
  17444. port_ = svr_.bind_to_any_port(HOST);
  17445. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17446. svr_.wait_until_ready();
  17447. }
  17448. void TearDown() override {
  17449. svr_.stop();
  17450. if (thread_.joinable()) { thread_.join(); }
  17451. }
  17452. std::string request(const char *version, const char *expect_value) const {
  17453. return std::string("POST /p ") + version +
  17454. "\r\n"
  17455. "Host: localhost\r\n"
  17456. "Content-Length: 2\r\n"
  17457. "Connection: close\r\n"
  17458. "Expect: " +
  17459. expect_value +
  17460. "\r\n"
  17461. "\r\n"
  17462. "hi";
  17463. }
  17464. Server svr_;
  17465. int port_ = 0;
  17466. thread thread_;
  17467. };
  17468. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17469. bool got_100 = false;
  17470. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17471. EXPECT_TRUE(got_100);
  17472. }
  17473. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17474. bool got_100 = true;
  17475. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17476. EXPECT_FALSE(got_100);
  17477. }
  17478. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17479. bool got_100 = false;
  17480. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17481. EXPECT_TRUE(got_100);
  17482. }
  17483. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17484. bool got_100 = false;
  17485. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17486. EXPECT_TRUE(got_100);
  17487. }
  17488. // `100 Continue` is sent only when the server starts reading the body, so a
  17489. // request rejected before that never invites the client to send it. The
  17490. // requests below carry the expectation but withhold the body, as a client
  17491. // waiting for `100 Continue` would.
  17492. // A POST that expects `100 Continue` and withholds its two-byte body.
  17493. static std::string expect_headers_only(const std::string &path) {
  17494. return "POST " + path +
  17495. " HTTP/1.1\r\n"
  17496. "Host: localhost\r\n"
  17497. "Content-Length: 2\r\n"
  17498. "Expect: 100-continue\r\n"
  17499. "\r\n";
  17500. }
  17501. class ExpectLazyContinueTest : public ::testing::Test {
  17502. protected:
  17503. void SetUp() override {
  17504. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17505. if (req.path == "/pre-routing") {
  17506. res.status = StatusCode::Unauthorized_401;
  17507. return Server::HandlerResponse::Handled;
  17508. }
  17509. return Server::HandlerResponse::Unhandled;
  17510. });
  17511. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17512. if (req.matched_route == "/pre-request") {
  17513. res.status = StatusCode::Forbidden_403;
  17514. return Server::HandlerResponse::Handled;
  17515. }
  17516. return Server::HandlerResponse::Unhandled;
  17517. });
  17518. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17519. res.set_content("ok", "text/plain");
  17520. });
  17521. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17522. res.set_content("ok", "text/plain");
  17523. });
  17524. svr_.Post("/reader-used", [](const Request &, Response &res,
  17525. const ContentReader &content_reader) {
  17526. std::string body;
  17527. content_reader([&](const char *data, size_t len) {
  17528. body.append(data, len);
  17529. return true;
  17530. });
  17531. res.set_content(body, "text/plain");
  17532. });
  17533. svr_.Post("/reader-unused",
  17534. [](const Request &, Response &res, const ContentReader &) {
  17535. res.set_content("ignored", "text/plain");
  17536. });
  17537. port_ = svr_.bind_to_any_port(HOST);
  17538. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17539. svr_.wait_until_ready();
  17540. }
  17541. void TearDown() override {
  17542. svr_.stop();
  17543. if (thread_.joinable()) { thread_.join(); }
  17544. }
  17545. // Sends `req` and reads until the server closes the connection. Returns
  17546. // false if the read had to wait for the client-side timeout instead.
  17547. bool send_until_closed(const std::string &req, std::string *resp) const {
  17548. auto start = std::chrono::steady_clock::now();
  17549. if (!send_request(3, req, resp, port_)) { return false; }
  17550. auto elapsed = std::chrono::steady_clock::now() - start;
  17551. return elapsed < std::chrono::seconds(2);
  17552. }
  17553. // The final response comes without `100 Continue`, and the server closes
  17554. // the connection since the body may or may not follow.
  17555. void expect_final_without_interim(const std::string &path,
  17556. const char *status_line) const {
  17557. std::string resp;
  17558. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17559. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17560. EXPECT_EQ(0u, resp.find(status_line));
  17561. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17562. }
  17563. Server svr_;
  17564. int port_ = 0;
  17565. thread thread_;
  17566. };
  17567. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17568. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17569. }
  17570. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17571. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17572. }
  17573. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17574. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17575. }
  17576. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17577. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17578. }
  17579. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17580. // The body follows once `100 Continue` has had time to arrive.
  17581. auto req = expect_headers_only("/reader-used");
  17582. req.insert(req.size() - 2, "Connection: close\r\n");
  17583. std::string resp;
  17584. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17585. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17586. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17587. EXPECT_NE(std::string::npos, resp.find("hi"));
  17588. }
  17589. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17590. // Large enough for the client to add `Expect: 100-continue` itself.
  17591. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17592. std::atomic<bool> body_sent{false};
  17593. Client cli(HOST, port_);
  17594. auto res = cli.Post(
  17595. "/pre-request", length,
  17596. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17597. body_sent = true;
  17598. std::string chunk(len, 'x');
  17599. sink.write(chunk.data(), chunk.size());
  17600. return true;
  17601. },
  17602. "application/octet-stream");
  17603. ASSERT_TRUE(res);
  17604. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17605. EXPECT_FALSE(body_sent);
  17606. }
  17607. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17608. Server svr;
  17609. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17610. return StatusCode::ExpectationFailed_417;
  17611. });
  17612. svr.Post("/p", [](const Request &, Response &res) {
  17613. res.set_content("ok", "text/plain");
  17614. });
  17615. auto port = svr.bind_to_any_port(HOST);
  17616. thread t = thread([&] { svr.listen_after_bind(); });
  17617. auto se = detail::scope_exit([&] {
  17618. svr.stop();
  17619. t.join();
  17620. });
  17621. svr.wait_until_ready();
  17622. std::string resp;
  17623. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17624. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17625. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17626. // Exactly one response: the route handler must not run after the 417.
  17627. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17628. }
  17629. #ifndef _WIN32
  17630. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17631. static constexpr char reject[] = "Unauthorized";
  17632. static constexpr char accept[] = "Upload accepted";
  17633. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17634. Server svr;
  17635. svr.set_expect_100_continue_handler(
  17636. [](const Request & /*req*/, Response &res) {
  17637. res.status = StatusCode::Unauthorized_401;
  17638. res.set_content(reject, "text/plain");
  17639. return res.status;
  17640. });
  17641. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17642. res.set_content(accept, "text/plain");
  17643. });
  17644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17645. auto se = detail::scope_exit([&] {
  17646. svr.stop();
  17647. thread.join();
  17648. ASSERT_FALSE(svr.is_running());
  17649. });
  17650. svr.wait_until_ready();
  17651. {
  17652. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17653. curl_easy_init(), &curl_easy_cleanup};
  17654. ASSERT_NE(curl, nullptr);
  17655. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17656. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17657. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17658. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17659. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17660. &curl_slist_free_all};
  17661. ASSERT_NE(list, nullptr);
  17662. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17663. struct read_data {
  17664. size_t read_size;
  17665. size_t total_size;
  17666. } data = {0, total_size};
  17667. using read_callback_t =
  17668. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17669. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17670. void *userdata) -> size_t {
  17671. read_data *d = (read_data *)userdata;
  17672. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17673. std::fill_n(ptr, size * nmemb, 'A');
  17674. d->read_size += size * nmemb;
  17675. return size * nmemb;
  17676. };
  17677. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17678. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17679. std::vector<char> buffer;
  17680. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17681. using write_callback_t =
  17682. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17683. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17684. void *userdata) -> size_t {
  17685. std::vector<char> *buf = (std::vector<char> *)userdata;
  17686. buf->reserve(buf->size() + size * nmemb + 1);
  17687. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17688. return size * nmemb;
  17689. };
  17690. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17691. {
  17692. const auto res = curl_easy_perform(curl.get());
  17693. ASSERT_EQ(res, CURLE_OK);
  17694. }
  17695. {
  17696. auto response_code = long{};
  17697. const auto res =
  17698. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17699. ASSERT_EQ(res, CURLE_OK);
  17700. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17701. }
  17702. {
  17703. auto dl = curl_off_t{};
  17704. const auto res =
  17705. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17706. ASSERT_EQ(res, CURLE_OK);
  17707. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17708. }
  17709. {
  17710. buffer.push_back('\0');
  17711. ASSERT_STRCASEEQ(buffer.data(), reject);
  17712. }
  17713. }
  17714. }
  17715. #endif
  17716. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17717. // Regression test for #2458.
  17718. //
  17719. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17720. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17721. // ticket can make the client socket spuriously readable during the
  17722. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17723. // the client withholds the body and then blocks reading a response that never
  17724. // comes, failing with `Failed to read connection`.
  17725. //
  17726. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17727. // within the timeout. This raw OpenSSL server deliberately never sends
  17728. // `100 Continue`; the client must still deliver the body and receive 200.
  17729. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17730. signal(SIGPIPE, SIG_IGN);
  17731. const auto port = PORT + 4;
  17732. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17733. ASSERT_NE(srv, INVALID_SOCKET);
  17734. int opt = 1;
  17735. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17736. sockaddr_in addr{};
  17737. addr.sin_family = AF_INET;
  17738. addr.sin_port = htons(static_cast<uint16_t>(port));
  17739. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17740. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17741. ASSERT_EQ(0, ::listen(srv, 1));
  17742. std::atomic<size_t> server_body_bytes{0};
  17743. auto server_thread = std::thread([&] {
  17744. sockaddr_in cli_addr{};
  17745. socklen_t cli_len = sizeof(cli_addr);
  17746. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17747. if (cli == INVALID_SOCKET) { return; }
  17748. // Bound the lifetime of the server side so a buggy client (which never
  17749. // sends the body) cannot make this thread block forever on join.
  17750. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17751. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17752. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17753. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17754. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17755. SSL *ssl = SSL_new(ctx);
  17756. SSL_set_fd(ssl, static_cast<int>(cli));
  17757. if (SSL_accept(ssl) > 0) {
  17758. // Read the request headers. Reading here also flushes the TLS 1.3
  17759. // session tickets to the client. Deliberately do NOT send
  17760. // `100 Continue`.
  17761. std::string buf;
  17762. char tmp[1024];
  17763. while (buf.find("\r\n\r\n") == std::string::npos) {
  17764. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17765. if (n <= 0) { break; }
  17766. buf.append(tmp, static_cast<size_t>(n));
  17767. }
  17768. // A correct client sends the body now; count what arrives.
  17769. auto pos = buf.find("\r\n\r\n");
  17770. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17771. while (body < 4096) {
  17772. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17773. if (n <= 0) { break; }
  17774. body += static_cast<size_t>(n);
  17775. }
  17776. server_body_bytes = body;
  17777. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17778. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17779. SSL_shutdown(ssl);
  17780. }
  17781. SSL_free(ssl);
  17782. detail::close_socket(cli);
  17783. SSL_CTX_free(ctx);
  17784. });
  17785. auto se = detail::scope_exit([&] {
  17786. server_thread.join();
  17787. detail::close_socket(srv);
  17788. });
  17789. SSLClient cli("127.0.0.1", port);
  17790. cli.enable_server_certificate_verification(false);
  17791. cli.set_connection_timeout(5, 0);
  17792. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17793. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17794. std::string body(4096, 'A');
  17795. auto res = cli.Put("/api/test", body, "application/json");
  17796. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17797. EXPECT_EQ(StatusCode::OK_200, res->status);
  17798. EXPECT_EQ(body.size(), server_body_bytes.load());
  17799. }
  17800. #endif
  17801. template <typename S, typename C>
  17802. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17803. svr.Get("/stream", [&](const Request &, Response &res) {
  17804. auto data = new std::string("01234567890123456789");
  17805. res.set_content_provider(
  17806. data->size(), "text/plain",
  17807. [&, data](size_t offset, size_t length, DataSink &sink) {
  17808. const size_t DATA_CHUNK_SIZE = 4;
  17809. const auto &d = *data;
  17810. std::this_thread::sleep_for(std::chrono::seconds(1));
  17811. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17812. return true;
  17813. },
  17814. [data](bool success) {
  17815. EXPECT_FALSE(success);
  17816. delete data;
  17817. });
  17818. });
  17819. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17820. auto i = new size_t(0);
  17821. res.set_content_provider(
  17822. "text/plain",
  17823. [i](size_t, DataSink &sink) {
  17824. if (*i < 5) {
  17825. std::this_thread::sleep_for(std::chrono::seconds(1));
  17826. sink.write("abcd", 4);
  17827. (*i)++;
  17828. } else {
  17829. sink.done();
  17830. }
  17831. return true;
  17832. },
  17833. [i](bool success) {
  17834. EXPECT_FALSE(success);
  17835. delete i;
  17836. });
  17837. });
  17838. svr.Get("/chunked", [&](const Request &, Response &res) {
  17839. auto i = new size_t(0);
  17840. res.set_chunked_content_provider(
  17841. "text/plain",
  17842. [i](size_t, DataSink &sink) {
  17843. if (*i < 5) {
  17844. std::this_thread::sleep_for(std::chrono::seconds(1));
  17845. sink.os << "abcd";
  17846. (*i)++;
  17847. } else {
  17848. sink.done();
  17849. }
  17850. return true;
  17851. },
  17852. [i](bool success) {
  17853. EXPECT_FALSE(success);
  17854. delete i;
  17855. });
  17856. });
  17857. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17858. auto se = detail::scope_exit([&] {
  17859. svr.stop();
  17860. listen_thread.join();
  17861. ASSERT_FALSE(svr.is_running());
  17862. });
  17863. svr.wait_until_ready();
  17864. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17865. {
  17866. auto start = std::chrono::steady_clock::now();
  17867. auto res = cli.Get("/stream");
  17868. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17869. std::chrono::steady_clock::now() - start)
  17870. .count();
  17871. ASSERT_FALSE(res);
  17872. EXPECT_EQ(Error::Read, res.error());
  17873. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17874. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17875. }
  17876. {
  17877. auto start = std::chrono::steady_clock::now();
  17878. auto res = cli.Get("/stream_without_length");
  17879. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17880. std::chrono::steady_clock::now() - start)
  17881. .count();
  17882. ASSERT_FALSE(res);
  17883. EXPECT_EQ(Error::Read, res.error());
  17884. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17885. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17886. }
  17887. {
  17888. auto start = std::chrono::steady_clock::now();
  17889. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17890. EXPECT_EQ("abcd", string(data, data_length));
  17891. return true;
  17892. });
  17893. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17894. std::chrono::steady_clock::now() - start)
  17895. .count();
  17896. ASSERT_FALSE(res);
  17897. EXPECT_EQ(Error::Read, res.error());
  17898. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17899. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17900. }
  17901. }
  17902. TEST(MaxTimeoutTest, ContentStream) {
  17903. time_t timeout = 2000;
  17904. time_t threshold = 200;
  17905. Server svr;
  17906. Client cli("localhost", PORT);
  17907. max_timeout_test(svr, cli, timeout, threshold);
  17908. }
  17909. #ifdef CPPHTTPLIB_SSL_ENABLED
  17910. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17911. time_t timeout = 2000;
  17912. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17913. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17914. SSLClient cli("localhost", PORT);
  17915. cli.enable_server_certificate_verification(false);
  17916. max_timeout_test(svr, cli, timeout, threshold);
  17917. }
  17918. #endif
  17919. class EventDispatcher {
  17920. public:
  17921. EventDispatcher() {}
  17922. bool wait_event(DataSink *sink) {
  17923. unique_lock<mutex> lk(m_);
  17924. int id = id_;
  17925. // Wait with timeout to prevent hanging if client disconnects
  17926. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17927. [&] { return cid_ == id; })) {
  17928. return false; // Timeout occurred
  17929. }
  17930. sink->write(message_.data(), message_.size());
  17931. return true;
  17932. }
  17933. void send_event(const string &message) {
  17934. lock_guard<mutex> lk(m_);
  17935. cid_ = id_++;
  17936. message_ = message;
  17937. cv_.notify_all();
  17938. }
  17939. private:
  17940. mutex m_;
  17941. condition_variable cv_;
  17942. atomic_int id_{0};
  17943. atomic_int cid_{-1};
  17944. string message_;
  17945. };
  17946. TEST(ClientInThreadTest, Issue2068) {
  17947. EventDispatcher ed;
  17948. Server svr;
  17949. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17950. res.set_chunked_content_provider("text/event-stream",
  17951. [&](size_t /*offset*/, DataSink &sink) {
  17952. return ed.wait_event(&sink);
  17953. });
  17954. });
  17955. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17956. svr.wait_until_ready();
  17957. thread event_thread([&] {
  17958. int id = 0;
  17959. while (svr.is_running()) {
  17960. this_thread::sleep_for(chrono::milliseconds(500));
  17961. std::stringstream ss;
  17962. ss << "data: " << id << "\n\n";
  17963. ed.send_event(ss.str());
  17964. id++;
  17965. }
  17966. });
  17967. auto se = detail::scope_exit([&] {
  17968. svr.stop();
  17969. listen_thread.join();
  17970. event_thread.join();
  17971. ASSERT_FALSE(svr.is_running());
  17972. });
  17973. {
  17974. auto client = detail::make_unique<Client>(HOST, PORT);
  17975. client->set_read_timeout(std::chrono::minutes(10));
  17976. std::atomic<bool> stop{false};
  17977. std::thread t([&] {
  17978. client->Get("/event1",
  17979. [&](const char *, size_t) -> bool { return !stop; });
  17980. });
  17981. std::this_thread::sleep_for(std::chrono::seconds(2));
  17982. stop = true;
  17983. client->stop();
  17984. t.join();
  17985. // Reset client after thread has finished
  17986. client.reset();
  17987. }
  17988. }
  17989. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17990. auto handled = false;
  17991. Server svr;
  17992. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17993. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17994. auto se = detail::scope_exit([&] {
  17995. svr.stop();
  17996. t.join();
  17997. ASSERT_FALSE(svr.is_running());
  17998. ASSERT_FALSE(handled);
  17999. });
  18000. svr.wait_until_ready();
  18001. // Two Content-Length headers with different values — must be rejected
  18002. auto req = "POST /test HTTP/1.1\r\n"
  18003. "Content-Length: 5\r\n"
  18004. "Content-Length: 10\r\n"
  18005. "\r\n"
  18006. "hello";
  18007. std::string response;
  18008. ASSERT_TRUE(send_request(1, req, &response));
  18009. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18010. response.substr(0, response.find("\r\n")));
  18011. }
  18012. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18013. auto handled = false;
  18014. Server svr;
  18015. svr.Post("/test", [&](const Request &, Response &res) {
  18016. handled = true;
  18017. res.set_content("ok", "text/plain");
  18018. });
  18019. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18020. auto se = detail::scope_exit([&] {
  18021. svr.stop();
  18022. t.join();
  18023. ASSERT_FALSE(svr.is_running());
  18024. ASSERT_TRUE(handled);
  18025. });
  18026. svr.wait_until_ready();
  18027. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18028. auto req = "POST /test HTTP/1.1\r\n"
  18029. "Host: localhost\r\n"
  18030. "Content-Length: 5\r\n"
  18031. "Content-Length: 5\r\n"
  18032. "\r\n"
  18033. "hello";
  18034. std::string response;
  18035. ASSERT_TRUE(send_request(1, req, &response));
  18036. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18037. }
  18038. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18039. Server svr;
  18040. svr.Get("/test", [](const Request &, Response &res) {
  18041. res.set_content("ok", "text/plain");
  18042. });
  18043. auto port = svr.bind_to_any_port(HOST);
  18044. thread t = thread([&] { svr.listen_after_bind(); });
  18045. auto se = detail::scope_exit([&] {
  18046. svr.stop();
  18047. t.join();
  18048. ASSERT_FALSE(svr.is_running());
  18049. });
  18050. svr.wait_until_ready();
  18051. auto status_line = [&](const std::string &host_lines) {
  18052. std::string res;
  18053. send_request(
  18054. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18055. &res, port);
  18056. return res.substr(0, res.find("\r\n"));
  18057. };
  18058. const char *accepted[] = {
  18059. "Host: localhost\r\n",
  18060. "Host: a.example:8080\r\n",
  18061. "Host: my_service\r\n",
  18062. "Host: [::1]:8080\r\n",
  18063. "Host: [fe80::1%25eth0]\r\n",
  18064. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18065. };
  18066. for (auto host_lines : accepted) {
  18067. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18068. }
  18069. const char *rejected[] = {
  18070. "Host: a.example\r\nHost: b.example\r\n",
  18071. "Host: a.example\r\nHost: a.example\r\n",
  18072. "Host: a@b.example\r\n",
  18073. "Host: a.example/b\r\n",
  18074. "Host: a.example\\b\r\n",
  18075. "Host: a.example?b\r\n",
  18076. "Host: a.example#b\r\n",
  18077. "Host: a.example b.example\r\n",
  18078. };
  18079. for (auto host_lines : rejected) {
  18080. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18081. << host_lines;
  18082. }
  18083. }
  18084. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18085. Server svr;
  18086. svr.Get("/", [](const Request &req, Response &res) {
  18087. EXPECT_EQ(2U, req.trailers.size());
  18088. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18089. // Denied
  18090. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18091. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18092. // Accepted
  18093. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18094. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18095. EXPECT_TRUE(req.has_trailer("X-World"));
  18096. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18097. res.set_content("ok", "text/plain");
  18098. });
  18099. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18100. auto se = detail::scope_exit([&] {
  18101. svr.stop();
  18102. t.join();
  18103. ASSERT_FALSE(svr.is_running());
  18104. });
  18105. svr.wait_until_ready();
  18106. const std::string req = "GET / HTTP/1.1\r\n"
  18107. "Transfer-Encoding: chunked\r\n"
  18108. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18109. "\r\n"
  18110. "0\r\n"
  18111. "Content-Length: 10\r\n"
  18112. "Host: internal.local\r\n"
  18113. "Content-Type: malicious/content\r\n"
  18114. "Cookie: any\r\n"
  18115. "Set-Cookie: any\r\n"
  18116. "X-Forwarded-For: attacker.com\r\n"
  18117. "X-Real-Ip: 1.1.1.1\r\n"
  18118. "X-Hello: hello\r\n"
  18119. "X-World: world\r\n"
  18120. "\r\n";
  18121. std::string res;
  18122. ASSERT_TRUE(send_request(1, req, &res));
  18123. }
  18124. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18125. // several field lines, and the combined value is what has to be parsed. A
  18126. // Trailer field split across lines therefore declares every name it lists;
  18127. // reading only the first line silently drops the trailers the later lines
  18128. // declare. The prohibited-trailer filter still applies to every line.
  18129. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18130. Server svr;
  18131. size_t observed_trailer_count = 0;
  18132. std::string observed_hello;
  18133. std::string observed_world;
  18134. bool observed_content_length = true;
  18135. svr.Get("/", [&](const Request &req, Response &res) {
  18136. observed_trailer_count = req.trailers.size();
  18137. observed_hello = req.get_trailer_value("X-Hello");
  18138. observed_world = req.get_trailer_value("X-World");
  18139. observed_content_length = req.has_trailer("Content-Length");
  18140. res.set_content("ok", "text/plain");
  18141. });
  18142. auto port = svr.bind_to_any_port(HOST);
  18143. thread t = thread([&]() { svr.listen_after_bind(); });
  18144. auto se = detail::scope_exit([&] {
  18145. svr.stop();
  18146. t.join();
  18147. ASSERT_FALSE(svr.is_running());
  18148. });
  18149. svr.wait_until_ready();
  18150. const std::string req = "GET / HTTP/1.1\r\n"
  18151. "Host: localhost\r\n"
  18152. "Transfer-Encoding: chunked\r\n"
  18153. "Trailer: X-Hello\r\n"
  18154. "Trailer: X-World, Content-Length\r\n"
  18155. "\r\n"
  18156. "0\r\n"
  18157. "X-Hello: hello\r\n"
  18158. "X-World: world\r\n"
  18159. "Content-Length: 10\r\n"
  18160. "\r\n";
  18161. std::string res;
  18162. ASSERT_TRUE(send_request(1, req, &res, port));
  18163. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18164. // Accepted: both field lines contribute to the declared set
  18165. EXPECT_EQ(2U, observed_trailer_count);
  18166. EXPECT_EQ(observed_hello, "hello");
  18167. EXPECT_EQ(observed_world, "world");
  18168. // Denied: a prohibited name stays prohibited on a later field line
  18169. EXPECT_FALSE(observed_content_length);
  18170. }
  18171. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18172. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18173. // unbounded run of fields that are never declared, because the counter would
  18174. // only advance for declared fields.
  18175. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18176. Server svr;
  18177. bool handler_called = false;
  18178. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18179. handler_called = true;
  18180. res.set_content("ok", "text/plain");
  18181. });
  18182. auto port = svr.bind_to_any_port(HOST);
  18183. thread t = thread([&]() { svr.listen_after_bind(); });
  18184. auto se = detail::scope_exit([&] {
  18185. svr.stop();
  18186. t.join();
  18187. ASSERT_FALSE(svr.is_running());
  18188. });
  18189. svr.wait_until_ready();
  18190. // Declare nothing, then send far more undeclared trailer fields than the
  18191. // header-count limit. Parsing must stop and reject the request rather than
  18192. // read every line.
  18193. std::string req = "GET / HTTP/1.1\r\n"
  18194. "Transfer-Encoding: chunked\r\n"
  18195. "\r\n"
  18196. "0\r\n";
  18197. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18198. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18199. }
  18200. req += "\r\n";
  18201. std::string res;
  18202. ASSERT_TRUE(send_request(1, req, &res, port));
  18203. // The request is rejected before the handler runs.
  18204. EXPECT_FALSE(handler_called);
  18205. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18206. }
  18207. // The set of declared trailer names is capped so a peer cannot grow it without
  18208. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18209. // declared past the cap is not honored, even if the field is actually sent.
  18210. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18211. Server svr;
  18212. // One name inside the cap and one past it, so the test tracks the cap rather
  18213. // than a fixed count.
  18214. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18215. const std::string within_cap_name = "X-T-0";
  18216. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18217. bool observed_within_cap = false;
  18218. bool observed_past_cap = false;
  18219. svr.Get("/", [&](const Request &req, Response &res) {
  18220. observed_within_cap = req.has_trailer(within_cap_name);
  18221. observed_past_cap = req.has_trailer(past_cap_name);
  18222. res.set_content("ok", "text/plain");
  18223. });
  18224. auto port = svr.bind_to_any_port(HOST);
  18225. thread t = thread([&]() { svr.listen_after_bind(); });
  18226. auto se = detail::scope_exit([&] {
  18227. svr.stop();
  18228. t.join();
  18229. ASSERT_FALSE(svr.is_running());
  18230. });
  18231. svr.wait_until_ready();
  18232. // Declare more trailer names than the cap in a single Trailer field, then
  18233. // actually send the first (within the cap) and the last (past it).
  18234. std::string trailer_decl = "Trailer: ";
  18235. for (int i = 0; i < declared_count; i++) {
  18236. if (i != 0) { trailer_decl += ", "; }
  18237. trailer_decl += "X-T-" + std::to_string(i);
  18238. }
  18239. trailer_decl += "\r\n";
  18240. const std::string req = "GET / HTTP/1.1\r\n"
  18241. "Host: localhost\r\n"
  18242. "Transfer-Encoding: chunked\r\n" +
  18243. trailer_decl +
  18244. "\r\n"
  18245. "0\r\n" +
  18246. within_cap_name + ": a\r\n" + past_cap_name +
  18247. ": b\r\n"
  18248. "\r\n";
  18249. std::string res;
  18250. ASSERT_TRUE(send_request(1, req, &res, port));
  18251. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18252. // A name within the cap is honored; one declared past the cap is dropped.
  18253. EXPECT_TRUE(observed_within_cap);
  18254. EXPECT_FALSE(observed_past_cap);
  18255. }
  18256. // A direct client that is not listed in trusted_proxies must not be able to
  18257. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18258. // the peer address on the actual TCP connection determines whether the
  18259. // header is honored.
  18260. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18261. Server svr;
  18262. // Deliberately does NOT include the loopback address the test client
  18263. // actually connects from, so the direct connection is not a trusted proxy.
  18264. svr.set_trusted_proxies({"203.0.113.66"});
  18265. std::string observed_remote_addr;
  18266. svr.Get("/ip", [&](const Request &req, Response &res) {
  18267. observed_remote_addr = req.remote_addr;
  18268. res.set_content("ok", "text/plain");
  18269. });
  18270. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18271. auto se = detail::scope_exit([&] {
  18272. svr.stop();
  18273. t.join();
  18274. ASSERT_FALSE(svr.is_running());
  18275. });
  18276. svr.wait_until_ready();
  18277. Client cli(HOST, PORT);
  18278. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18280. EXPECT_EQ(StatusCode::OK_200, res->status);
  18281. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18282. // ignored entirely and the real connection-level address retained.
  18283. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18284. observed_remote_addr == "127.0.0.1");
  18285. }
  18286. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18287. Server svr;
  18288. std::string observed_remote_addr;
  18289. std::string observed_xff;
  18290. svr.Get("/ip", [&](const Request &req, Response &res) {
  18291. observed_remote_addr = req.remote_addr;
  18292. observed_xff = req.get_header_value("X-Forwarded-For");
  18293. res.set_content("ok", "text/plain");
  18294. });
  18295. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18296. auto se = detail::scope_exit([&] {
  18297. svr.stop();
  18298. t.join();
  18299. ASSERT_FALSE(svr.is_running());
  18300. });
  18301. svr.wait_until_ready();
  18302. Client cli(HOST, PORT);
  18303. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18305. EXPECT_EQ(StatusCode::OK_200, res->status);
  18306. EXPECT_EQ(observed_xff, "203.0.113.66");
  18307. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18308. observed_remote_addr == "127.0.0.1");
  18309. }
  18310. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18311. Server svr;
  18312. svr.set_trusted_proxies({"203.0.113.66"});
  18313. std::string observed_remote_addr;
  18314. std::string observed_xff;
  18315. svr.Get("/ip", [&](const Request &req, Response &res) {
  18316. observed_remote_addr = req.remote_addr;
  18317. observed_xff = req.get_header_value("X-Forwarded-For");
  18318. res.set_content("ok", "text/plain");
  18319. });
  18320. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18321. auto se = detail::scope_exit([&] {
  18322. svr.stop();
  18323. t.join();
  18324. ASSERT_FALSE(svr.is_running());
  18325. });
  18326. svr.wait_until_ready();
  18327. Client cli(HOST, PORT);
  18328. auto res = cli.Get("/ip");
  18329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18330. EXPECT_EQ(StatusCode::OK_200, res->status);
  18331. EXPECT_EQ(observed_xff, "");
  18332. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18333. observed_remote_addr == "127.0.0.1");
  18334. }
  18335. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18336. Server svr;
  18337. // Include the loopback address the test client actually connects from, so
  18338. // the direct connection itself is recognized as the trusted proxy hop.
  18339. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18340. std::string observed_remote_addr;
  18341. std::string observed_xff;
  18342. svr.Get("/ip", [&](const Request &req, Response &res) {
  18343. observed_remote_addr = req.remote_addr;
  18344. observed_xff = req.get_header_value("X-Forwarded-For");
  18345. res.set_content("ok", "text/plain");
  18346. });
  18347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18348. auto se = detail::scope_exit([&] {
  18349. svr.stop();
  18350. t.join();
  18351. ASSERT_FALSE(svr.is_running());
  18352. });
  18353. svr.wait_until_ready();
  18354. Client cli(HOST, PORT);
  18355. auto res = cli.Get(
  18356. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18358. EXPECT_EQ(StatusCode::OK_200, res->status);
  18359. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18360. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18361. }
  18362. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18363. Server svr;
  18364. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18365. std::string observed_remote_addr;
  18366. std::string observed_xff;
  18367. svr.Get("/ip", [&](const Request &req, Response &res) {
  18368. observed_remote_addr = req.remote_addr;
  18369. observed_xff = req.get_header_value("X-Forwarded-For");
  18370. res.set_content("ok", "text/plain");
  18371. });
  18372. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18373. auto se = detail::scope_exit([&] {
  18374. svr.stop();
  18375. t.join();
  18376. ASSERT_FALSE(svr.is_running());
  18377. });
  18378. svr.wait_until_ready();
  18379. Client cli(HOST, PORT);
  18380. auto res = cli.Get(
  18381. "/ip",
  18382. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18384. EXPECT_EQ(StatusCode::OK_200, res->status);
  18385. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18386. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18387. }
  18388. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18389. Server svr;
  18390. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18391. std::string observed_remote_addr;
  18392. std::string observed_xff;
  18393. svr.Get("/ip", [&](const Request &req, Response &res) {
  18394. observed_remote_addr = req.remote_addr;
  18395. observed_xff = req.get_header_value("X-Forwarded-For");
  18396. res.set_content("ok", "text/plain");
  18397. });
  18398. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18399. auto se = detail::scope_exit([&] {
  18400. svr.stop();
  18401. t.join();
  18402. ASSERT_FALSE(svr.is_running());
  18403. });
  18404. svr.wait_until_ready();
  18405. Client cli(HOST, PORT);
  18406. auto res = cli.Get(
  18407. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18409. EXPECT_EQ(StatusCode::OK_200, res->status);
  18410. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18411. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18412. // and must not be selected.
  18413. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18414. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18415. }
  18416. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18417. Server svr;
  18418. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18419. std::string observed_remote_addr;
  18420. svr.Get("/ip", [&](const Request &req, Response &res) {
  18421. observed_remote_addr = req.remote_addr;
  18422. res.set_content("ok", "text/plain");
  18423. });
  18424. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18425. auto se = detail::scope_exit([&] {
  18426. svr.stop();
  18427. t.join();
  18428. ASSERT_FALSE(svr.is_running());
  18429. });
  18430. svr.wait_until_ready();
  18431. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18432. // a forged address and the trusted proxy's own address; the forged value must
  18433. // not win over the address the trusted proxy actually recorded.
  18434. Client cli(HOST, PORT);
  18435. auto res = cli.Get(
  18436. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18438. EXPECT_EQ(StatusCode::OK_200, res->status);
  18439. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18440. }
  18441. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18442. Server svr;
  18443. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18444. std::string observed_remote_addr;
  18445. std::string observed_xff;
  18446. svr.Get("/ip", [&](const Request &req, Response &res) {
  18447. observed_remote_addr = req.remote_addr;
  18448. observed_xff = req.get_header_value("X-Forwarded-For");
  18449. res.set_content("ok", "text/plain");
  18450. });
  18451. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18452. auto se = detail::scope_exit([&] {
  18453. svr.stop();
  18454. t.join();
  18455. ASSERT_FALSE(svr.is_running());
  18456. });
  18457. svr.wait_until_ready();
  18458. Client cli(HOST, PORT);
  18459. auto res = cli.Get(
  18460. "/ip",
  18461. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18463. EXPECT_EQ(StatusCode::OK_200, res->status);
  18464. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18465. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18466. }
  18467. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18468. Server svr;
  18469. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18470. std::string observed_remote_addr;
  18471. std::string observed_xff;
  18472. svr.Get("/ip", [&](const Request &req, Response &res) {
  18473. observed_remote_addr = req.remote_addr;
  18474. observed_xff = req.get_header_value("X-Forwarded-For");
  18475. res.set_content("ok", "text/plain");
  18476. });
  18477. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18478. auto se = detail::scope_exit([&] {
  18479. svr.stop();
  18480. t.join();
  18481. ASSERT_FALSE(svr.is_running());
  18482. });
  18483. svr.wait_until_ready();
  18484. std::string raw_req =
  18485. "GET /ip HTTP/1.1\r\n"
  18486. "Host: localhost\r\n"
  18487. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18488. "Connection: close\r\n"
  18489. "\r\n";
  18490. std::string out;
  18491. ASSERT_TRUE(send_request(5, raw_req, &out));
  18492. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18493. // Header parser trims surrounding whitespace of the header value
  18494. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18495. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18496. }
  18497. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18498. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18499. // their own X-Forwarded-For as a separate field line rather than extending the
  18500. // one the client sent, so every occurrence has to be taken into account.
  18501. // Reading only the first one hands back the address the client chose.
  18502. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18503. Server svr;
  18504. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18505. std::string observed_remote_addr;
  18506. size_t observed_xff_count = 0;
  18507. svr.Get("/ip", [&](const Request &req, Response &res) {
  18508. observed_remote_addr = req.remote_addr;
  18509. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18510. res.set_content("ok", "text/plain");
  18511. });
  18512. auto port = svr.bind_to_any_port(HOST);
  18513. thread t = thread([&]() { svr.listen_after_bind(); });
  18514. auto se = detail::scope_exit([&] {
  18515. svr.stop();
  18516. t.join();
  18517. ASSERT_FALSE(svr.is_running());
  18518. });
  18519. svr.wait_until_ready();
  18520. // The client supplies the first field line; the trusted proxy appends the
  18521. // address it observed as a second one.
  18522. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18523. "Host: localhost\r\n"
  18524. "X-Forwarded-For: 1.2.3.4\r\n"
  18525. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18526. "Connection: close\r\n"
  18527. "\r\n";
  18528. std::string out;
  18529. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18530. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18531. EXPECT_EQ(observed_xff_count, 2U);
  18532. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18533. // The same chain spread over one field line per hop derives the same client
  18534. // address, i.e. the split and the comma-joined representations agree.
  18535. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18536. "Host: localhost\r\n"
  18537. "X-Forwarded-For: 1.2.3.4\r\n"
  18538. "X-Forwarded-For: 198.51.100.23\r\n"
  18539. "X-Forwarded-For: 192.0.2.45\r\n"
  18540. "Connection: close\r\n"
  18541. "\r\n";
  18542. out.clear();
  18543. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18544. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18545. EXPECT_EQ(observed_xff_count, 3U);
  18546. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18547. }
  18548. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18549. // crash the server (it used to call front() on an empty vector inside
  18550. // get_client_ip). The connection-level remote address must be retained instead.
  18551. static void run_malformed_xff_test(const std::string &xff_value) {
  18552. Server svr;
  18553. svr.set_trusted_proxies({"192.0.2.45"});
  18554. std::string observed_remote_addr;
  18555. svr.Get("/ip", [&](const Request &req, Response &res) {
  18556. observed_remote_addr = req.remote_addr;
  18557. res.set_content("ok", "text/plain");
  18558. });
  18559. int port = 0;
  18560. thread t = thread([&]() {
  18561. port = svr.bind_to_any_port(HOST);
  18562. svr.listen_after_bind();
  18563. });
  18564. auto se = detail::scope_exit([&] {
  18565. svr.stop();
  18566. t.join();
  18567. ASSERT_FALSE(svr.is_running());
  18568. });
  18569. svr.wait_until_ready();
  18570. Client cli(HOST, port);
  18571. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18573. EXPECT_EQ(StatusCode::OK_200, res->status);
  18574. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18575. observed_remote_addr == "127.0.0.1");
  18576. }
  18577. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18578. run_malformed_xff_test("");
  18579. }
  18580. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18581. run_malformed_xff_test(",");
  18582. }
  18583. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18584. run_malformed_xff_test(", , ,");
  18585. }
  18586. // The same rule applies to Accept: a request whose acceptable types are spread
  18587. // over several field lines must be negotiated against all of them.
  18588. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18589. // case-insensitive connection options. Comparing the whole field value against
  18590. // one option misses a client that sends several of them, and misses every
  18591. // casing but the one written in the comparison.
  18592. //
  18593. // Sends req, reads the response, then reuses the same socket for a second
  18594. // request to find out whether the server kept the connection.
  18595. static void probe_connection_reuse(int port, const std::string &req,
  18596. bool *announced_close, bool *reusable) {
  18597. auto error = Error::Success;
  18598. auto sock = detail::create_client_socket(
  18599. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18600. /*connection_timeout_sec=*/5, 0,
  18601. /*read_timeout_sec=*/1, 0,
  18602. /*write_timeout_sec=*/5, 0, std::string(), error);
  18603. ASSERT_NE(sock, INVALID_SOCKET);
  18604. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18605. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18606. "Host: localhost\r\n"
  18607. "Connection: close\r\n"
  18608. "\r\n";
  18609. std::string first_response;
  18610. std::string second_response;
  18611. detail::process_client_socket(
  18612. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18613. [&](Stream &strm) {
  18614. if (strm.write(req.data(), req.size()) !=
  18615. static_cast<ssize_t>(req.size())) {
  18616. return false;
  18617. }
  18618. char buf[512];
  18619. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18620. // Headers plus the two-byte body of the handler below
  18621. while (reader.getline()) {
  18622. first_response += reader.ptr();
  18623. if (first_response.find("ok") != std::string::npos) { break; }
  18624. }
  18625. if (strm.write(second.data(), second.size()) !=
  18626. static_cast<ssize_t>(second.size())) {
  18627. return true;
  18628. }
  18629. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18630. while (reader2.getline()) {
  18631. second_response += reader2.ptr();
  18632. if (second_response.find("ok") != std::string::npos) { break; }
  18633. }
  18634. return true;
  18635. });
  18636. *announced_close =
  18637. first_response.find("Connection: close") != std::string::npos;
  18638. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18639. }
  18640. class ConnectionTokenTest : public ::testing::Test {
  18641. protected:
  18642. void SetUp() override {
  18643. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18644. res.set_content("ok", "text/plain");
  18645. });
  18646. port_ = svr_.bind_to_any_port(HOST);
  18647. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18648. svr_.wait_until_ready();
  18649. }
  18650. void TearDown() override {
  18651. svr_.stop();
  18652. if (thread_.joinable()) { thread_.join(); }
  18653. }
  18654. Server svr_;
  18655. int port_ = 0;
  18656. thread thread_;
  18657. };
  18658. // "close" alongside another option still closes the connection, and the
  18659. // response says so rather than leaving the peer to discover it.
  18660. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18661. bool announced_close = false;
  18662. bool reusable = true;
  18663. probe_connection_reuse(port_,
  18664. "GET /keepalive HTTP/1.1\r\n"
  18665. "Host: localhost\r\n"
  18666. "Connection: keep-alive, close\r\n"
  18667. "\r\n",
  18668. &announced_close, &reusable);
  18669. EXPECT_TRUE(announced_close);
  18670. EXPECT_FALSE(reusable);
  18671. }
  18672. // "close" split over two field lines is the same list, so it is honored too.
  18673. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18674. bool announced_close = false;
  18675. bool reusable = true;
  18676. probe_connection_reuse(port_,
  18677. "GET /keepalive HTTP/1.1\r\n"
  18678. "Host: localhost\r\n"
  18679. "Connection: keep-alive\r\n"
  18680. "Connection: close\r\n"
  18681. "\r\n",
  18682. &announced_close, &reusable);
  18683. EXPECT_TRUE(announced_close);
  18684. EXPECT_FALSE(reusable);
  18685. }
  18686. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18687. // keep-alive in the spelling everyone actually sends keeps its connection.
  18688. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18689. bool announced_close = false;
  18690. bool reusable = false;
  18691. probe_connection_reuse(port_,
  18692. "GET /keepalive HTTP/1.0\r\n"
  18693. "Host: localhost\r\n"
  18694. "Connection: keep-alive\r\n"
  18695. "\r\n",
  18696. &announced_close, &reusable);
  18697. EXPECT_FALSE(announced_close);
  18698. EXPECT_TRUE(reusable);
  18699. }
  18700. // A token the value merely contains is not the token itself.
  18701. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18702. bool announced_close = false;
  18703. bool reusable = false;
  18704. probe_connection_reuse(port_,
  18705. "GET /keepalive HTTP/1.1\r\n"
  18706. "Host: localhost\r\n"
  18707. "Connection: notclose\r\n"
  18708. "\r\n",
  18709. &announced_close, &reusable);
  18710. EXPECT_FALSE(announced_close);
  18711. EXPECT_TRUE(reusable);
  18712. }
  18713. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18714. Server svr;
  18715. std::vector<std::string> observed_types;
  18716. svr.Get("/", [&](const Request &req, Response &res) {
  18717. observed_types = req.accept_content_types;
  18718. res.set_content("ok", "text/plain");
  18719. });
  18720. auto port = svr.bind_to_any_port(HOST);
  18721. thread t = thread([&]() { svr.listen_after_bind(); });
  18722. auto se = detail::scope_exit([&] {
  18723. svr.stop();
  18724. t.join();
  18725. ASSERT_FALSE(svr.is_running());
  18726. });
  18727. svr.wait_until_ready();
  18728. Client cli(HOST, port);
  18729. Headers headers;
  18730. headers.emplace("Accept", "text/plain;q=0.5");
  18731. headers.emplace("Accept", "application/json");
  18732. auto res = cli.Get("/", headers);
  18733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18734. EXPECT_EQ(StatusCode::OK_200, res->status);
  18735. // Sorted by q-value, so the second field line's type comes first
  18736. ASSERT_EQ(2U, observed_types.size());
  18737. EXPECT_EQ("application/json", observed_types[0]);
  18738. EXPECT_EQ("text/plain", observed_types[1]);
  18739. }
  18740. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18741. // empty field line must not contribute a bare comma to the combined value.
  18742. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18743. Server svr;
  18744. std::vector<std::string> observed_types;
  18745. svr.Get("/", [&](const Request &req, Response &res) {
  18746. observed_types = req.accept_content_types;
  18747. res.set_content("ok", "text/plain");
  18748. });
  18749. auto port = svr.bind_to_any_port(HOST);
  18750. thread t = thread([&]() { svr.listen_after_bind(); });
  18751. auto se = detail::scope_exit([&] {
  18752. svr.stop();
  18753. t.join();
  18754. ASSERT_FALSE(svr.is_running());
  18755. });
  18756. svr.wait_until_ready();
  18757. // Empty first field line, then a real one
  18758. std::string raw_req = "GET / HTTP/1.1\r\n"
  18759. "Host: localhost\r\n"
  18760. "Accept:\r\n"
  18761. "Accept: application/json\r\n"
  18762. "Connection: close\r\n"
  18763. "\r\n";
  18764. std::string out;
  18765. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18766. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18767. ASSERT_EQ(1U, observed_types.size());
  18768. EXPECT_EQ("application/json", observed_types[0]);
  18769. }
  18770. // The skip in get_combined_header_value() is what keeps an empty field line
  18771. // from contributing a bare comma. Only a trailing empty field line exercises
  18772. // it: a leading one is already covered by the "combined is still empty" check,
  18773. // and parse_accept_header() now ignores the empty element either way, so the
  18774. // request-level test above can no longer tell the two apart.
  18775. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18776. Headers headers;
  18777. headers.emplace("Accept", "text/html");
  18778. headers.emplace("Accept", "");
  18779. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18780. headers.clear();
  18781. headers.emplace("Accept", "");
  18782. headers.emplace("Accept", "application/json");
  18783. EXPECT_EQ("application/json",
  18784. detail::get_combined_header_value(headers, "Accept"));
  18785. }
  18786. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18787. // An encoding offered on a later Accept-Encoding field line is still offered.
  18788. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18789. Server svr;
  18790. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18791. res.set_content(std::string(1024, 'x'), "text/plain");
  18792. });
  18793. auto port = svr.bind_to_any_port(HOST);
  18794. thread t = thread([&]() { svr.listen_after_bind(); });
  18795. auto se = detail::scope_exit([&] {
  18796. svr.stop();
  18797. t.join();
  18798. ASSERT_FALSE(svr.is_running());
  18799. });
  18800. svr.wait_until_ready();
  18801. Client cli(HOST, port);
  18802. cli.set_decompress(false);
  18803. Headers headers;
  18804. headers.emplace("Accept-Encoding", "identity");
  18805. headers.emplace("Accept-Encoding", "gzip");
  18806. auto res = cli.Get("/", headers);
  18807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18808. EXPECT_EQ(StatusCode::OK_200, res->status);
  18809. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18810. }
  18811. #endif
  18812. #ifndef _WIN32
  18813. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18814. Server svr;
  18815. svr.Post("/post", [&](const Request &req, Response &res) {
  18816. res.set_content(req.body, "text/plain");
  18817. });
  18818. svr.Put("/put", [&](const Request &req, Response &res) {
  18819. res.set_content(req.body, "text/plain");
  18820. });
  18821. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18822. res.set_content(req.body, "text/plain");
  18823. });
  18824. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18825. res.set_content(req.body, "text/plain");
  18826. });
  18827. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18828. auto se = detail::scope_exit([&] {
  18829. svr.stop();
  18830. t.join();
  18831. ASSERT_FALSE(svr.is_running());
  18832. });
  18833. svr.wait_until_ready();
  18834. std::string resp;
  18835. // POST without Content-Length
  18836. ASSERT_TRUE(send_request(5,
  18837. "POST /post HTTP/1.1\r\n"
  18838. "Host: localhost\r\n"
  18839. "Connection: close\r\n"
  18840. "\r\n",
  18841. &resp));
  18842. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18843. // PUT without Content-Length
  18844. resp.clear();
  18845. ASSERT_TRUE(send_request(5,
  18846. "PUT /put HTTP/1.1\r\n"
  18847. "Host: localhost\r\n"
  18848. "Connection: close\r\n"
  18849. "\r\n",
  18850. &resp));
  18851. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18852. // PATCH without Content-Length
  18853. resp.clear();
  18854. ASSERT_TRUE(send_request(5,
  18855. "PATCH /patch HTTP/1.1\r\n"
  18856. "Host: localhost\r\n"
  18857. "Connection: close\r\n"
  18858. "\r\n",
  18859. &resp));
  18860. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18861. // DELETE without Content-Length
  18862. resp.clear();
  18863. ASSERT_TRUE(send_request(5,
  18864. "DELETE /delete HTTP/1.1\r\n"
  18865. "Host: localhost\r\n"
  18866. "Connection: close\r\n"
  18867. "\r\n",
  18868. &resp));
  18869. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18870. }
  18871. #endif
  18872. //==============================================================================
  18873. // open_stream() Tests
  18874. //==============================================================================
  18875. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18876. std::string result;
  18877. char buf[8192];
  18878. ssize_t n;
  18879. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18880. result.append(buf, static_cast<size_t>(n));
  18881. }
  18882. return result;
  18883. }
  18884. // Mock stream for unit tests
  18885. class MockStream : public Stream {
  18886. public:
  18887. std::string data;
  18888. size_t pos = 0;
  18889. ssize_t error_after = -1; // -1 = no error
  18890. explicit MockStream(const std::string &d, ssize_t err = -1)
  18891. : data(d), error_after(err) {}
  18892. bool is_readable() const override { return true; }
  18893. bool wait_readable() const override { return true; }
  18894. bool wait_writable() const override { return true; }
  18895. ssize_t read(char *ptr, size_t size) override {
  18896. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18897. if (pos >= data.size()) return 0;
  18898. size_t limit =
  18899. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18900. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18901. std::memcpy(ptr, data.data() + pos, to_read);
  18902. pos += to_read;
  18903. return static_cast<ssize_t>(to_read);
  18904. }
  18905. ssize_t write(const char *, size_t) override { return -1; }
  18906. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18907. ip = "127.0.0.1";
  18908. port = 0;
  18909. }
  18910. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18911. ip = "127.0.0.1";
  18912. port = 0;
  18913. }
  18914. socket_t socket() const override { return INVALID_SOCKET; }
  18915. time_t duration() const override { return 0; }
  18916. };
  18917. TEST(StreamHandleTest, Basic) {
  18918. ClientImpl::StreamHandle handle;
  18919. EXPECT_FALSE(handle.is_valid());
  18920. handle.response = detail::make_unique<Response>();
  18921. handle.error = Error::Connection;
  18922. EXPECT_FALSE(handle.is_valid());
  18923. handle.error = Error::Success;
  18924. EXPECT_TRUE(handle.is_valid());
  18925. }
  18926. TEST(BodyReaderTest, Basic) {
  18927. MockStream stream("Hello, World!");
  18928. detail::BodyReader reader;
  18929. reader.stream = &stream;
  18930. reader.content_length = 13;
  18931. char buf[32];
  18932. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18933. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18934. EXPECT_TRUE(reader.eof);
  18935. }
  18936. TEST(BodyReaderTest, NoStream) {
  18937. detail::BodyReader reader;
  18938. char buf[32];
  18939. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18940. EXPECT_EQ(Error::Connection, reader.last_error);
  18941. }
  18942. TEST(BodyReaderTest, Error) {
  18943. MockStream stream("Hello, World!", 5);
  18944. detail::BodyReader reader;
  18945. reader.stream = &stream;
  18946. reader.content_length = 13;
  18947. char buf[32];
  18948. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18949. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18950. EXPECT_EQ(Error::Read, reader.last_error);
  18951. }
  18952. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18953. // Mock-based StreamHandle tests relying on private internals are removed.
  18954. class OpenStreamTest : public ::testing::Test {
  18955. protected:
  18956. void SetUp() override {
  18957. svr_.Get("/hello", [](const Request &, Response &res) {
  18958. res.set_content("Hello World!", "text/plain");
  18959. });
  18960. svr_.Get("/large", [](const Request &, Response &res) {
  18961. res.set_content(std::string(10000, 'X'), "text/plain");
  18962. });
  18963. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18964. res.set_content("Hello World!", "image/jpeg");
  18965. res.set_header("Content-Encoding", "UTF-8");
  18966. });
  18967. svr_.Get("/chunked", [](const Request &, Response &res) {
  18968. res.set_chunked_content_provider("text/plain",
  18969. [](size_t offset, DataSink &sink) {
  18970. if (offset < 15) {
  18971. sink.write("chunk", 5);
  18972. return true;
  18973. }
  18974. sink.done();
  18975. return true;
  18976. });
  18977. });
  18978. svr_.Get("/compressible", [](const Request &, Response &res) {
  18979. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18980. DataSink &sink) {
  18981. if (offset < 100 * 1024) {
  18982. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18983. sink.write(chunk.data(), chunk.size());
  18984. return true;
  18985. }
  18986. sink.done();
  18987. return true;
  18988. });
  18989. });
  18990. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18991. [](const Request & /*req*/, Response &res) {
  18992. auto i = new int(0);
  18993. res.set_header("Trailer", "Content-Length, X-Allowed");
  18994. res.set_chunked_content_provider(
  18995. "text/plain",
  18996. [i](size_t /*offset*/, DataSink &sink) {
  18997. switch (*i) {
  18998. case 0: sink.os << "123"; break;
  18999. case 1: sink.os << "456"; break;
  19000. case 2: sink.os << "789"; break;
  19001. case 3: {
  19002. sink.done_with_trailer(
  19003. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19004. } break;
  19005. }
  19006. (*i)++;
  19007. return true;
  19008. },
  19009. [i](bool success) {
  19010. EXPECT_TRUE(success);
  19011. delete i;
  19012. });
  19013. });
  19014. // Echo headers endpoint for header-related tests
  19015. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19016. std::string body;
  19017. for (const auto &h : req.headers) {
  19018. body.append(h.first);
  19019. body.push_back(':');
  19020. body.append(h.second);
  19021. body.push_back('\n');
  19022. }
  19023. res.set_content(body, "text/plain");
  19024. });
  19025. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19026. std::string body;
  19027. for (const auto &h : req.headers) {
  19028. body.append(h.first);
  19029. body.push_back(':');
  19030. body.append(h.second);
  19031. body.push_back('\n');
  19032. }
  19033. res.set_content(body, "text/plain");
  19034. });
  19035. port_ = svr_.bind_to_any_port("127.0.0.1");
  19036. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19037. svr_.wait_until_ready();
  19038. }
  19039. void TearDown() override {
  19040. svr_.stop();
  19041. if (thread_.joinable()) thread_.join();
  19042. }
  19043. Server svr_;
  19044. std::thread thread_;
  19045. int port_ = 0;
  19046. };
  19047. TEST_F(OpenStreamTest, Basic) {
  19048. Client cli("127.0.0.1", port_);
  19049. auto handle = cli.open_stream("GET", "/hello");
  19050. EXPECT_TRUE(handle.is_valid());
  19051. EXPECT_EQ("Hello World!", read_all(handle));
  19052. }
  19053. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19054. Client cli("127.0.0.1", port_);
  19055. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19056. ASSERT_TRUE(handle.is_valid());
  19057. EXPECT_EQ("Hello World!", read_all(handle));
  19058. }
  19059. TEST_F(OpenStreamTest, SmallBuffer) {
  19060. Client cli("127.0.0.1", port_);
  19061. auto handle = cli.open_stream("GET", "/hello");
  19062. std::string result;
  19063. char buf[4];
  19064. ssize_t n;
  19065. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19066. result.append(buf, static_cast<size_t>(n));
  19067. EXPECT_EQ("Hello World!", result);
  19068. }
  19069. TEST_F(OpenStreamTest, DefaultHeaders) {
  19070. Client cli("127.0.0.1", port_);
  19071. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19072. {
  19073. auto handle = cli.open_stream("GET", "/echo-headers");
  19074. ASSERT_TRUE(handle.is_valid());
  19075. auto body = read_all(handle);
  19076. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19077. std::string::npos);
  19078. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19079. std::string::npos);
  19080. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19081. }
  19082. // open_stream POST with body and no explicit content_type should NOT add
  19083. // text/plain Content-Type (behavior differs from non-streaming path), but
  19084. // should include Content-Length
  19085. {
  19086. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19087. ASSERT_TRUE(handle.is_valid());
  19088. auto body = read_all(handle);
  19089. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19090. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19091. }
  19092. // open_stream POST with explicit Content-Type should preserve it
  19093. {
  19094. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19095. {{"Content-Type", "application/custom"}},
  19096. "{}", "application/custom");
  19097. ASSERT_TRUE(handle.is_valid());
  19098. auto body = read_all(handle);
  19099. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19100. }
  19101. // User-specified User-Agent must not be overwritten for stream API
  19102. {
  19103. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19104. {{"User-Agent", "MyAgent/1.2"}});
  19105. ASSERT_TRUE(handle.is_valid());
  19106. auto body = read_all(handle);
  19107. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19108. }
  19109. }
  19110. TEST_F(OpenStreamTest, Large) {
  19111. Client cli("127.0.0.1", port_);
  19112. auto handle = cli.open_stream("GET", "/large");
  19113. EXPECT_EQ(10000u, read_all(handle).size());
  19114. }
  19115. TEST_F(OpenStreamTest, ConnectionError) {
  19116. Client cli("127.0.0.1", 9999);
  19117. auto handle = cli.open_stream("GET", "/hello");
  19118. EXPECT_FALSE(handle.is_valid());
  19119. }
  19120. TEST_F(OpenStreamTest, Chunked) {
  19121. Client cli("127.0.0.1", port_);
  19122. auto handle = cli.open_stream("GET", "/chunked");
  19123. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19124. "Transfer-Encoding") == "chunked");
  19125. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19126. }
  19127. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19128. Client cli("127.0.0.1", port_);
  19129. auto handle =
  19130. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19131. ASSERT_TRUE(handle.is_valid());
  19132. // Consume body to allow trailers to be received/parsed
  19133. auto body = read_all(handle);
  19134. // Explicitly parse trailers (ensure trailers are available for assertion)
  19135. handle.parse_trailers_if_needed();
  19136. EXPECT_EQ(std::string("123456789"), body);
  19137. // The response should include a Trailer header declaring both names
  19138. ASSERT_TRUE(handle.response);
  19139. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19140. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19141. handle.response->get_header_value("Trailer"));
  19142. // Prohibited trailer must not be present
  19143. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19144. // Allowed trailer should be present
  19145. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19146. EXPECT_EQ(std::string("yes"),
  19147. handle.response->get_trailer_value("X-Allowed"));
  19148. // Verify trailers are NOT present as regular headers
  19149. EXPECT_EQ(std::string(""),
  19150. handle.response->get_header_value("Content-Length"));
  19151. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19152. }
  19153. // Accepts one connection on an OS-assigned port, which it hands over through
  19154. // port_promise, reads the request head and sends back response. after_send,
  19155. // if given, runs on the connection before it is closed.
  19156. static std::thread
  19157. serve_single_response(std::promise<int> &port_promise,
  19158. const std::string &response,
  19159. std::function<void(socket_t)> after_send = nullptr) {
  19160. return std::thread([&port_promise, response, after_send] {
  19161. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19162. default_socket_options(srv);
  19163. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19164. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19165. sockaddr_in addr{};
  19166. addr.sin_family = AF_INET;
  19167. addr.sin_port = htons(0); // Let OS assign a free port
  19168. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19169. int opt = 1;
  19170. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19171. #ifdef _WIN32
  19172. reinterpret_cast<const char *>(&opt),
  19173. #else
  19174. &opt,
  19175. #endif
  19176. sizeof(opt));
  19177. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19178. ::listen(srv, 1) != 0) {
  19179. port_promise.set_value(-1);
  19180. detail::close_socket(srv);
  19181. return;
  19182. }
  19183. socklen_t addr_len = sizeof(addr);
  19184. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19185. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19186. sockaddr_in cli_addr{};
  19187. socklen_t cli_len = sizeof(cli_addr);
  19188. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19189. if (cli != INVALID_SOCKET) {
  19190. // Read the complete HTTP request (until the blank line that terminates
  19191. // headers) before sending the response. If the server closes the socket
  19192. // while the client's request data is still unread in the kernel receive
  19193. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19194. // connection on both sides: it discards the client's receive buffer
  19195. // (which already holds our response) and causes any in-progress write on
  19196. // the client to fail with ECONNRESET. Reading all request data first
  19197. // ensures close() emits a graceful FIN.
  19198. {
  19199. char rbuf[256];
  19200. std::string req;
  19201. while (req.find("\r\n\r\n") == std::string::npos) {
  19202. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19203. if (n <= 0) { break; }
  19204. req.append(rbuf, static_cast<size_t>(n));
  19205. }
  19206. }
  19207. ::send(cli,
  19208. #ifdef _WIN32
  19209. static_cast<const char *>(response.c_str()),
  19210. static_cast<int>(response.size()),
  19211. #else
  19212. response.c_str(), response.size(),
  19213. #endif
  19214. 0);
  19215. if (after_send) { after_send(cli); }
  19216. detail::close_socket(cli);
  19217. }
  19218. detail::close_socket(srv);
  19219. });
  19220. }
  19221. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19222. #ifndef _WIN32
  19223. signal(SIGPIPE, SIG_IGN);
  19224. #endif
  19225. std::promise<int> port_promise;
  19226. auto port_future = port_promise.get_future();
  19227. auto server_thread =
  19228. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19229. "Content-Type: text/plain\r\n"
  19230. "Content-Length: not-a-number\r\n"
  19231. "Connection: close\r\n"
  19232. "\r\n"
  19233. "hello");
  19234. auto port = port_future.get();
  19235. ASSERT_GT(port, 0);
  19236. Client cli("127.0.0.1", port);
  19237. auto handle = cli.open_stream("GET", "/");
  19238. EXPECT_FALSE(handle.is_valid());
  19239. server_thread.join();
  19240. }
  19241. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19242. #ifndef _WIN32
  19243. signal(SIGPIPE, SIG_IGN);
  19244. #endif
  19245. std::promise<int> port_promise;
  19246. auto port_future = port_promise.get_future();
  19247. auto server_thread = serve_single_response(
  19248. port_promise, "HTTP/1.1 200 OK\r\n"
  19249. "Content-Type: text/plain\r\n"
  19250. "Content-Length: 99999999999999999999999999\r\n"
  19251. "Connection: close\r\n"
  19252. "\r\n"
  19253. "hello");
  19254. auto port = port_future.get();
  19255. ASSERT_GT(port, 0);
  19256. // Historically std::stoull would throw std::out_of_range here and crash
  19257. // the process, then parsing silently clamped to a bogus framing length and
  19258. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19259. // so the stream fails to open, matching the not-a-number case above. The
  19260. // process still must NOT terminate.
  19261. Client cli("127.0.0.1", port);
  19262. auto handle = cli.open_stream("GET", "/");
  19263. EXPECT_FALSE(handle.is_valid());
  19264. server_thread.join();
  19265. }
  19266. // Serves `response` to the single request `fn` makes with a fresh client.
  19267. template <typename Fn>
  19268. static void with_single_response(const std::string &response, Fn fn) {
  19269. #ifndef _WIN32
  19270. signal(SIGPIPE, SIG_IGN);
  19271. #endif
  19272. std::promise<int> port_promise;
  19273. auto port_future = port_promise.get_future();
  19274. auto server_thread = serve_single_response(port_promise, response);
  19275. auto se = detail::scope_exit([&] { server_thread.join(); });
  19276. auto port = port_future.get();
  19277. ASSERT_GT(port, 0);
  19278. Client cli("127.0.0.1", port);
  19279. fn(cli);
  19280. }
  19281. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19282. const char *responses[] = {
  19283. "HTTP/1.1 103 Early Hints\r\n"
  19284. "Link: </style.css>; rel=preload\r\n"
  19285. "\r\n"
  19286. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19287. "HTTP/1.1 100 Continue\r\n"
  19288. "X-Note: interim\r\n"
  19289. "\r\n"
  19290. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19291. };
  19292. for (auto response : responses) {
  19293. with_single_response(response, [](Client &cli) {
  19294. auto res = cli.Get("/");
  19295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19296. EXPECT_EQ(StatusCode::OK_200, res->status);
  19297. EXPECT_EQ("ok", res->body);
  19298. });
  19299. }
  19300. }
  19301. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19302. #ifndef _WIN32
  19303. signal(SIGPIPE, SIG_IGN);
  19304. #endif
  19305. // The server answers the head without asking for the body. Bytes it then
  19306. // reads on the connection would be taken for the body the request declared.
  19307. auto closed_by_client = false;
  19308. std::promise<int> port_promise;
  19309. auto server_thread = serve_single_response(
  19310. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19311. [&](socket_t sock) {
  19312. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19313. char buf[256];
  19314. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19315. });
  19316. Client cli("127.0.0.1", port_promise.get_future().get());
  19317. cli.set_keep_alive(true);
  19318. cli.set_read_timeout(1, 0);
  19319. // Long enough for the client to send Expect: 100-continue.
  19320. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19322. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19323. cli.Get("/second");
  19324. server_thread.join();
  19325. EXPECT_TRUE(closed_by_client);
  19326. }
  19327. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19328. // Long enough for the client to send Expect: 100-continue
  19329. with_single_response(
  19330. "HTTP/1.1 103 Early Hints\r\n"
  19331. "Link: </style.css>; rel=preload\r\n"
  19332. "\r\n"
  19333. "HTTP/1.1 401 Unauthorized\r\n"
  19334. "Content-Length: 0\r\n\r\n",
  19335. [](Client &cli) {
  19336. cli.set_read_timeout(2, 0);
  19337. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19339. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19340. });
  19341. }
  19342. #ifdef CPPHTTPLIB_SSL_ENABLED
  19343. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19344. #ifndef _WIN32
  19345. signal(SIGPIPE, SIG_IGN);
  19346. #endif
  19347. auto reused = false;
  19348. std::promise<int> port_promise;
  19349. auto server_thread = serve_single_response(
  19350. port_promise,
  19351. "HTTP/1.1 401 Unauthorized\r\n"
  19352. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19353. "Content-Length: 0\r\n\r\n",
  19354. [&](socket_t sock) {
  19355. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19356. char buf[256];
  19357. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19358. });
  19359. Client cli("127.0.0.1", port_promise.get_future().get());
  19360. cli.set_keep_alive(true);
  19361. cli.set_digest_auth("user", "pass");
  19362. cli.set_read_timeout(1, 0);
  19363. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19364. server_thread.join();
  19365. EXPECT_FALSE(reused);
  19366. }
  19367. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19368. // Any other answer to CONNECT would read as the origin's response.
  19369. struct {
  19370. const char *response;
  19371. bool passed_on;
  19372. } cases[] = {
  19373. {"HTTP/1.1 201 Created\r\n"
  19374. "Set-Cookie: session=from-proxy\r\n"
  19375. "Content-Length: 0\r\n\r\n",
  19376. false},
  19377. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19378. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19379. "Content-Length: 0\r\n\r\n",
  19380. true},
  19381. };
  19382. for (const auto &c : cases) {
  19383. std::promise<int> port_promise;
  19384. auto server_thread = serve_single_response(port_promise, c.response);
  19385. SSLClient cli("example.com", 443);
  19386. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19387. auto res = cli.Get("/");
  19388. server_thread.join();
  19389. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19390. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19391. if (res) {
  19392. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19393. }
  19394. }
  19395. }
  19396. #endif
  19397. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19398. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19399. // the chunked coding and drop Content-Length, so a front-end that trusts
  19400. // Content-Length would disagree about where the body ends (response
  19401. // smuggling). The client must reject such a response.
  19402. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19403. for (const char *te : {"chunked", "gzip, chunked"}) {
  19404. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19405. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19406. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19407. "5\r\nhello\r\n0\r\n\r\n";
  19408. with_single_response(response, [&](Client &cli) {
  19409. auto res = cli.Get("/");
  19410. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19411. EXPECT_EQ(Error::Read, res.error()) << te;
  19412. });
  19413. with_single_response(response, [&](Client &cli) {
  19414. auto handle = cli.open_stream("GET", "/");
  19415. EXPECT_FALSE(handle.is_valid()) << te;
  19416. EXPECT_EQ(Error::Read, handle.error) << te;
  19417. });
  19418. }
  19419. }
  19420. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19421. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19422. // closing the connection (unlike a request, which must be rejected).
  19423. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19424. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19425. "Transfer-Encoding: chunked\r\n"
  19426. "Connection: close\r\n"
  19427. "\r\n"
  19428. "5\r\nhello\r\n0\r\n\r\n",
  19429. "HTTP/1.1 200 OK\r\n"
  19430. "Transfer-Encoding: gzip\r\n"
  19431. "Connection: close\r\n"
  19432. "\r\n"
  19433. "hello"}) {
  19434. with_single_response(response, [&](Client &cli) {
  19435. auto res = cli.Get("/");
  19436. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19437. EXPECT_EQ("hello", res->body);
  19438. });
  19439. with_single_response(response, [&](Client &cli) {
  19440. auto handle = cli.open_stream("GET", "/");
  19441. ASSERT_TRUE(handle.is_valid()) << response;
  19442. EXPECT_EQ("hello", read_all(handle));
  19443. });
  19444. }
  19445. }
  19446. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19447. // framing headers describe nothing to read and must not be rejected.
  19448. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19449. const std::string framing = "Content-Length: 5\r\n"
  19450. "Transfer-Encoding: chunked\r\n"
  19451. "Connection: close\r\n"
  19452. "\r\n";
  19453. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19454. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19455. });
  19456. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19457. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19458. });
  19459. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19460. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19461. with_single_response(response, [&](Client &cli) {
  19462. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19463. });
  19464. with_single_response(response, [&](Client &cli) {
  19465. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19466. });
  19467. }
  19468. }
  19469. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19470. // response, is faulty framing, so the connection is not reused after it.
  19471. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19472. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19473. "Content-Length: 0\r\n"
  19474. "Transfer-Encoding: chunked\r\n"
  19475. "\r\n"
  19476. "5\r\nhello\r\n0\r\n\r\n",
  19477. "HTTP/1.0 200 Connection established\r\n"
  19478. "Connection: keep-alive\r\n"
  19479. "Transfer-Encoding: chunked\r\n"
  19480. "\r\n"
  19481. "5\r\nhello\r\n0\r\n\r\n"}) {
  19482. with_single_response(response, [&](Client &cli) {
  19483. cli.set_keep_alive(true);
  19484. auto res = cli.Get("/");
  19485. ASSERT_TRUE(res) << response;
  19486. EXPECT_EQ("hello", res->body);
  19487. EXPECT_FALSE(cli.is_socket_open()) << response;
  19488. });
  19489. }
  19490. }
  19491. // A payload max length of 0 means no limit, however the body is framed.
  19492. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19493. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19494. "Transfer-Encoding: chunked\r\n"
  19495. "\r\n"
  19496. "5\r\nhello\r\n0\r\n\r\n",
  19497. "HTTP/1.1 200 OK\r\n"
  19498. "Connection: close\r\n"
  19499. "\r\n"
  19500. "hello"}) {
  19501. with_single_response(response, [&](Client &cli) {
  19502. cli.set_payload_max_length(0);
  19503. auto res = cli.Get("/");
  19504. ASSERT_TRUE(res) << response;
  19505. EXPECT_EQ("hello", res->body) << response;
  19506. });
  19507. }
  19508. }
  19509. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19510. Server svr;
  19511. svr.set_payload_max_length(0);
  19512. svr.Post("/echo", [](const Request &req, Response &res) {
  19513. res.set_content(req.body, "text/plain");
  19514. });
  19515. auto port = svr.bind_to_any_port(HOST);
  19516. thread t = thread([&] { svr.listen_after_bind(); });
  19517. auto se = detail::scope_exit([&] {
  19518. svr.stop();
  19519. t.join();
  19520. ASSERT_FALSE(svr.is_running());
  19521. });
  19522. svr.wait_until_ready();
  19523. Client cli(HOST, port);
  19524. auto res = cli.Post(
  19525. "/echo",
  19526. [](size_t /*offset*/, DataSink &sink) {
  19527. sink.write("hello", 5);
  19528. sink.done();
  19529. return true;
  19530. },
  19531. "text/plain");
  19532. ASSERT_TRUE(res);
  19533. EXPECT_EQ(StatusCode::OK_200, res->status);
  19534. EXPECT_EQ("hello", res->body);
  19535. }
  19536. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19537. TEST_F(OpenStreamTest, Gzip) {
  19538. Client cli("127.0.0.1", port_);
  19539. auto handle = cli.open_stream("GET", "/compressible", {},
  19540. {{"Accept-Encoding", "gzip"}});
  19541. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19542. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19543. }
  19544. #endif
  19545. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19546. TEST_F(OpenStreamTest, Brotli) {
  19547. Client cli("127.0.0.1", port_);
  19548. auto handle =
  19549. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19550. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19551. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19552. }
  19553. #endif
  19554. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19555. TEST_F(OpenStreamTest, Zstd) {
  19556. Client cli("127.0.0.1", port_);
  19557. auto handle = cli.open_stream("GET", "/compressible", {},
  19558. {{"Accept-Encoding", "zstd"}});
  19559. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19560. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19561. }
  19562. #endif
  19563. #ifdef CPPHTTPLIB_SSL_ENABLED
  19564. class SSLOpenStreamTest : public ::testing::Test {
  19565. protected:
  19566. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19567. void SetUp() override {
  19568. svr_.Get("/hello", [](const Request &, Response &res) {
  19569. res.set_content("Hello SSL World!", "text/plain");
  19570. });
  19571. svr_.Get("/chunked", [](const Request &, Response &res) {
  19572. res.set_chunked_content_provider("text/plain",
  19573. [](size_t offset, DataSink &sink) {
  19574. if (offset < 15) {
  19575. sink.write("chunk", 5);
  19576. return true;
  19577. }
  19578. sink.done();
  19579. return true;
  19580. });
  19581. });
  19582. svr_.Post("/echo", [](const Request &req, Response &res) {
  19583. res.set_content(req.body, req.get_header_value("Content-Type"));
  19584. });
  19585. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19586. std::string body = req.body;
  19587. res.set_chunked_content_provider(
  19588. "text/plain", [body](size_t offset, DataSink &sink) {
  19589. if (offset < body.size()) {
  19590. sink.write(body.data() + offset, body.size() - offset);
  19591. }
  19592. sink.done();
  19593. return true;
  19594. });
  19595. });
  19596. port_ = svr_.bind_to_any_port("127.0.0.1");
  19597. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19598. svr_.wait_until_ready();
  19599. }
  19600. void TearDown() override {
  19601. svr_.stop();
  19602. if (thread_.joinable()) thread_.join();
  19603. }
  19604. SSLServer svr_;
  19605. std::thread thread_;
  19606. int port_ = 0;
  19607. };
  19608. TEST_F(SSLOpenStreamTest, Basic) {
  19609. SSLClient cli("127.0.0.1", port_);
  19610. cli.enable_server_certificate_verification(false);
  19611. auto handle = cli.open_stream("GET", "/hello");
  19612. ASSERT_TRUE(handle.is_valid());
  19613. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19614. }
  19615. TEST_F(SSLOpenStreamTest, Chunked) {
  19616. SSLClient cli("127.0.0.1", port_);
  19617. cli.enable_server_certificate_verification(false);
  19618. auto handle = cli.open_stream("GET", "/chunked");
  19619. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19620. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19621. "Transfer-Encoding") == "chunked");
  19622. auto body = read_all(handle);
  19623. EXPECT_EQ("chunkchunkchunk", body);
  19624. }
  19625. TEST_F(SSLOpenStreamTest, Post) {
  19626. SSLClient cli("127.0.0.1", port_);
  19627. cli.enable_server_certificate_verification(false);
  19628. auto handle =
  19629. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19630. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19631. EXPECT_EQ(200, handle.response->status);
  19632. auto body = read_all(handle);
  19633. EXPECT_EQ("Hello SSL POST", body);
  19634. }
  19635. TEST_F(SSLOpenStreamTest, PostChunked) {
  19636. SSLClient cli("127.0.0.1", port_);
  19637. cli.enable_server_certificate_verification(false);
  19638. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19639. "Chunked SSL Data", "text/plain");
  19640. ASSERT_TRUE(handle.is_valid());
  19641. EXPECT_EQ(200, handle.response->status);
  19642. auto body = read_all(handle);
  19643. EXPECT_EQ("Chunked SSL Data", body);
  19644. }
  19645. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19646. // Content-Length is terminated by the server closing the connection. When the
  19647. // SSL peer sends a close_notify after the body, the client must treat it as a
  19648. // clean EOF and return a successful response rather than an error.
  19649. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19651. ASSERT_TRUE(svr.is_valid());
  19652. svr.set_keep_alive_max_count(1);
  19653. const std::string expected_body = "Hello from connection-close response!";
  19654. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19655. res.set_content_provider("text/plain",
  19656. [&](size_t offset, DataSink &sink) -> bool {
  19657. if (offset < expected_body.size()) {
  19658. sink.write(expected_body.data() + offset,
  19659. expected_body.size() - offset);
  19660. }
  19661. sink.done();
  19662. return true;
  19663. });
  19664. });
  19665. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19666. auto se = detail::scope_exit([&] {
  19667. svr.stop();
  19668. listen_thread.join();
  19669. ASSERT_FALSE(svr.is_running());
  19670. });
  19671. svr.wait_until_ready();
  19672. SSLClient cli(HOST, PORT);
  19673. cli.enable_server_certificate_verification(false);
  19674. auto res = cli.Get("/no-content-length");
  19675. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19676. EXPECT_EQ(StatusCode::OK_200, res->status);
  19677. EXPECT_EQ(expected_body, res->body);
  19678. }
  19679. #endif // CPPHTTPLIB_SSL_ENABLED
  19680. //==============================================================================
  19681. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19682. // results for various scenarios.
  19683. //==============================================================================
  19684. TEST(ParityTest, GetVsOpenStream) {
  19685. Server svr;
  19686. const std::string path = "/parity";
  19687. const std::string content = "Parity test content: hello world";
  19688. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19689. res.set_content(content, "text/plain");
  19690. });
  19691. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19692. auto se = detail::scope_exit([&] {
  19693. svr.stop();
  19694. t.join();
  19695. ASSERT_FALSE(svr.is_running());
  19696. });
  19697. svr.wait_until_ready();
  19698. Client cli(HOST, PORT);
  19699. // Non-stream path
  19700. auto r1 = cli.Get(path);
  19701. ASSERT_TRUE(r1);
  19702. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19703. // Stream path
  19704. auto h = cli.open_stream("GET", path);
  19705. ASSERT_TRUE(h.is_valid());
  19706. EXPECT_EQ(r1->body, read_all(h));
  19707. }
  19708. // Helper to compress data with provided compressor type T
  19709. template <typename Compressor>
  19710. static std::string compress_payload_for_parity(const std::string &in) {
  19711. std::string out;
  19712. Compressor compressor;
  19713. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19714. [&](const char *data, size_t n) {
  19715. out.append(data, n);
  19716. return true;
  19717. });
  19718. EXPECT_TRUE(ok);
  19719. return out;
  19720. }
  19721. // Helper function for compression parity tests
  19722. template <typename Compressor>
  19723. static void test_compression_parity(const std::string &original,
  19724. const std::string &path,
  19725. const std::string &encoding) {
  19726. const std::string compressed =
  19727. compress_payload_for_parity<Compressor>(original);
  19728. Server svr;
  19729. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19730. res.set_content(compressed, "application/octet-stream");
  19731. res.set_header("Content-Encoding", encoding);
  19732. });
  19733. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19734. auto se = detail::scope_exit([&] {
  19735. svr.stop();
  19736. t.join();
  19737. ASSERT_FALSE(svr.is_running());
  19738. });
  19739. svr.wait_until_ready();
  19740. Client cli(HOST, PORT);
  19741. // Non-streaming
  19742. {
  19743. auto res = cli.Get(path);
  19744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19745. EXPECT_EQ(StatusCode::OK_200, res->status);
  19746. EXPECT_EQ(original, res->body);
  19747. }
  19748. // Streaming
  19749. {
  19750. auto h = cli.open_stream("GET", path);
  19751. ASSERT_TRUE(h.is_valid());
  19752. EXPECT_EQ(original, read_all(h));
  19753. }
  19754. }
  19755. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19756. TEST(ParityTest, Gzip) {
  19757. test_compression_parity<detail::gzip_compressor>(
  19758. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19759. }
  19760. #endif
  19761. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19762. TEST(ParityTest, Brotli) {
  19763. test_compression_parity<detail::brotli_compressor>(
  19764. "Hello, brotli parity test payload", "/parity-br", "br");
  19765. }
  19766. #endif
  19767. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19768. TEST(ParityTest, Zstd) {
  19769. test_compression_parity<detail::zstd_compressor>(
  19770. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19771. }
  19772. #endif
  19773. //==============================================================================
  19774. // New Stream API Tests
  19775. //==============================================================================
  19776. inline std::string read_body(httplib::stream::Result &result) {
  19777. std::string body;
  19778. while (result.next()) {
  19779. body.append(result.data(), result.size());
  19780. }
  19781. return body;
  19782. }
  19783. TEST(ClientConnectionTest, Basic) {
  19784. httplib::ClientConnection conn;
  19785. EXPECT_FALSE(conn.is_open());
  19786. conn.sock = 1;
  19787. EXPECT_TRUE(conn.is_open());
  19788. httplib::ClientConnection conn2(std::move(conn));
  19789. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19790. conn2.sock = INVALID_SOCKET;
  19791. }
  19792. // Unified test server for all stream::* tests
  19793. class StreamApiTest : public ::testing::Test {
  19794. protected:
  19795. void SetUp() override {
  19796. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19797. res.set_content("Hello World!", "text/plain");
  19798. });
  19799. svr_.Get("/echo-params",
  19800. [](const httplib::Request &req, httplib::Response &res) {
  19801. std::string r;
  19802. for (const auto &p : req.params) {
  19803. if (!r.empty()) r += "&";
  19804. r += p.first + "=" + p.second;
  19805. }
  19806. res.set_content(r, "text/plain");
  19807. });
  19808. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19809. res.set_content(req.body, req.get_header_value("Content-Type"));
  19810. });
  19811. svr_.Post("/echo-headers",
  19812. [](const httplib::Request &req, httplib::Response &res) {
  19813. std::string r;
  19814. for (const auto &h : req.headers)
  19815. r += h.first + ": " + h.second + "\n";
  19816. res.set_content(r, "text/plain");
  19817. });
  19818. svr_.Post("/echo-params",
  19819. [](const httplib::Request &req, httplib::Response &res) {
  19820. std::string r = "params:";
  19821. for (const auto &p : req.params)
  19822. r += p.first + "=" + p.second + ";";
  19823. res.set_content(r + " body:" + req.body, "text/plain");
  19824. });
  19825. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19826. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19827. });
  19828. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19829. res.set_content("PUT:" + req.body, "text/plain");
  19830. });
  19831. svr_.Patch("/echo",
  19832. [](const httplib::Request &req, httplib::Response &res) {
  19833. res.set_content("PATCH:" + req.body, "text/plain");
  19834. });
  19835. svr_.Delete(
  19836. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19837. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19838. "text/plain");
  19839. });
  19840. svr_.Get("/head-test",
  19841. [](const httplib::Request &, httplib::Response &res) {
  19842. res.set_content("body for HEAD", "text/plain");
  19843. });
  19844. svr_.Options("/options",
  19845. [](const httplib::Request &, httplib::Response &res) {
  19846. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19847. });
  19848. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19849. svr_.wait_until_ready();
  19850. }
  19851. void TearDown() override {
  19852. svr_.stop();
  19853. if (thread_.joinable()) thread_.join();
  19854. }
  19855. httplib::Server svr_;
  19856. std::thread thread_;
  19857. };
  19858. // stream::Get tests
  19859. TEST_F(StreamApiTest, GetBasic) {
  19860. httplib::Client cli(HOST, PORT);
  19861. auto result = httplib::stream::Get(cli, "/hello");
  19862. ASSERT_TRUE(result.is_valid());
  19863. EXPECT_EQ(200, result.status());
  19864. EXPECT_EQ("Hello World!", read_body(result));
  19865. }
  19866. TEST_F(StreamApiTest, GetWithParams) {
  19867. httplib::Client cli(HOST, PORT);
  19868. httplib::Params params{{"foo", "bar"}};
  19869. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19870. ASSERT_TRUE(result.is_valid());
  19871. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19872. }
  19873. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19874. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19875. httplib::Client cli(HOST, PORT);
  19876. cli.set_payload_max_length(0);
  19877. auto result = httplib::stream::Get(cli, "/hello");
  19878. ASSERT_TRUE(result.is_valid());
  19879. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19880. EXPECT_EQ("Hello World!", read_body(result));
  19881. }
  19882. #endif
  19883. TEST_F(StreamApiTest, GetConnectionError) {
  19884. httplib::Client cli(HOST, 9999);
  19885. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19886. }
  19887. TEST_F(StreamApiTest, Get404) {
  19888. httplib::Client cli(HOST, PORT);
  19889. auto result = httplib::stream::Get(cli, "/nonexistent");
  19890. EXPECT_TRUE(result.is_valid());
  19891. EXPECT_EQ(404, result.status());
  19892. }
  19893. // stream::Post tests
  19894. TEST_F(StreamApiTest, PostBasic) {
  19895. httplib::Client cli(HOST, PORT);
  19896. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19897. "application/json");
  19898. ASSERT_TRUE(result.is_valid());
  19899. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19900. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19901. }
  19902. TEST_F(StreamApiTest, PostWithHeaders) {
  19903. httplib::Client cli(HOST, PORT);
  19904. httplib::Headers headers{{"X-Custom", "value"}};
  19905. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19906. "text/plain");
  19907. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19908. }
  19909. TEST_F(StreamApiTest, PostWithParams) {
  19910. httplib::Client cli(HOST, PORT);
  19911. httplib::Params params{{"k", "v"}};
  19912. auto result =
  19913. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19914. auto body = read_body(result);
  19915. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19916. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19917. }
  19918. TEST_F(StreamApiTest, PostLarge) {
  19919. httplib::Client cli(HOST, PORT);
  19920. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19921. size_t total = 0;
  19922. while (result.next()) {
  19923. total += result.size();
  19924. }
  19925. EXPECT_EQ(100u * 1024u, total);
  19926. }
  19927. // stream::Put/Patch tests
  19928. TEST_F(StreamApiTest, PutAndPatch) {
  19929. httplib::Client cli(HOST, PORT);
  19930. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19931. EXPECT_EQ("PUT:test", read_body(put));
  19932. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19933. EXPECT_EQ("PATCH:test", read_body(patch));
  19934. }
  19935. // stream::Delete tests
  19936. TEST_F(StreamApiTest, Delete) {
  19937. httplib::Client cli(HOST, PORT);
  19938. auto del1 = httplib::stream::Delete(cli, "/resource");
  19939. EXPECT_EQ("Deleted", read_body(del1));
  19940. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19941. EXPECT_EQ("Deleted:data", read_body(del2));
  19942. }
  19943. // stream::Head/Options tests
  19944. TEST_F(StreamApiTest, HeadAndOptions) {
  19945. httplib::Client cli(HOST, PORT);
  19946. auto head = httplib::stream::Head(cli, "/head-test");
  19947. EXPECT_TRUE(head.is_valid());
  19948. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19949. auto opts = httplib::stream::Options(cli, "/options");
  19950. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19951. }
  19952. // SSL stream::* tests
  19953. #ifdef CPPHTTPLIB_SSL_ENABLED
  19954. class SSLStreamApiTest : public ::testing::Test {
  19955. protected:
  19956. void SetUp() override {
  19957. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19958. res.set_content("Hello SSL!", "text/plain");
  19959. });
  19960. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19961. res.set_content(req.body, "text/plain");
  19962. });
  19963. port_ = svr_.bind_to_any_port("127.0.0.1");
  19964. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19965. svr_.wait_until_ready();
  19966. }
  19967. void TearDown() override {
  19968. svr_.stop();
  19969. if (thread_.joinable()) thread_.join();
  19970. }
  19971. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19972. std::thread thread_;
  19973. int port_ = 0;
  19974. };
  19975. TEST_F(SSLStreamApiTest, GetAndPost) {
  19976. httplib::SSLClient cli("127.0.0.1", port_);
  19977. cli.enable_server_certificate_verification(false);
  19978. auto get = httplib::stream::Get(cli, "/hello");
  19979. EXPECT_EQ("Hello SSL!", read_body(get));
  19980. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19981. EXPECT_EQ("test", read_body(post));
  19982. }
  19983. #endif
  19984. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19985. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19986. // BodyReader
  19987. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19988. // Test that read timeout during streaming is detected
  19989. // Use a large content-length response where server delays mid-stream
  19990. Server svr;
  19991. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19992. // Send a large response with delay in the middle
  19993. res.set_content_provider(
  19994. 1000, // content_length
  19995. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19996. if (offset < 100) {
  19997. // Send first 100 bytes immediately
  19998. std::string data(100, 'A');
  19999. sink.write(data.c_str(), data.size());
  20000. return true;
  20001. }
  20002. // Then delay longer than client timeout
  20003. std::this_thread::sleep_for(std::chrono::seconds(3));
  20004. std::string data(900, 'B');
  20005. sink.write(data.c_str(), data.size());
  20006. return true;
  20007. });
  20008. });
  20009. auto port = 8091;
  20010. std::thread t([&]() { svr.listen("localhost", port); });
  20011. svr.wait_until_ready();
  20012. Client cli("localhost", port);
  20013. cli.set_read_timeout(1, 0); // 1 second timeout
  20014. auto handle = cli.open_stream("GET", "/slow-stream");
  20015. ASSERT_TRUE(handle.is_valid());
  20016. char buf[256];
  20017. ssize_t total = 0;
  20018. ssize_t n;
  20019. bool got_error = false;
  20020. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20021. total += n;
  20022. }
  20023. if (n < 0) {
  20024. got_error = true;
  20025. // Should be timeout or read error
  20026. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20027. handle.get_read_error() == Error::Read)
  20028. << "Actual error: " << to_string(handle.get_read_error());
  20029. }
  20030. // Either we got an error, or we got less data than expected
  20031. EXPECT_TRUE(got_error || total < 1000)
  20032. << "Expected timeout but got all " << total << " bytes";
  20033. svr.stop();
  20034. t.join();
  20035. }
  20036. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20037. // Test connection closed detection via BodyReader
  20038. Server svr;
  20039. std::atomic<bool> close_now{false};
  20040. svr.Get("/will-close", [&](const Request &, Response &res) {
  20041. res.set_content_provider(
  20042. 10000, // Large content_length that we won't fully send
  20043. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20044. if (offset < 100) {
  20045. std::string data(100, 'X');
  20046. sink.write(data.c_str(), data.size());
  20047. return true;
  20048. }
  20049. // Wait for signal then abort
  20050. while (!close_now) {
  20051. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20052. }
  20053. return false; // Abort - server will close connection
  20054. });
  20055. });
  20056. auto port = 8092;
  20057. std::thread t([&]() { svr.listen("localhost", port); });
  20058. svr.wait_until_ready();
  20059. Client cli("localhost", port);
  20060. auto handle = cli.open_stream("GET", "/will-close");
  20061. ASSERT_TRUE(handle.is_valid());
  20062. char buf[256];
  20063. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20064. EXPECT_GT(n, 0) << "First read should succeed";
  20065. // Signal server to close
  20066. close_now = true;
  20067. // Keep reading until error or EOF
  20068. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20069. // Keep reading
  20070. }
  20071. // Should get an error since content_length wasn't satisfied
  20072. if (n < 0) {
  20073. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20074. handle.get_read_error() == Error::Read)
  20075. << "Actual error: " << to_string(handle.get_read_error());
  20076. }
  20077. svr.stop();
  20078. t.join();
  20079. }
  20080. #ifdef CPPHTTPLIB_SSL_ENABLED
  20081. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20082. // Test that read timeout during SSL streaming is detected
  20083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20084. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20085. res.set_content_provider(
  20086. 1000, "text/plain",
  20087. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20088. if (offset < 100) {
  20089. std::string data(100, 'A');
  20090. sink.write(data.c_str(), data.size());
  20091. return true;
  20092. }
  20093. std::this_thread::sleep_for(std::chrono::seconds(3));
  20094. std::string data(900, 'B');
  20095. sink.write(data.c_str(), data.size());
  20096. return true;
  20097. });
  20098. });
  20099. auto port = 8093;
  20100. std::thread t([&]() { svr.listen("localhost", port); });
  20101. svr.wait_until_ready();
  20102. SSLClient cli("localhost", port);
  20103. cli.enable_server_certificate_verification(false);
  20104. cli.set_read_timeout(1, 0); // 1 second timeout
  20105. auto handle = cli.open_stream("GET", "/slow-stream");
  20106. ASSERT_TRUE(handle.is_valid());
  20107. char buf[256];
  20108. ssize_t total = 0;
  20109. ssize_t n;
  20110. bool got_error = false;
  20111. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20112. total += n;
  20113. }
  20114. if (n < 0) {
  20115. got_error = true;
  20116. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20117. handle.get_read_error() == Error::Read)
  20118. << "Actual error: " << to_string(handle.get_read_error());
  20119. }
  20120. EXPECT_TRUE(got_error || total < 1000)
  20121. << "Expected timeout but got all " << total << " bytes";
  20122. svr.stop();
  20123. t.join();
  20124. }
  20125. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20126. // Test SSL connection closed detection
  20127. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20128. std::atomic<bool> close_now{false};
  20129. svr.Get("/will-close", [&](const Request &, Response &res) {
  20130. res.set_content_provider(
  20131. 10000, "text/plain",
  20132. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20133. if (offset < 100) {
  20134. std::string data(100, 'X');
  20135. sink.write(data.c_str(), data.size());
  20136. return true;
  20137. }
  20138. while (!close_now) {
  20139. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20140. }
  20141. return false;
  20142. });
  20143. });
  20144. auto port = 8094;
  20145. std::thread t([&]() { svr.listen("localhost", port); });
  20146. svr.wait_until_ready();
  20147. SSLClient cli("localhost", port);
  20148. cli.enable_server_certificate_verification(false);
  20149. auto handle = cli.open_stream("GET", "/will-close");
  20150. ASSERT_TRUE(handle.is_valid());
  20151. char buf[256];
  20152. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20153. EXPECT_GT(n, 0);
  20154. // Signal server to close
  20155. close_now = true;
  20156. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20157. // Keep reading
  20158. }
  20159. if (n < 0) {
  20160. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20161. handle.get_read_error() == Error::Read)
  20162. << "Actual error: " << to_string(handle.get_read_error());
  20163. }
  20164. svr.stop();
  20165. t.join();
  20166. }
  20167. #endif
  20168. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20169. using namespace httplib;
  20170. // Create a test file
  20171. const char *fname = "etag_testfile.txt";
  20172. const char *content = "etag-content";
  20173. {
  20174. std::ofstream ofs(fname);
  20175. ofs << content;
  20176. ASSERT_TRUE(ofs.good());
  20177. }
  20178. Server svr;
  20179. svr.set_mount_point("/static", ".");
  20180. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20181. svr.wait_until_ready();
  20182. Client cli(HOST, PORT);
  20183. // First request: should get 200 with ETag header
  20184. auto res1 = cli.Get("/static/etag_testfile.txt");
  20185. ASSERT_TRUE(res1);
  20186. ASSERT_EQ(200, res1->status);
  20187. ASSERT_TRUE(res1->has_header("ETag"));
  20188. std::string etag = res1->get_header_value("ETag");
  20189. EXPECT_FALSE(etag.empty());
  20190. // Verify ETag format: W/"hex-hex"
  20191. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20192. EXPECT_EQ('W', etag[0]);
  20193. EXPECT_EQ('/', etag[1]);
  20194. EXPECT_EQ('"', etag[2]);
  20195. EXPECT_EQ('"', etag.back());
  20196. // Exact match: expect 304 Not Modified
  20197. Headers h2 = {{"If-None-Match", etag}};
  20198. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20199. ASSERT_TRUE(res2);
  20200. EXPECT_EQ(304, res2->status);
  20201. // Wildcard match: expect 304 Not Modified
  20202. Headers h3 = {{"If-None-Match", "*"}};
  20203. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20204. ASSERT_TRUE(res3);
  20205. EXPECT_EQ(304, res3->status);
  20206. // Non-matching ETag: expect 200
  20207. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20208. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20209. ASSERT_TRUE(res4);
  20210. EXPECT_EQ(200, res4->status);
  20211. // Multiple ETags with one matching: expect 304
  20212. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20213. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20214. ASSERT_TRUE(res5);
  20215. EXPECT_EQ(304, res5->status);
  20216. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20217. // that equivalent to the single comma-separated list above, so the match on
  20218. // the second line must still be found.
  20219. Headers h6;
  20220. h6.emplace("If-None-Match", "W/\"other\"");
  20221. h6.emplace("If-None-Match", etag);
  20222. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20223. ASSERT_TRUE(res6);
  20224. EXPECT_EQ(304, res6->status);
  20225. svr.stop();
  20226. t.join();
  20227. std::remove(fname);
  20228. }
  20229. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20230. using namespace httplib;
  20231. Server svr;
  20232. svr.set_mount_point("/static", ".");
  20233. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20234. svr.wait_until_ready();
  20235. Client cli(HOST, PORT);
  20236. // Send If-None-Match: * to a non-existent file
  20237. Headers h = {{"If-None-Match", "*"}};
  20238. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20240. EXPECT_EQ(404, res->status);
  20241. svr.stop();
  20242. t.join();
  20243. }
  20244. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20245. using namespace httplib;
  20246. // Create a test file
  20247. const char *fname = "etag_boundary_testfile.txt";
  20248. const char *content = "boundary-test";
  20249. {
  20250. std::ofstream ofs(fname);
  20251. ofs << content;
  20252. ASSERT_TRUE(ofs.good());
  20253. }
  20254. Server svr;
  20255. svr.set_mount_point("/static", ".");
  20256. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20257. svr.wait_until_ready();
  20258. Client cli(HOST, PORT);
  20259. // Get the actual ETag
  20260. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20261. ASSERT_TRUE(res1);
  20262. ASSERT_EQ(200, res1->status);
  20263. ASSERT_TRUE(res1->has_header("ETag"));
  20264. std::string etag = res1->get_header_value("ETag");
  20265. // Test 1: Very long ETag value (longer than actual ETag)
  20266. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20267. Headers h1 = {{"If-None-Match", "W/"
  20268. "\"very-long-etag-value-that-is-much-longer-"
  20269. "than-the-actual-etag-value\""}};
  20270. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20271. ASSERT_TRUE(res2);
  20272. EXPECT_EQ(200, res2->status); // Should not match
  20273. // Test 2: Long string followed by wildcard
  20274. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20275. // string)
  20276. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20277. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20278. ASSERT_TRUE(res3);
  20279. EXPECT_EQ(304, res3->status); // Should match on "*"
  20280. // Test 3: Wildcard followed by long string
  20281. // Should match on "*" immediately and return 304
  20282. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20283. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20284. ASSERT_TRUE(res4);
  20285. EXPECT_EQ(304, res4->status); // Should match on "*"
  20286. // Test 4: Multiple long non-matching values
  20287. // Should NOT match and return 200 (test that all comparisons are safe)
  20288. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20289. "W/\"second-long-non-matching-value\", "
  20290. "W/\"third-long-non-matching-value\""}};
  20291. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20292. ASSERT_TRUE(res5);
  20293. EXPECT_EQ(200, res5->status); // Should not match
  20294. // Test 5: Single character that is not "*" (edge case)
  20295. Headers h5 = {{"If-None-Match", "X"}};
  20296. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20297. ASSERT_TRUE(res6);
  20298. EXPECT_EQ(200, res6->status); // Should not match
  20299. svr.stop();
  20300. t.join();
  20301. std::remove(fname);
  20302. }
  20303. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20304. using namespace httplib;
  20305. // Create a test file
  20306. const char *fname = "ims_testfile.txt";
  20307. const char *content = "if-modified-since-test";
  20308. {
  20309. std::ofstream ofs(fname);
  20310. ofs << content;
  20311. ASSERT_TRUE(ofs.good());
  20312. }
  20313. Server svr;
  20314. svr.set_mount_point("/static", ".");
  20315. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20316. svr.wait_until_ready();
  20317. Client cli(HOST, PORT);
  20318. // First request: should get 200 with Last-Modified header
  20319. auto res1 = cli.Get("/static/ims_testfile.txt");
  20320. ASSERT_TRUE(res1);
  20321. ASSERT_EQ(200, res1->status);
  20322. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20323. std::string last_modified = res1->get_header_value("Last-Modified");
  20324. EXPECT_FALSE(last_modified.empty());
  20325. // If-Modified-Since with same time: expect 304
  20326. Headers h2 = {{"If-Modified-Since", last_modified}};
  20327. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20328. ASSERT_TRUE(res2);
  20329. EXPECT_EQ(304, res2->status);
  20330. // If-Modified-Since with future time: expect 304
  20331. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20332. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20333. ASSERT_TRUE(res3);
  20334. EXPECT_EQ(304, res3->status);
  20335. // If-Modified-Since with past time: expect 200
  20336. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20337. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20338. ASSERT_TRUE(res4);
  20339. EXPECT_EQ(200, res4->status);
  20340. // If-None-Match takes precedence over If-Modified-Since
  20341. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20342. ASSERT_TRUE(res1->has_header("ETag"));
  20343. std::string etag = res1->get_header_value("ETag");
  20344. Headers h5 = {{"If-None-Match", etag},
  20345. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20346. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20347. ASSERT_TRUE(res5);
  20348. EXPECT_EQ(304, res5->status);
  20349. svr.stop();
  20350. t.join();
  20351. std::remove(fname);
  20352. }
  20353. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20354. using namespace httplib;
  20355. Server svr;
  20356. // Endpoint that returns compressible content
  20357. svr.Get("/compressible", [](const Request &, Response &res) {
  20358. // Return a large enough body to trigger compression
  20359. std::string body(1000, 'a');
  20360. res.set_content(body, "text/plain");
  20361. });
  20362. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20363. svr.wait_until_ready();
  20364. Client cli(HOST, PORT);
  20365. // Request with gzip support: should get Vary header when compressed
  20366. cli.set_compress(true);
  20367. auto res1 = cli.Get("/compressible");
  20368. ASSERT_TRUE(res1);
  20369. EXPECT_EQ(200, res1->status);
  20370. // If Content-Encoding is set, Vary should also be set
  20371. if (res1->has_header("Content-Encoding")) {
  20372. EXPECT_TRUE(res1->has_header("Vary"));
  20373. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20374. }
  20375. // Request without Accept-Encoding header: should not have compression
  20376. Headers h_no_compress;
  20377. auto res2 = cli.Get("/compressible", h_no_compress);
  20378. ASSERT_TRUE(res2);
  20379. EXPECT_EQ(200, res2->status);
  20380. // Verify Vary header is present when compression is applied
  20381. // (the exact behavior depends on server configuration)
  20382. svr.stop();
  20383. t.join();
  20384. }
  20385. TEST(ETagTest, IfRangeWithETag) {
  20386. using namespace httplib;
  20387. // Create a test file with known content
  20388. const char *fname = "if_range_testfile.txt";
  20389. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20390. {
  20391. std::ofstream ofs(fname);
  20392. ofs << content;
  20393. ASSERT_TRUE(ofs.good());
  20394. }
  20395. Server svr;
  20396. svr.set_mount_point("/static", ".");
  20397. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20398. svr.wait_until_ready();
  20399. Client cli(HOST, PORT);
  20400. // First request: get ETag
  20401. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20402. ASSERT_TRUE(res1);
  20403. ASSERT_EQ(200, res1->status);
  20404. ASSERT_TRUE(res1->has_header("ETag"));
  20405. std::string etag = res1->get_header_value("ETag");
  20406. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20407. // Since our server generates weak ETags (W/"..."), If-Range with our
  20408. // ETag should NOT result in partial content - it should return full content.
  20409. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20410. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20411. ASSERT_TRUE(res2);
  20412. // Weak ETag in If-Range -> full content (200), not partial (206)
  20413. EXPECT_EQ(200, res2->status);
  20414. EXPECT_EQ(content, res2->body);
  20415. EXPECT_FALSE(res2->has_header("Content-Range"));
  20416. // Range request with non-matching If-Range (ETag): should get 200 (full
  20417. // content)
  20418. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20419. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20420. ASSERT_TRUE(res3);
  20421. EXPECT_EQ(200, res3->status);
  20422. EXPECT_EQ(content, res3->body);
  20423. EXPECT_FALSE(res3->has_header("Content-Range"));
  20424. // Range request with strong ETag (hypothetical - our server doesn't generate
  20425. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20426. // should return full content)
  20427. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20428. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20429. ASSERT_TRUE(res4);
  20430. EXPECT_EQ(200, res4->status);
  20431. EXPECT_EQ(content, res4->body);
  20432. EXPECT_FALSE(res4->has_header("Content-Range"));
  20433. svr.stop();
  20434. t.join();
  20435. std::remove(fname);
  20436. }
  20437. TEST(ETagTest, IfRangeWithDate) {
  20438. using namespace httplib;
  20439. // Create a test file
  20440. const char *fname = "if_range_date_testfile.txt";
  20441. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20442. {
  20443. std::ofstream ofs(fname);
  20444. ofs << content;
  20445. ASSERT_TRUE(ofs.good());
  20446. }
  20447. Server svr;
  20448. svr.set_mount_point("/static", ".");
  20449. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20450. svr.wait_until_ready();
  20451. Client cli(HOST, PORT);
  20452. // First request: get Last-Modified
  20453. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20454. ASSERT_TRUE(res1);
  20455. ASSERT_EQ(200, res1->status);
  20456. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20457. std::string last_modified = res1->get_header_value("Last-Modified");
  20458. // Range request with matching If-Range (date): should get 206
  20459. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20460. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20461. ASSERT_TRUE(res2);
  20462. EXPECT_EQ(206, res2->status);
  20463. EXPECT_EQ("FGHIJ", res2->body);
  20464. // Range request with old If-Range date: should get 200 (full content)
  20465. Headers h3 = {{"Range", "bytes=5-9"},
  20466. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20467. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20468. ASSERT_TRUE(res3);
  20469. EXPECT_EQ(200, res3->status);
  20470. EXPECT_EQ(content, res3->body);
  20471. // Range request with future If-Range date: should get 206
  20472. Headers h4 = {{"Range", "bytes=0-4"},
  20473. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20474. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20475. ASSERT_TRUE(res4);
  20476. EXPECT_EQ(206, res4->status);
  20477. EXPECT_EQ("ABCDE", res4->body);
  20478. svr.stop();
  20479. t.join();
  20480. std::remove(fname);
  20481. }
  20482. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20483. using namespace httplib;
  20484. const char *fname = "etag_malformed.txt";
  20485. const char *content = "malformed-etag";
  20486. {
  20487. std::ofstream ofs(fname);
  20488. ofs << content;
  20489. ASSERT_TRUE(ofs.good());
  20490. }
  20491. Server svr;
  20492. svr.set_mount_point("/static", ".");
  20493. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20494. svr.wait_until_ready();
  20495. Client cli(HOST, PORT);
  20496. // baseline: should get 200 and an ETag
  20497. auto res1 = cli.Get("/static/etag_malformed.txt");
  20498. ASSERT_TRUE(res1);
  20499. ASSERT_EQ(200, res1->status);
  20500. ASSERT_TRUE(res1->has_header("ETag"));
  20501. // Malformed ETag value (missing quotes) should be treated as non-matching
  20502. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20503. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20504. ASSERT_TRUE(res_bad);
  20505. EXPECT_EQ(200, res_bad->status);
  20506. // Whitespace-only header value should be considered invalid / non-matching
  20507. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20508. "Host: localhost\r\n"
  20509. "If-None-Match: \r\n"
  20510. "Connection: close\r\n"
  20511. "\r\n";
  20512. std::string out;
  20513. ASSERT_TRUE(send_request(5, raw_req, &out));
  20514. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20515. svr.stop();
  20516. t.join();
  20517. std::remove(fname);
  20518. }
  20519. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20520. using namespace httplib;
  20521. const char *fname = "ims_invalid_format.txt";
  20522. const char *content = "ims-bad-format";
  20523. {
  20524. std::ofstream ofs(fname);
  20525. ofs << content;
  20526. ASSERT_TRUE(ofs.good());
  20527. }
  20528. Server svr;
  20529. svr.set_mount_point("/static", ".");
  20530. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20531. svr.wait_until_ready();
  20532. Client cli(HOST, PORT);
  20533. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20534. ASSERT_TRUE(res1);
  20535. ASSERT_EQ(200, res1->status);
  20536. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20537. // If-Modified-Since with invalid format should not result in 304
  20538. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20539. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20540. ASSERT_TRUE(res_bad);
  20541. EXPECT_EQ(200, res_bad->status);
  20542. // If-Range with invalid date format should be treated as mismatch -> full
  20543. // content (200)
  20544. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20545. {"If-Range", "invalid-date"}};
  20546. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20547. ASSERT_TRUE(res_ifrange);
  20548. EXPECT_EQ(200, res_ifrange->status);
  20549. svr.stop();
  20550. t.join();
  20551. std::remove(fname);
  20552. }
  20553. TEST(ETagTest, IfRangeWithMalformedETag) {
  20554. using namespace httplib;
  20555. const char *fname = "ifrange_malformed.txt";
  20556. const std::string content = "0123456789";
  20557. {
  20558. std::ofstream ofs(fname);
  20559. ofs << content;
  20560. ASSERT_TRUE(ofs.good());
  20561. }
  20562. Server svr;
  20563. svr.set_mount_point("/static", ".");
  20564. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20565. svr.wait_until_ready();
  20566. Client cli(HOST, PORT);
  20567. // First request: get ETag
  20568. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20569. ASSERT_TRUE(res1);
  20570. ASSERT_EQ(200, res1->status);
  20571. ASSERT_TRUE(res1->has_header("ETag"));
  20572. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20573. // full content (200)
  20574. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20575. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20576. ASSERT_TRUE(res2);
  20577. EXPECT_EQ(200, res2->status);
  20578. EXPECT_EQ(content, res2->body);
  20579. svr.stop();
  20580. t.join();
  20581. std::remove(fname);
  20582. }
  20583. TEST(ETagTest, ExtremeLargeDateValues) {
  20584. using namespace httplib;
  20585. const char *fname = "ims_extreme_date.txt";
  20586. const char *content = "ims-extreme-date";
  20587. {
  20588. std::ofstream ofs(fname);
  20589. ofs << content;
  20590. ASSERT_TRUE(ofs.good());
  20591. }
  20592. Server svr;
  20593. svr.set_mount_point("/static", ".");
  20594. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20595. svr.wait_until_ready();
  20596. Client cli(HOST, PORT);
  20597. auto res1 = cli.Get(std::string("/static/") + fname);
  20598. ASSERT_TRUE(res1);
  20599. ASSERT_EQ(200, res1->status);
  20600. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20601. // Extremely large year that may overflow date parsing routines.
  20602. Headers h_large_date = {
  20603. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20604. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20605. ASSERT_TRUE(res_bad);
  20606. // Expect server to treat this as invalid/mismatch and return full content
  20607. EXPECT_EQ(200, res_bad->status);
  20608. // If-Range with extremely large date should be treated as mismatch -> full
  20609. // content (200)
  20610. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20611. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20612. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20613. ASSERT_TRUE(res_ifrange);
  20614. EXPECT_EQ(200, res_ifrange->status);
  20615. svr.stop();
  20616. t.join();
  20617. std::remove(fname);
  20618. }
  20619. TEST(ETagTest, NegativeFileModificationTime) {
  20620. using namespace httplib;
  20621. const char *fname = "ims_negative_mtime.txt";
  20622. const std::string content = "negative-mtime";
  20623. {
  20624. std::ofstream ofs(fname);
  20625. ofs << content;
  20626. ASSERT_TRUE(ofs.good());
  20627. }
  20628. // Try to set file mtime to a negative value. This may fail on some
  20629. // platforms/filesystems; if it fails, the test will still verify server
  20630. // behaves safely by performing a regular conditional request.
  20631. #if defined(__APPLE__) || defined(__linux__)
  20632. bool set_negative = false;
  20633. do {
  20634. struct timeval times[2];
  20635. // access time: now
  20636. times[0].tv_sec = time(nullptr);
  20637. times[0].tv_usec = 0;
  20638. // modification time: negative (e.g., -1)
  20639. times[1].tv_sec = -1;
  20640. times[1].tv_usec = 0;
  20641. if (utimes(fname, times) == 0) { set_negative = true; }
  20642. } while (0);
  20643. #else
  20644. bool set_negative = false;
  20645. #endif
  20646. Server svr;
  20647. svr.set_mount_point("/static", ".");
  20648. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20649. svr.wait_until_ready();
  20650. Client cli(HOST, PORT);
  20651. auto res1 = cli.Get(std::string("/static/") + fname);
  20652. ASSERT_TRUE(res1);
  20653. ASSERT_EQ(200, res1->status);
  20654. bool has_last_modified = res1->has_header("Last-Modified");
  20655. std::string last_modified;
  20656. if (has_last_modified) {
  20657. last_modified = res1->get_header_value("Last-Modified");
  20658. }
  20659. if (set_negative) {
  20660. // If we successfully set a negative mtime, ensure server returns a
  20661. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20662. // with an old date and ensure server handles it without crash.
  20663. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20664. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20665. ASSERT_TRUE(res2);
  20666. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20667. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20668. } else {
  20669. // Could not set negative mtime on this platform; fall back to verifying
  20670. // that normal invalid/malformed dates are treated safely (non-304).
  20671. Headers h_bad_date = {
  20672. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20673. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20674. ASSERT_TRUE(res_bad);
  20675. EXPECT_EQ(200, res_bad->status);
  20676. }
  20677. svr.stop();
  20678. t.join();
  20679. std::remove(fname);
  20680. }
  20681. //==============================================================================
  20682. // Integration Tests with Server
  20683. //==============================================================================
  20684. class SSEIntegrationTest : public ::testing::Test {
  20685. protected:
  20686. void SetUp() override {
  20687. stop_server_.store(false);
  20688. events_.clear();
  20689. server_ = httplib::detail::make_unique<Server>();
  20690. setup_server();
  20691. start_server();
  20692. }
  20693. void TearDown() override {
  20694. stop_server_.store(true);
  20695. event_cv_.notify_all();
  20696. server_->stop();
  20697. if (server_thread_.joinable()) { server_thread_.join(); }
  20698. }
  20699. void setup_server() {
  20700. // Simple SSE endpoint
  20701. server_->Get("/events", [this](const Request &req, Response &res) {
  20702. auto last_id = req.get_header_value("Last-Event-ID");
  20703. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20704. res.set_chunked_content_provider(
  20705. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20706. std::unique_lock<std::mutex> lock(event_mutex_);
  20707. if (event_cv_.wait_for(
  20708. lock, std::chrono::milliseconds(200), [this] {
  20709. return !events_.empty() || stop_server_.load();
  20710. })) {
  20711. if (stop_server_.load()) { return false; }
  20712. if (!events_.empty()) {
  20713. std::string event = events_.front();
  20714. events_.erase(events_.begin());
  20715. sink.write(event.data(), event.size());
  20716. return true;
  20717. }
  20718. }
  20719. return !stop_server_.load();
  20720. });
  20721. });
  20722. // Endpoint that returns error
  20723. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20724. res.status = 500;
  20725. res.set_content("Internal Server Error", "text/plain");
  20726. });
  20727. // Endpoint for custom event types
  20728. server_->Get("/custom-events", [](const Request &, Response &res) {
  20729. res.set_chunked_content_provider(
  20730. "text/event-stream", [](size_t offset, DataSink &sink) {
  20731. if (offset == 0) {
  20732. std::string event = "event: update\ndata: updated\n\n"
  20733. "event: delete\ndata: deleted\n\n";
  20734. sink.write(event.data(), event.size());
  20735. }
  20736. return false; // End stream after sending
  20737. });
  20738. });
  20739. }
  20740. void start_server() {
  20741. port_ = server_->bind_to_any_port(HOST);
  20742. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20743. // Wait for server to start
  20744. while (!server_->is_running()) {
  20745. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20746. }
  20747. }
  20748. int get_port() const { return port_; }
  20749. void send_event(const std::string &event) {
  20750. std::lock_guard<std::mutex> lock(event_mutex_);
  20751. events_.push_back(event);
  20752. event_cv_.notify_all();
  20753. }
  20754. std::unique_ptr<Server> server_;
  20755. std::thread server_thread_;
  20756. std::mutex event_mutex_;
  20757. std::condition_variable event_cv_;
  20758. std::vector<std::string> events_;
  20759. std::atomic<bool> stop_server_{false};
  20760. std::string last_received_event_id_;
  20761. int port_ = 0;
  20762. };
  20763. //==============================================================================
  20764. // SSE Parsing Tests
  20765. //==============================================================================
  20766. class SSEParsingTest : public SSEIntegrationTest {
  20767. protected:
  20768. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20769. // A trailing sentinel event tells when the whole stream has been parsed.
  20770. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20771. auto body = stream + "event: end\ndata: end\n\n";
  20772. server_->Get("/parse", [body](const Request &, Response &res) {
  20773. res.set_content(body, "text/event-stream");
  20774. });
  20775. return collect("/parse");
  20776. }
  20777. // Runs SSEClient against path until an "end" event arrives and returns the
  20778. // messages dispatched before it
  20779. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20780. Client client(HOST, get_port());
  20781. sse::SSEClient sse(client, path);
  20782. std::mutex mutex;
  20783. std::condition_variable cv;
  20784. std::vector<sse::SSEMessage> messages;
  20785. auto done = false;
  20786. sse.on_message([&](const sse::SSEMessage &msg) {
  20787. std::lock_guard<std::mutex> lock(mutex);
  20788. // Ignore a replay from a reconnect that races with stop()
  20789. if (!done) { messages.push_back(msg); }
  20790. });
  20791. sse.on_event("end", [&](const sse::SSEMessage &) {
  20792. std::lock_guard<std::mutex> lock(mutex);
  20793. done = true;
  20794. cv.notify_all();
  20795. });
  20796. sse.set_reconnect_interval(100);
  20797. sse.start_async();
  20798. {
  20799. std::unique_lock<std::mutex> lock(mutex);
  20800. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20801. }
  20802. sse.stop();
  20803. EXPECT_TRUE(done);
  20804. return messages;
  20805. }
  20806. };
  20807. TEST_F(SSEParsingTest, SingleLineData) {
  20808. auto msgs = parse("data: hello\n\n");
  20809. ASSERT_EQ(msgs.size(), 1u);
  20810. EXPECT_EQ(msgs[0].data, "hello");
  20811. EXPECT_EQ(msgs[0].event, "message");
  20812. }
  20813. TEST_F(SSEParsingTest, MultiLineData) {
  20814. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20815. ASSERT_EQ(msgs.size(), 1u);
  20816. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20817. }
  20818. TEST_F(SSEParsingTest, CustomEventType) {
  20819. auto msgs = parse("event: update\ndata: payload\n\n");
  20820. ASSERT_EQ(msgs.size(), 1u);
  20821. EXPECT_EQ(msgs[0].event, "update");
  20822. EXPECT_EQ(msgs[0].data, "payload");
  20823. }
  20824. TEST_F(SSEParsingTest, EventIdHandling) {
  20825. auto msgs = parse("id: 12345\ndata: test\n\n");
  20826. ASSERT_EQ(msgs.size(), 1u);
  20827. EXPECT_EQ(msgs[0].id, "12345");
  20828. }
  20829. TEST_F(SSEParsingTest, EmptyEventId) {
  20830. auto msgs = parse("id:\ndata: test\n\n");
  20831. ASSERT_EQ(msgs.size(), 1u);
  20832. EXPECT_EQ(msgs[0].id, "");
  20833. }
  20834. TEST_F(SSEParsingTest, CommentsIgnored) {
  20835. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20836. ASSERT_EQ(msgs.size(), 1u);
  20837. EXPECT_EQ(msgs[0].data, "hello");
  20838. EXPECT_EQ(msgs[0].event, "message");
  20839. }
  20840. TEST_F(SSEParsingTest, ColonInValue) {
  20841. auto msgs = parse("data: hello:world:test\n\n");
  20842. ASSERT_EQ(msgs.size(), 1u);
  20843. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20844. }
  20845. TEST_F(SSEParsingTest, FieldNameOnly) {
  20846. // A line without a colon is a field name with an empty value
  20847. auto msgs = parse("data\n\n");
  20848. ASSERT_EQ(msgs.size(), 1u);
  20849. EXPECT_EQ(msgs[0].data, "");
  20850. }
  20851. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20852. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20853. ASSERT_EQ(msgs.size(), 1u);
  20854. EXPECT_EQ(msgs[0].event, "update");
  20855. EXPECT_EQ(msgs[0].data, "hello");
  20856. }
  20857. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20858. auto msgs = parse("data\r\n\r\n");
  20859. ASSERT_EQ(msgs.size(), 1u);
  20860. EXPECT_EQ(msgs[0].data, "");
  20861. }
  20862. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20863. auto msgs = parse("event: update\rdata: hello\r\r");
  20864. ASSERT_EQ(msgs.size(), 1u);
  20865. EXPECT_EQ(msgs[0].event, "update");
  20866. EXPECT_EQ(msgs[0].data, "hello");
  20867. }
  20868. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20869. // Chunk boundaries fall inside every \r\n and right before the first one
  20870. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20871. "\n\r", "\nevent: end\ndata: end\n\n"};
  20872. server_->Get("/split", [chunks](const Request &, Response &res) {
  20873. auto i = std::make_shared<size_t>(0);
  20874. res.set_chunked_content_provider(
  20875. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20876. if (*i == chunks.size()) {
  20877. sink.done();
  20878. } else {
  20879. sink.write(chunks[*i].data(), chunks[*i].size());
  20880. (*i)++;
  20881. }
  20882. return true;
  20883. });
  20884. });
  20885. auto msgs = collect("/split");
  20886. ASSERT_EQ(msgs.size(), 1u);
  20887. EXPECT_EQ(msgs[0].event, "update");
  20888. EXPECT_EQ(msgs[0].data, "hello");
  20889. }
  20890. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20891. // Only a BOM at the start of the stream is ignored
  20892. auto msgs = parse("\xEF\xBB\xBF"
  20893. "data: first\n\n"
  20894. "\xEF\xBB\xBF"
  20895. "data: second\n\n");
  20896. ASSERT_EQ(msgs.size(), 1u);
  20897. EXPECT_EQ(msgs[0].data, "first");
  20898. }
  20899. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20900. auto msgs = parse("unknown: value\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, SpaceAfterColonOptional) {
  20906. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20907. ASSERT_EQ(msgs.size(), 2u);
  20908. EXPECT_EQ(msgs[0].data, "hello");
  20909. EXPECT_EQ(msgs[1].data, "hello");
  20910. }
  20911. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20912. // An event without data is not dispatched, and its type must not leak
  20913. // into the next event
  20914. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20915. ASSERT_EQ(msgs.size(), 1u);
  20916. EXPECT_EQ(msgs[0].event, "message");
  20917. EXPECT_EQ(msgs[0].data, "hello");
  20918. }
  20919. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20920. // The first connection sends only an id; the second echoes back the
  20921. // Last-Event-ID it was reconnected with
  20922. std::atomic<int> connection_count{0};
  20923. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20924. if (connection_count++ == 0) {
  20925. res.set_content("id: 42\n\n", "text/event-stream");
  20926. } else {
  20927. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20928. "\n\nevent: end\ndata: end\n\n",
  20929. "text/event-stream");
  20930. }
  20931. });
  20932. auto msgs = collect("/id-only");
  20933. ASSERT_EQ(msgs.size(), 1u);
  20934. EXPECT_EQ(msgs[0].data, "42");
  20935. }
  20936. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20937. // The first connection sets an id and then clears it with an empty one; the
  20938. // second reports whether it was reconnected with a Last-Event-ID
  20939. std::atomic<int> connection_count{0};
  20940. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20941. if (connection_count++ == 0) {
  20942. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20943. "text/event-stream");
  20944. } else {
  20945. res.set_content(
  20946. std::string("data: ") +
  20947. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20948. "\n\nevent: end\ndata: end\n\n",
  20949. "text/event-stream");
  20950. }
  20951. });
  20952. auto msgs = collect("/id-clear");
  20953. ASSERT_EQ(msgs.size(), 3u);
  20954. EXPECT_EQ(msgs[0].id, "1");
  20955. EXPECT_EQ(msgs[1].id, "");
  20956. EXPECT_EQ(msgs[2].data, "not sent");
  20957. }
  20958. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20959. // The first connection sets an id and then sends ids that cannot be carried
  20960. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20961. // with
  20962. std::atomic<int> connection_count{0};
  20963. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20964. if (connection_count++ == 0) {
  20965. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20966. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20967. "text/event-stream");
  20968. } else {
  20969. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20970. "\n\nevent: end\ndata: end\n\n",
  20971. "text/event-stream");
  20972. }
  20973. });
  20974. auto msgs = collect("/id-unsendable");
  20975. ASSERT_EQ(msgs.size(), 1u);
  20976. EXPECT_EQ(msgs[0].data, "42");
  20977. }
  20978. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20979. auto msgs = parse("event: notification\nid: evt-42\n"
  20980. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20981. ASSERT_EQ(msgs.size(), 1u);
  20982. EXPECT_EQ(msgs[0].event, "notification");
  20983. EXPECT_EQ(msgs[0].id, "evt-42");
  20984. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20985. }
  20986. TEST(SSEMessageTest, Clear) {
  20987. sse::SSEMessage msg;
  20988. msg.event = "custom";
  20989. msg.data = "some data";
  20990. msg.id = "123";
  20991. msg.clear();
  20992. EXPECT_EQ(msg.event, "message");
  20993. EXPECT_EQ(msg.data, "");
  20994. EXPECT_EQ(msg.id, "");
  20995. }
  20996. //==============================================================================
  20997. // SSE Integration Tests
  20998. //==============================================================================
  20999. // Test: Successful connection and on_open callback
  21000. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21001. // Add a simple endpoint that sends one event and closes
  21002. server_->Get("/simple-event", [](const Request &, Response &res) {
  21003. res.set_chunked_content_provider(
  21004. "text/event-stream", [](size_t offset, DataSink &sink) {
  21005. if (offset == 0) {
  21006. std::string event = "data: hello\n\n";
  21007. sink.write(event.data(), event.size());
  21008. }
  21009. return false; // Close stream after sending
  21010. });
  21011. });
  21012. Client client("localhost", get_port());
  21013. sse::SSEClient sse(client, "/simple-event");
  21014. std::atomic<bool> open_called{false};
  21015. std::atomic<bool> message_received{false};
  21016. sse.on_open([&open_called]() { open_called.store(true); });
  21017. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21018. if (msg.data == "hello") { message_received.store(true); }
  21019. });
  21020. sse.set_reconnect_interval(100);
  21021. sse.set_max_reconnect_attempts(1);
  21022. // Start async
  21023. sse.start_async();
  21024. // Wait for message to be processed
  21025. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21026. sse.stop();
  21027. EXPECT_TRUE(open_called.load());
  21028. EXPECT_TRUE(message_received.load());
  21029. }
  21030. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21031. // A data line that never ends.
  21032. server_->Get("/endless-line", [](const Request &, Response &res) {
  21033. res.set_chunked_content_provider(
  21034. "text/event-stream", [](size_t offset, DataSink &sink) {
  21035. if (offset == 0) { sink.write("data: ", 6); }
  21036. std::string chunk(64 * 1024, 'A');
  21037. return sink.write(chunk.data(), chunk.size());
  21038. });
  21039. });
  21040. Client client("localhost", get_port());
  21041. sse::SSEClient sse(client, "/endless-line");
  21042. std::atomic<bool> too_long{false};
  21043. sse.on_error([&](Error err) {
  21044. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21045. });
  21046. sse.set_max_reconnect_attempts(1);
  21047. sse.start_async();
  21048. for (int i = 0; i < 500 && !too_long; i++) {
  21049. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21050. }
  21051. sse.stop();
  21052. EXPECT_TRUE(too_long);
  21053. }
  21054. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21055. // Far more in all than the client's payload limit below.
  21056. server_->Get("/many-events", [](const Request &, Response &res) {
  21057. res.set_chunked_content_provider(
  21058. "text/event-stream", [](size_t offset, DataSink &sink) {
  21059. if (offset == 0) {
  21060. std::string events;
  21061. for (int i = 0; i < 1000; i++) {
  21062. events += "data: message\n\n";
  21063. }
  21064. sink.write(events.data(), events.size());
  21065. }
  21066. return false;
  21067. });
  21068. });
  21069. Client client("localhost", get_port());
  21070. client.set_payload_max_length(1024);
  21071. sse::SSEClient sse(client, "/many-events");
  21072. std::atomic<int> messages{0};
  21073. std::atomic<bool> too_large{false};
  21074. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21075. sse.on_error([&](Error err) {
  21076. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21077. });
  21078. sse.set_max_reconnect_attempts(1);
  21079. sse.start_async();
  21080. for (int i = 0; i < 500 && messages < 1000; i++) {
  21081. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21082. }
  21083. sse.stop();
  21084. EXPECT_GE(messages.load(), 1000);
  21085. EXPECT_FALSE(too_large);
  21086. }
  21087. // Test: on_message callback
  21088. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21089. // Endpoint that sends multiple events then closes
  21090. server_->Get("/multi-event", [](const Request &, Response &res) {
  21091. res.set_chunked_content_provider(
  21092. "text/event-stream", [](size_t offset, DataSink &sink) {
  21093. if (offset == 0) {
  21094. std::string events = "data: message1\n\ndata: message2\n\n";
  21095. sink.write(events.data(), events.size());
  21096. }
  21097. return false;
  21098. });
  21099. });
  21100. Client client("localhost", get_port());
  21101. sse::SSEClient sse(client, "/multi-event");
  21102. std::vector<std::string> received_messages;
  21103. std::mutex messages_mutex;
  21104. sse.on_message([&](const sse::SSEMessage &msg) {
  21105. std::lock_guard<std::mutex> lock(messages_mutex);
  21106. received_messages.push_back(msg.data);
  21107. });
  21108. sse.set_reconnect_interval(100);
  21109. sse.set_max_reconnect_attempts(1);
  21110. sse.start_async();
  21111. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21112. sse.stop();
  21113. std::lock_guard<std::mutex> lock(messages_mutex);
  21114. EXPECT_GE(received_messages.size(), 2u);
  21115. if (received_messages.size() >= 2) {
  21116. EXPECT_EQ(received_messages[0], "message1");
  21117. EXPECT_EQ(received_messages[1], "message2");
  21118. }
  21119. }
  21120. // Test: on_event for specific types
  21121. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21122. Client client("localhost", get_port());
  21123. sse::SSEClient sse(client, "/custom-events");
  21124. std::atomic<bool> update_received{false};
  21125. std::atomic<bool> delete_received{false};
  21126. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21127. if (msg.data == "updated") { update_received.store(true); }
  21128. });
  21129. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21130. if (msg.data == "deleted") { delete_received.store(true); }
  21131. });
  21132. sse.set_max_reconnect_attempts(1);
  21133. sse.start_async();
  21134. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21135. sse.stop();
  21136. EXPECT_TRUE(update_received.load());
  21137. EXPECT_TRUE(delete_received.load());
  21138. }
  21139. // Test: on_error callback on connection failure
  21140. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21141. // Connect to a non-existent port
  21142. Client client("localhost", 59999);
  21143. sse::SSEClient sse(client, "/events");
  21144. std::atomic<bool> error_called{false};
  21145. Error received_error = Error::Success;
  21146. sse.on_error([&](Error err) {
  21147. error_called.store(true);
  21148. received_error = err;
  21149. });
  21150. sse.set_reconnect_interval(50);
  21151. sse.set_max_reconnect_attempts(1);
  21152. sse.start_async();
  21153. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21154. sse.stop();
  21155. EXPECT_TRUE(error_called.load());
  21156. EXPECT_NE(received_error, Error::Success);
  21157. }
  21158. // Test: Last-Event-ID header sent on reconnect
  21159. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21160. // Endpoint that sends event with ID
  21161. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21162. res.set_chunked_content_provider(
  21163. "text/event-stream", [](size_t offset, DataSink &sink) {
  21164. if (offset == 0) {
  21165. std::string event = "id: evt-123\ndata: test\n\n";
  21166. sink.write(event.data(), event.size());
  21167. }
  21168. return false;
  21169. });
  21170. });
  21171. Client client("localhost", get_port());
  21172. sse::SSEClient sse(client, "/event-with-id");
  21173. std::atomic<bool> id_received{false};
  21174. sse.on_message([&](const sse::SSEMessage &msg) {
  21175. if (!msg.id.empty()) { id_received.store(true); }
  21176. });
  21177. sse.set_reconnect_interval(100);
  21178. sse.set_max_reconnect_attempts(1);
  21179. sse.start_async();
  21180. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21181. sse.stop();
  21182. EXPECT_TRUE(id_received.load());
  21183. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21184. }
  21185. // Test: Manual stop
  21186. TEST_F(SSEIntegrationTest, ManualStop) {
  21187. // Endpoint that sends one event and stays open briefly
  21188. std::atomic<bool> handler_running{true};
  21189. server_->Get("/stay-open", [&handler_running](const Request &,
  21190. Response &res) {
  21191. res.set_chunked_content_provider(
  21192. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21193. if (offset == 0) {
  21194. std::string event = "data: connected\n\n";
  21195. sink.write(event.data(), event.size());
  21196. }
  21197. // Keep connection open while handler_running is true
  21198. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21199. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21200. }
  21201. return false;
  21202. });
  21203. });
  21204. Client client("localhost", get_port());
  21205. sse::SSEClient sse(client, "/stay-open");
  21206. std::atomic<bool> connected{false};
  21207. sse.on_open([&connected]() { connected.store(true); });
  21208. sse.set_reconnect_interval(100);
  21209. sse.set_max_reconnect_attempts(1);
  21210. sse.start_async();
  21211. // Wait for connection to establish
  21212. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21213. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21214. }
  21215. EXPECT_TRUE(connected.load());
  21216. EXPECT_TRUE(sse.is_connected());
  21217. // Signal handler to stop
  21218. handler_running.store(false);
  21219. // Stop SSE client
  21220. sse.stop();
  21221. EXPECT_FALSE(sse.is_connected());
  21222. }
  21223. // Test: SSEClient with custom headers
  21224. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21225. // Setup a server endpoint that checks for custom header
  21226. std::atomic<bool> header_received{false};
  21227. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21228. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21229. header_received.store(true);
  21230. }
  21231. res.set_chunked_content_provider("text/event-stream",
  21232. [](size_t, DataSink &) { return false; });
  21233. });
  21234. Client client("localhost", get_port());
  21235. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21236. sse::SSEClient sse(client, "/header-check", headers);
  21237. sse.set_max_reconnect_attempts(1);
  21238. sse.start_async();
  21239. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21240. sse.stop();
  21241. EXPECT_TRUE(header_received.load());
  21242. }
  21243. // Test: Reconnect interval configuration
  21244. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21245. Client client("localhost", get_port());
  21246. sse::SSEClient sse(client, "/events");
  21247. auto &result = sse.set_reconnect_interval(500);
  21248. // Builder pattern should return reference to self
  21249. EXPECT_EQ(&result, &sse);
  21250. }
  21251. // Test: Max reconnect attempts
  21252. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21253. // Connect to non-existent port to force reconnects
  21254. Client client("localhost", 59998);
  21255. sse::SSEClient sse(client, "/events");
  21256. std::atomic<int> error_count{0};
  21257. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21258. sse.set_reconnect_interval(50);
  21259. sse.set_max_reconnect_attempts(2);
  21260. auto start = std::chrono::steady_clock::now();
  21261. sse.start(); // Blocking call
  21262. auto end = std::chrono::steady_clock::now();
  21263. // Should have stopped after 2 failed attempts
  21264. EXPECT_GE(error_count.load(), 2);
  21265. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21266. auto duration =
  21267. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21268. #ifdef _WIN32
  21269. // Windows is much slower for socket connection failures
  21270. EXPECT_LT(duration.count(), 7000);
  21271. #else
  21272. EXPECT_LT(duration.count(), 1000);
  21273. #endif
  21274. }
  21275. // Test: Multi-line data in integration
  21276. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21277. // Endpoint with multi-line data
  21278. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21279. res.set_chunked_content_provider(
  21280. "text/event-stream", [](size_t offset, DataSink &sink) {
  21281. if (offset == 0) {
  21282. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21283. sink.write(event.data(), event.size());
  21284. }
  21285. return false;
  21286. });
  21287. });
  21288. Client client("localhost", get_port());
  21289. sse::SSEClient sse(client, "/multiline-data");
  21290. std::string received_data;
  21291. std::mutex data_mutex;
  21292. sse.on_message([&](const sse::SSEMessage &msg) {
  21293. std::lock_guard<std::mutex> lock(data_mutex);
  21294. received_data = msg.data;
  21295. });
  21296. sse.set_reconnect_interval(100);
  21297. sse.set_max_reconnect_attempts(1);
  21298. sse.start_async();
  21299. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21300. sse.stop();
  21301. std::lock_guard<std::mutex> lock(data_mutex);
  21302. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21303. }
  21304. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21305. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21306. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21307. DataSink &sink) {
  21308. if (offset == 0) {
  21309. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21310. sink.write(events.data(), events.size());
  21311. }
  21312. return false;
  21313. });
  21314. });
  21315. Client client("localhost", get_port());
  21316. sse::SSEClient sse(client, "/empty-data-lines");
  21317. std::mutex mutex;
  21318. std::condition_variable cv;
  21319. std::vector<std::string> received;
  21320. sse.on_message([&](const sse::SSEMessage &msg) {
  21321. std::lock_guard<std::mutex> lock(mutex);
  21322. received.push_back(msg.data);
  21323. cv.notify_all();
  21324. });
  21325. sse.set_max_reconnect_attempts(1);
  21326. sse.start_async();
  21327. {
  21328. std::unique_lock<std::mutex> lock(mutex);
  21329. cv.wait_for(lock, std::chrono::seconds(2),
  21330. [&] { return received.size() >= 3; });
  21331. }
  21332. sse.stop();
  21333. ASSERT_GE(received.size(), 3u);
  21334. EXPECT_EQ(received[0], "");
  21335. EXPECT_EQ(received[1], "\nhello");
  21336. EXPECT_EQ(received[2], "");
  21337. }
  21338. // Test: Auto-reconnect after server disconnection
  21339. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21340. std::atomic<int> connection_count{0};
  21341. std::atomic<int> message_count{0};
  21342. // Endpoint that sends one event and closes, forcing reconnect
  21343. server_->Get("/reconnect-test",
  21344. [&connection_count](const Request &, Response &res) {
  21345. connection_count.fetch_add(1);
  21346. res.set_chunked_content_provider(
  21347. "text/event-stream", [](size_t offset, DataSink &sink) {
  21348. if (offset == 0) {
  21349. std::string event = "data: hello\n\n";
  21350. sink.write(event.data(), event.size());
  21351. }
  21352. return false; // Close connection after sending
  21353. });
  21354. });
  21355. Client client("localhost", get_port());
  21356. sse::SSEClient sse(client, "/reconnect-test");
  21357. sse.on_message([&message_count](const sse::SSEMessage &) {
  21358. message_count.fetch_add(1);
  21359. });
  21360. sse.set_reconnect_interval(100);
  21361. sse.set_max_reconnect_attempts(3);
  21362. sse.start_async();
  21363. // Wait long enough for multiple reconnects
  21364. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21365. sse.stop();
  21366. // Should have connected multiple times (initial + reconnects)
  21367. EXPECT_GE(connection_count.load(), 2);
  21368. // Should have received messages from multiple connections
  21369. EXPECT_GE(message_count.load(), 2);
  21370. }
  21371. // Test: A retry field that is not all ASCII digits is ignored
  21372. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21373. std::atomic<int> connection_count{0};
  21374. server_->Get("/bad-retry",
  21375. [&connection_count](const Request &, Response &res) {
  21376. connection_count.fetch_add(1);
  21377. res.set_chunked_content_provider(
  21378. "text/event-stream", [](size_t offset, DataSink &sink) {
  21379. if (offset == 0) {
  21380. std::string event = "retry: -1\ndata: hello\n\n";
  21381. sink.write(event.data(), event.size());
  21382. }
  21383. return false;
  21384. });
  21385. });
  21386. Client client("localhost", get_port());
  21387. sse::SSEClient sse(client, "/bad-retry");
  21388. sse.set_reconnect_interval(10000);
  21389. sse.start_async();
  21390. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21391. sse.stop();
  21392. EXPECT_EQ(connection_count.load(), 1);
  21393. }
  21394. // Test: A retry field of all ASCII digits sets the reconnection time
  21395. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21396. std::mutex mutex;
  21397. std::condition_variable cv;
  21398. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21399. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21400. {
  21401. std::lock_guard<std::mutex> lock(mutex);
  21402. connected_at.push_back(std::chrono::steady_clock::now());
  21403. cv.notify_all();
  21404. }
  21405. res.set_chunked_content_provider(
  21406. "text/event-stream", [](size_t offset, DataSink &sink) {
  21407. if (offset == 0) {
  21408. std::string event = "retry: 0\ndata: hello\n\n";
  21409. sink.write(event.data(), event.size());
  21410. }
  21411. return false;
  21412. });
  21413. });
  21414. Client client("localhost", get_port());
  21415. sse::SSEClient sse(client, "/zero-retry");
  21416. sse.set_reconnect_interval(10000);
  21417. sse.start_async();
  21418. {
  21419. std::unique_lock<std::mutex> lock(mutex);
  21420. cv.wait_for(lock, std::chrono::seconds(5),
  21421. [&] { return connected_at.size() >= 2; });
  21422. }
  21423. sse.stop();
  21424. // The server-supplied interval is applied, but never below 100ms, so
  21425. // "retry: 0" does not cause a busy reconnect loop
  21426. std::lock_guard<std::mutex> lock(mutex);
  21427. ASSERT_GE(connected_at.size(), 2u);
  21428. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21429. connected_at[1] - connected_at[0])
  21430. .count();
  21431. EXPECT_GE(interval_ms, 100);
  21432. }
  21433. // Test: Last-Event-ID sent on reconnect
  21434. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21435. std::atomic<int> connection_count{0};
  21436. std::vector<std::string> received_last_event_ids;
  21437. std::mutex id_mutex;
  21438. // Endpoint that checks Last-Event-ID header and sends event with ID
  21439. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21440. int conn = connection_count.fetch_add(1);
  21441. // Capture the Last-Event-ID header from each connection
  21442. {
  21443. std::lock_guard<std::mutex> lock(id_mutex);
  21444. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21445. }
  21446. res.set_chunked_content_provider(
  21447. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21448. if (offset == 0) {
  21449. std::string event =
  21450. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21451. sink.write(event.data(), event.size());
  21452. }
  21453. return false;
  21454. });
  21455. });
  21456. Client client("localhost", get_port());
  21457. sse::SSEClient sse(client, "/reconnect-with-id");
  21458. sse.set_reconnect_interval(100);
  21459. sse.set_max_reconnect_attempts(3);
  21460. sse.start_async();
  21461. // Wait for at least 2 connections
  21462. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21463. sse.stop();
  21464. // Verify behavior
  21465. std::lock_guard<std::mutex> lock(id_mutex);
  21466. EXPECT_GE(received_last_event_ids.size(), 2u);
  21467. // First connection should have no Last-Event-ID
  21468. if (!received_last_event_ids.empty()) {
  21469. EXPECT_EQ(received_last_event_ids[0], "");
  21470. }
  21471. // Second connection should have Last-Event-ID from first connection
  21472. if (received_last_event_ids.size() >= 2) {
  21473. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21474. }
  21475. }
  21476. // Test: set_headers updates headers used on reconnect
  21477. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21478. std::vector<std::string> received_tokens;
  21479. std::mutex token_mutex;
  21480. // Endpoint that captures Authorization header
  21481. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21482. {
  21483. std::lock_guard<std::mutex> lock(token_mutex);
  21484. received_tokens.push_back(req.get_header_value("Authorization"));
  21485. }
  21486. res.set_chunked_content_provider(
  21487. "text/event-stream", [](size_t offset, DataSink &sink) {
  21488. if (offset == 0) {
  21489. std::string event = "data: hello\n\n";
  21490. sink.write(event.data(), event.size());
  21491. }
  21492. return false; // Close connection to trigger reconnect
  21493. });
  21494. });
  21495. Client client("localhost", get_port());
  21496. Headers headers = {{"Authorization", "Bearer old-token"}};
  21497. sse::SSEClient sse(client, "/auth-check", headers);
  21498. // Update headers on each successful connection
  21499. sse.on_open(
  21500. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21501. sse.set_reconnect_interval(100);
  21502. sse.set_max_reconnect_attempts(3);
  21503. sse.start_async();
  21504. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21505. sse.stop();
  21506. std::lock_guard<std::mutex> lock(token_mutex);
  21507. ASSERT_GE(received_tokens.size(), 2u);
  21508. // First connection uses original header
  21509. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21510. // Second connection uses updated header from set_headers
  21511. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21512. }
  21513. // Test: 401 allows reconnection (so on_error can refresh headers)
  21514. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21515. std::atomic<int> connection_count{0};
  21516. // Endpoint: returns 401 on first attempt, 200 on second
  21517. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21518. int conn = connection_count.fetch_add(1);
  21519. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21520. res.status = StatusCode::Unauthorized_401;
  21521. res.set_content("Unauthorized", "text/plain");
  21522. return;
  21523. }
  21524. res.set_chunked_content_provider(
  21525. "text/event-stream", [](size_t offset, DataSink &sink) {
  21526. if (offset == 0) {
  21527. std::string event = "data: authenticated\n\n";
  21528. sink.write(event.data(), event.size());
  21529. }
  21530. return false;
  21531. });
  21532. });
  21533. Client client("localhost", get_port());
  21534. Headers headers = {{"Authorization", "Bearer expired"}};
  21535. sse::SSEClient sse(client, "/auth-retry", headers);
  21536. std::atomic<bool> message_received{false};
  21537. // Refresh token on error
  21538. sse.on_error(
  21539. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21540. sse.on_message([&](const sse::SSEMessage &msg) {
  21541. if (msg.data == "authenticated") { message_received.store(true); }
  21542. });
  21543. sse.set_reconnect_interval(100);
  21544. sse.set_max_reconnect_attempts(3);
  21545. sse.start_async();
  21546. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21547. sse.stop();
  21548. // Should have reconnected after 401 and succeeded with new token
  21549. EXPECT_GE(connection_count.load(), 2);
  21550. EXPECT_TRUE(message_received.load());
  21551. }
  21552. TEST(Issue2318Test, EmptyHostString) {
  21553. {
  21554. httplib::Client cli_empty("", PORT);
  21555. auto res = cli_empty.Get("/");
  21556. ASSERT_FALSE(res);
  21557. EXPECT_EQ(httplib::Error::Connection, res.error());
  21558. }
  21559. {
  21560. httplib::Client cli(" ", PORT);
  21561. auto res = cli.Get("/");
  21562. ASSERT_FALSE(res);
  21563. EXPECT_EQ(httplib::Error::Connection, res.error());
  21564. }
  21565. }
  21566. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21567. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21568. Server svr;
  21569. // Set a small payload limit (1KB)
  21570. svr.set_payload_max_length(1024);
  21571. svr.Post("/test", [&](const Request &req, Response &res) {
  21572. res.set_content("Body size: " + std::to_string(req.body.size()),
  21573. "text/plain");
  21574. });
  21575. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21576. auto se = detail::scope_exit([&] {
  21577. svr.stop();
  21578. listen_thread.join();
  21579. });
  21580. svr.wait_until_ready();
  21581. // Create data that compresses well but exceeds limit when decompressed
  21582. // 8KB of repeated null bytes compresses to a very small size
  21583. std::string original_data(8 * 1024, '\0');
  21584. // Compress the data using gzip
  21585. std::string compressed_data;
  21586. detail::gzip_compressor compressor;
  21587. compressor.compress(original_data.data(), original_data.size(), true,
  21588. [&](const char *data, size_t size) {
  21589. compressed_data.append(data, size);
  21590. return true;
  21591. });
  21592. // Verify compression worked (compressed should be much smaller)
  21593. ASSERT_LT(compressed_data.size(), original_data.size());
  21594. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21595. // Send compressed data with Content-Encoding: gzip
  21596. Client cli(HOST, PORT);
  21597. Headers headers = {{"Content-Encoding", "gzip"}};
  21598. auto res =
  21599. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21600. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21602. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21603. }
  21604. #endif
  21605. // ============================================================================
  21606. // OpenSSL-Specific Tests
  21607. // ============================================================================
  21608. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21609. X509 *readCertificate(const std::string &strFileName) {
  21610. std::ifstream inStream(strFileName);
  21611. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21612. std::istreambuf_iterator<char>());
  21613. if (strCertPEM.empty()) return (nullptr);
  21614. BIO *pbCert = BIO_new(BIO_s_mem());
  21615. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21616. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21617. BIO_free(pbCert);
  21618. return (pCert);
  21619. }
  21620. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21621. std::ifstream inStream(strFileName);
  21622. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21623. std::istreambuf_iterator<char>());
  21624. if (strPrivateKeyPEM.empty()) return (nullptr);
  21625. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21626. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21627. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21628. BIO_free(pbPrivKey);
  21629. return (pPrivateKey);
  21630. }
  21631. TEST(BindServerTest, UpdateCerts) {
  21632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21633. int port = svr.bind_to_any_port("0.0.0.0");
  21634. ASSERT_TRUE(svr.is_valid());
  21635. ASSERT_TRUE(port > 0);
  21636. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21637. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21638. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21639. ASSERT_TRUE(cert != nullptr);
  21640. ASSERT_TRUE(ca_cert != nullptr);
  21641. ASSERT_TRUE(key != nullptr);
  21642. X509_STORE *cert_store = X509_STORE_new();
  21643. X509_STORE_add_cert(cert_store, ca_cert);
  21644. // svr.update_certs(cert, key, cert_store); // deprecated
  21645. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21646. CLIENT_CA_CERT_FILE);
  21647. ASSERT_TRUE(svr.is_valid());
  21648. svr.stop();
  21649. X509_STORE_free(cert_store);
  21650. X509_free(cert);
  21651. X509_free(ca_cert);
  21652. EVP_PKEY_free(key);
  21653. }
  21654. // Test that update_certs() updates client CA list correctly
  21655. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21656. // Start with file-based constructor
  21657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21658. ASSERT_TRUE(svr.is_valid());
  21659. // Initially no client CA list should be set
  21660. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21661. ASSERT_TRUE(ssl_ctx != nullptr);
  21662. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21663. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21664. EXPECT_EQ(0, count_before);
  21665. // Now update with client CA (PEM string)
  21666. std::string cert_pem, key_pem, ca_pem;
  21667. read_file(SERVER_CERT_FILE, cert_pem);
  21668. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21669. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21670. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21671. ASSERT_TRUE(svr.is_valid());
  21672. // Now client CA list should be set
  21673. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21674. ASSERT_TRUE(ca_list_after != nullptr);
  21675. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21676. }
  21677. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21678. // Test that the file-path SSLServer constructor properly sets the client CA
  21679. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21681. ASSERT_TRUE(svr.is_valid());
  21682. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21683. ASSERT_TRUE(ssl_ctx != nullptr);
  21684. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21685. ASSERT_TRUE(ca_list != nullptr);
  21686. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21687. }
  21688. #endif
  21689. // ============================================================================
  21690. // MbedTLS-Specific Tests
  21691. // ============================================================================
  21692. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21693. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21694. using namespace httplib::tls;
  21695. // Track if callback was invoked
  21696. bool callback_invoked = false;
  21697. // The callback receives void* ctx which is actually MbedTlsContext*
  21698. // We can access the mbedtls_ssl_config via the context
  21699. auto setup_callback = [&callback_invoked](void *ctx) {
  21700. callback_invoked = true;
  21701. // Cast to MbedTlsContext* to access the ssl config
  21702. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21703. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21704. // Use static variables to hold certificate data (simplified for test)
  21705. static mbedtls_x509_crt own_cert;
  21706. static mbedtls_pk_context own_key;
  21707. static mbedtls_x509_crt ca_chain;
  21708. static bool initialized = false;
  21709. if (!initialized) {
  21710. mbedtls_x509_crt_init(&own_cert);
  21711. mbedtls_pk_init(&own_key);
  21712. mbedtls_x509_crt_init(&ca_chain);
  21713. // Load server certificate
  21714. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21715. return false;
  21716. }
  21717. // Load server private key.
  21718. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21719. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21720. #if MBEDTLS_VERSION_MAJOR == 3
  21721. ,
  21722. mbedtls_ctr_drbg_random, nullptr
  21723. #endif
  21724. ) != 0) {
  21725. return false;
  21726. }
  21727. // Load CA chain for client verification
  21728. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21729. return false;
  21730. }
  21731. initialized = true;
  21732. }
  21733. // Configure the SSL config
  21734. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21735. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21736. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21737. // Set minimum TLS version using mbedTLS native API
  21738. #if MBEDTLS_VERSION_MAJOR >= 3
  21739. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21740. #else
  21741. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21742. MBEDTLS_SSL_MINOR_VERSION_3);
  21743. #endif
  21744. return true;
  21745. };
  21746. SSLServer svr(setup_callback);
  21747. ASSERT_TRUE(svr.is_valid());
  21748. ASSERT_TRUE(callback_invoked);
  21749. svr.Get("/test", [&](const Request &req, Response &res) {
  21750. res.set_content("test", "text/plain");
  21751. auto cert = req.peer_cert();
  21752. ASSERT_TRUE(static_cast<bool>(cert));
  21753. auto common_name = cert.subject_cn();
  21754. EXPECT_EQ("Common Name", common_name);
  21755. });
  21756. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21757. auto se = detail::scope_exit([&] {
  21758. svr.stop();
  21759. t.join();
  21760. ASSERT_FALSE(svr.is_running());
  21761. });
  21762. svr.wait_until_ready();
  21763. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21764. cli.enable_server_certificate_verification(false);
  21765. cli.set_connection_timeout(30);
  21766. auto res = cli.Get("/test");
  21767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21768. ASSERT_EQ(StatusCode::OK_200, res->status);
  21769. }
  21770. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21771. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21772. // keep-alive SSL session, which reads through that config in
  21773. // mbedtls_ssl_close_notify.
  21774. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21776. ASSERT_TRUE(svr.is_valid());
  21777. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21778. res.set_content("test", "text/plain");
  21779. });
  21780. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21781. auto se = detail::scope_exit([&] {
  21782. svr.stop();
  21783. t.join();
  21784. ASSERT_FALSE(svr.is_running());
  21785. });
  21786. svr.wait_until_ready();
  21787. {
  21788. SSLClient cli(HOST, PORT);
  21789. cli.enable_server_certificate_verification(false);
  21790. cli.set_keep_alive(true);
  21791. auto res = cli.Get("/test");
  21792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21793. ASSERT_EQ(StatusCode::OK_200, res->status);
  21794. // cli is destructed here with the keep-alive SSL session still open.
  21795. }
  21796. }
  21797. #endif
  21798. // WebSocket Tests
  21799. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21800. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21801. // defining the meaning of these bits has been negotiated.
  21802. auto make_frame = [](uint8_t first_byte) {
  21803. std::string frame;
  21804. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21805. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21806. frame += "Hello";
  21807. return frame;
  21808. };
  21809. // RSV1 set (0x40)
  21810. {
  21811. detail::BufferStream strm;
  21812. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21813. ws::Opcode opcode;
  21814. std::string payload;
  21815. bool fin;
  21816. EXPECT_EQ(
  21817. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21818. ws::impl::FrameRead::Fail);
  21819. }
  21820. // RSV2 set (0x20)
  21821. {
  21822. detail::BufferStream strm;
  21823. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21824. ws::Opcode opcode;
  21825. std::string payload;
  21826. bool fin;
  21827. EXPECT_EQ(
  21828. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21829. ws::impl::FrameRead::Fail);
  21830. }
  21831. // RSV3 set (0x10)
  21832. {
  21833. detail::BufferStream strm;
  21834. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21835. ws::Opcode opcode;
  21836. std::string payload;
  21837. bool fin;
  21838. EXPECT_EQ(
  21839. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21840. ws::impl::FrameRead::Fail);
  21841. }
  21842. // No RSV bits set - should succeed
  21843. {
  21844. detail::BufferStream strm;
  21845. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21846. ws::Opcode opcode;
  21847. std::string payload;
  21848. bool fin;
  21849. EXPECT_EQ(
  21850. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21851. ws::impl::FrameRead::Ok);
  21852. EXPECT_EQ(ws::Opcode::Text, opcode);
  21853. EXPECT_EQ("Hello", payload);
  21854. EXPECT_TRUE(fin);
  21855. }
  21856. }
  21857. TEST(WebSocketTest, ControlFrameValidation) {
  21858. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21859. // payload length <= 125.
  21860. // Ping with FIN=0 - must be rejected
  21861. {
  21862. detail::BufferStream strm;
  21863. std::string frame;
  21864. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21865. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21866. strm.write(frame.data(), frame.size());
  21867. ws::Opcode opcode;
  21868. std::string payload;
  21869. bool fin;
  21870. EXPECT_EQ(
  21871. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21872. ws::impl::FrameRead::Fail);
  21873. }
  21874. // Close with FIN=0 - must be rejected
  21875. {
  21876. detail::BufferStream strm;
  21877. std::string frame;
  21878. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21879. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21880. strm.write(frame.data(), frame.size());
  21881. ws::Opcode opcode;
  21882. std::string payload;
  21883. bool fin;
  21884. EXPECT_EQ(
  21885. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21886. ws::impl::FrameRead::Fail);
  21887. }
  21888. // Ping with payload_len=126 (extended length) - must be rejected
  21889. {
  21890. detail::BufferStream strm;
  21891. std::string frame;
  21892. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21893. frame += static_cast<char>(126); // payload_len=126 (>125)
  21894. frame += static_cast<char>(0x00); // extended length high byte
  21895. frame += static_cast<char>(126); // extended length low byte
  21896. frame += std::string(126, 'x');
  21897. strm.write(frame.data(), frame.size());
  21898. ws::Opcode opcode;
  21899. std::string payload;
  21900. bool fin;
  21901. EXPECT_EQ(
  21902. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21903. ws::impl::FrameRead::Fail);
  21904. }
  21905. // Ping with FIN=1 and payload_len=125 - should succeed
  21906. {
  21907. detail::BufferStream strm;
  21908. std::string frame;
  21909. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21910. frame += static_cast<char>(125); // payload_len=125
  21911. frame += std::string(125, 'x');
  21912. strm.write(frame.data(), frame.size());
  21913. ws::Opcode opcode;
  21914. std::string payload;
  21915. bool fin;
  21916. EXPECT_EQ(
  21917. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21918. ws::impl::FrameRead::Ok);
  21919. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21920. EXPECT_EQ(125u, payload.size());
  21921. EXPECT_TRUE(fin);
  21922. }
  21923. }
  21924. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21925. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21926. // length MUST be 0.
  21927. // MSB set - must be rejected
  21928. {
  21929. detail::BufferStream strm;
  21930. std::string frame;
  21931. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21932. frame += static_cast<char>(127); // 64-bit extended length
  21933. frame += static_cast<char>(0x80); // MSB set (invalid)
  21934. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21935. strm.write(frame.data(), frame.size());
  21936. ws::Opcode opcode;
  21937. std::string payload;
  21938. bool fin;
  21939. EXPECT_EQ(
  21940. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21941. ws::impl::FrameRead::Fail);
  21942. }
  21943. // MSB clear - should pass length parsing (will be rejected by max_len,
  21944. // but that's a different check; use a small length to verify)
  21945. {
  21946. detail::BufferStream strm;
  21947. std::string frame;
  21948. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21949. frame += static_cast<char>(127); // 64-bit extended length
  21950. frame += std::string(7, '\0'); // high bytes = 0
  21951. frame += static_cast<char>(0x03); // length = 3
  21952. frame += "abc";
  21953. strm.write(frame.data(), frame.size());
  21954. ws::Opcode opcode;
  21955. std::string payload;
  21956. bool fin;
  21957. EXPECT_EQ(
  21958. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21959. ws::impl::FrameRead::Ok);
  21960. EXPECT_EQ(ws::Opcode::Text, opcode);
  21961. EXPECT_EQ("abc", payload);
  21962. }
  21963. }
  21964. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21965. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21966. // Valid UTF-8
  21967. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21968. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21969. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21970. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21971. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21972. // Invalid UTF-8
  21973. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21974. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21975. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21976. EXPECT_FALSE(
  21977. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21978. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21979. }
  21980. TEST(WebSocketTest, ConnectAndDisconnect) {
  21981. Server svr;
  21982. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21983. std::string msg;
  21984. while (ws.read(msg)) {}
  21985. });
  21986. auto port = svr.bind_to_any_port(HOST);
  21987. std::thread t([&]() { svr.listen_after_bind(); });
  21988. svr.wait_until_ready();
  21989. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21990. auto res = client.connect();
  21991. ASSERT_TRUE(res);
  21992. EXPECT_EQ(Error::Success, res.error());
  21993. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21994. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21995. EXPECT_TRUE(client.is_open());
  21996. client.close();
  21997. EXPECT_FALSE(client.is_open());
  21998. svr.stop();
  21999. t.join();
  22000. }
  22001. TEST(WebSocketTest, ValidURL) {
  22002. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22003. EXPECT_TRUE(ws1.is_valid());
  22004. ws::WebSocketClient ws2("ws://example.com/path");
  22005. EXPECT_TRUE(ws2.is_valid());
  22006. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22007. EXPECT_TRUE(ws3.is_valid());
  22008. #ifdef CPPHTTPLIB_SSL_ENABLED
  22009. ws::WebSocketClient wss1("wss://example.com/path");
  22010. EXPECT_TRUE(wss1.is_valid());
  22011. ws::WebSocketClient wss2("wss://example.com:443/path");
  22012. EXPECT_TRUE(wss2.is_valid());
  22013. #endif
  22014. }
  22015. TEST(WebSocketTest, InvalidURL) {
  22016. // No scheme
  22017. ws::WebSocketClient ws1("localhost:8080/path");
  22018. EXPECT_FALSE(ws1.is_valid());
  22019. // No path
  22020. ws::WebSocketClient ws2("ws://localhost:8080");
  22021. EXPECT_FALSE(ws2.is_valid());
  22022. // Empty string
  22023. ws::WebSocketClient ws3("");
  22024. EXPECT_FALSE(ws3.is_valid());
  22025. // Missing host
  22026. ws::WebSocketClient ws4("ws://:8080/path");
  22027. EXPECT_FALSE(ws4.is_valid());
  22028. // Port number overflow — should not crash
  22029. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22030. EXPECT_FALSE(ws5.is_valid());
  22031. // Port out of range
  22032. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22033. EXPECT_FALSE(ws6.is_valid());
  22034. }
  22035. TEST(WebSocketTest, UnsupportedScheme) {
  22036. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22037. ws::WebSocketClient ws1("http://localhost:8080/path");
  22038. EXPECT_FALSE(ws1.is_valid());
  22039. ws::WebSocketClient ws2("https://localhost:8080/path");
  22040. EXPECT_FALSE(ws2.is_valid());
  22041. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22042. EXPECT_FALSE(ws3.is_valid());
  22043. #else
  22044. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22045. std::invalid_argument);
  22046. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22047. std::invalid_argument);
  22048. #endif
  22049. }
  22050. TEST(WebSocketTest, ConnectWhenInvalid) {
  22051. ws::WebSocketClient ws("not a valid url");
  22052. EXPECT_FALSE(ws.is_valid());
  22053. auto res = ws.connect();
  22054. EXPECT_FALSE(res);
  22055. EXPECT_EQ(Error::Connection, res.error());
  22056. EXPECT_EQ(-1, res.status());
  22057. }
  22058. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22059. // Grab a port that is free, then close it again so nothing listens there
  22060. Server svr;
  22061. auto port = svr.bind_to_any_port(HOST);
  22062. svr.stop();
  22063. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22064. auto res = client.connect();
  22065. ASSERT_FALSE(res);
  22066. EXPECT_EQ(Error::Connection, res.error());
  22067. EXPECT_EQ(-1, res.status());
  22068. }
  22069. TEST(WebSocketTest, DefaultPort) {
  22070. ws::WebSocketClient ws1("ws://example.com/path");
  22071. EXPECT_TRUE(ws1.is_valid());
  22072. // ws:// defaults to port 80 (verified by successful parse)
  22073. #ifdef CPPHTTPLIB_SSL_ENABLED
  22074. ws::WebSocketClient ws2("wss://example.com/path");
  22075. EXPECT_TRUE(ws2.is_valid());
  22076. // wss:// defaults to port 443 (verified by successful parse)
  22077. #endif
  22078. }
  22079. TEST(WebSocketTest, IPv6LiteralAddress) {
  22080. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22081. EXPECT_TRUE(ws1.is_valid());
  22082. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22083. EXPECT_TRUE(ws2.is_valid());
  22084. }
  22085. TEST(WebSocketTest, ComplexPath) {
  22086. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22087. EXPECT_TRUE(ws1.is_valid());
  22088. ws::WebSocketClient ws2("ws://localhost:8080/");
  22089. EXPECT_TRUE(ws2.is_valid());
  22090. }
  22091. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22092. Server svr;
  22093. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22094. std::string msg;
  22095. while (ws.read(msg)) {}
  22096. });
  22097. auto port = svr.bind_to_any_port(HOST);
  22098. std::thread t([&]() { svr.listen_after_bind(); });
  22099. svr.wait_until_ready();
  22100. auto another_host = "example.com";
  22101. auto wrong_ip = "192.0.2.1";
  22102. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22103. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22104. ASSERT_TRUE(client.connect());
  22105. EXPECT_TRUE(client.is_open());
  22106. client.close();
  22107. svr.stop();
  22108. t.join();
  22109. }
  22110. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22111. Server svr;
  22112. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22113. std::string msg;
  22114. while (ws.read(msg)) {}
  22115. });
  22116. auto port = svr.bind_to_any_port(HOST);
  22117. std::thread t([&]() { svr.listen_after_bind(); });
  22118. svr.wait_until_ready();
  22119. auto wrong_ip = "192.0.2.1";
  22120. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22121. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22122. client.set_connection_timeout(1);
  22123. client.set_read_timeout(1);
  22124. client.set_write_timeout(1);
  22125. EXPECT_FALSE(client.connect());
  22126. EXPECT_FALSE(client.is_open());
  22127. svr.stop();
  22128. t.join();
  22129. }
  22130. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22131. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22132. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22133. // (RFC 6761) is only a map key and the Host header value.
  22134. auto host = "target.invalid";
  22135. Server svr;
  22136. std::string received_host;
  22137. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22138. received_host = req.get_header_value("Host");
  22139. std::string msg;
  22140. while (ws.read(msg)) {}
  22141. });
  22142. auto port = svr.bind_to_any_port(HOST);
  22143. std::thread t([&]() { svr.listen_after_bind(); });
  22144. // ASSERT_* below returns from the test body, which would leave t joinable
  22145. // and make ~thread call std::terminate.
  22146. auto se = detail::scope_exit([&] {
  22147. svr.stop();
  22148. if (t.joinable()) { t.join(); }
  22149. });
  22150. svr.wait_until_ready();
  22151. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22152. std::to_string(port) + "/ws");
  22153. client.set_hostname_addr_map({{host, HOST}});
  22154. ASSERT_TRUE(client.connect());
  22155. EXPECT_TRUE(client.is_open());
  22156. client.close();
  22157. svr.stop();
  22158. t.join();
  22159. // The mapping only redirects the connection; the identity stays host_.
  22160. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22161. }
  22162. class WebSocketIntegrationTest : public ::testing::Test {
  22163. protected:
  22164. void SetUp() override {
  22165. server_ = httplib::detail::make_unique<Server>();
  22166. setup_server();
  22167. start_server();
  22168. }
  22169. void TearDown() override {
  22170. server_->stop();
  22171. if (server_thread_.joinable()) { server_thread_.join(); }
  22172. }
  22173. void setup_server() {
  22174. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22175. std::string msg;
  22176. ws::ReadResult ret;
  22177. while ((ret = ws.read(msg))) {
  22178. if (ret == ws::Binary) {
  22179. ws.send(msg.data(), msg.size());
  22180. } else {
  22181. ws.send(msg);
  22182. }
  22183. }
  22184. });
  22185. server_->WebSocket("/ws-echo-string",
  22186. [](const Request &, ws::WebSocket &ws) {
  22187. std::string msg;
  22188. while (ws.read(msg)) {
  22189. ws.send("echo: " + msg);
  22190. }
  22191. });
  22192. server_->WebSocket(
  22193. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22194. // Echo back request metadata
  22195. ws.send("path:" + req.path);
  22196. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22197. std::string msg;
  22198. while (ws.read(msg)) {}
  22199. });
  22200. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22201. std::string msg;
  22202. ws.read(msg); // wait for a message
  22203. ws.close();
  22204. });
  22205. server_->WebSocket("/ws-close-status",
  22206. [](const Request &, ws::WebSocket &ws) {
  22207. std::string msg;
  22208. ws.read(msg); // wait for a message
  22209. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22210. });
  22211. server_->WebSocket(
  22212. "/ws-subprotocol",
  22213. [](const Request &, ws::WebSocket &ws) {
  22214. std::string msg;
  22215. while (ws.read(msg)) {
  22216. ws.send(msg);
  22217. }
  22218. },
  22219. [](const std::vector<std::string> &protocols) -> std::string {
  22220. for (const auto &p : protocols) {
  22221. if (p == "graphql-ws") { return p; }
  22222. }
  22223. return "";
  22224. });
  22225. server_->WebSocket(
  22226. "/ws-subprotocol-unoffered",
  22227. [](const Request &, ws::WebSocket &ws) {
  22228. std::string msg;
  22229. while (ws.read(msg)) {
  22230. ws.send(msg);
  22231. }
  22232. },
  22233. [](const std::vector<std::string> &) -> std::string {
  22234. return "admin";
  22235. });
  22236. }
  22237. void start_server() {
  22238. port_ = server_->bind_to_any_port(HOST);
  22239. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22240. server_->wait_until_ready();
  22241. }
  22242. std::unique_ptr<Server> server_;
  22243. std::thread server_thread_;
  22244. int port_ = 0;
  22245. };
  22246. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22247. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22248. "/ws-echo");
  22249. ASSERT_TRUE(client.connect());
  22250. ASSERT_TRUE(client.is_open());
  22251. ASSERT_TRUE(client.send("Hello WebSocket"));
  22252. std::string msg;
  22253. EXPECT_EQ(ws::Text, client.read(msg));
  22254. EXPECT_EQ("Hello WebSocket", msg);
  22255. client.close();
  22256. }
  22257. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22259. "/ws-echo");
  22260. ASSERT_TRUE(client.connect());
  22261. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22262. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22263. std::string msg;
  22264. EXPECT_EQ(ws::Binary, client.read(msg));
  22265. EXPECT_EQ(binary_data, msg);
  22266. client.close();
  22267. }
  22268. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22269. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22270. "/ws-echo");
  22271. ASSERT_TRUE(client.connect());
  22272. for (int i = 0; i < 10; i++) {
  22273. auto text = "message " + std::to_string(i);
  22274. ASSERT_TRUE(client.send(text));
  22275. std::string msg;
  22276. ASSERT_TRUE(client.read(msg));
  22277. EXPECT_EQ(text, msg);
  22278. }
  22279. client.close();
  22280. }
  22281. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22282. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22283. "/ws-close");
  22284. ASSERT_TRUE(client.connect());
  22285. // Send a message to trigger the server to close
  22286. ASSERT_TRUE(client.send("trigger close"));
  22287. // The server will close, so read should return false
  22288. std::string msg;
  22289. EXPECT_FALSE(client.read(msg));
  22290. EXPECT_FALSE(client.is_open());
  22291. }
  22292. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22293. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22294. "/ws-echo");
  22295. ASSERT_TRUE(client.connect());
  22296. // 128KB message
  22297. std::string large_data(128 * 1024, 'X');
  22298. ASSERT_TRUE(client.send(large_data));
  22299. std::string msg;
  22300. ASSERT_TRUE(client.read(msg));
  22301. EXPECT_EQ(large_data, msg);
  22302. client.close();
  22303. }
  22304. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22305. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22306. "/ws-echo");
  22307. ASSERT_TRUE(client.connect());
  22308. const int num_threads = 4;
  22309. std::vector<std::thread> threads;
  22310. std::atomic<int> send_count{0};
  22311. for (int t = 0; t < num_threads; t++) {
  22312. threads.emplace_back([&client, &send_count, t]() {
  22313. for (int i = 0; i < 5; i++) {
  22314. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22315. if (client.send(text)) { send_count++; }
  22316. }
  22317. });
  22318. }
  22319. for (auto &th : threads) {
  22320. th.join();
  22321. }
  22322. int received = 0;
  22323. std::string msg;
  22324. while (received < send_count.load()) {
  22325. if (!client.read(msg)) { break; }
  22326. received++;
  22327. }
  22328. EXPECT_EQ(send_count.load(), received);
  22329. client.close();
  22330. }
  22331. TEST_F(WebSocketIntegrationTest, ReadString) {
  22332. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22333. "/ws-echo-string");
  22334. ASSERT_TRUE(client.connect());
  22335. ASSERT_TRUE(client.send("hello"));
  22336. std::string msg;
  22337. ASSERT_TRUE(client.read(msg));
  22338. EXPECT_EQ("echo: hello", msg);
  22339. ASSERT_TRUE(client.send("world"));
  22340. ASSERT_TRUE(client.read(msg));
  22341. EXPECT_EQ("echo: world", msg);
  22342. client.close();
  22343. }
  22344. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22345. Headers headers = {{"X-Test-Header", "test-value"}};
  22346. ws::WebSocketClient client(
  22347. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22348. ASSERT_TRUE(client.connect());
  22349. std::string msg;
  22350. ASSERT_TRUE(client.read(msg));
  22351. EXPECT_EQ("path:/ws-request-info", msg);
  22352. ASSERT_TRUE(client.read(msg));
  22353. EXPECT_EQ("header:test-value", msg);
  22354. client.close();
  22355. }
  22356. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22357. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22358. "/ws-echo");
  22359. client.set_read_timeout(1, 0); // 1 second
  22360. ASSERT_TRUE(client.connect());
  22361. // Don't send anything — server echo handler waits for a message, so read()
  22362. // should time out. The connection survives it: nothing was consumed.
  22363. std::string msg;
  22364. EXPECT_EQ(client.read(msg), ws::Timeout);
  22365. EXPECT_TRUE(client.is_open());
  22366. // And it is still usable afterwards.
  22367. EXPECT_TRUE(client.send("after timeout"));
  22368. EXPECT_EQ(client.read(msg), ws::Text);
  22369. EXPECT_EQ(msg, "after timeout");
  22370. }
  22371. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22372. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22373. "/ws-echo");
  22374. client.set_read_timeout(1, 0);
  22375. ASSERT_TRUE(client.connect());
  22376. ASSERT_TRUE(client.send("first"));
  22377. std::string msg;
  22378. ASSERT_EQ(client.read(msg), ws::Text);
  22379. ASSERT_EQ(msg, "first");
  22380. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22381. // not be used with a read timeout: it would reprocess the previous message.
  22382. EXPECT_EQ(client.read(msg), ws::Timeout);
  22383. EXPECT_EQ(msg, "first");
  22384. }
  22385. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22386. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22387. "/ws-echo");
  22388. ASSERT_TRUE(client.connect());
  22389. // Setting it once the connection is open reaches the live stream, not just
  22390. // the seed for the next connect().
  22391. client.set_read_timeout(1, 0);
  22392. std::string msg;
  22393. EXPECT_EQ(client.read(msg), ws::Timeout);
  22394. EXPECT_TRUE(client.is_open());
  22395. }
  22396. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22397. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22398. "/ws-echo");
  22399. client.set_read_timeout(5, 0);
  22400. ASSERT_TRUE(client.connect());
  22401. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22402. // The server should reject it and close the connection.
  22403. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22404. client.send(oversized);
  22405. // The server's read() should have failed due to payload limit,
  22406. // so our read() should return false (connection closed).
  22407. std::string msg;
  22408. EXPECT_FALSE(client.read(msg));
  22409. }
  22410. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22411. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22412. "/ws-echo");
  22413. client.set_read_timeout(10, 0);
  22414. ASSERT_TRUE(client.connect());
  22415. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22416. // This should succeed.
  22417. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22418. ASSERT_TRUE(client.send(at_limit));
  22419. std::string msg;
  22420. ASSERT_TRUE(client.read(msg));
  22421. EXPECT_EQ(at_limit.size(), msg.size());
  22422. client.close();
  22423. }
  22424. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22426. "/nonexistent");
  22427. auto res = client.connect();
  22428. EXPECT_FALSE(res);
  22429. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22430. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22431. EXPECT_FALSE(client.is_open());
  22432. }
  22433. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22434. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22435. "/ws-echo");
  22436. ASSERT_TRUE(client.connect());
  22437. ASSERT_TRUE(client.send(""));
  22438. std::string msg;
  22439. EXPECT_EQ(ws::Text, client.read(msg));
  22440. EXPECT_EQ("", msg);
  22441. client.close();
  22442. }
  22443. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22444. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22445. "/ws-echo");
  22446. // First connection
  22447. ASSERT_TRUE(client.connect());
  22448. ASSERT_TRUE(client.send("first"));
  22449. std::string msg;
  22450. ASSERT_TRUE(client.read(msg));
  22451. EXPECT_EQ("first", msg);
  22452. client.close();
  22453. EXPECT_FALSE(client.is_open());
  22454. // Reconnect using the same client object
  22455. ASSERT_TRUE(client.connect());
  22456. ASSERT_TRUE(client.is_open());
  22457. ASSERT_TRUE(client.send("second"));
  22458. ASSERT_TRUE(client.read(msg));
  22459. EXPECT_EQ("second", msg);
  22460. client.close();
  22461. }
  22462. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22463. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22464. "/ws-close-status");
  22465. ASSERT_TRUE(client.connect());
  22466. // Trigger the server to close with GoingAway status
  22467. ASSERT_TRUE(client.send("trigger"));
  22468. // read() should return false after receiving the close frame
  22469. std::string msg;
  22470. EXPECT_FALSE(client.read(msg));
  22471. EXPECT_FALSE(client.is_open());
  22472. }
  22473. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22474. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22475. "/ws-echo");
  22476. ASSERT_TRUE(client.connect());
  22477. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22478. EXPECT_FALSE(client.is_open());
  22479. }
  22480. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22481. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22482. ws::WebSocketClient client(
  22483. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22484. ASSERT_TRUE(client.connect());
  22485. // Server should have selected graphql-ws
  22486. EXPECT_EQ("graphql-ws", client.subprotocol());
  22487. client.close();
  22488. }
  22489. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22490. Headers headers;
  22491. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22492. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22493. ws::WebSocketClient client(
  22494. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22495. ASSERT_TRUE(client.connect());
  22496. // The offer on the second field line counts too, so graphql-ws is selected
  22497. EXPECT_EQ("graphql-ws", client.subprotocol());
  22498. client.close();
  22499. }
  22500. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22501. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22502. ws::WebSocketClient client(
  22503. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22504. ASSERT_TRUE(client.connect());
  22505. // Server should not have selected any subprotocol
  22506. EXPECT_TRUE(client.subprotocol().empty());
  22507. client.close();
  22508. }
  22509. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22510. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22511. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22512. "/ws-subprotocol-unoffered",
  22513. headers);
  22514. ASSERT_TRUE(client.connect());
  22515. EXPECT_TRUE(client.subprotocol().empty());
  22516. client.close();
  22517. }
  22518. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22519. // Connect without requesting any subprotocol
  22520. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22521. "/ws-subprotocol");
  22522. ASSERT_TRUE(client.connect());
  22523. EXPECT_TRUE(client.subprotocol().empty());
  22524. client.close();
  22525. }
  22526. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22527. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22528. "/ws-echo");
  22529. client.set_tcp_nodelay(true);
  22530. client.set_connection_timeout(3, 0);
  22531. bool socket_options_called = false;
  22532. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22533. ASSERT_TRUE(client.connect());
  22534. ASSERT_TRUE(client.is_open());
  22535. EXPECT_TRUE(socket_options_called);
  22536. ASSERT_TRUE(client.send("hello"));
  22537. std::string msg;
  22538. auto result = client.read(msg);
  22539. EXPECT_EQ(result, ws::ReadResult::Text);
  22540. EXPECT_EQ(msg, "hello");
  22541. client.close();
  22542. }
  22543. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22544. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22545. "/ws-echo");
  22546. client.set_connection_timeout(std::chrono::seconds(3));
  22547. client.set_write_timeout(std::chrono::seconds(3));
  22548. // A sub-second remainder exercises the seconds/microseconds split.
  22549. client.set_read_timeout(std::chrono::milliseconds(1500));
  22550. ASSERT_TRUE(client.connect());
  22551. auto start = std::chrono::steady_clock::now();
  22552. std::string msg;
  22553. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22554. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22555. std::chrono::steady_clock::now() - start)
  22556. .count();
  22557. // Above 1s so that dropping the microseconds half of the split fails here.
  22558. // Ignoring the setter altogether would not reach this line at all: a client
  22559. // waits forever by default.
  22560. EXPECT_GE(elapsed, 1400);
  22561. EXPECT_LT(elapsed, 30000);
  22562. }
  22563. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22564. Server svr;
  22565. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22566. if (!req.has_header("Authorization")) {
  22567. res.status = StatusCode::Unauthorized_401;
  22568. res.set_content("Unauthorized", "text/plain");
  22569. return Server::HandlerResponse::Handled;
  22570. }
  22571. return Server::HandlerResponse::Unhandled;
  22572. });
  22573. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22574. std::string msg;
  22575. while (ws.read(msg)) {
  22576. ws.send(msg);
  22577. }
  22578. });
  22579. auto port = svr.bind_to_any_port("localhost");
  22580. std::thread t([&]() { svr.listen_after_bind(); });
  22581. svr.wait_until_ready();
  22582. // Without Authorization header - should be rejected before upgrade
  22583. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22584. EXPECT_FALSE(client1.connect());
  22585. // The rejection is framed like any other HTTP response
  22586. {
  22587. Client cli("localhost", port);
  22588. Headers headers = {{"Upgrade", "websocket"},
  22589. {"Connection", "Upgrade"},
  22590. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22591. {"Sec-WebSocket-Version", "13"}};
  22592. auto res = cli.Get("/ws", headers);
  22593. ASSERT_TRUE(res);
  22594. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22595. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22596. EXPECT_EQ("Unauthorized", res->body);
  22597. }
  22598. // With Authorization header - should succeed
  22599. Headers headers = {{"Authorization", "Bearer token123"}};
  22600. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22601. headers);
  22602. ASSERT_TRUE(client2.connect());
  22603. ASSERT_TRUE(client2.send("hello"));
  22604. std::string msg;
  22605. ASSERT_TRUE(client2.read(msg));
  22606. EXPECT_EQ("hello", msg);
  22607. client2.close();
  22608. svr.stop();
  22609. t.join();
  22610. }
  22611. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22612. Server svr;
  22613. std::atomic<int> pre_request_calls{0};
  22614. std::atomic<bool> route_matched{false};
  22615. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22616. pre_request_calls++;
  22617. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22618. if (req.get_header_value("Authorization") != "Bearer token123") {
  22619. res.status = StatusCode::Unauthorized_401;
  22620. res.set_content("Unauthorized", "text/plain");
  22621. return Server::HandlerResponse::Handled;
  22622. }
  22623. return Server::HandlerResponse::Unhandled;
  22624. });
  22625. std::atomic<bool> handler_called{false};
  22626. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22627. handler_called = true;
  22628. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22629. });
  22630. auto port = svr.bind_to_any_port("localhost");
  22631. std::thread t([&]() { svr.listen_after_bind(); });
  22632. svr.wait_until_ready();
  22633. // Without Authorization header - should be rejected before upgrade
  22634. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22635. "/ws/1");
  22636. EXPECT_FALSE(client1.connect());
  22637. EXPECT_FALSE(handler_called);
  22638. EXPECT_EQ(1, pre_request_calls);
  22639. EXPECT_TRUE(route_matched);
  22640. // The rejection is an ordinary HTTP response, not a protocol switch
  22641. {
  22642. Client cli("localhost", port);
  22643. Headers headers = {{"Upgrade", "websocket"},
  22644. {"Connection", "Upgrade"},
  22645. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22646. {"Sec-WebSocket-Version", "13"}};
  22647. auto res = cli.Get("/ws/1", headers);
  22648. ASSERT_TRUE(res);
  22649. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22650. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22651. EXPECT_EQ("Unauthorized", res->body);
  22652. }
  22653. EXPECT_FALSE(handler_called);
  22654. // With Authorization header - should succeed
  22655. Headers headers = {{"Authorization", "Bearer token123"}};
  22656. ws::WebSocketClient client2(
  22657. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22658. ASSERT_TRUE(client2.connect());
  22659. std::string msg;
  22660. ASSERT_TRUE(client2.read(msg));
  22661. EXPECT_EQ("/ws/:id 2", msg);
  22662. EXPECT_TRUE(handler_called);
  22663. client2.close();
  22664. svr.stop();
  22665. t.join();
  22666. }
  22667. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22668. Server svr;
  22669. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22670. // A read timeout is how a handler gets control back. Without it, a handler
  22671. // parked in read() can never write on the connection it is reading.
  22672. ws.set_read_timeout(std::chrono::milliseconds(100));
  22673. std::string msg;
  22674. while (ws.is_open()) {
  22675. auto r = ws.read(msg);
  22676. if (r == httplib::ws::Timeout) {
  22677. ws.send("tick");
  22678. continue;
  22679. }
  22680. if (r == httplib::ws::Fail) { break; }
  22681. ws.send(msg);
  22682. }
  22683. });
  22684. auto port = svr.bind_to_any_port("localhost");
  22685. std::thread t([&]() { svr.listen_after_bind(); });
  22686. svr.wait_until_ready();
  22687. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22688. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22689. ASSERT_TRUE(client.connect());
  22690. // The client sends nothing, so anything it receives came out of the
  22691. // handler's timeout path.
  22692. std::string msg;
  22693. ASSERT_EQ(client.read(msg), ws::Text);
  22694. EXPECT_EQ("tick", msg);
  22695. client.close();
  22696. svr.stop();
  22697. t.join();
  22698. }
  22699. // Stream::read may return fewer bytes than asked for. This is that contract at
  22700. // its worst -- one byte per call -- which is what a frame header straddling a
  22701. // read buffer's boundary looks like to the frame parser.
  22702. class WsByteAtATimeStream : public Stream {
  22703. public:
  22704. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22705. bool is_readable() const override { return true; }
  22706. bool wait_readable() const override { return true; }
  22707. bool wait_writable() const override { return true; }
  22708. ssize_t read(char *ptr, size_t size) override {
  22709. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22710. *ptr = data_[pos_++];
  22711. return 1;
  22712. }
  22713. ssize_t write(const char *, size_t size) override {
  22714. return static_cast<ssize_t>(size);
  22715. }
  22716. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22717. ip = "127.0.0.1";
  22718. port = 0;
  22719. }
  22720. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22721. ip = "127.0.0.1";
  22722. port = 0;
  22723. }
  22724. socket_t socket() const override { return INVALID_SOCKET; }
  22725. time_t duration() const override { return 0; }
  22726. private:
  22727. std::string data_;
  22728. size_t pos_ = 0;
  22729. };
  22730. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22731. // The payload uses the 16-bit extended length, so the header, the length
  22732. // and the mask key are all multi-byte fields here. Each used to be read
  22733. // with a single read() call, which fails as soon as one is split. The
  22734. // payload is also a little over one read chunk, so it is read in two.
  22735. std::string body;
  22736. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22737. body += static_cast<char>(i % 251);
  22738. }
  22739. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22740. std::string frame;
  22741. frame += static_cast<char>(0x81); // FIN + Text
  22742. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22743. frame += static_cast<char>(body.size() >> 8);
  22744. frame += static_cast<char>(body.size() & 0xff);
  22745. for (size_t i = 0; i < 4; i++) {
  22746. frame += static_cast<char>(mask[i]);
  22747. }
  22748. for (size_t i = 0; i < body.size(); i++) {
  22749. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22750. }
  22751. WsByteAtATimeStream strm(frame);
  22752. ws::Opcode opcode;
  22753. std::string payload;
  22754. bool fin = false;
  22755. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22756. /*expect_masked=*/true, body.size()),
  22757. ws::impl::FrameRead::Ok);
  22758. EXPECT_TRUE(fin);
  22759. EXPECT_EQ(opcode, ws::Opcode::Text);
  22760. EXPECT_EQ(payload, body);
  22761. }
  22762. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22763. std::string body(2000, 'x');
  22764. std::string frame;
  22765. frame += static_cast<char>(0x82); // FIN + Binary
  22766. frame += static_cast<char>(126); // 16-bit length follows
  22767. frame += static_cast<char>(body.size() >> 8);
  22768. frame += static_cast<char>(body.size() & 0xff);
  22769. frame += body;
  22770. detail::BufferStream strm;
  22771. strm.write(frame.data(), frame.size());
  22772. ws::Opcode opcode;
  22773. std::string payload;
  22774. bool fin;
  22775. EXPECT_EQ(
  22776. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22777. ws::impl::FrameRead::Ok);
  22778. EXPECT_EQ(body, payload);
  22779. }
  22780. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22781. // The header announces the largest payload allowed, and only 3 bytes of it
  22782. // ever arrive.
  22783. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22784. std::string frame;
  22785. frame += static_cast<char>(0x82); // FIN + Binary
  22786. frame += static_cast<char>(127); // 64-bit length follows
  22787. for (int shift = 56; shift >= 0; shift -= 8) {
  22788. frame += static_cast<char>((len >> shift) & 0xff);
  22789. }
  22790. frame += "abc";
  22791. detail::BufferStream strm;
  22792. strm.write(frame.data(), frame.size());
  22793. ws::Opcode opcode;
  22794. std::string payload;
  22795. bool fin;
  22796. EXPECT_EQ(
  22797. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22798. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22799. ws::impl::FrameRead::Fail);
  22800. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22801. }
  22802. TEST(WebSocketTest, QueryStringInHandshake) {
  22803. Server svr;
  22804. std::mutex mtx;
  22805. std::string received_target;
  22806. std::string received_token;
  22807. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22808. {
  22809. std::lock_guard<std::mutex> lock(mtx);
  22810. received_target = req.target;
  22811. if (req.has_param("token")) {
  22812. received_token = req.get_param_value("token");
  22813. }
  22814. }
  22815. std::string msg;
  22816. while (ws.read(msg)) {
  22817. ws.send(msg);
  22818. }
  22819. });
  22820. auto port = svr.bind_to_any_port("localhost");
  22821. std::thread t([&]() { svr.listen_after_bind(); });
  22822. svr.wait_until_ready();
  22823. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22824. "/ws?token=ABC&session=123");
  22825. ASSERT_TRUE(client.connect());
  22826. // Round-trip ensures the handler has run and captured the request.
  22827. ASSERT_TRUE(client.send("hello"));
  22828. std::string msg;
  22829. ASSERT_TRUE(client.read(msg));
  22830. EXPECT_EQ("hello", msg);
  22831. client.close();
  22832. {
  22833. std::lock_guard<std::mutex> lock(mtx);
  22834. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22835. EXPECT_EQ("ABC", received_token);
  22836. }
  22837. svr.stop();
  22838. t.join();
  22839. }
  22840. // Run a handshake against a throwaway server and hand the request the server
  22841. // received back to the caller, so tests can assert on the headers the client
  22842. // actually put on the wire.
  22843. static void capture_websocket_handshake_request(
  22844. const Headers &client_headers,
  22845. std::function<void(const Request &, int port)> verify) {
  22846. Server svr;
  22847. std::mutex mtx;
  22848. Request received;
  22849. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22850. {
  22851. std::lock_guard<std::mutex> lock(mtx);
  22852. received = req;
  22853. }
  22854. std::string msg;
  22855. while (ws.read(msg)) {
  22856. ws.send(msg);
  22857. }
  22858. });
  22859. auto port = svr.bind_to_any_port("localhost");
  22860. std::thread t([&]() { svr.listen_after_bind(); });
  22861. auto se = detail::scope_exit([&] {
  22862. svr.stop();
  22863. t.join();
  22864. });
  22865. svr.wait_until_ready();
  22866. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22867. client_headers);
  22868. ASSERT_TRUE(client.connect());
  22869. ASSERT_TRUE(client.send("hello"));
  22870. std::string msg;
  22871. ASSERT_TRUE(client.read(msg));
  22872. client.close();
  22873. {
  22874. std::lock_guard<std::mutex> lock(mtx);
  22875. verify(received, port);
  22876. }
  22877. }
  22878. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22879. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22880. // Non-default port must be present in the Host header. Default ports
  22881. // (80/443) are omitted; that logic is covered by
  22882. // MakeHostAndPortStringTest.
  22883. EXPECT_EQ("localhost:" + std::to_string(port),
  22884. req.get_header_value("Host"));
  22885. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22886. req.get_header_value("User-Agent"));
  22887. EXPECT_FALSE(req.has_header("Accept"));
  22888. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22889. EXPECT_FALSE(req.has_header("Content-Length"));
  22890. });
  22891. }
  22892. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22893. capture_websocket_handshake_request(
  22894. {{"Host", "example.com"},
  22895. {"User-Agent", "custom-agent"},
  22896. {"X-Custom", "value"}},
  22897. [](const Request &req, int) {
  22898. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22899. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22900. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22901. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22902. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22903. });
  22904. }
  22905. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22906. capture_websocket_handshake_request(
  22907. {{"Upgrade", "bogus"},
  22908. {"Connection", "close"},
  22909. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22910. {"Sec-WebSocket-Version", "8"}},
  22911. [](const Request &req, int) {
  22912. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22913. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22914. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22915. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22916. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22917. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22918. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22919. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22920. req.get_header_value("Sec-WebSocket-Key"));
  22921. });
  22922. }
  22923. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22924. // A header the client refuses to send must abort the handshake before any
  22925. // part of it reaches the wire; a lone request line would otherwise sit in
  22926. // the peer's buffer as a truncated request.
  22927. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22928. ASSERT_NE(INVALID_SOCKET, srv);
  22929. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22930. sockaddr_in addr{};
  22931. addr.sin_family = AF_INET;
  22932. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22933. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22934. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22935. ASSERT_EQ(0, ::listen(srv, 1));
  22936. sockaddr_in bound{};
  22937. socklen_t bound_len = sizeof(bound);
  22938. ASSERT_EQ(
  22939. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22940. auto port = ntohs(bound.sin_port);
  22941. ssize_t received = -1;
  22942. std::thread t([&] {
  22943. // Bound every blocking call so a regression fails the test with a bad
  22944. // value instead of hanging the suite.
  22945. fd_set rfds;
  22946. FD_ZERO(&rfds);
  22947. FD_SET(srv, &rfds);
  22948. timeval tv{5, 0};
  22949. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22950. 0) {
  22951. return;
  22952. }
  22953. sockaddr_in cli_addr{};
  22954. socklen_t cli_len = sizeof(cli_addr);
  22955. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22956. if (cli == INVALID_SOCKET) { return; }
  22957. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22958. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22959. char buf[4096];
  22960. received = ::recv(cli, buf, sizeof(buf), 0);
  22961. });
  22962. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22963. // connect() has already shut the socket down by the time it returns false,
  22964. // so the peer sees EOF without waiting for the client to be destroyed.
  22965. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22966. {{"X-Bad", "a\r\nInjected: 1"}});
  22967. EXPECT_FALSE(client.connect());
  22968. t.join();
  22969. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22970. EXPECT_EQ(0, received);
  22971. }
  22972. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22973. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22974. // contains "upgrade" as a substring is a different token and must not
  22975. // start a WebSocket handshake.
  22976. auto make_request = [](const std::vector<std::string> &connection_values) {
  22977. Request req;
  22978. req.method = "GET";
  22979. req.headers.emplace("Upgrade", "websocket");
  22980. for (const auto &value : connection_values) {
  22981. req.headers.emplace("Connection", value);
  22982. }
  22983. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22984. req.headers.emplace("Sec-WebSocket-Version", "13");
  22985. return req;
  22986. };
  22987. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22988. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22989. EXPECT_TRUE(
  22990. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22991. EXPECT_TRUE(
  22992. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22993. EXPECT_TRUE(
  22994. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22995. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22996. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22997. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22998. EXPECT_FALSE(
  22999. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23000. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23001. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23002. }
  23003. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23004. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23005. // asks recipients to match each protocol-name case-insensitively, and RFC
  23006. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23007. // client naming websocket alongside another protocol, or on a second field
  23008. // line, is offering websocket; a value that merely contains "websocket" as a
  23009. // substring is a different protocol name and is not.
  23010. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23011. Request req;
  23012. req.method = "GET";
  23013. for (const auto &value : upgrade_values) {
  23014. req.headers.emplace("Upgrade", value);
  23015. }
  23016. req.headers.emplace("Connection", "Upgrade");
  23017. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23018. req.headers.emplace("Sec-WebSocket-Version", "13");
  23019. return req;
  23020. };
  23021. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23022. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23023. EXPECT_TRUE(
  23024. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23025. EXPECT_TRUE(
  23026. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23027. EXPECT_TRUE(
  23028. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23029. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23030. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23031. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23032. EXPECT_FALSE(
  23033. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23034. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23035. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23036. }
  23037. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23038. Server svr;
  23039. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23040. auto port = svr.bind_to_any_port("localhost");
  23041. std::thread t([&]() { svr.listen_after_bind(); });
  23042. auto se = detail::scope_exit([&] {
  23043. svr.stop();
  23044. t.join();
  23045. });
  23046. svr.wait_until_ready();
  23047. Headers headers = {{"Upgrade", "websocket"},
  23048. {"Connection", "notupgrade"},
  23049. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23050. {"Sec-WebSocket-Version", "13"}};
  23051. Client cli("localhost", port);
  23052. auto res = cli.Get("/ws", headers);
  23053. // The route exists only as a WebSocket route, so a request that fails the
  23054. // handshake check falls through to ordinary routing.
  23055. ASSERT_TRUE(res);
  23056. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23057. }
  23058. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23059. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23060. // Connection value is the only thing left for the client to reject.
  23061. Server svr;
  23062. svr.Get("/ws", [](const Request &req, Response &res) {
  23063. res.status = StatusCode::SwitchingProtocol_101;
  23064. res.set_header("Upgrade", "websocket");
  23065. res.set_header("Connection", "notupgrade");
  23066. res.set_header("Sec-WebSocket-Accept",
  23067. detail::websocket_accept_key(
  23068. req.get_header_value("Sec-WebSocket-Key")));
  23069. });
  23070. auto port = svr.bind_to_any_port("localhost");
  23071. std::thread t([&]() { svr.listen_after_bind(); });
  23072. auto se = detail::scope_exit([&] {
  23073. svr.stop();
  23074. t.join();
  23075. });
  23076. svr.wait_until_ready();
  23077. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23078. auto res = client.connect();
  23079. EXPECT_FALSE(res);
  23080. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23081. EXPECT_FALSE(client.is_open());
  23082. }
  23083. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23084. Server svr;
  23085. svr.Get("/ws", [](const Request &req, Response &res) {
  23086. res.status = StatusCode::SwitchingProtocol_101;
  23087. res.set_header("Upgrade", "websocket");
  23088. res.set_header("Connection", "Upgrade");
  23089. res.set_header("Sec-WebSocket-Accept",
  23090. detail::websocket_accept_key(
  23091. req.get_header_value("Sec-WebSocket-Key")));
  23092. res.set_header("Sec-WebSocket-Protocol", "admin");
  23093. });
  23094. auto port = svr.bind_to_any_port("localhost");
  23095. std::thread t([&]() { svr.listen_after_bind(); });
  23096. auto se = detail::scope_exit([&] {
  23097. svr.stop();
  23098. t.join();
  23099. });
  23100. svr.wait_until_ready();
  23101. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23102. // Server selects a subprotocol the client never offered
  23103. {
  23104. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23105. ws::WebSocketClient client(url, headers);
  23106. auto res = client.connect();
  23107. EXPECT_FALSE(res);
  23108. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23109. EXPECT_FALSE(client.is_open());
  23110. EXPECT_TRUE(client.subprotocol().empty());
  23111. }
  23112. // Client offered none but the server named one anyway
  23113. {
  23114. ws::WebSocketClient client(url);
  23115. auto res = client.connect();
  23116. EXPECT_FALSE(res);
  23117. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23118. EXPECT_FALSE(client.is_open());
  23119. EXPECT_TRUE(client.subprotocol().empty());
  23120. }
  23121. }
  23122. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23123. // The socket path doubles as the URL host, so it must not contain '/'.
  23124. const char *shard = getenv("GTEST_SHARD_INDEX");
  23125. const std::string sock_path =
  23126. shard ? std::string("httplib-ws-") + shard + ".sock"
  23127. : std::string("httplib-ws.sock");
  23128. std::remove(sock_path.c_str());
  23129. Server svr;
  23130. std::mutex mtx;
  23131. std::string received_host;
  23132. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23133. {
  23134. std::lock_guard<std::mutex> lock(mtx);
  23135. received_host = req.get_header_value("Host");
  23136. }
  23137. std::string msg;
  23138. while (ws.read(msg)) {
  23139. ws.send(msg);
  23140. }
  23141. });
  23142. svr.set_address_family(AF_UNIX);
  23143. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23144. auto se = detail::scope_exit([&] {
  23145. svr.stop();
  23146. t.join();
  23147. std::remove(sock_path.c_str());
  23148. });
  23149. svr.wait_until_ready();
  23150. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23151. client.set_address_family(AF_UNIX);
  23152. ASSERT_TRUE(client.connect());
  23153. ASSERT_TRUE(client.send("hello"));
  23154. std::string msg;
  23155. ASSERT_TRUE(client.read(msg));
  23156. client.close();
  23157. {
  23158. std::lock_guard<std::mutex> lock(mtx);
  23159. // There is no host:port for a Unix socket, so the same "localhost"
  23160. // placeholder the HTTP client uses is expected.
  23161. EXPECT_EQ("localhost", received_host);
  23162. }
  23163. }
  23164. // Two threads must never parse WebSocket frames from the same stream.
  23165. // close() used to read the peer's Close reply with its own frame read, so it
  23166. // raced a reader thread that was in the middle of a payload: the payload loop
  23167. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23168. // so bytes taken by close() were replaced with bytes from further along the
  23169. // stream. The message kept its length and silently changed content.
  23170. //
  23171. // The raw peer below sends a frame header plus part of the payload, waits for
  23172. // the handler to call close(), and only then sends the rest. Whichever thread
  23173. // would win the race for those bytes, the message must arrive intact, because
  23174. // close() must not touch the stream while read() owns it.
  23175. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23176. #ifndef _WIN32
  23177. signal(SIGPIPE, SIG_IGN);
  23178. #endif
  23179. const size_t payload_len = 120; // fits the 7-bit length field
  23180. const size_t prefix_len = 8;
  23181. const int attempts = 8;
  23182. std::string expected(payload_len, '\0');
  23183. for (size_t i = 0; i < payload_len; i++) {
  23184. expected[i] = static_cast<char>('a' + i % 26);
  23185. }
  23186. std::atomic<bool> peer_stalled{false};
  23187. std::atomic<bool> handler_done{false};
  23188. std::mutex received_mutex;
  23189. std::vector<std::string> received;
  23190. // Bound every wait, so a regression fails the test instead of hanging the
  23191. // suite.
  23192. auto wait_for = [](const std::atomic<bool> &flag) {
  23193. for (int i = 0; i < 500 && !flag; i++) {
  23194. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23195. }
  23196. };
  23197. Server svr;
  23198. svr.set_websocket_ping_interval(0);
  23199. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23200. std::thread reader([&]() {
  23201. std::string msg;
  23202. while (ws.read(msg)) {
  23203. std::lock_guard<std::mutex> guard(received_mutex);
  23204. received.push_back(msg);
  23205. }
  23206. });
  23207. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23208. // inside read_websocket_frame() when close() runs.
  23209. wait_for(peer_stalled);
  23210. ws.close();
  23211. reader.join();
  23212. handler_done = true;
  23213. });
  23214. auto port = svr.bind_to_any_port("127.0.0.1");
  23215. std::thread t([&]() { svr.listen_after_bind(); });
  23216. auto se = detail::scope_exit([&] {
  23217. svr.stop();
  23218. t.join();
  23219. });
  23220. svr.wait_until_ready();
  23221. auto send_bytes = [](socket_t s, const std::string &data) {
  23222. #ifdef _WIN32
  23223. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23224. #else
  23225. auto n = ::send(s, data.data(), data.size(), 0);
  23226. #endif
  23227. return n == static_cast<decltype(n)>(data.size());
  23228. };
  23229. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23230. // Every length used here fits the 7-bit length field.
  23231. auto masked_header = [](uint8_t first_byte, size_t len) {
  23232. std::string h;
  23233. h += static_cast<char>(first_byte);
  23234. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23235. h.append(4, '\0'); // mask key
  23236. return h;
  23237. };
  23238. for (int attempt = 0; attempt < attempts; attempt++) {
  23239. peer_stalled = false;
  23240. handler_done = false;
  23241. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23242. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23243. auto se_sock = detail::scope_exit([&] {
  23244. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23245. });
  23246. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23247. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23248. sockaddr_in addr{};
  23249. addr.sin_family = AF_INET;
  23250. addr.sin_port = htons(static_cast<uint16_t>(port));
  23251. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23252. ASSERT_EQ(
  23253. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23254. << "attempt " << attempt;
  23255. ASSERT_TRUE(send_bytes(sock,
  23256. "GET /ws HTTP/1.1\r\n"
  23257. "Host: 127.0.0.1\r\n"
  23258. "Upgrade: websocket\r\n"
  23259. "Connection: Upgrade\r\n"
  23260. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23261. "Sec-WebSocket-Version: 13\r\n"
  23262. "\r\n"))
  23263. << "attempt " << attempt;
  23264. std::string response;
  23265. while (response.find("\r\n\r\n") == std::string::npos) {
  23266. char buf[512];
  23267. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23268. if (n <= 0) { break; }
  23269. response.append(buf, static_cast<size_t>(n));
  23270. }
  23271. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23272. << "attempt " << attempt;
  23273. // Send the header of a Binary message but only the first prefix_len bytes
  23274. // of its payload, leaving the reader thread stalled inside the payload.
  23275. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23276. expected.substr(0, prefix_len)))
  23277. << "attempt " << attempt;
  23278. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23279. peer_stalled = true;
  23280. // Let close() send its Close frame and park in its own read before the
  23281. // rest of the payload arrives, so both threads are waiting for it.
  23282. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23283. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23284. close_frame += static_cast<char>(0x03); // status 1000
  23285. close_frame += static_cast<char>(0xE8);
  23286. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23287. << "attempt " << attempt;
  23288. // Closing the peer releases the reader thread even on the buggy path,
  23289. // where it waits for bytes another thread already consumed.
  23290. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23291. detail::close_socket(sock);
  23292. sock = INVALID_SOCKET;
  23293. wait_for(handler_done);
  23294. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23295. }
  23296. std::lock_guard<std::mutex> guard(received_mutex);
  23297. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23298. << "a message in flight when close() ran was dropped";
  23299. for (size_t i = 0; i < received.size(); i++) {
  23300. EXPECT_EQ(expected, received[i]) << "message " << i;
  23301. }
  23302. }
  23303. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23304. // returning the socket, or INVALID_SOCKET.
  23305. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23306. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23307. if (sock == INVALID_SOCKET) { return sock; }
  23308. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23309. sockaddr_in addr{};
  23310. addr.sin_family = AF_INET;
  23311. addr.sin_port = htons(static_cast<uint16_t>(port));
  23312. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23313. std::string req = "GET " + path +
  23314. " HTTP/1.1\r\n"
  23315. "Host: 127.0.0.1\r\n"
  23316. "Upgrade: websocket\r\n"
  23317. "Connection: Upgrade\r\n"
  23318. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23319. "Sec-WebSocket-Version: 13\r\n"
  23320. "\r\n";
  23321. std::string res;
  23322. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23323. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23324. static_cast<int>(req.size())) {
  23325. char c;
  23326. while (res.find("\r\n\r\n") == std::string::npos &&
  23327. ::recv(sock, &c, 1, 0) == 1) {
  23328. res += c;
  23329. }
  23330. }
  23331. if (res.find(" 101 ") == std::string::npos) {
  23332. detail::close_socket(sock);
  23333. return INVALID_SOCKET;
  23334. }
  23335. return sock;
  23336. }
  23337. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23338. // The payload must fit the 7-bit length field.
  23339. static std::string masked_frame(uint8_t first_byte,
  23340. const std::string &payload) {
  23341. std::string f;
  23342. f += static_cast<char>(first_byte);
  23343. f += static_cast<char>(0x80 | payload.size());
  23344. f.append(4, '\0');
  23345. return f + payload;
  23346. }
  23347. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23348. std::atomic<bool> done{false};
  23349. std::string received;
  23350. Server svr;
  23351. svr.set_websocket_ping_interval(0);
  23352. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23353. std::string msg;
  23354. if (ws.read(msg) == ws::Binary) { received = msg; }
  23355. done = true;
  23356. });
  23357. auto port = svr.bind_to_any_port("127.0.0.1");
  23358. std::thread t([&]() { svr.listen_after_bind(); });
  23359. auto se = detail::scope_exit([&] {
  23360. svr.stop();
  23361. t.join();
  23362. });
  23363. svr.wait_until_ready();
  23364. auto sock = connect_raw_websocket(port, "/ws");
  23365. ASSERT_NE(INVALID_SOCKET, sock);
  23366. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23367. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23368. masked_frame(0x89, "p") + // FIN + Ping
  23369. masked_frame(0x80, "lo"); // FIN + Continuation
  23370. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23371. for (int i = 0; i < 500 && !done; i++) {
  23372. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23373. }
  23374. ASSERT_TRUE(done);
  23375. EXPECT_EQ("Hello", received);
  23376. // The Ping between the fragments is answered with a Pong.
  23377. char pong[3];
  23378. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23379. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23380. }
  23381. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23382. Server svr;
  23383. svr.set_websocket_ping_interval(-1);
  23384. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23385. std::string msg;
  23386. while (ws.read(msg)) {}
  23387. });
  23388. auto port = svr.bind_to_any_port("127.0.0.1");
  23389. std::thread t([&]() { svr.listen_after_bind(); });
  23390. auto se = detail::scope_exit([&] {
  23391. svr.stop();
  23392. t.join();
  23393. });
  23394. svr.wait_until_ready();
  23395. auto sock = connect_raw_websocket(port, "/ws");
  23396. ASSERT_NE(INVALID_SOCKET, sock);
  23397. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23398. // Nothing comes while the client stays quiet.
  23399. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23400. char c;
  23401. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23402. }
  23403. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23404. Server svr;
  23405. svr.set_websocket_ping_interval(0);
  23406. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23407. std::string msg;
  23408. while (ws.read(msg)) {}
  23409. });
  23410. auto port = svr.bind_to_any_port("127.0.0.1");
  23411. std::thread t([&]() { svr.listen_after_bind(); });
  23412. auto se = detail::scope_exit([&] {
  23413. svr.stop();
  23414. t.join();
  23415. });
  23416. svr.wait_until_ready();
  23417. // Each Close payload and the reply it should get: an echo when valid, 1002
  23418. // otherwise.
  23419. std::vector<std::pair<std::string, std::string>> cases = {
  23420. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23421. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23422. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23423. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23424. };
  23425. // Also between the fragments of a message.
  23426. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23427. for (const auto &c : cases) {
  23428. auto sock = connect_raw_websocket(port, "/ws");
  23429. ASSERT_NE(INVALID_SOCKET, sock);
  23430. auto frames = prefix + masked_frame(0x88, c.first);
  23431. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23432. std::string reply;
  23433. char buf[256];
  23434. while (reply.size() < 2 + c.second.size()) {
  23435. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23436. if (n <= 0) { break; }
  23437. reply.append(buf, static_cast<size_t>(n));
  23438. }
  23439. detail::close_socket(sock);
  23440. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23441. c.second,
  23442. reply);
  23443. }
  23444. }
  23445. }
  23446. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23447. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23448. protected:
  23449. void SetUp() override {
  23450. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23451. SERVER_PRIVATE_KEY_FILE);
  23452. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23453. std::string msg;
  23454. ws::ReadResult ret;
  23455. while ((ret = ws.read(msg))) {
  23456. if (ret == ws::Binary) {
  23457. ws.send(msg.data(), msg.size());
  23458. } else {
  23459. ws.send(msg);
  23460. }
  23461. }
  23462. });
  23463. port_ = server_->bind_to_any_port(HOST);
  23464. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23465. server_->wait_until_ready();
  23466. }
  23467. void TearDown() override {
  23468. server_->stop();
  23469. if (server_thread_.joinable()) { server_thread_.join(); }
  23470. }
  23471. std::unique_ptr<SSLServer> server_;
  23472. std::thread server_thread_;
  23473. int port_ = 0;
  23474. };
  23475. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23476. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23477. {
  23478. ws::WebSocketClient client(url);
  23479. client.enable_server_certificate_verification(false);
  23480. auto calls = 0;
  23481. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23482. calls++;
  23483. return false;
  23484. });
  23485. EXPECT_FALSE(client.connect());
  23486. EXPECT_GT(calls, 0);
  23487. }
  23488. {
  23489. ws::WebSocketClient client(url);
  23490. client.enable_server_certificate_verification(false);
  23491. client.set_session_verifier([](tls::session_t) {
  23492. return SSLVerifierResponse::CertificateRejected;
  23493. });
  23494. EXPECT_FALSE(client.connect());
  23495. }
  23496. {
  23497. ws::WebSocketClient client(url);
  23498. client.enable_server_certificate_verification(false);
  23499. client.set_session_verifier([](tls::session_t) {
  23500. return SSLVerifierResponse::CertificateAccepted;
  23501. });
  23502. EXPECT_TRUE(client.connect());
  23503. }
  23504. }
  23505. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23506. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23507. "/ws-echo");
  23508. client.enable_server_certificate_verification(false);
  23509. ASSERT_TRUE(client.connect());
  23510. ASSERT_TRUE(client.is_open());
  23511. ASSERT_TRUE(client.send("Hello WSS"));
  23512. std::string msg;
  23513. EXPECT_EQ(ws::Text, client.read(msg));
  23514. EXPECT_EQ("Hello WSS", msg);
  23515. client.close();
  23516. }
  23517. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23518. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23519. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23520. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23521. // client (without calling close() first) is the only path that runs
  23522. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23523. // bug exactly.
  23524. //
  23525. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23526. // when linked against an instrumented libssl; run under Valgrind to catch it
  23527. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23528. // suite (the freed session otherwise stalls on the close handshake) — this test
  23529. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23530. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23531. {
  23532. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23533. "/ws-echo");
  23534. client.enable_server_certificate_verification(false);
  23535. client.set_read_timeout(2, 0);
  23536. client.set_write_timeout(2, 0);
  23537. ASSERT_TRUE(client.connect());
  23538. ASSERT_TRUE(client.is_open());
  23539. ASSERT_TRUE(client.send("still open"));
  23540. // Intentionally do NOT call client.close(): leaving scope runs
  23541. // shutdown_and_close() with the WebSocket still open, which must send the
  23542. // close frame while the TLS session is still alive.
  23543. }
  23544. }
  23545. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23546. // shutdown_and_close() at the start of connect(), reproducing the same
  23547. // use-after-free within the test body rather than at scope exit. The second
  23548. // connect must succeed and echo, proving the close handshake ran over a live
  23549. // session. See the note above about memory-tool requirements.
  23550. TEST_F(WebSocketSSLIntegrationTest,
  23551. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23552. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23553. "/ws-echo");
  23554. client.enable_server_certificate_verification(false);
  23555. client.set_read_timeout(2, 0);
  23556. client.set_write_timeout(2, 0);
  23557. ASSERT_TRUE(client.connect());
  23558. ASSERT_TRUE(client.is_open());
  23559. ASSERT_TRUE(client.send("still open"));
  23560. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23561. // the still-open connection, which must not touch a freed TLS session.
  23562. ASSERT_TRUE(client.connect());
  23563. ASSERT_TRUE(client.is_open());
  23564. ASSERT_TRUE(client.send("after reconnect"));
  23565. std::string msg;
  23566. EXPECT_EQ(ws::Text, client.read(msg));
  23567. EXPECT_EQ("after reconnect", msg);
  23568. client.close();
  23569. }
  23570. #endif
  23571. #ifdef CPPHTTPLIB_SSL_ENABLED
  23572. class WebSocketSSLCATest : public ::testing::Test {
  23573. protected:
  23574. void SetUp() override {
  23575. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23576. SERVER_PRIVATE_KEY_FILE);
  23577. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23578. std::string msg;
  23579. while (ws.read(msg)) {
  23580. ws.send(msg);
  23581. }
  23582. });
  23583. port_ = server_->bind_to_any_port("127.0.0.1");
  23584. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23585. server_->wait_until_ready();
  23586. }
  23587. void TearDown() override {
  23588. server_->stop();
  23589. if (server_thread_.joinable()) { server_thread_.join(); }
  23590. }
  23591. std::string url() const {
  23592. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23593. }
  23594. std::unique_ptr<SSLServer> server_;
  23595. std::thread server_thread_;
  23596. int port_ = 0;
  23597. };
  23598. // A custom CA loaded as PEM verifies the server with full certificate
  23599. // verification enabled
  23600. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23601. ws::WebSocketClient client(url());
  23602. std::string cert;
  23603. read_file(SERVER_CERT2_FILE, cert);
  23604. client.load_ca_cert_store(cert.c_str(), cert.size());
  23605. ASSERT_TRUE(client.connect());
  23606. ASSERT_TRUE(client.send("hello"));
  23607. std::string msg;
  23608. EXPECT_EQ(ws::Text, client.read(msg));
  23609. EXPECT_EQ("hello", msg);
  23610. client.close();
  23611. }
  23612. // A custom CA that does not cover the server must fail verification (the
  23613. // custom CA is exclusive; system certs are not loaded alongside it)
  23614. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23615. ws::WebSocketClient client(url());
  23616. std::string cert;
  23617. read_file(CLIENT_CA_CERT_FILE, cert);
  23618. client.load_ca_cert_store(cert.c_str(), cert.size());
  23619. auto res = client.connect();
  23620. ASSERT_FALSE(res);
  23621. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23622. EXPECT_EQ(-1, res.status());
  23623. EXPECT_NE(0u, res.ssl_backend_error());
  23624. }
  23625. // The same CA as a file path rather than PEM in memory
  23626. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23627. ws::WebSocketClient client(url());
  23628. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23629. ASSERT_TRUE(client.connect());
  23630. ASSERT_TRUE(client.send("hello"));
  23631. std::string msg;
  23632. EXPECT_EQ(ws::Text, client.read(msg));
  23633. EXPECT_EQ("hello", msg);
  23634. client.close();
  23635. }
  23636. // ...and a CA file that does not cover the server still fails, so it is the
  23637. // path above that decides the outcome
  23638. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23639. ws::WebSocketClient client(url());
  23640. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23641. ASSERT_FALSE(client.connect());
  23642. }
  23643. // Regression test: reconnecting with a native custom CA store used to reuse
  23644. // a store handle the previous TLS context had already freed (use-after-free
  23645. // under the OpenSSL backend). The context now lives as long as the client.
  23646. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23647. ws::WebSocketClient client(url());
  23648. std::string cert;
  23649. read_file(SERVER_CERT2_FILE, cert);
  23650. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23651. ASSERT_TRUE(client.connect());
  23652. client.close();
  23653. ASSERT_TRUE(client.connect());
  23654. ASSERT_TRUE(client.send("again"));
  23655. std::string msg;
  23656. EXPECT_EQ(ws::Text, client.read(msg));
  23657. EXPECT_EQ("again", msg);
  23658. client.close();
  23659. }
  23660. // Regression test: a certificate with a trusted chain but no identity match
  23661. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23662. // verification entirely for IP hosts, so this connection succeeded there.
  23663. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23664. // chain verification while the identity check must still fail.
  23665. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23667. ASSERT_TRUE(svr.is_valid());
  23668. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23669. std::string msg;
  23670. while (ws.read(msg)) {
  23671. ws.send(msg);
  23672. }
  23673. });
  23674. auto port = svr.bind_to_any_port("127.0.0.1");
  23675. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23676. auto se = detail::scope_exit([&] {
  23677. svr.stop();
  23678. t.join();
  23679. });
  23680. svr.wait_until_ready();
  23681. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23682. "/echo");
  23683. std::string cert;
  23684. read_file(SERVER_CERT_FILE, cert);
  23685. client.load_ca_cert_store(cert.c_str(), cert.size());
  23686. ASSERT_FALSE(client.connect());
  23687. }
  23688. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23689. // SNI, so nothing binds the host name to the TLS session. These bind the
  23690. // server to "localhost" instead, the only shape that exercises the SNI and
  23691. // hostname-verification path with certificate verification left enabled.
  23692. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23693. protected:
  23694. void Start(const char *cert_file) {
  23695. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23696. SERVER_PRIVATE_KEY_FILE);
  23697. ASSERT_TRUE(server_->is_valid());
  23698. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23699. std::string msg;
  23700. while (ws.read(msg)) {
  23701. ws.send(msg);
  23702. }
  23703. });
  23704. port_ = server_->bind_to_any_port("localhost");
  23705. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23706. server_->wait_until_ready();
  23707. }
  23708. void TearDown() override {
  23709. if (server_) { server_->stop(); }
  23710. if (server_thread_.joinable()) { server_thread_.join(); }
  23711. }
  23712. std::string url() const {
  23713. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23714. }
  23715. std::unique_ptr<SSLServer> server_;
  23716. std::thread server_thread_;
  23717. int port_ = 0;
  23718. };
  23719. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23720. // out and the connection is usable
  23721. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23722. Start(SERVER_CERT2_FILE);
  23723. ws::WebSocketClient client(url());
  23724. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23725. ASSERT_TRUE(client.connect());
  23726. ASSERT_TRUE(client.send("hello"));
  23727. std::string msg;
  23728. EXPECT_EQ(ws::Text, client.read(msg));
  23729. EXPECT_EQ("hello", msg);
  23730. client.close();
  23731. }
  23732. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23733. // while the identity check must still reject "localhost"
  23734. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23735. Start(SERVER_CERT_FILE);
  23736. ws::WebSocketClient client(url());
  23737. client.set_ca_cert_path(SERVER_CERT_FILE);
  23738. auto res = client.connect();
  23739. ASSERT_FALSE(res);
  23740. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23741. EXPECT_EQ(-1, res.status());
  23742. }
  23743. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23744. // disabled: the chain is still checked, only the identity check is skipped
  23745. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23746. Start(SERVER_CERT_FILE);
  23747. ws::WebSocketClient client(url());
  23748. client.set_ca_cert_path(SERVER_CERT_FILE);
  23749. client.enable_server_hostname_verification(false);
  23750. ASSERT_TRUE(client.connect());
  23751. ASSERT_TRUE(client.send("hello"));
  23752. std::string msg;
  23753. EXPECT_EQ(ws::Text, client.read(msg));
  23754. EXPECT_EQ("hello", msg);
  23755. client.close();
  23756. }
  23757. // A CA that did not sign the server certificate fails the chain, even though
  23758. // the name would match
  23759. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23760. Start(SERVER_CERT2_FILE);
  23761. ws::WebSocketClient client(url());
  23762. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23763. ASSERT_FALSE(client.connect());
  23764. }
  23765. // With verification disabled, neither the chain nor the name is checked
  23766. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23767. Start(SERVER_CERT_FILE);
  23768. ws::WebSocketClient client(url());
  23769. client.enable_server_certificate_verification(false);
  23770. ASSERT_TRUE(client.connect());
  23771. ASSERT_TRUE(client.send("hello"));
  23772. std::string msg;
  23773. EXPECT_EQ(ws::Text, client.read(msg));
  23774. EXPECT_EQ("hello", msg);
  23775. client.close();
  23776. }
  23777. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23778. protected:
  23779. void SetUp() override {
  23780. server_ = httplib::detail::make_unique<SSLServer>(
  23781. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23782. ASSERT_TRUE(server_->is_valid());
  23783. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23784. std::string msg;
  23785. while (ws.read(msg)) {
  23786. ws.send(msg);
  23787. }
  23788. });
  23789. port_ = server_->bind_to_any_port("localhost");
  23790. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23791. server_->wait_until_ready();
  23792. }
  23793. void TearDown() override {
  23794. server_->stop();
  23795. if (server_thread_.joinable()) { server_thread_.join(); }
  23796. }
  23797. std::string url() const {
  23798. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23799. }
  23800. void ConnectWithClientCert(const std::string &client_cert_file,
  23801. const std::string &client_private_key_file,
  23802. const char *private_key_password) {
  23803. std::string cert_pem, key_pem;
  23804. read_file(client_cert_file, cert_pem);
  23805. read_file(client_private_key_file, key_pem);
  23806. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23807. key_pem.c_str(), key_pem.size(),
  23808. private_key_password};
  23809. ws::WebSocketClient client(url(), pem);
  23810. ASSERT_TRUE(client.is_valid());
  23811. client.enable_server_certificate_verification(false);
  23812. ASSERT_TRUE(client.connect());
  23813. ASSERT_TRUE(client.send("hello"));
  23814. std::string msg;
  23815. EXPECT_EQ(ws::Text, client.read(msg));
  23816. EXPECT_EQ("hello", msg);
  23817. client.close();
  23818. }
  23819. std::unique_ptr<SSLServer> server_;
  23820. std::thread server_thread_;
  23821. int port_ = 0;
  23822. };
  23823. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23824. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23825. }
  23826. // Control for the tests above: the fixture's server really does require a
  23827. // client certificate, so it is the PEM the constructor installed that decides
  23828. // the outcome.
  23829. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23830. ws::WebSocketClient client(url());
  23831. ASSERT_TRUE(client.is_valid());
  23832. client.enable_server_certificate_verification(false);
  23833. EXPECT_FALSE(client.connect());
  23834. }
  23835. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23836. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23837. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23838. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23839. }
  23840. #endif
  23841. #if !defined(_WIN32)
  23842. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23843. auto secret_dir = std::string("./symlink_test_secret");
  23844. auto served_dir = std::string("./symlink_test_served");
  23845. auto secret_file = secret_dir + "/secret.txt";
  23846. auto symlink_path = served_dir + "/escape";
  23847. // Setup: create directories and files
  23848. mkdir(secret_dir.c_str(), 0755);
  23849. mkdir(served_dir.c_str(), 0755);
  23850. {
  23851. std::ofstream ofs(secret_file);
  23852. ofs << "SECRET_DATA";
  23853. }
  23854. // Create symlink using absolute path so it resolves correctly
  23855. #ifdef PATH_MAX
  23856. char abs_secret[PATH_MAX];
  23857. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23858. #else
  23859. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23860. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23861. ASSERT_NE(nullptr, abs_secret);
  23862. #endif
  23863. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23864. auto se = detail::scope_exit([&] {
  23865. unlink(symlink_path.c_str());
  23866. unlink(secret_file.c_str());
  23867. rmdir(served_dir.c_str());
  23868. rmdir(secret_dir.c_str());
  23869. });
  23870. Server svr;
  23871. svr.set_mount_point("/", served_dir);
  23872. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23873. auto se2 = detail::scope_exit([&] {
  23874. svr.stop();
  23875. listen_thread.join();
  23876. });
  23877. svr.wait_until_ready();
  23878. Client cli("localhost", PORT);
  23879. // Symlink pointing outside base dir should be blocked
  23880. auto res = cli.Get("/escape/secret.txt");
  23881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23882. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23883. }
  23884. #endif
  23885. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23886. // "GET /smuggled" request), reads the first response, and only then sends the
  23887. // embedded request as the body. Returns how many times /smuggled ran.
  23888. //
  23889. // The body is sent AFTER receiving the first response (as in the original
  23890. // PoC) so that the stream_line_reader cannot buffer it together with the
  23891. // headers of the first request.
  23892. static int count_smuggled_requests(const std::string &outer_head,
  23893. std::string &first_response) {
  23894. Server svr;
  23895. svr.set_mount_point("/", "./www");
  23896. std::atomic<int> smuggled_count(0);
  23897. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23898. smuggled_count++;
  23899. res.set_content("oops", "text/plain");
  23900. });
  23901. svr.Post("/post", [&](const Request &req, Response &res) {
  23902. res.set_content(req.body, "text/plain");
  23903. });
  23904. auto port = svr.bind_to_any_port("localhost");
  23905. thread t = thread([&] { svr.listen_after_bind(); });
  23906. auto se = detail::scope_exit([&] {
  23907. svr.stop();
  23908. t.join();
  23909. });
  23910. svr.wait_until_ready();
  23911. auto error = Error::Success;
  23912. auto sock = detail::create_client_socket(
  23913. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23914. /*connection_timeout_sec=*/2, 0,
  23915. /*read_timeout_sec=*/2, 0,
  23916. /*write_timeout_sec=*/2, 0, std::string(), error);
  23917. EXPECT_NE(INVALID_SOCKET, sock);
  23918. if (sock == INVALID_SOCKET) { return -1; }
  23919. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23920. // The "smuggled" request will be sent as the body of the outer request
  23921. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23922. "Host: localhost\r\n"
  23923. "Connection: close\r\n"
  23924. "\r\n";
  23925. auto head = outer_head;
  23926. auto len = std::to_string(smuggled.size());
  23927. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23928. pos = head.find("{len}", pos + len.size())) {
  23929. head.replace(pos, 5, len);
  23930. }
  23931. // Step 1: Send only the outer request headers (no body yet)
  23932. auto sent = send(sock, head.data(), head.size(), 0);
  23933. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23934. // Step 2: Read the first response
  23935. char buf[4096];
  23936. for (;;) {
  23937. auto n = recv(sock, buf, sizeof(buf), 0);
  23938. if (n <= 0) break;
  23939. first_response.append(buf, static_cast<size_t>(n));
  23940. // Stop once we have a complete response (headers + body)
  23941. auto hdr_end = first_response.find("\r\n\r\n");
  23942. if (hdr_end != std::string::npos) {
  23943. // Check for Content-Length to know when the body is complete
  23944. auto cl_pos = first_response.find("Content-Length:");
  23945. if (cl_pos != std::string::npos) {
  23946. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23947. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23948. auto cl = std::stoul(
  23949. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23950. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23951. } else {
  23952. break; // No Content-Length, assume headers-only response
  23953. }
  23954. }
  23955. }
  23956. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23957. // vulnerable server the keep-alive loop reads this as a second request. The
  23958. // server may already have closed the connection, so the result is ignored.
  23959. send(sock, smuggled.data(), smuggled.size(), 0);
  23960. // Half-close so that a server which drained the body sees EOF and closes,
  23961. // instead of the read below waiting for the read timeout.
  23962. #ifdef _WIN32
  23963. ::shutdown(sock, SD_SEND);
  23964. #else
  23965. ::shutdown(sock, SHUT_WR);
  23966. #endif
  23967. // Step 4: Read until the server closes the connection
  23968. for (;;) {
  23969. auto n = recv(sock, buf, sizeof(buf), 0);
  23970. if (n <= 0) break;
  23971. }
  23972. return smuggled_count.load();
  23973. }
  23974. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23975. // A GET request with Content-Length to a static file handler must have its
  23976. // body drained before the keep-alive connection is reused. Otherwise the
  23977. // unread body bytes are interpreted as the next HTTP request.
  23978. std::string first_response;
  23979. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23980. "Host: localhost\r\n"
  23981. "Content-Length: {len}\r\n"
  23982. "\r\n",
  23983. first_response));
  23984. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23985. }
  23986. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23987. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23988. // be answered with 400 and the connection closed. Treating it as "no body"
  23989. // leaves the body to be parsed as the next request.
  23990. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23991. const char *targets[] = {
  23992. "GET /file", // handler that never reads the body
  23993. "GET /not-found", // no handler matches (404)
  23994. "POST /post", // handler that reads the body
  23995. };
  23996. for (auto target : targets) {
  23997. for (auto value : values) {
  23998. std::string first_response;
  23999. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24000. " HTTP/1.1\r\n"
  24001. "Host: localhost\r\n"
  24002. "Content-Length: " +
  24003. value + "\r\n\r\n",
  24004. first_response))
  24005. << target << " with Content-Length: " << value;
  24006. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24007. << target << " with Content-Length: " << value;
  24008. }
  24009. }
  24010. }
  24011. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24012. // A 400 for an unparseable request line leaves the rest of the message
  24013. // unread, so the connection must be closed rather than reused.
  24014. std::string first_response;
  24015. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24016. "Host: localhost\r\n"
  24017. "Content-Length: {len}\r\n"
  24018. "\r\n",
  24019. first_response));
  24020. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24021. }
  24022. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24023. // Same as above for a header block that fails to parse.
  24024. std::string first_response;
  24025. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24026. "Host: localhost\r\n"
  24027. "Bad Header\r\n"
  24028. "Content-Length: {len}\r\n"
  24029. "\r\n",
  24030. first_response));
  24031. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24032. }
  24033. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24034. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24035. // server must not read another request on that connection, even when the
  24036. // request had no body to drain.
  24037. std::string first_response;
  24038. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24039. "Host: localhost\r\n"
  24040. "\r\n",
  24041. first_response));
  24042. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24043. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24044. }
  24045. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24046. // A content reader that stops early leaves the stream inside the body.
  24047. // Draining the whole Content-Length from there, or reading the body again,
  24048. // reads into the next request, and whatever follows is parsed as a request
  24049. // of its own.
  24050. Server svr;
  24051. std::atomic<int> smuggled_count(0);
  24052. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24053. svr.Post("/upload", [](const Request &req, Response &res,
  24054. const ContentReader &content_reader) {
  24055. // Stop at the last chunk, so the whole body has been read however it
  24056. // arrives.
  24057. auto length = req.get_header_value_u64("Content-Length");
  24058. size_t total = 0;
  24059. auto consumed = content_reader([&](const char *, size_t n) {
  24060. total += n;
  24061. return total < length;
  24062. });
  24063. EXPECT_FALSE(consumed);
  24064. if (req.has_param("retry")) {
  24065. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24066. }
  24067. // Replace the 400 the aborted read set, which would close the connection.
  24068. res.set_redirect("/done");
  24069. });
  24070. auto port = svr.bind_to_any_port(HOST);
  24071. thread t = thread([&] { svr.listen_after_bind(); });
  24072. auto se = detail::scope_exit([&] {
  24073. svr.stop();
  24074. t.join();
  24075. });
  24076. svr.wait_until_ready();
  24077. // A front end sees the second request as a POST whose body is the GET. The
  24078. // first body is as long as the POST's headers, so draining it again reads
  24079. // exactly those and leaves the GET to be parsed next.
  24080. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24081. "Host: localhost\r\n"
  24082. "\r\n";
  24083. std::string second_head = "POST /post HTTP/1.1\r\n"
  24084. "Host: localhost\r\n"
  24085. "Content-Length: " +
  24086. std::to_string(inner.size()) +
  24087. "\r\n"
  24088. "\r\n";
  24089. for (auto target : {"/upload", "/upload?retry"}) {
  24090. smuggled_count = 0;
  24091. std::string request = "POST " + std::string(target) +
  24092. " HTTP/1.1\r\n"
  24093. "Host: localhost\r\n"
  24094. "Content-Length: " +
  24095. std::to_string(second_head.size()) +
  24096. "\r\n"
  24097. "\r\n" +
  24098. std::string(second_head.size(), 'A') + second_head +
  24099. inner;
  24100. std::string response;
  24101. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24102. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24103. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24104. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24105. EXPECT_EQ(0, smuggled_count.load()) << target;
  24106. }
  24107. }
  24108. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24109. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24110. // must be rejected with 400 Bad Request.
  24111. Server svr;
  24112. svr.Post("/test", [&](const Request &, Response &res) {
  24113. res.set_content("ok", "text/plain");
  24114. });
  24115. thread t = thread([&] { svr.listen(HOST, PORT); });
  24116. auto se = detail::scope_exit([&] {
  24117. svr.stop();
  24118. t.join();
  24119. ASSERT_FALSE(svr.is_running());
  24120. });
  24121. svr.wait_until_ready();
  24122. // Exact "chunked"
  24123. {
  24124. auto req = "POST /test HTTP/1.1\r\n"
  24125. "Host: localhost\r\n"
  24126. "Content-Length: 5\r\n"
  24127. "Transfer-Encoding: chunked\r\n"
  24128. "Connection: close\r\n"
  24129. "\r\n"
  24130. "hello";
  24131. std::string response;
  24132. ASSERT_TRUE(send_request(1, req, &response));
  24133. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24134. response.substr(0, response.find("\r\n")));
  24135. }
  24136. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24137. {
  24138. auto req = "POST /test HTTP/1.1\r\n"
  24139. "Host: localhost\r\n"
  24140. "Content-Length: 5\r\n"
  24141. "Transfer-Encoding: gzip, chunked\r\n"
  24142. "Connection: close\r\n"
  24143. "\r\n"
  24144. "hello";
  24145. std::string response;
  24146. ASSERT_TRUE(send_request(1, req, &response));
  24147. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24148. response.substr(0, response.find("\r\n")));
  24149. }
  24150. }
  24151. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24152. Server svr;
  24153. svr.Post("/test", [&](const Request &, Response &res) {
  24154. res.set_content("ok", "text/plain");
  24155. });
  24156. thread t = thread([&] { svr.listen(HOST, PORT); });
  24157. auto se = detail::scope_exit([&] {
  24158. svr.stop();
  24159. t.join();
  24160. ASSERT_FALSE(svr.is_running());
  24161. });
  24162. svr.wait_until_ready();
  24163. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24164. // length cannot be determined, so the server must answer 400 and close
  24165. // rather than treat the request as bodyless and leave the body in the
  24166. // socket for the next request to pick up.
  24167. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24168. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24169. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24170. std::string response;
  24171. ASSERT_TRUE(send_request(1, req, &response));
  24172. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24173. response.substr(0, response.find("\r\n")))
  24174. << transfer_encoding;
  24175. }
  24176. // RFC 9110 5.3: the codings may also be split across several
  24177. // Transfer-Encoding lines, which combine in the order they were received.
  24178. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24179. // just like the single-line "chunked, gzip" above.
  24180. {
  24181. auto req = "POST /test HTTP/1.1\r\n"
  24182. "Host: localhost\r\n"
  24183. "Transfer-Encoding: chunked\r\n"
  24184. "Transfer-Encoding: gzip\r\n"
  24185. "\r\n"
  24186. "0\r\n\r\n";
  24187. std::string response;
  24188. ASSERT_TRUE(send_request(1, req, &response));
  24189. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24190. response.substr(0, response.find("\r\n")));
  24191. }
  24192. // A sequence ending in chunked stays valid.
  24193. auto req = "POST /test HTTP/1.1\r\n"
  24194. "Host: localhost\r\n"
  24195. "Transfer-Encoding: gzip, chunked\r\n"
  24196. "Connection: close\r\n"
  24197. "\r\n"
  24198. "0\r\n\r\n";
  24199. std::string response;
  24200. ASSERT_TRUE(send_request(1, req, &response));
  24201. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24202. // ...including when it is spread over several lines.
  24203. auto split_req = "POST /test HTTP/1.1\r\n"
  24204. "Host: localhost\r\n"
  24205. "Transfer-Encoding: gzip\r\n"
  24206. "Transfer-Encoding: chunked\r\n"
  24207. "Connection: close\r\n"
  24208. "\r\n"
  24209. "0\r\n\r\n";
  24210. std::string split_response;
  24211. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24212. EXPECT_EQ("HTTP/1.1 200 OK",
  24213. split_response.substr(0, split_response.find("\r\n")));
  24214. }
  24215. // Regression for issue #2450: a DELETE without Content-Length on a
  24216. // keep-alive connection must not let the post-response drain consume the
  24217. // next request's bytes.
  24218. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24219. Server svr;
  24220. std::atomic<int> delete_count(0);
  24221. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24222. delete_count++;
  24223. res.status = StatusCode::NoContent_204;
  24224. });
  24225. auto port = svr.bind_to_any_port(HOST);
  24226. thread t = thread([&] { svr.listen_after_bind(); });
  24227. auto se = detail::scope_exit([&] {
  24228. svr.stop();
  24229. t.join();
  24230. });
  24231. svr.wait_until_ready();
  24232. auto error = Error::Success;
  24233. auto sock = detail::create_client_socket(
  24234. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24235. /*connection_timeout_sec=*/2, 0,
  24236. /*read_timeout_sec=*/2, 0,
  24237. /*write_timeout_sec=*/2, 0, std::string(), error);
  24238. ASSERT_NE(INVALID_SOCKET, sock);
  24239. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24240. auto send_request_and_read_response = [&](const std::string &req,
  24241. std::string &out) -> bool {
  24242. auto sent = send(sock, req.data(), req.size(), 0);
  24243. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24244. char buf[4096];
  24245. for (;;) {
  24246. auto n = recv(sock, buf, sizeof(buf), 0);
  24247. if (n <= 0) { return !out.empty(); }
  24248. out.append(buf, static_cast<size_t>(n));
  24249. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24250. }
  24251. };
  24252. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24253. "Host: localhost\r\n"
  24254. "\r\n";
  24255. std::string resp1;
  24256. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24257. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24258. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24259. "Host: localhost\r\n"
  24260. "Connection: close\r\n"
  24261. "\r\n";
  24262. std::string resp2;
  24263. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24264. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24265. EXPECT_EQ(2, delete_count.load());
  24266. }
  24267. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24268. Server svr;
  24269. svr.Post("/ingest", [&](const Request &, Response &res,
  24270. const ContentReader &content_reader) {
  24271. auto consumed = content_reader([](const char *, size_t) { return false; });
  24272. EXPECT_FALSE(consumed);
  24273. res.status = StatusCode::Conflict_409;
  24274. res.set_header("Connection", "close");
  24275. });
  24276. auto port = svr.bind_to_any_port(HOST);
  24277. thread t = thread([&] { svr.listen_after_bind(); });
  24278. auto se = detail::scope_exit([&] {
  24279. svr.stop();
  24280. t.join();
  24281. });
  24282. svr.wait_until_ready();
  24283. auto error = Error::Success;
  24284. auto sock = detail::create_client_socket(
  24285. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24286. /*connection_timeout_sec=*/2, 0,
  24287. /*read_timeout_sec=*/1, 0,
  24288. /*write_timeout_sec=*/2, 0, std::string(), error);
  24289. ASSERT_NE(INVALID_SOCKET, sock);
  24290. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24291. std::string request = "POST /ingest HTTP/1.1\r\n"
  24292. "Host: localhost\r\n"
  24293. "Transfer-Encoding: chunked\r\n"
  24294. "\r\n"
  24295. "4\r\n"
  24296. "data\r\n";
  24297. auto sent = send(sock, request.data(), request.size(), 0);
  24298. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24299. std::string response;
  24300. ssize_t received = 0;
  24301. do {
  24302. char buf[4096];
  24303. received = recv(sock, buf, sizeof(buf), 0);
  24304. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24305. } while (received > 0);
  24306. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24307. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24308. EXPECT_EQ(0, received);
  24309. }
  24310. namespace no_proxy_test {
  24311. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24312. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24313. // calling listen().
  24314. class ScopedServer {
  24315. public:
  24316. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24317. ~ScopedServer() {
  24318. svr_.stop();
  24319. if (th_.joinable()) { th_.join(); }
  24320. }
  24321. Server &svr() { return svr_; }
  24322. int port() const { return port_; }
  24323. void listen() {
  24324. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24325. svr_.wait_until_ready();
  24326. }
  24327. private:
  24328. Server svr_;
  24329. std::thread th_;
  24330. int port_ = 0;
  24331. };
  24332. class ProxyAndTargetServers {
  24333. public:
  24334. ProxyAndTargetServers() {
  24335. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24336. proxy_hits_++;
  24337. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24338. res.set_content("via-proxy", "text/plain");
  24339. });
  24340. target_.Get(".*", [this](const Request &req, Response &res) {
  24341. target_hits_++;
  24342. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24343. res.set_content("direct", "text/plain");
  24344. });
  24345. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24346. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24347. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24348. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24349. proxy_mock_.wait_until_ready();
  24350. target_.wait_until_ready();
  24351. }
  24352. ~ProxyAndTargetServers() {
  24353. proxy_mock_.stop();
  24354. target_.stop();
  24355. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24356. if (target_thread_.joinable()) { target_thread_.join(); }
  24357. }
  24358. Server &proxy_mock() { return proxy_mock_; }
  24359. Server &target() { return target_; }
  24360. int proxy_port() const { return proxy_port_; }
  24361. int target_port() const { return target_port_; }
  24362. int proxy_hits() const { return proxy_hits_.load(); }
  24363. int target_hits() const { return target_hits_.load(); }
  24364. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24365. void reset_counters() {
  24366. proxy_hits_ = 0;
  24367. target_hits_ = 0;
  24368. last_had_proxy_authz_ = false;
  24369. }
  24370. private:
  24371. Server proxy_mock_;
  24372. Server target_;
  24373. std::thread proxy_thread_;
  24374. std::thread target_thread_;
  24375. int proxy_port_ = 0;
  24376. int target_port_ = 0;
  24377. std::atomic<int> proxy_hits_{0};
  24378. std::atomic<int> target_hits_{0};
  24379. std::atomic<bool> last_had_proxy_authz_{false};
  24380. };
  24381. inline std::unique_ptr<Client> make_client(const std::string &host,
  24382. ProxyAndTargetServers &s) {
  24383. auto cli = detail::make_unique<Client>(host, s.target_port());
  24384. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24385. cli->set_proxy("127.0.0.1", s.proxy_port());
  24386. return cli;
  24387. }
  24388. } // namespace no_proxy_test
  24389. using no_proxy_test::make_client;
  24390. using no_proxy_test::ProxyAndTargetServers;
  24391. TEST(NoProxyTest, ExactHostnameBypasses) {
  24392. ProxyAndTargetServers s;
  24393. auto cli = make_client("example.com", s);
  24394. cli->set_no_proxy({"example.com"});
  24395. auto res = cli->Get("/");
  24396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24397. EXPECT_EQ(0, s.proxy_hits());
  24398. EXPECT_EQ(1, s.target_hits());
  24399. }
  24400. TEST(NoProxyTest, SubdomainBypasses) {
  24401. ProxyAndTargetServers s;
  24402. auto cli = make_client("foo.example.com", s);
  24403. cli->set_no_proxy({"example.com"});
  24404. auto res = cli->Get("/");
  24405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24406. EXPECT_EQ(0, s.proxy_hits());
  24407. EXPECT_EQ(1, s.target_hits());
  24408. }
  24409. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24410. // Regression guard: "evilexample.com" must not be considered a subdomain
  24411. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24412. // check would let traffic bypass the proxy and leak credentials direct
  24413. // to the attacker host.
  24414. ProxyAndTargetServers s;
  24415. auto cli = make_client("evilexample.com", s);
  24416. cli->set_no_proxy({"example.com"});
  24417. auto res = cli->Get("/");
  24418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24419. EXPECT_GE(s.proxy_hits(), 1);
  24420. EXPECT_EQ(0, s.target_hits());
  24421. }
  24422. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24423. ProxyAndTargetServers s;
  24424. auto cli = make_client("example.com.evil.com", s);
  24425. cli->set_no_proxy({"example.com"});
  24426. auto res = cli->Get("/");
  24427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24428. EXPECT_GE(s.proxy_hits(), 1);
  24429. EXPECT_EQ(0, s.target_hits());
  24430. }
  24431. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24432. ProxyAndTargetServers s;
  24433. auto cli = make_client("example.com", s);
  24434. cli->set_no_proxy({".example.com"});
  24435. auto res = cli->Get("/");
  24436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24437. EXPECT_EQ(0, s.proxy_hits());
  24438. EXPECT_EQ(1, s.target_hits());
  24439. }
  24440. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24441. ProxyAndTargetServers s;
  24442. auto cli = make_client("Example.COM", s);
  24443. cli->set_no_proxy({"EXAMPLE.com"});
  24444. auto res = cli->Get("/");
  24445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24446. EXPECT_EQ(0, s.proxy_hits());
  24447. EXPECT_EQ(1, s.target_hits());
  24448. }
  24449. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24450. ProxyAndTargetServers s;
  24451. auto cli = make_client("example.com.", s);
  24452. cli->set_no_proxy({"example.com"});
  24453. auto res = cli->Get("/");
  24454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24455. EXPECT_EQ(0, s.proxy_hits());
  24456. EXPECT_EQ(1, s.target_hits());
  24457. }
  24458. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24459. // Trailing dots must be normalized on BOTH sides — host and entry.
  24460. // An implementation that only strips the host-side trailing dot would
  24461. // fail to match host "example.com" against entry "example.com." because
  24462. // a literal substring search would compare 11 chars against 12.
  24463. ProxyAndTargetServers s;
  24464. auto cli = make_client("example.com", s);
  24465. cli->set_no_proxy({"example.com."});
  24466. auto res = cli->Get("/");
  24467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24468. EXPECT_EQ(0, s.proxy_hits());
  24469. EXPECT_EQ(1, s.target_hits());
  24470. }
  24471. TEST(NoProxyTest, WildcardBypassesEverything) {
  24472. ProxyAndTargetServers s;
  24473. auto cli = make_client("anything.invalid.test", s);
  24474. cli->set_no_proxy({"*"});
  24475. auto res = cli->Get("/");
  24476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24477. EXPECT_EQ(0, s.proxy_hits());
  24478. EXPECT_EQ(1, s.target_hits());
  24479. }
  24480. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24481. ProxyAndTargetServers s;
  24482. Client cli("127.0.0.1", s.target_port());
  24483. cli.set_proxy("127.0.0.1", s.proxy_port());
  24484. cli.set_no_proxy({"127.0.0.1"});
  24485. auto res = cli.Get("/");
  24486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24487. EXPECT_EQ(0, s.proxy_hits());
  24488. EXPECT_EQ(1, s.target_hits());
  24489. }
  24490. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24491. ProxyAndTargetServers s;
  24492. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24493. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24494. cli.set_proxy("127.0.0.1", s.proxy_port());
  24495. cli.set_no_proxy({"::1"});
  24496. auto res = cli.Get("/");
  24497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24498. EXPECT_EQ(0, s.proxy_hits());
  24499. EXPECT_EQ(1, s.target_hits());
  24500. }
  24501. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24502. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24503. // must still be recognized as IPv6 for CIDR matching. Implementations
  24504. // that detect IPv6 only when the host begins with '[' would parse the
  24505. // host as a hostname and miss the match.
  24506. ProxyAndTargetServers s;
  24507. Client cli("fe80::1", s.target_port());
  24508. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24509. cli.set_proxy("127.0.0.1", s.proxy_port());
  24510. cli.set_no_proxy({"fe80::/10"});
  24511. auto res = cli.Get("/");
  24512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24513. EXPECT_EQ(0, s.proxy_hits());
  24514. EXPECT_EQ(1, s.target_hits());
  24515. }
  24516. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24517. ProxyAndTargetServers s;
  24518. Client cli("::1", s.target_port());
  24519. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24520. cli.set_proxy("127.0.0.1", s.proxy_port());
  24521. cli.set_no_proxy({"[::1]"});
  24522. auto res = cli.Get("/");
  24523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24524. EXPECT_EQ(0, s.proxy_hits());
  24525. EXPECT_EQ(1, s.target_hits());
  24526. }
  24527. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24528. ProxyAndTargetServers s;
  24529. Client cli("fe80::1", s.target_port());
  24530. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24531. cli.set_proxy("127.0.0.1", s.proxy_port());
  24532. cli.set_no_proxy({"[fe80::]/10"});
  24533. auto res = cli.Get("/");
  24534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24535. EXPECT_EQ(0, s.proxy_hits());
  24536. EXPECT_EQ(1, s.target_hits());
  24537. }
  24538. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24539. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24540. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24541. // tricks via address-family conversion.
  24542. ProxyAndTargetServers s;
  24543. Client cli("::ffff:127.0.0.1", s.target_port());
  24544. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24545. cli.set_proxy("127.0.0.1", s.proxy_port());
  24546. cli.set_no_proxy({"127.0.0.1"});
  24547. auto res = cli.Get("/");
  24548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24549. EXPECT_GE(s.proxy_hits(), 1);
  24550. EXPECT_EQ(0, s.target_hits());
  24551. }
  24552. TEST(NoProxyTest, IPv4CidrMatch) {
  24553. ProxyAndTargetServers s;
  24554. Client cli("127.0.0.1", s.target_port());
  24555. cli.set_proxy("127.0.0.1", s.proxy_port());
  24556. cli.set_no_proxy({"127.0.0.0/8"});
  24557. auto res = cli.Get("/");
  24558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24559. EXPECT_EQ(0, s.proxy_hits());
  24560. EXPECT_EQ(1, s.target_hits());
  24561. }
  24562. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24563. ProxyAndTargetServers s;
  24564. Client cli("127.0.0.1", s.target_port());
  24565. cli.set_proxy("127.0.0.1", s.proxy_port());
  24566. cli.set_no_proxy({"10.0.0.0/8"});
  24567. auto res = cli.Get("/");
  24568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24569. EXPECT_GE(s.proxy_hits(), 1);
  24570. EXPECT_EQ(0, s.target_hits());
  24571. }
  24572. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24573. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24574. // IPv4 target matches.
  24575. ProxyAndTargetServers s;
  24576. Client cli("127.0.0.1", s.target_port());
  24577. cli.set_proxy("127.0.0.1", s.proxy_port());
  24578. cli.set_no_proxy({"0.0.0.0/0"});
  24579. auto res = cli.Get("/");
  24580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24581. EXPECT_EQ(0, s.proxy_hits());
  24582. EXPECT_EQ(1, s.target_hits());
  24583. }
  24584. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24585. ProxyAndTargetServers s;
  24586. Client cli("127.0.0.1", s.target_port());
  24587. cli.set_proxy("127.0.0.1", s.proxy_port());
  24588. cli.set_no_proxy({"127.0.0.1"});
  24589. auto res = cli.Get("/");
  24590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24591. EXPECT_EQ(0, s.proxy_hits());
  24592. EXPECT_EQ(1, s.target_hits());
  24593. }
  24594. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24595. ProxyAndTargetServers s;
  24596. Client cli("127.0.0.1", s.target_port());
  24597. cli.set_proxy("127.0.0.1", s.proxy_port());
  24598. cli.set_no_proxy({"127.0.0.0/33"});
  24599. auto res = cli.Get("/");
  24600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24601. EXPECT_GE(s.proxy_hits(), 1);
  24602. EXPECT_EQ(0, s.target_hits());
  24603. }
  24604. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24605. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24606. ProxyAndTargetServers s;
  24607. Client cli("127.0.0.1", s.target_port());
  24608. cli.set_proxy("127.0.0.1", s.proxy_port());
  24609. cli.set_no_proxy({"127.0.0.1/"});
  24610. auto res = cli.Get("/");
  24611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24612. EXPECT_GE(s.proxy_hits(), 1);
  24613. EXPECT_EQ(0, s.target_hits());
  24614. }
  24615. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24616. ProxyAndTargetServers s;
  24617. auto cli = make_client("internal.corp", s);
  24618. cli->set_proxy_basic_auth("u", "p");
  24619. cli->set_no_proxy({"internal.corp"});
  24620. auto res = cli->Get("/");
  24621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24622. EXPECT_EQ(1, s.target_hits());
  24623. EXPECT_EQ(0, s.proxy_hits());
  24624. EXPECT_FALSE(s.last_had_proxy_authz())
  24625. << "Proxy-Authorization must not be sent direct to the target";
  24626. }
  24627. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24628. ProxyAndTargetServers s;
  24629. auto cli = make_client("public.example", s);
  24630. cli->set_proxy_basic_auth("u", "p");
  24631. cli->set_no_proxy({"internal.corp"}); // does not match
  24632. auto res = cli->Get("/");
  24633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24634. EXPECT_GE(s.proxy_hits(), 1);
  24635. EXPECT_TRUE(s.last_had_proxy_authz());
  24636. }
  24637. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24638. std::atomic<int> hits{0};
  24639. std::atomic<int> hits_with_authz{0};
  24640. no_proxy_test::ScopedServer proxy_mock;
  24641. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24642. hits++;
  24643. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24644. if (req.target.find("/redir") != std::string::npos) {
  24645. res.set_redirect("http://other.example/landed");
  24646. } else {
  24647. res.set_content("via-proxy", "text/plain");
  24648. }
  24649. });
  24650. proxy_mock.listen();
  24651. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24652. hits = 0;
  24653. hits_with_authz = 0;
  24654. Client cli("public.example", 80);
  24655. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24656. cli.set_proxy_basic_auth(c.first, c.second);
  24657. cli.set_follow_location(true);
  24658. // The redirect to another host goes through the proxy as well
  24659. auto res = cli.Get("/redir");
  24660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24661. EXPECT_EQ(2, hits.load());
  24662. EXPECT_EQ(2, hits_with_authz.load());
  24663. }
  24664. }
  24665. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24666. ProxyAndTargetServers s;
  24667. auto cli = make_client("anything.test", s);
  24668. auto res = cli->Get("/");
  24669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24670. EXPECT_GE(s.proxy_hits(), 1);
  24671. EXPECT_EQ(0, s.target_hits());
  24672. }
  24673. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24674. ProxyAndTargetServers s;
  24675. auto cli = make_client("example.com", s);
  24676. cli->set_no_proxy({"example.com:8080"});
  24677. auto res = cli->Get("/");
  24678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24679. EXPECT_GE(s.proxy_hits(), 1);
  24680. EXPECT_EQ(0, s.target_hits());
  24681. }
  24682. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24683. ProxyAndTargetServers s;
  24684. auto cli = make_client("anything.test", s);
  24685. cli->set_no_proxy({"", " ", "\t"});
  24686. auto res = cli->Get("/");
  24687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24688. EXPECT_GE(s.proxy_hits(), 1);
  24689. EXPECT_EQ(0, s.target_hits());
  24690. }
  24691. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24692. // An entry with leading/trailing whitespace must still match — env-style
  24693. // values are commonly pasted with stray spaces and an implementation
  24694. // that feeds the raw token directly to inet_pton would fail to match
  24695. // valid CIDRs because of the spaces.
  24696. ProxyAndTargetServers s;
  24697. Client cli("127.0.0.1", s.target_port());
  24698. cli.set_proxy("127.0.0.1", s.proxy_port());
  24699. cli.set_no_proxy({" 127.0.0.0/8 "});
  24700. auto res = cli.Get("/");
  24701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24702. EXPECT_EQ(0, s.proxy_hits());
  24703. EXPECT_EQ(1, s.target_hits());
  24704. }
  24705. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24706. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24707. // go direct and must NOT carry Proxy-Authorization.
  24708. std::atomic<int> proxy_hits{0};
  24709. std::atomic<int> target_hits{0};
  24710. std::atomic<bool> target_saw_authz{false};
  24711. no_proxy_test::ScopedServer proxy_mock, target;
  24712. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24713. proxy_hits++;
  24714. res.status = 302;
  24715. res.set_header("Location", "http://127.0.0.1:" +
  24716. std::to_string(target.port()) + "/landed");
  24717. });
  24718. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24719. target_hits++;
  24720. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24721. res.set_content("direct", "text/plain");
  24722. });
  24723. proxy_mock.listen();
  24724. target.listen();
  24725. Client cli("public.example", target.port());
  24726. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24727. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24728. cli.set_proxy_basic_auth("u", "p");
  24729. cli.set_no_proxy({"127.0.0.1"});
  24730. cli.set_follow_location(true);
  24731. auto res = cli.Get("/redir");
  24732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24733. EXPECT_GE(proxy_hits.load(), 1);
  24734. EXPECT_GE(target_hits.load(), 1);
  24735. EXPECT_FALSE(target_saw_authz.load());
  24736. }
  24737. #ifdef CPPHTTPLIB_SSL_ENABLED
  24738. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24739. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24740. // proxy creds would be sent to the (possibly hostile) origin.
  24741. std::atomic<int> target_hits{0};
  24742. std::atomic<bool> target_saw_proxy_authz{false};
  24743. no_proxy_test::ScopedServer target;
  24744. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24745. target_hits++;
  24746. if (req.has_header("Proxy-Authorization")) {
  24747. target_saw_proxy_authz = true;
  24748. }
  24749. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24750. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24751. "nonce=\"abc\", algorithm=MD5");
  24752. });
  24753. target.listen();
  24754. // The proxy address is set to the target's port: the bypass MUST kick in;
  24755. // if it doesn't, the test still routes "via proxy" to the same server and
  24756. // the Proxy-Authorization assertion below catches the leak.
  24757. Client cli("evil.example", target.port());
  24758. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24759. cli.set_proxy("127.0.0.1", target.port());
  24760. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24761. cli.set_no_proxy({"evil.example"});
  24762. auto res = cli.Get("/x");
  24763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24764. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24765. EXPECT_EQ(1, target_hits.load());
  24766. EXPECT_FALSE(target_saw_proxy_authz.load());
  24767. }
  24768. #endif
  24769. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24770. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24771. std::atomic<int> proxy_hits{0};
  24772. std::atomic<int> bypass_hits{0};
  24773. std::atomic<bool> proxy_saw_c_url{false};
  24774. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24775. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24776. proxy_hits++;
  24777. if (req.path.find("/start") != std::string::npos) {
  24778. res.status = 302;
  24779. res.set_header("Location", "http://127.0.0.1:" +
  24780. std::to_string(bypass_server.port()) +
  24781. "/middle");
  24782. return;
  24783. }
  24784. if (req.path.find("/end") != std::string::npos) {
  24785. proxy_saw_c_url = true;
  24786. res.set_content("c-via-proxy", "text/plain");
  24787. return;
  24788. }
  24789. res.set_content("unexpected", "text/plain");
  24790. });
  24791. // public.example's "advertised" port is arbitrary (the request never lands
  24792. // there — it goes through the proxy), but use a dynamic value to stay
  24793. // friendly with sharded parallel runs.
  24794. int public_port = bypass_server.port();
  24795. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24796. bypass_hits++;
  24797. res.status = 302;
  24798. res.set_header("Location", "http://public.example:" +
  24799. std::to_string(public_port) + "/end");
  24800. });
  24801. proxy_mock.listen();
  24802. bypass_server.listen();
  24803. Client cli("public.example", public_port);
  24804. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24805. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24806. cli.set_no_proxy({"127.0.0.1"});
  24807. cli.set_follow_location(true);
  24808. auto res = cli.Get("/start");
  24809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24810. EXPECT_EQ(StatusCode::OK_200, res->status);
  24811. EXPECT_EQ("c-via-proxy", res->body);
  24812. EXPECT_GE(proxy_hits.load(), 2);
  24813. EXPECT_GE(bypass_hits.load(), 1);
  24814. EXPECT_TRUE(proxy_saw_c_url.load());
  24815. }
  24816. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24817. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24818. // request reconnects to the correct endpoint.
  24819. std::atomic<int> proxy_hits{0};
  24820. std::atomic<int> target_hits{0};
  24821. no_proxy_test::ScopedServer proxy_mock, target;
  24822. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24823. proxy_hits++;
  24824. res.set_content("via-proxy", "text/plain");
  24825. });
  24826. target.svr().Get(".*", [&](const Request &, Response &res) {
  24827. target_hits++;
  24828. res.set_content("direct", "text/plain");
  24829. });
  24830. proxy_mock.listen();
  24831. target.listen();
  24832. Client cli("public.example", target.port());
  24833. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24834. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24835. cli.set_keep_alive(true);
  24836. auto res1 = cli.Get("/a");
  24837. ASSERT_TRUE(res1);
  24838. EXPECT_EQ("via-proxy", res1->body);
  24839. EXPECT_EQ(1, proxy_hits.load());
  24840. EXPECT_EQ(0, target_hits.load());
  24841. cli.set_no_proxy({"public.example"});
  24842. auto res2 = cli.Get("/b");
  24843. ASSERT_TRUE(res2);
  24844. EXPECT_EQ("direct", res2->body);
  24845. EXPECT_EQ(1, proxy_hits.load());
  24846. EXPECT_EQ(1, target_hits.load());
  24847. }
  24848. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24849. namespace proxy_tunnel_test {
  24850. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24851. class ScopedSSLServer {
  24852. public:
  24853. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24854. port_ = svr_.bind_to_any_port("127.0.0.1");
  24855. }
  24856. ~ScopedSSLServer() {
  24857. svr_.stop();
  24858. if (th_.joinable()) { th_.join(); }
  24859. }
  24860. SSLServer &svr() { return svr_; }
  24861. int port() const { return port_; }
  24862. void listen() {
  24863. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24864. svr_.wait_until_ready();
  24865. }
  24866. private:
  24867. SSLServer svr_;
  24868. std::thread th_;
  24869. int port_ = 0;
  24870. };
  24871. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24872. class ScopedConnectProxy {
  24873. public:
  24874. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24875. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24876. if (listen_fd_ < 0) { return; }
  24877. int yes = 1;
  24878. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24879. sockaddr_in a{};
  24880. a.sin_family = AF_INET;
  24881. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24882. a.sin_port = 0;
  24883. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24884. return;
  24885. }
  24886. socklen_t alen = sizeof(a);
  24887. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24888. 0) {
  24889. return;
  24890. }
  24891. port_ = ntohs(a.sin_port);
  24892. if (::listen(listen_fd_, 1) != 0) { return; }
  24893. th_ = std::thread([this] { run(); });
  24894. }
  24895. ~ScopedConnectProxy() {
  24896. stop_ = true;
  24897. if (listen_fd_ >= 0) {
  24898. ::shutdown(listen_fd_, SHUT_RDWR);
  24899. ::close(listen_fd_);
  24900. }
  24901. if (th_.joinable()) { th_.join(); }
  24902. }
  24903. int port() const { return port_; }
  24904. int connect_hits() const { return connect_hits_.load(); }
  24905. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24906. std::string connect_request() const {
  24907. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24908. return connect_request_;
  24909. }
  24910. private:
  24911. void run() {
  24912. while (!stop_.load()) {
  24913. fd_set rfds;
  24914. FD_ZERO(&rfds);
  24915. FD_SET(listen_fd_, &rfds);
  24916. timeval tv{0, 100 * 1000};
  24917. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24918. if (sel <= 0) { continue; }
  24919. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24920. if (client_fd < 0) { continue; }
  24921. std::string req;
  24922. char buf[2048];
  24923. while (req.find("\r\n\r\n") == std::string::npos) {
  24924. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24925. if (n <= 0) { break; }
  24926. req.append(buf, static_cast<size_t>(n));
  24927. }
  24928. if (req.compare(0, 7, "CONNECT") != 0) {
  24929. ::close(client_fd);
  24930. continue;
  24931. }
  24932. connect_hits_++;
  24933. {
  24934. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24935. connect_request_ = req;
  24936. }
  24937. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24938. ::send(client_fd, ok, std::strlen(ok), 0);
  24939. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24940. sockaddr_in o{};
  24941. o.sin_family = AF_INET;
  24942. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24943. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24944. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24945. 0) {
  24946. ::close(client_fd);
  24947. ::close(origin_fd);
  24948. continue;
  24949. }
  24950. auto forward = [](int from, int to) {
  24951. char b[8192];
  24952. for (;;) {
  24953. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24954. if (n <= 0) { break; }
  24955. ssize_t off = 0;
  24956. while (off < n) {
  24957. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24958. if (s <= 0) {
  24959. off = n;
  24960. break;
  24961. }
  24962. off += s;
  24963. }
  24964. }
  24965. ::shutdown(to, SHUT_WR);
  24966. };
  24967. std::thread t1([&] { forward(client_fd, origin_fd); });
  24968. std::thread t2([&] { forward(origin_fd, client_fd); });
  24969. t1.join();
  24970. t2.join();
  24971. ::close(client_fd);
  24972. ::close(origin_fd);
  24973. }
  24974. }
  24975. int forward_port_ = -1;
  24976. int listen_fd_ = -1;
  24977. int port_ = 0;
  24978. std::thread th_;
  24979. std::atomic<bool> stop_{false};
  24980. std::atomic<int> connect_hits_{0};
  24981. mutable std::mutex connect_request_mutex_;
  24982. std::string connect_request_;
  24983. };
  24984. // Sends one request through the CONNECT proxy to the TLS origin with a
  24985. // credential configured for each hop, and checks that each credential reaches
  24986. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24987. // origin's (every header in origin_headers) on the tunnelled request.
  24988. void CredentialsStayWithTheirHop(
  24989. const std::function<void(SSLClient &)> &set_credentials,
  24990. const std::string &scheme,
  24991. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24992. std::atomic<int> origin_hits{0};
  24993. std::atomic<bool> origin_saw_proxy_authz{false};
  24994. std::atomic<bool> origin_saw_headers{false};
  24995. ScopedSSLServer origin;
  24996. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24997. origin_hits++;
  24998. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24999. origin_saw_headers =
  25000. std::all_of(origin_headers.begin(), origin_headers.end(),
  25001. [&](const std::string &h) { return req.has_header(h); });
  25002. res.set_content("ok", "text/plain");
  25003. });
  25004. origin.listen();
  25005. ScopedConnectProxy proxy(origin.port());
  25006. ASSERT_NE(0, proxy.port());
  25007. // Pinned to 127.0.0.1 for the same reason as the test below.
  25008. SSLClient cli("127.0.0.1", origin.port());
  25009. cli.enable_server_certificate_verification(false);
  25010. cli.set_proxy("127.0.0.1", proxy.port());
  25011. set_credentials(cli);
  25012. auto res = cli.Get("/x");
  25013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25014. EXPECT_EQ(StatusCode::OK_200, res->status);
  25015. EXPECT_EQ(1, origin_hits.load());
  25016. EXPECT_EQ(1, proxy.connect_hits());
  25017. EXPECT_TRUE(origin_saw_headers.load());
  25018. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25019. << "Proxy-Authorization must not be sent inside the tunnel";
  25020. auto connect_req = proxy.connect_request();
  25021. EXPECT_NE(std::string::npos,
  25022. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25023. for (const auto &h : origin_headers) {
  25024. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25025. << h << " must not be sent to the proxy on CONNECT";
  25026. }
  25027. }
  25028. } // namespace proxy_tunnel_test
  25029. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25030. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25031. [](SSLClient &cli) {
  25032. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25033. cli.set_basic_auth("origin-user", "origin-pass");
  25034. },
  25035. "Basic");
  25036. }
  25037. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25038. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25039. [](SSLClient &cli) {
  25040. cli.set_proxy_bearer_token_auth("proxy-token");
  25041. cli.set_bearer_token_auth("origin-token");
  25042. },
  25043. "Bearer");
  25044. }
  25045. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25046. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25047. [](SSLClient &cli) {
  25048. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25049. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25050. {"Cookie", "sid=origin-session"},
  25051. {"X-Api-Key", "origin-key"}});
  25052. },
  25053. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25054. }
  25055. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25056. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25057. // retry; otherwise proxy creds would be sent to the origin.
  25058. std::atomic<int> origin_hits{0};
  25059. std::atomic<bool> origin_saw_proxy_authz{false};
  25060. proxy_tunnel_test::ScopedSSLServer origin;
  25061. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25062. origin_hits++;
  25063. if (req.has_header("Proxy-Authorization")) {
  25064. origin_saw_proxy_authz = true;
  25065. }
  25066. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25067. res.set_header("Proxy-Authenticate",
  25068. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25069. "algorithm=MD5");
  25070. });
  25071. origin.listen();
  25072. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25073. ASSERT_NE(0, proxy.port());
  25074. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25075. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25076. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25077. // and answer with its own status, making this test flaky.
  25078. SSLClient cli("127.0.0.1", origin.port());
  25079. cli.enable_server_certificate_verification(false);
  25080. cli.set_proxy("127.0.0.1", proxy.port());
  25081. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25082. auto res = cli.Get("/x");
  25083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25084. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25085. EXPECT_EQ(1, origin_hits.load());
  25086. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25087. EXPECT_EQ(1, proxy.connect_hits());
  25088. }
  25089. #endif