test.cc 924 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declarations (see the base64_encode note below).
  474. namespace httplib {
  475. namespace detail {
  476. bool parse_status_line(const char *line, std::string &version, int &status,
  477. std::string &reason);
  478. std::string file_extension(const std::string &path);
  479. std::string
  480. find_content_type(const std::string &path,
  481. const std::map<std::string, std::string> &user_data,
  482. const std::string &default_content_type);
  483. bool can_compress_content_type(const std::string &content_type);
  484. bool is_prohibited_header_name(const std::string &name);
  485. } // namespace detail
  486. } // namespace httplib
  487. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  488. struct {
  489. const char *line;
  490. const char *version;
  491. int status;
  492. const char *reason;
  493. } cases[] = {
  494. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  495. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  496. // The reason phrase may be empty, or left out along with its space.
  497. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  498. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  499. };
  500. for (const auto &c : cases) {
  501. std::string version;
  502. int status = 0;
  503. std::string reason = "unset";
  504. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  505. << c.line;
  506. EXPECT_EQ(c.version, version);
  507. EXPECT_EQ(c.status, status);
  508. EXPECT_EQ(c.reason, reason);
  509. }
  510. }
  511. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  512. const char *lines[] = {
  513. "HTTP/2 200 OK\r\n",
  514. "HTTP/1.2 200 OK\r\n",
  515. "HTTP/1.1 20 OK\r\n",
  516. "HTTP/1.1 2000 OK\r\n",
  517. "HTTP/1.1 2x0 OK\r\n",
  518. "HTTP/1.1 200 OK\r\n",
  519. "HTTP/1.1 200OK\r\n",
  520. "HTTP/1.1 200 O\rK\r\n",
  521. "HTTP/1.1 200 OK",
  522. "HTTP/1.1 200 OK\r\nX",
  523. "",
  524. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  525. "HTTP/1.1 200 OK\n",
  526. #endif
  527. };
  528. for (auto line : lines) {
  529. std::string version;
  530. int status = 0;
  531. std::string reason;
  532. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  533. << line;
  534. }
  535. }
  536. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  537. // Long enough to overflow the stack when matched with std::regex.
  538. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  539. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  540. std::string version;
  541. int status = 0;
  542. std::string reason;
  543. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  544. EXPECT_EQ(200, status);
  545. EXPECT_EQ(long_reason, reason);
  546. }
  547. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  548. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  549. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  550. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  551. EXPECT_EQ("", detail::file_extension("noext"));
  552. EXPECT_EQ("", detail::file_extension("a."));
  553. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  554. EXPECT_EQ("", detail::file_extension("a.b-c"));
  555. // Long enough to overflow the stack when matched with std::regex.
  556. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  557. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  558. }
  559. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  560. detail::case_ignore::hash hash;
  561. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  562. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  563. // Long enough to overflow the stack if hashed one call per character.
  564. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  565. }
  566. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  567. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  568. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  569. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  570. // Same 26-bit hash as html, svg and js.
  571. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  572. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  573. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  574. }
  575. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  576. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  577. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  578. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  579. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  580. // Same 26-bit hash as application/json.
  581. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  582. }
  583. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  584. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  585. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  586. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  587. // Same 26-bit hash as REMOTE_ADDR.
  588. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  589. }
  590. // Forward declaration: in split builds split.py strips `inline` and moves the
  591. // definition into httplib.cc, so detail::base64_encode is not visible from the
  592. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  593. // in both header-only and split builds.
  594. namespace httplib {
  595. namespace detail {
  596. std::string base64_encode(const std::string &in);
  597. } // namespace detail
  598. } // namespace httplib
  599. TEST(Base64EncodeTest, KnownAnswers) {
  600. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  601. // where the accumulator's top bit is already set before the next shift.
  602. EXPECT_EQ("", detail::base64_encode(""));
  603. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  604. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  605. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  606. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  607. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  608. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  609. // High bytes keep the top bit set across several rounds.
  610. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  611. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  612. }
  613. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  614. string unescapedCharacters = "-_.!~*'()";
  615. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  616. }
  617. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  618. string reservedCharacters = ";,/?:@&=+$";
  619. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  620. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  621. }
  622. TEST(ClientQueryOrder, PreserveOrder) {
  623. // This test reproduces Issue #2259: client may reorder query parameters
  624. // when sending a GET request. The expected behavior is that the client
  625. // preserves the original query string order when the caller supplied it
  626. // as part of the path.
  627. Server svr;
  628. svr.Get("/", [&](const Request &req, Response &res) {
  629. // Echo back the raw target so the test can assert ordering
  630. res.set_content(req.target, "text/plain");
  631. });
  632. std::thread t{[&] { svr.listen(HOST, PORT); }};
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. t.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli(HOST, PORT);
  640. ASSERT_TRUE(cli.is_valid());
  641. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  642. auto res = cli.Get(original);
  643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  644. // Expect the echoed target to exactly match the original path (order
  645. // preserved)
  646. EXPECT_EQ(res->body, original);
  647. }
  648. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  649. string chineseCharacters = U8("中国語");
  650. string russianCharacters = U8("дом");
  651. string brazilianCharacters = U8("óculos");
  652. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  653. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  654. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  655. "%D0%B4%D0%BE%D0%BC");
  656. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  657. }
  658. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  659. string unescapedCharacters = "-_.!~*'()";
  660. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  661. }
  662. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  663. string reservedCharacters = ";,/?:@&=+$";
  664. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  665. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  666. }
  667. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  668. string chineseCharacters = U8("中国語");
  669. string russianCharacters = U8("дом");
  670. string brazilianCharacters = U8("óculos");
  671. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  672. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  673. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  674. "%D0%B4%D0%BE%D0%BC");
  675. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  676. }
  677. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  678. // Issue #2082 use case: encoding path component with ampersand
  679. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  680. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  681. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  682. }
  683. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  684. string unescapedCharacters = "-_.!~*'()";
  685. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  686. }
  687. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  688. string reservedCharacters = ";,/?:@&=+$#";
  689. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  690. }
  691. TEST(EncodeUriTest, TestUTF8Characters) {
  692. string chineseCharacters = U8("中国語");
  693. string russianCharacters = U8("дом");
  694. string brazilianCharacters = U8("óculos");
  695. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  696. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  697. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  698. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  699. }
  700. TEST(EncodeUriTest, TestCompleteUri) {
  701. string uri =
  702. "https://example.com/path/to/resource?query=value&param=test#fragment";
  703. EXPECT_EQ(
  704. httplib::encode_uri(uri),
  705. "https://example.com/path/to/resource?query=value&param=test#fragment");
  706. }
  707. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  708. string uri =
  709. "https://example.com/path with spaces/file name.html?q=hello world";
  710. EXPECT_EQ(httplib::encode_uri(uri),
  711. "https://example.com/path%20with%20spaces/"
  712. "file%20name.html?q=hello%20world");
  713. }
  714. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  715. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  716. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  717. }
  718. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  723. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  724. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  725. string encodedBrazilian = "%C3%B3culos";
  726. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  727. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  728. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  729. }
  730. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  731. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  732. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  733. "Piri Tommy Villiers - on & on");
  734. }
  735. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  736. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  737. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  738. }
  739. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  740. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  741. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  742. }
  743. TEST(DecodeUriTest, TestUTF8Characters) {
  744. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  745. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  746. string encodedBrazilian = "%C3%B3culos";
  747. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  748. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  749. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  750. }
  751. TEST(DecodeUriTest, TestCompleteUri) {
  752. string encodedUri = "https://example.com/path%20with%20spaces/"
  753. "file%20name.html?q=hello%20world";
  754. EXPECT_EQ(
  755. httplib::decode_uri(encodedUri),
  756. "https://example.com/path with spaces/file name.html?q=hello world");
  757. }
  758. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  759. string original =
  760. "https://example.com/path with spaces/file name.html?q=hello world";
  761. string encoded = httplib::encode_uri(original);
  762. string decoded = httplib::decode_uri(encoded);
  763. EXPECT_EQ(decoded, original);
  764. }
  765. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  766. // decode_uri is the inverse of encode_uri: an escaped reserved character
  767. // stays encoded so it is not promoted into a real delimiter, while
  768. // non-reserved escapes still decode (like JS decodeURI).
  769. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  770. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  771. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  772. "%3F%3A%40%26%3D%2B%24%2C%3B");
  773. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  774. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  775. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  776. "http://example.com/a%2Fb");
  777. // decode_uri_component still decodes the reserved character.
  778. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  779. }
  780. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  781. string original = "Piri Tommy Villiers - on & on";
  782. string encoded = httplib::encode_uri_component(original);
  783. string decoded = httplib::decode_uri_component(encoded);
  784. EXPECT_EQ(decoded, original);
  785. }
  786. TEST(TrimTests, TrimStringTests) {
  787. EXPECT_EQ("abc", detail::trim_copy("abc"));
  788. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  789. EXPECT_TRUE(detail::trim_copy("").empty());
  790. }
  791. TEST(AsciiTest, LocaleIndependentClassification) {
  792. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  793. // which consult the global C locale: std::isalnum(0xC5) can return true
  794. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  795. // helpers must classify every byte by the ASCII grammar alone.
  796. for (int i = 0; i < 256; i++) {
  797. auto c = static_cast<char>(i);
  798. auto is_digit = i >= '0' && i <= '9';
  799. auto is_upper = i >= 'A' && i <= 'Z';
  800. auto is_lower = i >= 'a' && i <= 'z';
  801. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  802. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  803. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  804. << "byte " << i;
  805. }
  806. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  807. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  808. // Non-ASCII bytes must be percent-encoded, never passed through as
  809. // alphanumeric.
  810. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  811. }
  812. TEST(FromCharsTest, Double) {
  813. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  814. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  815. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  816. auto parse = [](const std::string &s, double &v) {
  817. return detail::from_chars(s.data(), s.data() + s.size(), v);
  818. };
  819. double v = -1.0;
  820. // Representative quality values.
  821. EXPECT_EQ(parse("0", v).ec, std::errc{});
  822. EXPECT_DOUBLE_EQ(v, 0.0);
  823. EXPECT_EQ(parse("1", v).ec, std::errc{});
  824. EXPECT_DOUBLE_EQ(v, 1.0);
  825. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  826. EXPECT_DOUBLE_EQ(v, 0.8);
  827. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  828. EXPECT_DOUBLE_EQ(v, 0.001);
  829. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  830. EXPECT_DOUBLE_EQ(v, 1.0);
  831. // A missing integer or fractional part is tolerated.
  832. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  833. EXPECT_DOUBLE_EQ(v, 0.5);
  834. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  835. EXPECT_DOUBLE_EQ(v, 5.0);
  836. // Values outside [0, 1] still parse; the caller range-checks them.
  837. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  838. EXPECT_DOUBLE_EQ(v, 123.456);
  839. // Stops at the first byte that is not part of the number and reports where.
  840. std::string trailing = "0.9, text/html";
  841. auto r = parse(trailing, v);
  842. EXPECT_EQ(r.ec, std::errc{});
  843. EXPECT_DOUBLE_EQ(v, 0.9);
  844. EXPECT_EQ(*r.ptr, ',');
  845. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  846. // outright, and an 'e'/'E' simply ends the number.
  847. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  848. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  849. std::string exp_input = "1.5e3";
  850. r = parse(exp_input, v);
  851. EXPECT_EQ(r.ec, std::errc{});
  852. EXPECT_DOUBLE_EQ(v, 1.5);
  853. EXPECT_EQ(*r.ptr, 'e');
  854. // Invalid inputs.
  855. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  856. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  857. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  858. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  859. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  860. // Pathological but well-formed inputs must stay bounded (no overflow, no
  861. // out-of-bounds table access) and stay within [0, 1] for the caller.
  862. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  863. std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.0);
  865. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  866. std::errc{});
  867. EXPECT_GE(v, 0.0);
  868. EXPECT_LE(v, 1.0);
  869. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  870. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  871. }
  872. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  873. // Simple case without quality values
  874. std::vector<std::string> result1;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "text/html,application/json,text/plain", result1));
  877. EXPECT_EQ(result1.size(), 3U);
  878. EXPECT_EQ(result1[0], "text/html");
  879. EXPECT_EQ(result1[1], "application/json");
  880. EXPECT_EQ(result1[2], "text/plain");
  881. // With quality values
  882. std::vector<std::string> result2;
  883. EXPECT_TRUE(detail::parse_accept_header(
  884. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  885. EXPECT_EQ(result2.size(), 3U);
  886. EXPECT_EQ(result2[0], "application/json"); // highest q value
  887. EXPECT_EQ(result2[1], "text/html");
  888. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  889. }
  890. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  891. // Mixed with and without quality values
  892. std::vector<std::string> result;
  893. EXPECT_TRUE(detail::parse_accept_header(
  894. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  895. EXPECT_EQ(result.size(), 3U);
  896. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  897. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  898. EXPECT_EQ(result[2], "application/json"); // q=0.5
  899. }
  900. TEST(ParseAcceptHeaderTest, EdgeCases) {
  901. // Empty header
  902. std::vector<std::string> empty_result;
  903. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  904. EXPECT_TRUE(empty_result.empty());
  905. // Single type
  906. std::vector<std::string> single_result;
  907. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  908. EXPECT_EQ(single_result.size(), 1U);
  909. EXPECT_EQ(single_result[0], "application/json");
  910. // Wildcard types
  911. std::vector<std::string> wildcard_result;
  912. EXPECT_TRUE(detail::parse_accept_header(
  913. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  914. EXPECT_EQ(wildcard_result.size(), 3U);
  915. EXPECT_EQ(wildcard_result[0], "application/json");
  916. EXPECT_EQ(wildcard_result[1], "text/*");
  917. EXPECT_EQ(wildcard_result[2], "*/*");
  918. }
  919. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  920. // Common browser Accept header
  921. std::vector<std::string> browser_result;
  922. EXPECT_TRUE(
  923. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  924. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  925. browser_result));
  926. EXPECT_EQ(browser_result.size(), 6U);
  927. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  928. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  929. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  930. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  931. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  932. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  933. // API client header
  934. std::vector<std::string> api_result;
  935. EXPECT_TRUE(detail::parse_accept_header(
  936. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  937. api_result));
  938. EXPECT_EQ(api_result.size(), 3U);
  939. EXPECT_EQ(api_result[0], "application/json");
  940. EXPECT_EQ(api_result[1], "application/xml");
  941. EXPECT_EQ(api_result[2], "text/plain");
  942. }
  943. TEST(ParseAcceptHeaderTest, SpecialCases) {
  944. // Quality value with 3 decimal places
  945. std::vector<std::string> decimal_result;
  946. EXPECT_TRUE(detail::parse_accept_header(
  947. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  948. EXPECT_EQ(decimal_result.size(), 2U);
  949. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  950. EXPECT_EQ(decimal_result[1], "text/html");
  951. // Zero quality (should still be included but with lowest priority)
  952. std::vector<std::string> zero_q_result;
  953. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  954. zero_q_result));
  955. EXPECT_EQ(zero_q_result.size(), 2U);
  956. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  957. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  958. // No spaces around commas
  959. std::vector<std::string> no_space_result;
  960. EXPECT_TRUE(detail::parse_accept_header(
  961. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  962. no_space_result));
  963. EXPECT_EQ(no_space_result.size(), 3U);
  964. EXPECT_EQ(no_space_result[0], "text/html");
  965. EXPECT_EQ(no_space_result[1], "application/json");
  966. EXPECT_EQ(no_space_result[2], "text/plain");
  967. }
  968. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  969. // Quality values always use '.' as the decimal separator, so parsing must
  970. // not depend on the process locale. An embedding application may have
  971. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  972. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  973. std::string saved = cur ? cur : "C";
  974. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  975. "fr_FR.UTF-8"};
  976. bool switched = false;
  977. for (const auto loc : comma_locales) {
  978. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  979. std::localeconv()->decimal_point[0] == ',') {
  980. switched = true;
  981. break;
  982. }
  983. }
  984. if (!switched) {
  985. std::setlocale(LC_NUMERIC, saved.c_str());
  986. GTEST_SKIP() << "no comma-decimal locale available on this host";
  987. }
  988. // The higher-weighted type appears later in the list, so a correct parse
  989. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  990. // sensitive parse reads both weights as 0 and leaves the original order.
  991. std::vector<std::string> result;
  992. EXPECT_TRUE(detail::parse_accept_header(
  993. "application/json;q=0.1,text/html;q=0.9", result));
  994. ASSERT_EQ(result.size(), 2U);
  995. EXPECT_EQ(result[0], "text/html");
  996. EXPECT_EQ(result[1], "application/json");
  997. std::setlocale(LC_NUMERIC, saved.c_str());
  998. }
  999. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1000. std::vector<std::string> result;
  1001. // Invalid quality value (> 1.0)
  1002. EXPECT_FALSE(
  1003. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1004. // Invalid quality value (< 0.0)
  1005. EXPECT_FALSE(
  1006. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1007. // Invalid quality value (not a number)
  1008. EXPECT_FALSE(detail::parse_accept_header(
  1009. "text/html;q=invalid,application/json", result));
  1010. // A valid numeric prefix does not make the entire quality value valid.
  1011. EXPECT_FALSE(detail::parse_accept_header(
  1012. "text/html;q=0.5junk,application/json", result));
  1013. // Empty quality value
  1014. EXPECT_FALSE(
  1015. detail::parse_accept_header("text/html;q=,application/json", result));
  1016. // Invalid media type format (no slash and not wildcard)
  1017. EXPECT_FALSE(
  1018. detail::parse_accept_header("invalidtype,application/json", result));
  1019. // Valid cases should still work
  1020. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1021. EXPECT_EQ(result.size(), 1U);
  1022. EXPECT_EQ(result[0], "*/*");
  1023. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1024. EXPECT_EQ(result.size(), 1U);
  1025. EXPECT_EQ(result[0], "*");
  1026. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1027. EXPECT_EQ(result.size(), 1U);
  1028. EXPECT_EQ(result[0], "text/*");
  1029. }
  1030. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1031. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1032. // and must not be answered with 400 Bad Request.
  1033. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1034. struct {
  1035. const char *value;
  1036. std::vector<std::string> expected;
  1037. } cases[] = {
  1038. {",application/json", {"application/json"}},
  1039. {"text/html,", {"text/html"}},
  1040. {"text/html,,*/*", {"text/html", "*/*"}},
  1041. // An empty element may be spelled with whitespace in it
  1042. {"text/html, , application/json", {"text/html", "application/json"}},
  1043. // Nothing but empty elements is an empty list, which means the same
  1044. // thing as no Accept header at all
  1045. {",,,", {}},
  1046. // Quality values still apply across ignored empty elements
  1047. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1048. };
  1049. for (const auto &c : cases) {
  1050. std::vector<std::string> result;
  1051. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1052. << "value: " << c.value;
  1053. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1054. }
  1055. // An invalid entry is still rejected when empty elements surround it
  1056. std::vector<std::string> result;
  1057. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1058. }
  1059. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1060. // or ';' inside one does not end the list element or the parameter. Section
  1061. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1062. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1063. struct {
  1064. const char *value;
  1065. std::vector<std::string> expected;
  1066. } cases[] = {
  1067. {"text/html;profile=\"a,b\",application/json",
  1068. {"text/html", "application/json"}},
  1069. // A "q=" inside a quoted value is not the weight
  1070. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1071. {"text/html", "application/json"}},
  1072. // The weight after a quoted value still applies
  1073. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1074. {"application/json", "text/html"}},
  1075. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1076. {"application/json", "text/html"}},
  1077. {"text/html;profile=\"a\\\"b\",application/json",
  1078. {"text/html", "application/json"}},
  1079. // An escaped backslash does not escape the '"' after it
  1080. {"text/html;profile=\"a\\\\\",application/json",
  1081. {"text/html", "application/json"}},
  1082. };
  1083. for (const auto &c : cases) {
  1084. std::vector<std::string> result;
  1085. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1086. << "value: " << c.value;
  1087. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1088. }
  1089. }
  1090. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1091. Server svr;
  1092. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1093. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1094. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1095. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1096. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1097. res.set_content("ok", "text/plain");
  1098. });
  1099. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1100. EXPECT_TRUE(false);
  1101. res.set_content("bad request", "text/plain");
  1102. });
  1103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. listen_thread.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli("localhost", PORT);
  1111. {
  1112. auto res = cli.Get(
  1113. "/accept_ok",
  1114. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1116. EXPECT_EQ(StatusCode::OK_200, res->status);
  1117. }
  1118. {
  1119. auto res = cli.Get("/accept_bad_request",
  1120. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1122. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1123. }
  1124. }
  1125. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1126. Server svr;
  1127. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1128. res.set_content("ok", "text/plain");
  1129. });
  1130. std::atomic<int> start_count{0};
  1131. std::atomic<bool> running_when_called{false};
  1132. svr.set_start_handler([&]() {
  1133. running_when_called = svr.is_running();
  1134. start_count++;
  1135. });
  1136. auto port = svr.bind_to_any_port(HOST);
  1137. std::thread t([&]() { svr.listen_after_bind(); });
  1138. auto se = detail::scope_exit([&] {
  1139. svr.stop();
  1140. t.join();
  1141. ASSERT_FALSE(svr.is_running());
  1142. });
  1143. svr.wait_until_ready();
  1144. // A successful request proves the accept loop is running, which the start
  1145. // handler precedes; so by now the handler must have run exactly once.
  1146. Client cli(HOST, port);
  1147. cli.set_connection_timeout(std::chrono::seconds(5));
  1148. auto res = cli.Get("/");
  1149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1150. EXPECT_EQ(StatusCode::OK_200, res->status);
  1151. EXPECT_EQ(1, start_count.load());
  1152. EXPECT_TRUE(running_when_called.load());
  1153. }
  1154. TEST(DivideTest, DivideStringTests) {
  1155. auto divide = [](const std::string &str, char d) {
  1156. std::string lhs;
  1157. std::string rhs;
  1158. detail::divide(str, d,
  1159. [&](const char *lhs_data, std::size_t lhs_size,
  1160. const char *rhs_data, std::size_t rhs_size) {
  1161. lhs.assign(lhs_data, lhs_size);
  1162. rhs.assign(rhs_data, rhs_size);
  1163. });
  1164. return std::make_pair(std::move(lhs), std::move(rhs));
  1165. };
  1166. {
  1167. const auto res = divide("", '=');
  1168. EXPECT_EQ(res.first, "");
  1169. EXPECT_EQ(res.second, "");
  1170. }
  1171. {
  1172. const auto res = divide("=", '=');
  1173. EXPECT_EQ(res.first, "");
  1174. EXPECT_EQ(res.second, "");
  1175. }
  1176. {
  1177. const auto res = divide(" ", '=');
  1178. EXPECT_EQ(res.first, " ");
  1179. EXPECT_EQ(res.second, "");
  1180. }
  1181. {
  1182. const auto res = divide("a", '=');
  1183. EXPECT_EQ(res.first, "a");
  1184. EXPECT_EQ(res.second, "");
  1185. }
  1186. {
  1187. const auto res = divide("a=", '=');
  1188. EXPECT_EQ(res.first, "a");
  1189. EXPECT_EQ(res.second, "");
  1190. }
  1191. {
  1192. const auto res = divide("=b", '=');
  1193. EXPECT_EQ(res.first, "");
  1194. EXPECT_EQ(res.second, "b");
  1195. }
  1196. {
  1197. const auto res = divide("a=b", '=');
  1198. EXPECT_EQ(res.first, "a");
  1199. EXPECT_EQ(res.second, "b");
  1200. }
  1201. {
  1202. const auto res = divide("a=b=", '=');
  1203. EXPECT_EQ(res.first, "a");
  1204. EXPECT_EQ(res.second, "b=");
  1205. }
  1206. {
  1207. const auto res = divide("a=b=c", '=');
  1208. EXPECT_EQ(res.first, "a");
  1209. EXPECT_EQ(res.second, "b=c");
  1210. }
  1211. }
  1212. TEST(SplitTest, ParseQueryString) {
  1213. string s = "key1=val1&key2=val2&key3=val3";
  1214. Params dic;
  1215. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1216. [&](const char *b, const char *e) {
  1217. string key, val;
  1218. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1219. if (key.empty()) {
  1220. key.assign(b2, e2);
  1221. } else {
  1222. val.assign(b2, e2);
  1223. }
  1224. });
  1225. dic.emplace(key, val);
  1226. });
  1227. EXPECT_EQ("val1", dic.find("key1")->second);
  1228. EXPECT_EQ("val2", dic.find("key2")->second);
  1229. EXPECT_EQ("val3", dic.find("key3")->second);
  1230. }
  1231. TEST(SplitTest, ParseInvalidQueryTests) {
  1232. {
  1233. string s = " ";
  1234. Params dict;
  1235. detail::parse_query_text(s, dict);
  1236. EXPECT_TRUE(dict.empty());
  1237. }
  1238. {
  1239. string s = " = =";
  1240. Params dict;
  1241. detail::parse_query_text(s, dict);
  1242. EXPECT_TRUE(dict.empty());
  1243. }
  1244. }
  1245. TEST(ParseQueryTest, ParseQueryString) {
  1246. {
  1247. std::string s = "key1=val1&key2=val2&key3=val3";
  1248. Params dic;
  1249. detail::parse_query_text(s, dic);
  1250. EXPECT_EQ("val1", dic.find("key1")->second);
  1251. EXPECT_EQ("val2", dic.find("key2")->second);
  1252. EXPECT_EQ("val3", dic.find("key3")->second);
  1253. }
  1254. {
  1255. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1256. Params dic;
  1257. detail::parse_query_text(s, dic);
  1258. EXPECT_EQ("", dic.find("key1")->second);
  1259. EXPECT_EQ("val1", dic.find("key2")->second);
  1260. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1261. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1262. }
  1263. }
  1264. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1265. Params dic;
  1266. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1267. dic.emplace("key1", "val1");
  1268. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1269. dic.emplace("key2", "val2");
  1270. dic.emplace("key3", "val3");
  1271. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1272. }
  1273. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1274. Params params;
  1275. params.emplace("a", "1");
  1276. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1277. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1278. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1279. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1280. // Long enough to overflow the stack when matched with std::regex.
  1281. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1282. EXPECT_EQ("/p?" + long_query + "&a=1",
  1283. append_query_params("/p?" + long_query, params));
  1284. }
  1285. // Joins every entry of a Headers or Params into "key=value " so a whole
  1286. // traversal can be compared in one assertion. Both are instantiations of the
  1287. // same insertion-ordered container, so one helper serves both.
  1288. template <typename Map> static std::string entries_to_string(const Map &m) {
  1289. std::string s;
  1290. for (const auto &entry : m) {
  1291. s += entry.first + "=" + entry.second + " ";
  1292. }
  1293. return s;
  1294. }
  1295. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1296. // Params used to be a std::multimap, which sorted by name and handed the
  1297. // caller's query back alphabetised. A client signing its query string could
  1298. // not reproduce the order it asked for.
  1299. Params dic;
  1300. dic.emplace("zulu", "1");
  1301. dic.emplace("alpha", "2");
  1302. dic.emplace("mike", "3");
  1303. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1304. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1305. }
  1306. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1307. Params dic;
  1308. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1309. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1310. }
  1311. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1312. Request req;
  1313. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1314. req.params);
  1315. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1316. EXPECT_EQ("first", req.get_param_value("tag"));
  1317. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1318. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1319. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1320. EXPECT_EQ("", req.get_param_value("tag", 3));
  1321. }
  1322. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1323. // Params shares its container with Headers, which matches field names
  1324. // case-insensitively. Parameter names must not pick that up.
  1325. Params dic;
  1326. dic.emplace("Key", "upper");
  1327. dic.emplace("key", "lower");
  1328. EXPECT_EQ(2U, dic.size());
  1329. EXPECT_EQ(1U, dic.count("Key"));
  1330. EXPECT_EQ(1U, dic.count("key"));
  1331. EXPECT_EQ("upper", dic.find("Key")->second);
  1332. EXPECT_EQ("lower", dic.find("key")->second);
  1333. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1334. }
  1335. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1336. Server svr;
  1337. std::string order;
  1338. svr.Get("/order", [&](const Request &req, Response &res) {
  1339. order = entries_to_string(req.params);
  1340. res.set_content("ok", "text/plain");
  1341. });
  1342. auto port = svr.bind_to_any_port(HOST);
  1343. thread t = thread([&] { svr.listen_after_bind(); });
  1344. auto se = detail::scope_exit([&] {
  1345. svr.stop();
  1346. t.join();
  1347. ASSERT_FALSE(svr.is_running());
  1348. });
  1349. svr.wait_until_ready();
  1350. Client cli(HOST, port);
  1351. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1352. ASSERT_TRUE(res);
  1353. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1354. }
  1355. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1356. Server svr;
  1357. std::string field_order, file_order;
  1358. svr.Post("/order", [&](const Request &req, Response &res) {
  1359. for (const auto &field : req.form.fields) {
  1360. field_order += field.first + "=" + field.second.content + " ";
  1361. }
  1362. for (const auto &file : req.form.files) {
  1363. file_order += file.first + "=" + file.second.filename + " ";
  1364. }
  1365. res.set_content("ok", "text/plain");
  1366. });
  1367. auto port = svr.bind_to_any_port(HOST);
  1368. thread t = thread([&] { svr.listen_after_bind(); });
  1369. auto se = detail::scope_exit([&] {
  1370. svr.stop();
  1371. t.join();
  1372. ASSERT_FALSE(svr.is_running());
  1373. });
  1374. svr.wait_until_ready();
  1375. UploadFormDataItems items = {
  1376. {"zulu", "1", "", ""},
  1377. {"alpha", "2", "", ""},
  1378. {"mike", "3", "", ""},
  1379. {"zebra", "z", "z.txt", "text/plain"},
  1380. {"apple", "a", "a.txt", "text/plain"},
  1381. };
  1382. Client cli(HOST, port);
  1383. auto res = cli.Post("/order", items);
  1384. ASSERT_TRUE(res);
  1385. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1386. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1387. }
  1388. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1389. Server svr;
  1390. std::vector<std::string> values;
  1391. std::string first, second, out_of_range, order;
  1392. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1393. values = req.form.get_fields("tag");
  1394. first = req.form.get_field("tag", 0);
  1395. second = req.form.get_field("tag", 1);
  1396. out_of_range = req.form.get_field("tag", 2);
  1397. for (const auto &field : req.form.fields) {
  1398. order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1411. // not adjacent in the container.
  1412. UploadFormDataItems items = {
  1413. {"tag", "first", "", ""},
  1414. {"other", "x", "", ""},
  1415. {"tag", "second", "", ""},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/repeated", items);
  1419. ASSERT_TRUE(res);
  1420. ASSERT_EQ(2U, values.size());
  1421. EXPECT_EQ("first", values[0]);
  1422. EXPECT_EQ("second", values[1]);
  1423. EXPECT_EQ("first", first);
  1424. EXPECT_EQ("second", second);
  1425. // std::multimap already kept entries sharing a name in insertion order, so
  1426. // everything above passes without this change too. The whole traversal is
  1427. // what tells the two apart: sorting by name would hoist "other" to the front
  1428. // and the two "tag" parts would end up adjacent.
  1429. EXPECT_EQ("tag=first other=x tag=second ", order);
  1430. // Advancing past the last entry of a name used to run off the container;
  1431. // the container's saturating increment makes it return the default instead.
  1432. EXPECT_EQ("", out_of_range);
  1433. }
  1434. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1435. // Server::read_content() keeps a FormFields::iterator alive across the
  1436. // content callbacks that fill the part it points at. The container is
  1437. // vector-backed, so a later emplace can reallocate and invalidate an older
  1438. // iterator; 64 parts grow the vector through seven reallocations, which
  1439. // checks that every part's content still lands in its own entry.
  1440. const size_t part_count = 64;
  1441. // One formula for both the parts sent and the values expected back, so the
  1442. // two cannot drift apart.
  1443. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1444. auto content_of = [](size_t i) {
  1445. return std::string(64, static_cast<char>('a' + (i % 26)));
  1446. };
  1447. Server svr;
  1448. std::vector<std::pair<std::string, std::string>> received;
  1449. svr.Post("/many", [&](const Request &req, Response &res) {
  1450. for (const auto &field : req.form.fields) {
  1451. received.emplace_back(field.first, field.second.content);
  1452. }
  1453. res.set_content("ok", "text/plain");
  1454. });
  1455. auto port = svr.bind_to_any_port(HOST);
  1456. thread t = thread([&] { svr.listen_after_bind(); });
  1457. auto se = detail::scope_exit([&] {
  1458. svr.stop();
  1459. t.join();
  1460. ASSERT_FALSE(svr.is_running());
  1461. });
  1462. svr.wait_until_ready();
  1463. UploadFormDataItems items;
  1464. for (size_t i = 0; i < part_count; i++) {
  1465. items.push_back({name_of(i), content_of(i), "", ""});
  1466. }
  1467. Client cli(HOST, port);
  1468. auto res = cli.Post("/many", items);
  1469. ASSERT_TRUE(res);
  1470. ASSERT_EQ(part_count, received.size());
  1471. for (size_t i = 0; i < part_count; i++) {
  1472. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1473. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1474. }
  1475. }
  1476. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1477. string content_type = "multipart/form-data; boundary=something";
  1478. string boundary;
  1479. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1480. EXPECT_TRUE(ret);
  1481. EXPECT_EQ(boundary, "something");
  1482. }
  1483. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1484. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1485. string boundary;
  1486. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1487. EXPECT_TRUE(ret);
  1488. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1489. }
  1490. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1491. string content_type =
  1492. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1493. string boundary;
  1494. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1495. EXPECT_TRUE(ret);
  1496. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1497. }
  1498. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1499. string content_type =
  1500. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1501. string boundary;
  1502. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1503. EXPECT_TRUE(ret);
  1504. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1505. }
  1506. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1507. const string boundary(70, 'a');
  1508. string content_type = "multipart/form-data; boundary=" + boundary;
  1509. string parsed;
  1510. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1511. EXPECT_TRUE(ret);
  1512. EXPECT_EQ(parsed, boundary);
  1513. }
  1514. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1515. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1516. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1517. string parsed;
  1518. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1519. EXPECT_FALSE(ret);
  1520. }
  1521. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1522. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1523. // is 72 characters on the wire and still valid.
  1524. const string boundary(70, 'a');
  1525. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1526. string parsed;
  1527. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1528. EXPECT_EQ(parsed, boundary);
  1529. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1530. parsed.clear();
  1531. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1534. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1535. // The parameter parser must not treat that '=' as the key/value separator.
  1536. string content_type =
  1537. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1538. "charset=UTF-8";
  1539. string parsed;
  1540. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1541. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1542. }
  1543. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1544. // A ';' inside the quoted-string is part of the value, not a parameter
  1545. // separator, so it must not truncate the boundary.
  1546. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1547. string parsed;
  1548. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1549. EXPECT_EQ(parsed, "a;b");
  1550. }
  1551. TEST(ParseDispositionParamsTest, QuotedValues) {
  1552. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1553. // ';' and '=' are ordinary characters inside one.
  1554. struct {
  1555. const char *value;
  1556. std::vector<std::pair<const char *, const char *>> expected;
  1557. } cases[] = {
  1558. {"name=\"file1\"; filename=\"a.txt\"",
  1559. {{"name", "file1"}, {"filename", "a.txt"}}},
  1560. // Whitespace around '=' and ';' is still trimmed
  1561. {"name=\"file2\" ;filename = \"a.html\"",
  1562. {{"name", "file2"}, {"filename", "a.html"}}},
  1563. // '=' inside the value used to leave only the text after the last one
  1564. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1565. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1566. {"name=\"x=y\"", {{"name", "x=y"}}},
  1567. // ';' inside the value used to truncate the pair and leave a bogus one
  1568. {"name=\"file3\"; filename=\"a;b.txt\"",
  1569. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1570. // An unquoted value keeps working, and so does filename*
  1571. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1572. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1573. // A parameter with no key is dropped rather than turned into one whose
  1574. // key is the value
  1575. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1576. // An escaped quote does not end the value
  1577. {"name=\"a\\\"; filename=evil.php\"",
  1578. {{"name", "a\"; filename=evil.php"}}},
  1579. // Other backslashes, as in a Windows path, are kept
  1580. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1581. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1582. };
  1583. for (const auto &c : cases) {
  1584. Params params;
  1585. detail::parse_disposition_params(c.value, params);
  1586. for (const auto &kv : c.expected) {
  1587. auto it = params.find(kv.first);
  1588. ASSERT_NE(it, params.end())
  1589. << "value: " << c.value << ", key: " << kv.first;
  1590. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1591. }
  1592. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1593. }
  1594. }
  1595. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1596. Server svr;
  1597. std::string filename;
  1598. std::string content;
  1599. svr.Post("/upload", [&](const Request &req, Response &) {
  1600. const auto &file = req.form.get_file("file");
  1601. filename = file.filename;
  1602. content = file.content;
  1603. });
  1604. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1605. auto se = detail::scope_exit([&] {
  1606. svr.stop();
  1607. thread.join();
  1608. ASSERT_FALSE(svr.is_running());
  1609. });
  1610. svr.wait_until_ready();
  1611. std::string body = "--B\r\n"
  1612. "Content-Disposition: form-data; name=\"file\"; "
  1613. "filename=\"a.txt\"\r\n"
  1614. "Content-Type: text/plain\r\n"
  1615. "\r\n"
  1616. "hello\r\n"
  1617. "--B--\r\n";
  1618. Client cli(HOST, PORT);
  1619. auto res = cli.Post(
  1620. "/upload",
  1621. [&](size_t offset, DataSink &sink) {
  1622. if (offset < body.size()) {
  1623. sink.write(&body[offset], 1);
  1624. } else {
  1625. sink.done();
  1626. }
  1627. return true;
  1628. },
  1629. "multipart/form-data; boundary=B");
  1630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1631. EXPECT_EQ(StatusCode::OK_200, res->status);
  1632. EXPECT_EQ("a.txt", filename);
  1633. EXPECT_EQ("hello", content);
  1634. }
  1635. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1636. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1637. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1638. Server svr;
  1639. std::string field_value, file_name, file_filename;
  1640. bool has_field = false, has_file = false;
  1641. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1642. has_field = req.form.has_field("x=y");
  1643. field_value = req.form.get_field("x=y");
  1644. has_file = req.form.has_file("file1");
  1645. const auto &file = req.form.get_file("file1");
  1646. file_name = file.name;
  1647. file_filename = file.filename;
  1648. res.set_content("ok", "text/plain");
  1649. });
  1650. auto port = svr.bind_to_any_port(HOST);
  1651. thread t = thread([&] { svr.listen_after_bind(); });
  1652. auto se = detail::scope_exit([&] {
  1653. svr.stop();
  1654. t.join();
  1655. ASSERT_FALSE(svr.is_running());
  1656. });
  1657. svr.wait_until_ready();
  1658. UploadFormDataItems items = {
  1659. {"x=y", "field-value", "", ""},
  1660. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1661. };
  1662. Client cli(HOST, port);
  1663. auto res = cli.Post("/quoted", items);
  1664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1665. ASSERT_EQ(StatusCode::OK_200, res->status);
  1666. EXPECT_TRUE(has_field);
  1667. EXPECT_EQ("field-value", field_value);
  1668. EXPECT_TRUE(has_file);
  1669. EXPECT_EQ("file1", file_name);
  1670. EXPECT_EQ("a;b=report.pdf", file_filename);
  1671. }
  1672. TEST(GetHeaderValueTest, DefaultValue) {
  1673. Headers headers = {{"Dummy", "Dummy"}};
  1674. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1675. EXPECT_STREQ("text/plain", val);
  1676. }
  1677. TEST(GetHeaderValueTest, DefaultValueInt) {
  1678. Headers headers = {{"Dummy", "Dummy"}};
  1679. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1680. EXPECT_EQ(100ull, val);
  1681. }
  1682. TEST(GetHeaderValueTest, RegularValue) {
  1683. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1684. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1685. EXPECT_STREQ("text/html", val);
  1686. }
  1687. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1688. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1689. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1690. EXPECT_STREQ("text/html", val);
  1691. }
  1692. TEST(GetHeaderValueTest, SetContent) {
  1693. Response res;
  1694. res.set_content("html", "text/html");
  1695. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1696. res.set_content("text", "text/plain");
  1697. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1698. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1699. }
  1700. TEST(GetHeaderValueTest, RegularValueInt) {
  1701. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1702. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1703. EXPECT_EQ(100ull, val);
  1704. }
  1705. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1706. Headers headers = {{"Content-Length", "x"}};
  1707. auto is_invalid_value = false;
  1708. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1709. is_invalid_value);
  1710. EXPECT_EQ(0ull, val);
  1711. EXPECT_TRUE(is_invalid_value);
  1712. }
  1713. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1714. // An all-digit value that overflows size_t must be reported as invalid, not
  1715. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1716. // a large length to a small one on 32-bit builds, leaving the framing length
  1717. // wrong while is_invalid_value stayed false.
  1718. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1719. auto is_invalid_value = false;
  1720. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1721. is_invalid_value);
  1722. EXPECT_TRUE(is_invalid_value);
  1723. // A well-formed length is unaffected.
  1724. Headers ok = {{"Content-Length", "1234"}};
  1725. is_invalid_value = false;
  1726. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1727. is_invalid_value);
  1728. EXPECT_EQ(1234ull, val);
  1729. EXPECT_FALSE(is_invalid_value);
  1730. }
  1731. TEST(GetHeaderValueTest, Range) {
  1732. {
  1733. Headers headers = {make_range_header({{1, -1}})};
  1734. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1735. EXPECT_STREQ("bytes=1-", val);
  1736. }
  1737. {
  1738. Headers headers = {make_range_header({{-1, 1}})};
  1739. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1740. EXPECT_STREQ("bytes=-1", val);
  1741. }
  1742. {
  1743. Headers headers = {make_range_header({{1, 10}})};
  1744. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1745. EXPECT_STREQ("bytes=1-10", val);
  1746. }
  1747. {
  1748. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1749. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1750. EXPECT_STREQ("bytes=1-10, 100-", val);
  1751. }
  1752. {
  1753. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1754. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1755. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1756. }
  1757. {
  1758. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1759. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1760. EXPECT_STREQ("bytes=0-0, -1", val);
  1761. }
  1762. }
  1763. TEST(BearerTokenAuthTest, SchemeValidation) {
  1764. // A value shorter than "Bearer " must not throw from the fixed-length
  1765. // substr, and a non-Bearer scheme must not be reported as a token.
  1766. struct {
  1767. const char *value;
  1768. const char *expected;
  1769. } cases[] = {
  1770. {"x", ""},
  1771. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1772. {"Bearer abc123", "abc123"},
  1773. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1774. };
  1775. for (const auto &c : cases) {
  1776. Request req;
  1777. req.set_header("Authorization", c.value);
  1778. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1779. }
  1780. }
  1781. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1782. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1783. // to depend on the standard library (libstdc++ handed back duplicates in
  1784. // reverse insertion order, libc++ in insertion order).
  1785. Request req;
  1786. req.set_header("Accept-Encoding", "gzip");
  1787. req.set_header("Accept-Encoding", "deflate");
  1788. req.set_header("Accept-Encoding", "br");
  1789. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1790. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1791. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1792. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1793. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1794. }
  1795. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1796. Request req;
  1797. req.set_header("X-Test", "only");
  1798. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1799. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1800. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1801. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1802. }
  1803. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1804. Request req;
  1805. req.set_header("X-First", "1");
  1806. req.set_header("X-Test", "2");
  1807. req.params.emplace("first", "1");
  1808. req.params.emplace("test", "2");
  1809. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1810. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1811. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1812. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1813. // The second one is negative when read as a signed value
  1814. const auto max_id = (std::numeric_limits<size_t>::max)();
  1815. for (auto id : {max_id / 2, max_id}) {
  1816. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1817. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1818. EXPECT_EQ("", req.get_param_value("test", id));
  1819. EXPECT_EQ("", req.form.get_field("test", id));
  1820. EXPECT_EQ("", req.form.get_file("test", id).content);
  1821. }
  1822. }
  1823. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1824. Headers headers;
  1825. headers.emplace("Host", "example.com");
  1826. headers.emplace("Accept-Encoding", "gzip");
  1827. headers.emplace("User-Agent", "test");
  1828. headers.emplace("Accept-Encoding", "deflate");
  1829. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1830. "Accept-Encoding=deflate ",
  1831. entries_to_string(headers));
  1832. }
  1833. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1834. Headers headers = {{"Content-Type", "text/html"},
  1835. {"CONTENT-TYPE", "text/xml"}};
  1836. EXPECT_EQ(2U, headers.count("content-type"));
  1837. auto it = headers.find("content-type");
  1838. ASSERT_TRUE(it != headers.end());
  1839. EXPECT_EQ("text/html", it->second);
  1840. }
  1841. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1842. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1843. // drop only those fields and leave everything positioned between them.
  1844. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1845. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1846. auto rng = headers.equal_range("a");
  1847. headers.erase(rng.first, rng.second);
  1848. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1849. }
  1850. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1851. Headers headers = {
  1852. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1853. EXPECT_EQ(3U, headers.erase("A"));
  1854. EXPECT_EQ(0U, headers.count("A"));
  1855. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1856. }
  1857. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1858. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1859. headers.emplace_front("Host", "example.com");
  1860. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1861. entries_to_string(headers));
  1862. }
  1863. TEST(ParseHeaderValueTest, Range) {
  1864. {
  1865. Ranges ranges;
  1866. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1867. EXPECT_TRUE(ret);
  1868. EXPECT_EQ(1u, ranges.size());
  1869. EXPECT_EQ(1u, ranges[0].first);
  1870. EXPECT_EQ(-1, ranges[0].second);
  1871. }
  1872. {
  1873. Ranges ranges;
  1874. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1875. EXPECT_TRUE(ret);
  1876. EXPECT_EQ(1u, ranges.size());
  1877. EXPECT_EQ(-1, ranges[0].first);
  1878. EXPECT_EQ(1u, ranges[0].second);
  1879. }
  1880. {
  1881. Ranges ranges;
  1882. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1883. EXPECT_TRUE(ret);
  1884. EXPECT_EQ(1u, ranges.size());
  1885. EXPECT_EQ(1u, ranges[0].first);
  1886. EXPECT_EQ(10u, ranges[0].second);
  1887. }
  1888. {
  1889. Ranges ranges;
  1890. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1891. EXPECT_FALSE(ret);
  1892. }
  1893. {
  1894. Ranges ranges;
  1895. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1896. EXPECT_TRUE(ret);
  1897. EXPECT_EQ(2u, ranges.size());
  1898. EXPECT_EQ(1u, ranges[0].first);
  1899. EXPECT_EQ(10u, ranges[0].second);
  1900. EXPECT_EQ(100u, ranges[1].first);
  1901. EXPECT_EQ(-1, ranges[1].second);
  1902. }
  1903. {
  1904. Ranges ranges;
  1905. auto ret =
  1906. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1907. EXPECT_TRUE(ret);
  1908. EXPECT_EQ(3u, ranges.size());
  1909. EXPECT_EQ(1u, ranges[0].first);
  1910. EXPECT_EQ(10u, ranges[0].second);
  1911. EXPECT_EQ(100u, ranges[1].first);
  1912. EXPECT_EQ(200u, ranges[1].second);
  1913. EXPECT_EQ(300u, ranges[2].first);
  1914. EXPECT_EQ(400u, ranges[2].second);
  1915. }
  1916. {
  1917. Ranges ranges;
  1918. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1919. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1920. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1921. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1922. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1923. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1924. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1925. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1926. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1927. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1928. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1929. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1930. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1931. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1932. EXPECT_FALSE(
  1933. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1934. EXPECT_TRUE(ranges.empty());
  1935. }
  1936. {
  1937. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1938. // remainder of the representation, so it stays accepted.
  1939. Ranges ranges;
  1940. auto ret =
  1941. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1942. EXPECT_TRUE(ret);
  1943. ASSERT_EQ(1u, ranges.size());
  1944. EXPECT_EQ(0, ranges[0].first);
  1945. EXPECT_EQ(-1, ranges[0].second);
  1946. }
  1947. // RFC 9110 14.1: range unit names are case-insensitive.
  1948. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1949. Ranges ranges;
  1950. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1951. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1952. }
  1953. }
  1954. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1955. Request req;
  1956. req.set_header("Accept-Encoding", "gzip");
  1957. Response res;
  1958. res.set_header("Content-Type", "text/plain");
  1959. auto ret = detail::encoding_type(req, res);
  1960. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1961. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1962. #else
  1963. EXPECT_TRUE(ret == detail::EncodingType::None);
  1964. #endif
  1965. }
  1966. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1967. Request req;
  1968. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1969. Response res;
  1970. res.set_header("Content-Type", "text/plain");
  1971. auto ret = detail::encoding_type(req, res);
  1972. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1973. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1974. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1975. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1976. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1977. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1978. #else
  1979. EXPECT_TRUE(ret == detail::EncodingType::None);
  1980. #endif
  1981. }
  1982. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1983. Request req;
  1984. req.set_header("Accept-Encoding",
  1985. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1986. Response res;
  1987. res.set_header("Content-Type", "text/plain");
  1988. auto ret = detail::encoding_type(req, res);
  1989. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1990. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1991. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1992. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1993. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1994. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1995. #else
  1996. EXPECT_TRUE(ret == detail::EncodingType::None);
  1997. #endif
  1998. }
  1999. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2000. // All supported encodings rejected with q=0 should return None
  2001. Request req;
  2002. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2003. Response res;
  2004. res.set_header("Content-Type", "text/plain");
  2005. auto ret = detail::encoding_type(req, res);
  2006. EXPECT_TRUE(ret == detail::EncodingType::None);
  2007. }
  2008. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2009. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2010. Request req;
  2011. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2012. Response res;
  2013. res.set_header("Content-Type", "text/plain");
  2014. auto ret = detail::encoding_type(req, res);
  2015. EXPECT_TRUE(ret == detail::EncodingType::None);
  2016. }
  2017. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2018. Request req;
  2019. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2020. Response res;
  2021. res.set_header("Content-Type", "text/plain");
  2022. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2023. }
  2024. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2025. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. EXPECT_TRUE(ret == detail::EncodingType::None);
  2032. }
  2033. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2034. // RFC 7231: Accept-Encoding values are case-insensitive
  2035. Request req;
  2036. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2037. Response res;
  2038. res.set_header("Content-Type", "text/plain");
  2039. auto ret = detail::encoding_type(req, res);
  2040. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2041. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2042. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2043. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2044. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2046. #else
  2047. EXPECT_TRUE(ret == detail::EncodingType::None);
  2048. #endif
  2049. }
  2050. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2051. // q value should determine priority, not hardcoded order
  2052. Request req;
  2053. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2054. Response res;
  2055. res.set_header("Content-Type", "text/plain");
  2056. auto ret = detail::encoding_type(req, res);
  2057. // gzip has highest q=1.0, so it should be selected even though
  2058. // br and zstd are also supported
  2059. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2060. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2061. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2063. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2065. #else
  2066. EXPECT_TRUE(ret == detail::EncodingType::None);
  2067. #endif
  2068. }
  2069. TEST(BufferStreamTest, read) {
  2070. detail::BufferStream strm1;
  2071. Stream &strm = strm1;
  2072. EXPECT_EQ(5, strm.write("hello"));
  2073. char buf[512];
  2074. EXPECT_EQ(2, strm.read(buf, 2));
  2075. EXPECT_EQ('h', buf[0]);
  2076. EXPECT_EQ('e', buf[1]);
  2077. EXPECT_EQ(2, strm.read(buf, 2));
  2078. EXPECT_EQ('l', buf[0]);
  2079. EXPECT_EQ('l', buf[1]);
  2080. EXPECT_EQ(1, strm.read(buf, 1));
  2081. EXPECT_EQ('o', buf[0]);
  2082. EXPECT_EQ(0, strm.read(buf, 1));
  2083. }
  2084. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2085. auto host = "www.httpwatch.com";
  2086. auto ip = hosted_at(host);
  2087. EXPECT_EQ("23.96.13.243", ip);
  2088. std::vector<std::string> addrs;
  2089. hosted_at(host, addrs);
  2090. EXPECT_EQ(1u, addrs.size());
  2091. }
  2092. #if 0 // It depends on each test environment...
  2093. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2094. auto host = "www.youtube.com";
  2095. std::vector<std::string> addrs;
  2096. hosted_at(host, addrs);
  2097. EXPECT_EQ(20u, addrs.size());
  2098. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2099. EXPECT_TRUE(it != addrs.end());
  2100. }
  2101. #endif
  2102. class ChunkedEncodingTest : public ::testing::Test {
  2103. protected:
  2104. ChunkedEncodingTest()
  2105. : cli_(HOST, PORT)
  2106. #ifdef CPPHTTPLIB_SSL_ENABLED
  2107. ,
  2108. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2109. #endif
  2110. {
  2111. cli_.set_connection_timeout(2);
  2112. #ifdef CPPHTTPLIB_SSL_ENABLED
  2113. cli_.enable_server_certificate_verification(false);
  2114. #endif
  2115. }
  2116. virtual void SetUp() {
  2117. read_file("./image.jpg", image_data_);
  2118. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2119. res.set_content("Hello World!", "text/plain");
  2120. });
  2121. svr_.Get(
  2122. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2123. res.set_chunked_content_provider(
  2124. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2125. size_t remaining = image_data_.size() - offset;
  2126. if (remaining == 0) {
  2127. sink.done();
  2128. } else {
  2129. constexpr size_t CHUNK_SIZE = 1024;
  2130. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2131. sink.write(&image_data_[offset], send_size);
  2132. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2133. }
  2134. return true;
  2135. });
  2136. });
  2137. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2138. svr_.wait_until_ready();
  2139. }
  2140. virtual void TearDown() {
  2141. svr_.stop();
  2142. if (!request_threads_.empty()) {
  2143. std::this_thread::sleep_for(std::chrono::seconds(1));
  2144. for (auto &t : request_threads_) {
  2145. t.join();
  2146. }
  2147. }
  2148. t_.join();
  2149. }
  2150. #ifdef CPPHTTPLIB_SSL_ENABLED
  2151. SSLClient cli_;
  2152. SSLServer svr_;
  2153. #else
  2154. Client cli_;
  2155. Server svr_;
  2156. #endif
  2157. thread t_;
  2158. std::vector<thread> request_threads_;
  2159. std::string image_data_;
  2160. };
  2161. TEST_F(ChunkedEncodingTest, NormalGet) {
  2162. auto res = cli_.Get("/chunked");
  2163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2164. std::string out;
  2165. read_file("./image.jpg", out);
  2166. EXPECT_EQ(StatusCode::OK_200, res->status);
  2167. EXPECT_EQ(out, res->body);
  2168. }
  2169. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2170. std::string body;
  2171. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2172. body.append(data, data_length);
  2173. return true;
  2174. });
  2175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2176. std::string out;
  2177. read_file("./image.jpg", out);
  2178. EXPECT_EQ(StatusCode::OK_200, res->status);
  2179. EXPECT_EQ(out, body);
  2180. }
  2181. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2182. std::string body;
  2183. auto res = cli_.Get(
  2184. "/chunked",
  2185. [&](const Response &response) {
  2186. EXPECT_EQ(StatusCode::OK_200, response.status);
  2187. return true;
  2188. },
  2189. [&](const char *data, size_t data_length) {
  2190. body.append(data, data_length);
  2191. return true;
  2192. });
  2193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2194. std::string out;
  2195. read_file("./image.jpg", out);
  2196. EXPECT_EQ(StatusCode::OK_200, res->status);
  2197. EXPECT_EQ(out, body);
  2198. }
  2199. TEST(RangeTest, FromHTTPBin_Online) {
  2200. auto host = "httpbingo.org";
  2201. auto path = std::string{"/range/32"};
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. auto port = 443;
  2204. SSLClient cli(host, port);
  2205. #else
  2206. auto port = 80;
  2207. Client cli(host, port);
  2208. #endif
  2209. cli.set_connection_timeout(5);
  2210. {
  2211. auto res = cli.Get(path);
  2212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2213. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2214. EXPECT_EQ(StatusCode::OK_200, res->status);
  2215. }
  2216. {
  2217. Headers headers = {make_range_header({{1, -1}})};
  2218. auto res = cli.Get(path, headers);
  2219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2220. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2222. }
  2223. {
  2224. Headers headers = {make_range_header({{1, 10}})};
  2225. auto res = cli.Get(path, headers);
  2226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2227. EXPECT_EQ("bcdefghijk", res->body);
  2228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2229. }
  2230. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2231. // entire resource, while the original httpbin returned 200. Both are
  2232. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2233. {
  2234. Headers headers = {make_range_header({{0, 31}})};
  2235. auto res = cli.Get(path, headers);
  2236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2237. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2238. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2239. res->status == StatusCode::PartialContent_206);
  2240. }
  2241. {
  2242. Headers headers = {make_range_header({{0, -1}})};
  2243. auto res = cli.Get(path, headers);
  2244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2245. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2246. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2247. res->status == StatusCode::PartialContent_206);
  2248. }
  2249. // go-httpbin returns 206 with clamped range for over-range requests,
  2250. // while the original httpbin returned 416. Both behaviors are observed
  2251. // in real servers, so we only verify the request succeeds.
  2252. {
  2253. Headers headers = {make_range_header({{0, 32}})};
  2254. auto res = cli.Get(path, headers);
  2255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2256. }
  2257. }
  2258. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2259. auto host = "unresolvableaddress.local";
  2260. auto path = std::string{"/"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(1);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_FALSE(res);
  2272. }
  2273. std::this_thread::sleep_for(std::chrono::seconds(8));
  2274. }
  2275. #if defined(__linux__) && defined(__GLIBC__) && \
  2276. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2277. // Forward declaration: in split builds split.py strips `inline` and moves the
  2278. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2279. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2280. // against the symbol in both header-only and split builds.
  2281. namespace httplib {
  2282. namespace detail {
  2283. int getaddrinfo_with_timeout(const char *node, const char *service,
  2284. const struct addrinfo *hints,
  2285. struct addrinfo **res, time_t timeout_sec);
  2286. } // namespace detail
  2287. } // namespace httplib
  2288. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2289. //
  2290. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2291. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2292. // gai_suspend() call hits the connection timeout the function calls
  2293. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2294. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2295. // still alive and still references the now-destroyed stack frame.
  2296. //
  2297. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2298. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2299. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2300. // and runs them in a container.
  2301. namespace {
  2302. bool should_run_issue_2431_tests() {
  2303. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2304. return v && *v && std::string(v) != "0";
  2305. }
  2306. std::string unique_unresolvable_host(int n) {
  2307. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2308. // glibc still asks the configured nameserver — which is exactly the path
  2309. // we want to exercise. A unique label per call avoids the resolver cache.
  2310. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2311. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2312. std::to_string(n) + ".invalid";
  2313. }
  2314. } // namespace
  2315. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2316. if (!should_run_issue_2431_tests()) {
  2317. GTEST_SKIP()
  2318. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2319. }
  2320. for (int i = 0; i < 8; ++i) {
  2321. struct addrinfo hints;
  2322. memset(&hints, 0, sizeof(hints));
  2323. hints.ai_family = AF_UNSPEC;
  2324. hints.ai_socktype = SOCK_STREAM;
  2325. auto host = unique_unresolvable_host(i);
  2326. struct addrinfo *result = nullptr;
  2327. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2328. &result, /*timeout_sec=*/1);
  2329. if (rc == 0 && result) { freeaddrinfo(result); }
  2330. }
  2331. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2332. // stack region they still believe holds their gaicb.
  2333. std::this_thread::sleep_for(std::chrono::seconds(3));
  2334. }
  2335. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2336. if (!should_run_issue_2431_tests()) {
  2337. GTEST_SKIP()
  2338. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2339. }
  2340. std::atomic<bool> stop{false};
  2341. std::vector<std::thread> threads;
  2342. for (int t = 0; t < 8; ++t) {
  2343. threads.emplace_back([t, &stop] {
  2344. int i = 0;
  2345. while (!stop.load(std::memory_order_relaxed)) {
  2346. struct addrinfo hints;
  2347. memset(&hints, 0, sizeof(hints));
  2348. hints.ai_family = AF_UNSPEC;
  2349. hints.ai_socktype = SOCK_STREAM;
  2350. auto host = unique_unresolvable_host(t * 100000 + i++);
  2351. struct addrinfo *result = nullptr;
  2352. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2353. &result, /*timeout_sec=*/1);
  2354. if (rc == 0 && result) { freeaddrinfo(result); }
  2355. }
  2356. });
  2357. }
  2358. std::this_thread::sleep_for(std::chrono::seconds(8));
  2359. stop.store(true, std::memory_order_relaxed);
  2360. for (auto &th : threads) {
  2361. th.join();
  2362. }
  2363. std::this_thread::sleep_for(std::chrono::seconds(3));
  2364. }
  2365. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2366. if (!should_run_issue_2431_tests()) {
  2367. GTEST_SKIP()
  2368. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2369. }
  2370. std::atomic<bool> stop{false};
  2371. std::vector<std::thread> threads;
  2372. for (int t = 0; t < 8; ++t) {
  2373. threads.emplace_back([t, &stop] {
  2374. int i = 0;
  2375. while (!stop.load(std::memory_order_relaxed)) {
  2376. auto host = unique_unresolvable_host(t * 100000 + i++);
  2377. Client cli(host, 80);
  2378. cli.set_connection_timeout(1, 0);
  2379. cli.set_read_timeout(1, 0);
  2380. cli.set_write_timeout(1, 0);
  2381. (void)cli.Get("/");
  2382. }
  2383. });
  2384. }
  2385. std::this_thread::sleep_for(std::chrono::seconds(8));
  2386. stop.store(true, std::memory_order_relaxed);
  2387. for (auto &th : threads) {
  2388. th.join();
  2389. }
  2390. std::this_thread::sleep_for(std::chrono::seconds(3));
  2391. }
  2392. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2393. TEST(ConnectionErrorTest, InvalidHost) {
  2394. auto host = "-abcde.com";
  2395. #ifdef CPPHTTPLIB_SSL_ENABLED
  2396. auto port = 443;
  2397. SSLClient cli(host, port);
  2398. #else
  2399. auto port = 80;
  2400. Client cli(host, port);
  2401. #endif
  2402. cli.set_connection_timeout(std::chrono::seconds(2));
  2403. auto res = cli.Get("/");
  2404. ASSERT_TRUE(!res);
  2405. EXPECT_EQ(Error::Connection, res.error());
  2406. }
  2407. TEST(ConnectionErrorTest, InvalidHost2) {
  2408. auto host = "httpcan.org/";
  2409. #ifdef CPPHTTPLIB_SSL_ENABLED
  2410. SSLClient cli(host);
  2411. #else
  2412. Client cli(host);
  2413. #endif
  2414. cli.set_connection_timeout(std::chrono::seconds(2));
  2415. auto res = cli.Get("/");
  2416. ASSERT_TRUE(!res);
  2417. EXPECT_EQ(Error::Connection, res.error());
  2418. }
  2419. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2420. auto host = "httpcan.org/";
  2421. #ifdef CPPHTTPLIB_SSL_ENABLED
  2422. SSLClient cli(host);
  2423. #else
  2424. Client cli(host);
  2425. #endif
  2426. cli.set_connection_timeout(std::chrono::seconds(2));
  2427. auto res = cli.Get("/");
  2428. ASSERT_TRUE(!res);
  2429. stringstream s;
  2430. s << "error code: " << res.error();
  2431. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2432. }
  2433. TEST(ConnectionErrorTest, InvalidPort) {
  2434. auto host = "localhost";
  2435. auto port = 44380;
  2436. #ifdef CPPHTTPLIB_SSL_ENABLED
  2437. SSLClient cli(host, port);
  2438. #else
  2439. Client cli(host, port);
  2440. #endif
  2441. cli.set_connection_timeout(std::chrono::seconds(2));
  2442. auto res = cli.Get("/");
  2443. ASSERT_TRUE(!res);
  2444. EXPECT_TRUE(Error::Connection == res.error() ||
  2445. Error::ConnectionTimeout == res.error());
  2446. }
  2447. TEST(ConnectionErrorTest, Timeout_Online) {
  2448. auto host = "google.com";
  2449. #ifdef CPPHTTPLIB_SSL_ENABLED
  2450. auto port = 44380;
  2451. SSLClient cli(host, port);
  2452. #else
  2453. auto port = 8080;
  2454. Client cli(host, port);
  2455. #endif
  2456. cli.set_connection_timeout(std::chrono::seconds(2));
  2457. // only probe one address type so that the error reason
  2458. // correlates to the timed-out IPv4, not the unsupported
  2459. // IPv6 connection attempt
  2460. cli.set_address_family(AF_INET);
  2461. auto res = cli.Get("/");
  2462. ASSERT_TRUE(!res);
  2463. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2464. }
  2465. TEST(CancelTest, NoCancel_Online) {
  2466. auto host = "httpbingo.org";
  2467. auto path = std::string{"/range/32"};
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. auto port = 443;
  2470. SSLClient cli(host, port);
  2471. #else
  2472. auto port = 80;
  2473. Client cli(host, port);
  2474. #endif
  2475. cli.set_connection_timeout(std::chrono::seconds(5));
  2476. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2478. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2479. EXPECT_EQ(StatusCode::OK_200, res->status);
  2480. }
  2481. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2482. // Use /bytes with a large payload so that the DownloadProgress callback
  2483. // (which only fires for Content-Length responses) is invoked before the
  2484. // entire body is received, giving cancellation a chance to fire.
  2485. auto host = "httpbingo.org";
  2486. auto path = std::string{"/bytes/524288"};
  2487. #ifdef CPPHTTPLIB_SSL_ENABLED
  2488. auto port = 443;
  2489. SSLClient cli(host, port);
  2490. #else
  2491. auto port = 80;
  2492. Client cli(host, port);
  2493. #endif
  2494. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2495. cli.set_connection_timeout(std::chrono::seconds(5));
  2496. ASSERT_TRUE(!res);
  2497. EXPECT_EQ(Error::Canceled, res.error());
  2498. }
  2499. TEST(CancelTest, WithCancelLargePayload_Online) {
  2500. auto host = "httpbingo.org";
  2501. auto path = std::string{"/bytes/524288"};
  2502. #ifdef CPPHTTPLIB_SSL_ENABLED
  2503. auto port = 443;
  2504. SSLClient cli(host, port);
  2505. #else
  2506. auto port = 80;
  2507. Client cli(host, port);
  2508. #endif
  2509. cli.set_connection_timeout(std::chrono::seconds(5));
  2510. uint32_t count = 0;
  2511. auto res =
  2512. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2513. ASSERT_TRUE(!res);
  2514. EXPECT_EQ(Error::Canceled, res.error());
  2515. }
  2516. TEST(CancelTest, NoCancelPost) {
  2517. Server svr;
  2518. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2519. res.set_content("Hello World!", "text/plain");
  2520. });
  2521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2522. auto se = detail::scope_exit([&] {
  2523. svr.stop();
  2524. thread.join();
  2525. ASSERT_FALSE(svr.is_running());
  2526. });
  2527. svr.wait_until_ready();
  2528. Client cli(HOST, PORT);
  2529. cli.set_connection_timeout(std::chrono::seconds(5));
  2530. auto res =
  2531. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2532. "application/json", [](uint64_t, uint64_t) { return true; });
  2533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2534. EXPECT_EQ("Hello World!", res->body);
  2535. EXPECT_EQ(StatusCode::OK_200, res->status);
  2536. }
  2537. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2538. Server svr;
  2539. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2540. res.set_content("Hello World!", "text/plain");
  2541. });
  2542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2543. auto se = detail::scope_exit([&] {
  2544. svr.stop();
  2545. thread.join();
  2546. ASSERT_FALSE(svr.is_running());
  2547. });
  2548. svr.wait_until_ready();
  2549. Client cli(HOST, PORT);
  2550. cli.set_connection_timeout(std::chrono::seconds(5));
  2551. auto res =
  2552. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2553. "application/json", [](uint64_t, uint64_t) { return false; });
  2554. ASSERT_TRUE(!res);
  2555. EXPECT_EQ(Error::Canceled, res.error());
  2556. }
  2557. TEST(CancelTest, WithCancelLargePayloadPost) {
  2558. Server svr;
  2559. svr.set_payload_max_length(200 * 1024 * 1024);
  2560. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2561. res.set_content(LARGE_DATA, "text/plain");
  2562. });
  2563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2564. auto se = detail::scope_exit([&] {
  2565. svr.stop();
  2566. thread.join();
  2567. ASSERT_FALSE(svr.is_running());
  2568. });
  2569. svr.wait_until_ready();
  2570. Client cli(HOST, PORT);
  2571. cli.set_payload_max_length(200 * 1024 * 1024);
  2572. cli.set_connection_timeout(std::chrono::seconds(5));
  2573. auto res =
  2574. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2575. "application/json", [](uint64_t, uint64_t) { return false; });
  2576. ASSERT_TRUE(!res);
  2577. EXPECT_EQ(Error::Canceled, res.error());
  2578. }
  2579. TEST(CancelTest, NoCancelPut) {
  2580. Server svr;
  2581. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2582. res.set_content("Hello World!", "text/plain");
  2583. });
  2584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2585. auto se = detail::scope_exit([&] {
  2586. svr.stop();
  2587. thread.join();
  2588. ASSERT_FALSE(svr.is_running());
  2589. });
  2590. svr.wait_until_ready();
  2591. Client cli(HOST, PORT);
  2592. cli.set_connection_timeout(std::chrono::seconds(5));
  2593. auto res =
  2594. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2595. "application/json", [](uint64_t, uint64_t) { return true; });
  2596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2597. EXPECT_EQ("Hello World!", res->body);
  2598. EXPECT_EQ(StatusCode::OK_200, res->status);
  2599. }
  2600. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2601. Server svr;
  2602. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2603. res.set_content("Hello World!", "text/plain");
  2604. });
  2605. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2606. auto se = detail::scope_exit([&] {
  2607. svr.stop();
  2608. thread.join();
  2609. ASSERT_FALSE(svr.is_running());
  2610. });
  2611. svr.wait_until_ready();
  2612. Client cli(HOST, PORT);
  2613. cli.set_connection_timeout(std::chrono::seconds(5));
  2614. auto res =
  2615. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2616. "application/json", [](uint64_t, uint64_t) { return false; });
  2617. ASSERT_TRUE(!res);
  2618. EXPECT_EQ(Error::Canceled, res.error());
  2619. }
  2620. TEST(CancelTest, WithCancelLargePayloadPut) {
  2621. Server svr;
  2622. svr.set_payload_max_length(200 * 1024 * 1024);
  2623. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2624. res.set_content(LARGE_DATA, "text/plain");
  2625. });
  2626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2627. auto se = detail::scope_exit([&] {
  2628. svr.stop();
  2629. thread.join();
  2630. ASSERT_FALSE(svr.is_running());
  2631. });
  2632. svr.wait_until_ready();
  2633. Client cli(HOST, PORT);
  2634. cli.set_payload_max_length(200 * 1024 * 1024);
  2635. cli.set_connection_timeout(std::chrono::seconds(5));
  2636. auto res =
  2637. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2638. "application/json", [](uint64_t, uint64_t) { return false; });
  2639. ASSERT_TRUE(!res);
  2640. EXPECT_EQ(Error::Canceled, res.error());
  2641. }
  2642. TEST(CancelTest, NoCancelPatch) {
  2643. Server svr;
  2644. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2645. res.set_content("Hello World!", "text/plain");
  2646. });
  2647. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2648. auto se = detail::scope_exit([&] {
  2649. svr.stop();
  2650. thread.join();
  2651. ASSERT_FALSE(svr.is_running());
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, PORT);
  2655. cli.set_connection_timeout(std::chrono::seconds(5));
  2656. auto res =
  2657. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2658. "application/json", [](uint64_t, uint64_t) { return true; });
  2659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2660. EXPECT_EQ("Hello World!", res->body);
  2661. EXPECT_EQ(StatusCode::OK_200, res->status);
  2662. }
  2663. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2664. Server svr;
  2665. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2666. res.set_content("Hello World!", "text/plain");
  2667. });
  2668. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2669. auto se = detail::scope_exit([&] {
  2670. svr.stop();
  2671. thread.join();
  2672. ASSERT_FALSE(svr.is_running());
  2673. });
  2674. svr.wait_until_ready();
  2675. Client cli(HOST, PORT);
  2676. cli.set_connection_timeout(std::chrono::seconds(5));
  2677. auto res =
  2678. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2679. "application/json", [](uint64_t, uint64_t) { return false; });
  2680. ASSERT_TRUE(!res);
  2681. EXPECT_EQ(Error::Canceled, res.error());
  2682. }
  2683. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2684. Server svr;
  2685. svr.set_payload_max_length(200 * 1024 * 1024);
  2686. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2687. res.set_content(LARGE_DATA, "text/plain");
  2688. });
  2689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2690. auto se = detail::scope_exit([&] {
  2691. svr.stop();
  2692. thread.join();
  2693. ASSERT_FALSE(svr.is_running());
  2694. });
  2695. svr.wait_until_ready();
  2696. Client cli(HOST, PORT);
  2697. cli.set_payload_max_length(200 * 1024 * 1024);
  2698. cli.set_connection_timeout(std::chrono::seconds(5));
  2699. auto res =
  2700. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2701. "application/json", [](uint64_t, uint64_t) { return false; });
  2702. ASSERT_TRUE(!res);
  2703. EXPECT_EQ(Error::Canceled, res.error());
  2704. }
  2705. TEST(CancelTest, NoCancelDelete) {
  2706. Server svr;
  2707. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2708. res.set_content("Hello World!", "text/plain");
  2709. });
  2710. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2711. auto se = detail::scope_exit([&] {
  2712. svr.stop();
  2713. thread.join();
  2714. ASSERT_FALSE(svr.is_running());
  2715. });
  2716. svr.wait_until_ready();
  2717. Client cli(HOST, PORT);
  2718. cli.set_connection_timeout(std::chrono::seconds(5));
  2719. auto res =
  2720. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2721. "application/json", [](uint64_t, uint64_t) { return true; });
  2722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2723. EXPECT_EQ("Hello World!", res->body);
  2724. EXPECT_EQ(StatusCode::OK_200, res->status);
  2725. }
  2726. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2727. Server svr;
  2728. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2729. res.set_content("Hello World!", "text/plain");
  2730. });
  2731. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2732. auto se = detail::scope_exit([&] {
  2733. svr.stop();
  2734. thread.join();
  2735. ASSERT_FALSE(svr.is_running());
  2736. });
  2737. svr.wait_until_ready();
  2738. Client cli(HOST, PORT);
  2739. cli.set_connection_timeout(std::chrono::seconds(5));
  2740. auto res =
  2741. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2742. "application/json", [](uint64_t, uint64_t) { return false; });
  2743. ASSERT_TRUE(!res);
  2744. EXPECT_EQ(Error::Canceled, res.error());
  2745. }
  2746. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2747. Server svr;
  2748. svr.set_payload_max_length(200 * 1024 * 1024);
  2749. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2750. res.set_content(LARGE_DATA, "text/plain");
  2751. });
  2752. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2753. auto se = detail::scope_exit([&] {
  2754. svr.stop();
  2755. thread.join();
  2756. ASSERT_FALSE(svr.is_running());
  2757. });
  2758. svr.wait_until_ready();
  2759. Client cli(HOST, PORT);
  2760. cli.set_payload_max_length(200 * 1024 * 1024);
  2761. cli.set_connection_timeout(std::chrono::seconds(5));
  2762. auto res =
  2763. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2764. "application/json", [](uint64_t, uint64_t) { return false; });
  2765. ASSERT_TRUE(!res);
  2766. EXPECT_EQ(Error::Canceled, res.error());
  2767. }
  2768. static std::string remove_whitespace(const std::string &input) {
  2769. std::string output;
  2770. output.reserve(input.size());
  2771. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2772. [](unsigned char c) { return !std::isspace(c); });
  2773. return output;
  2774. }
  2775. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2776. auto host = "httpbingo.org";
  2777. auto path = std::string{"/basic-auth/hello/world"};
  2778. #ifdef CPPHTTPLIB_SSL_ENABLED
  2779. auto port = 443;
  2780. SSLClient cli(host, port);
  2781. #else
  2782. auto port = 80;
  2783. Client cli(host, port);
  2784. #endif
  2785. {
  2786. auto res = cli.Get(path);
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2789. }
  2790. {
  2791. auto res = cli.Get(
  2792. path, Headers{make_basic_authentication_header("hello", "world")});
  2793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2794. auto body = remove_whitespace(res->body);
  2795. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2796. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2797. EXPECT_EQ(StatusCode::OK_200, res->status);
  2798. }
  2799. {
  2800. cli.set_basic_auth("hello", "world");
  2801. auto res = cli.Get(path);
  2802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2803. auto body = remove_whitespace(res->body);
  2804. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2805. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2806. EXPECT_EQ(StatusCode::OK_200, res->status);
  2807. }
  2808. {
  2809. cli.set_basic_auth("hello", "bad");
  2810. auto res = cli.Get(path);
  2811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2812. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2813. }
  2814. {
  2815. cli.set_basic_auth("bad", "world");
  2816. auto res = cli.Get(path);
  2817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2818. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2819. }
  2820. }
  2821. #ifdef CPPHTTPLIB_SSL_ENABLED
  2822. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2823. auto host = "httpbingo.org";
  2824. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2825. auto paths = std::vector<std::string>{
  2826. "/digest-auth/auth/hello/world/MD5",
  2827. "/digest-auth/auth/hello/world/SHA-256",
  2828. };
  2829. auto port = 443;
  2830. SSLClient cli(host, port);
  2831. {
  2832. auto res = cli.Get(unauth_path);
  2833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2834. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2835. }
  2836. {
  2837. cli.set_digest_auth("hello", "world");
  2838. for (const auto &path : paths) {
  2839. auto res = cli.Get(path.c_str());
  2840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2841. auto body = remove_whitespace(res->body);
  2842. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2843. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2844. EXPECT_EQ(StatusCode::OK_200, res->status);
  2845. }
  2846. cli.set_digest_auth("hello", "bad");
  2847. for (const auto &path : paths) {
  2848. auto res = cli.Get(path.c_str());
  2849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2850. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2851. }
  2852. }
  2853. }
  2854. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2855. // comma-separated list of challenges, and each challenge may itself carry a
  2856. // comma-separated auth-param list, so a server can legally offer Basic
  2857. // before Digest, either as two field lines or packed into one. Runs one 401
  2858. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2859. // value() joins them in receipt order) and checks that the retry carries a
  2860. // well-formed Digest Authorization header naming expected_realm.
  2861. static void
  2862. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2863. const std::string &expected_realm) {
  2864. std::atomic<int> hits{0};
  2865. Server svr;
  2866. svr.Get("/x", [&](const Request &req, Response &res) {
  2867. if (++hits == 1) {
  2868. res.status = StatusCode::Unauthorized_401;
  2869. for (const auto &challenge : challenges) {
  2870. res.set_header("WWW-Authenticate", challenge);
  2871. }
  2872. } else {
  2873. auto authorization = req.get_header_value("Authorization");
  2874. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2875. EXPECT_NE(std::string::npos,
  2876. authorization.find("realm=\"" + expected_realm + "\""));
  2877. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2878. res.set_content("ok", "text/plain");
  2879. }
  2880. });
  2881. auto port = svr.bind_to_any_port(HOST);
  2882. std::thread t([&]() { svr.listen_after_bind(); });
  2883. auto se = detail::scope_exit([&] {
  2884. svr.stop();
  2885. t.join();
  2886. });
  2887. svr.wait_until_ready();
  2888. Client cli(HOST, port);
  2889. cli.set_digest_auth("hello", "world");
  2890. auto res = cli.Get("/x");
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(2, hits.load());
  2893. }
  2894. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2895. static const char *kDigestChallenge =
  2896. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2897. "algorithm=MD5";
  2898. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2899. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2900. "testrealm");
  2901. }
  2902. // Same challenge list with the schemes in the opposite order, to make sure
  2903. // the fix above didn't just special-case "Basic first".
  2904. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2905. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2906. "testrealm");
  2907. }
  2908. // A comma inside a quoted auth-param value must not be mistaken for the
  2909. // separator between two challenges (or two auth-params).
  2910. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2911. run_digest_challenge_list_test(
  2912. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2913. "algorithm=MD5"},
  2914. "test,realm");
  2915. }
  2916. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2917. // make_digest_authentication_header() dereferences both unconditionally, so
  2918. // a server sending a challenge missing either one must not be treated as
  2919. // usable -- doing so used to crash the client with std::out_of_range.
  2920. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2921. Server svr;
  2922. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2923. res.status = StatusCode::Unauthorized_401;
  2924. res.set_header("WWW-Authenticate", challenge);
  2925. });
  2926. auto port = svr.bind_to_any_port(HOST);
  2927. std::thread t([&]() { svr.listen_after_bind(); });
  2928. auto se = detail::scope_exit([&] {
  2929. svr.stop();
  2930. t.join();
  2931. });
  2932. svr.wait_until_ready();
  2933. Client cli(HOST, port);
  2934. cli.set_digest_auth("hello", "world");
  2935. auto res = cli.Get("/x");
  2936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2937. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2938. }
  2939. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2940. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2941. }
  2942. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2943. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2944. }
  2945. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2946. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2947. }
  2948. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2949. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2950. // when storing the values, so the header builder has to re-escape them (and
  2951. // keep algorithm a bare token); otherwise the value breaks out of its
  2952. // quoted-string and injects extra auth-params into the client's Authorization.
  2953. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2954. std::atomic<int> hits{0};
  2955. std::string authorization;
  2956. Server svr;
  2957. svr.Get("/x", [&](const Request &req, Response &res) {
  2958. if (++hits == 1) {
  2959. res.status = StatusCode::Unauthorized_401;
  2960. // On the wire the quotes embedded in the values are backslash-escaped.
  2961. res.set_header("WWW-Authenticate",
  2962. "Digest realm=\"testrealm\", "
  2963. "nonce=\"n\\\"; injected=\\\"x\", "
  2964. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2965. } else {
  2966. authorization = req.get_header_value("Authorization");
  2967. res.set_content("ok", "text/plain");
  2968. }
  2969. });
  2970. auto port = svr.bind_to_any_port(HOST);
  2971. std::thread t([&]() { svr.listen_after_bind(); });
  2972. auto se = detail::scope_exit([&] {
  2973. svr.stop();
  2974. t.join();
  2975. });
  2976. svr.wait_until_ready();
  2977. Client cli(HOST, port);
  2978. cli.set_digest_auth("hello", "world");
  2979. auto res = cli.Get("/x");
  2980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2981. EXPECT_EQ(2, hits.load());
  2982. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2983. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2984. // inside its quoted-string rather than starting an "injected" auth-param.
  2985. EXPECT_NE(std::string::npos,
  2986. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2987. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2988. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2989. }
  2990. #endif
  2991. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2992. auto host = "google.com";
  2993. auto another_host = "example.com";
  2994. auto wrong_ip = "0.0.0.0";
  2995. #ifdef CPPHTTPLIB_SSL_ENABLED
  2996. SSLClient cli(host);
  2997. #else
  2998. Client cli(host);
  2999. #endif
  3000. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3001. auto res = cli.Get("/");
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3004. }
  3005. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3006. auto host = "google.com";
  3007. auto wrong_ip = "0.0.0.0";
  3008. #ifdef CPPHTTPLIB_SSL_ENABLED
  3009. SSLClient cli(host);
  3010. #else
  3011. Client cli(host);
  3012. #endif
  3013. cli.set_hostname_addr_map({{host, wrong_ip}});
  3014. auto res = cli.Get("/");
  3015. ASSERT_TRUE(!res);
  3016. EXPECT_EQ(Error::Connection, res.error());
  3017. }
  3018. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3019. // A mapped value that is not an IP literal must be resolved. "localhost"
  3020. // resolves from the hosts file, so this test needs no external DNS.
  3021. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3022. auto host = "target.invalid";
  3023. Server svr;
  3024. std::string received_host;
  3025. svr.Get("/hi", [&](const Request &req, Response &res) {
  3026. received_host = req.get_header_value("Host");
  3027. res.set_content("Hello World!", "text/plain");
  3028. });
  3029. auto port = svr.bind_to_any_port(HOST);
  3030. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3031. auto se = detail::scope_exit([&] {
  3032. svr.stop();
  3033. thread.join();
  3034. ASSERT_FALSE(svr.is_running());
  3035. });
  3036. svr.wait_until_ready();
  3037. Client cli(host, port);
  3038. cli.set_hostname_addr_map({{host, HOST}});
  3039. auto res = cli.Get("/hi");
  3040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3041. EXPECT_EQ(StatusCode::OK_200, res->status);
  3042. // The mapping only redirects the connection; the identity stays host_.
  3043. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3044. }
  3045. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3046. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3047. auto host = "target.invalid";
  3048. Server svr;
  3049. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3050. res.set_content("Hello World!", "text/plain");
  3051. });
  3052. auto port = svr.bind_to_any_port("127.0.0.1");
  3053. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3054. auto se = detail::scope_exit([&] {
  3055. svr.stop();
  3056. thread.join();
  3057. ASSERT_FALSE(svr.is_running());
  3058. });
  3059. svr.wait_until_ready();
  3060. Client cli(host, port);
  3061. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3062. auto res = cli.Get("/hi");
  3063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3064. EXPECT_EQ(StatusCode::OK_200, res->status);
  3065. }
  3066. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3067. // An empty mapped value must leave host_ as the connection target. Without
  3068. // that guard the empty value would become the host argument, getaddrinfo
  3069. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3070. // loopback - silently connecting somewhere the caller never asked for.
  3071. // The server listens on loopback, so such a fallback would succeed and is
  3072. // therefore observable as a failure of this test.
  3073. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3074. Server svr;
  3075. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3076. res.set_content("Hello World!", "text/plain");
  3077. });
  3078. auto port = svr.bind_to_any_port(HOST);
  3079. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3080. auto se = detail::scope_exit([&] {
  3081. svr.stop();
  3082. thread.join();
  3083. ASSERT_FALSE(svr.is_running());
  3084. });
  3085. svr.wait_until_ready();
  3086. Client cli(blackhole, port);
  3087. cli.set_hostname_addr_map({{blackhole, ""}});
  3088. cli.set_connection_timeout(1);
  3089. auto res = cli.Get("/hi");
  3090. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3091. }
  3092. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3093. auto host = "httpbingo.org";
  3094. auto path = std::string{"/absolute-redirect/3"};
  3095. #ifdef CPPHTTPLIB_SSL_ENABLED
  3096. SSLClient cli(host);
  3097. #else
  3098. Client cli(host);
  3099. #endif
  3100. cli.set_follow_location(true);
  3101. auto res = cli.Get(path);
  3102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3103. EXPECT_EQ(StatusCode::OK_200, res->status);
  3104. }
  3105. TEST(RedirectTest, Redirect_Online) {
  3106. auto host = "httpbingo.org";
  3107. auto path = std::string{"/redirect/3"};
  3108. #ifdef CPPHTTPLIB_SSL_ENABLED
  3109. SSLClient cli(host);
  3110. #else
  3111. Client cli(host);
  3112. #endif
  3113. cli.set_follow_location(true);
  3114. auto res = cli.Get(path);
  3115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3116. EXPECT_EQ(StatusCode::OK_200, res->status);
  3117. }
  3118. TEST(RelativeRedirectTest, Redirect_Online) {
  3119. auto host = "httpbingo.org";
  3120. auto path = std::string{"/relative-redirect/3"};
  3121. #ifdef CPPHTTPLIB_SSL_ENABLED
  3122. SSLClient cli(host);
  3123. #else
  3124. Client cli(host);
  3125. #endif
  3126. cli.set_follow_location(true);
  3127. auto res = cli.Get(path);
  3128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3129. EXPECT_EQ(StatusCode::OK_200, res->status);
  3130. }
  3131. TEST(TooManyRedirectTest, Redirect_Online) {
  3132. auto host = "httpbingo.org";
  3133. auto path = std::string{"/redirect/21"};
  3134. #ifdef CPPHTTPLIB_SSL_ENABLED
  3135. SSLClient cli(host);
  3136. #else
  3137. Client cli(host);
  3138. #endif
  3139. cli.set_follow_location(true);
  3140. auto res = cli.Get(path);
  3141. ASSERT_TRUE(!res);
  3142. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3143. }
  3144. #ifdef CPPHTTPLIB_SSL_ENABLED
  3145. TEST(YahooRedirectTest, Redirect_Online) {
  3146. Client cli("yahoo.com");
  3147. auto res = cli.Get("/");
  3148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3149. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3150. cli.set_follow_location(true);
  3151. res = cli.Get("/");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3155. }
  3156. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3157. #define REDIR_HOST "httpbingo.org"
  3158. #define REDIR_PATH "/redirect-to"
  3159. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3160. SSLClient cli(REDIR_HOST);
  3161. cli.set_follow_location(true);
  3162. auto res =
  3163. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3165. EXPECT_EQ(StatusCode::OK_200, res->status);
  3166. }
  3167. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3168. SSLClient cli(REDIR_HOST);
  3169. cli.set_follow_location(true);
  3170. Params params;
  3171. params.emplace("url", "http://example.com");
  3172. params.emplace("status_code", "302");
  3173. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3175. EXPECT_EQ(StatusCode::OK_200, res->status);
  3176. }
  3177. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3178. SSLClient cli(REDIR_HOST);
  3179. cli.set_follow_location(true);
  3180. Params params;
  3181. params.emplace("url", "http://example.com");
  3182. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::OK_200, res->status);
  3185. }
  3186. TEST(UrlWithSpace, Redirect_Online) {
  3187. SSLClient cli("edge.forgecdn.net");
  3188. cli.set_follow_location(true);
  3189. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3191. EXPECT_EQ(StatusCode::OK_200, res->status);
  3192. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3193. }
  3194. #endif
  3195. #if !defined(_WIN32) && !defined(_WIN64)
  3196. TEST(ReceiveSignals, Signal) {
  3197. auto setupSignalHandlers = []() {
  3198. struct sigaction act;
  3199. sigemptyset(&act.sa_mask);
  3200. act.sa_flags = SA_SIGINFO;
  3201. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3202. switch (sig) {
  3203. case SIGINT:
  3204. default: break;
  3205. }
  3206. };
  3207. ::sigaction(SIGINT, &act, nullptr);
  3208. };
  3209. Server svr;
  3210. int port = 0;
  3211. auto thread = std::thread([&]() {
  3212. setupSignalHandlers();
  3213. port = svr.bind_to_any_port(HOST);
  3214. svr.listen_after_bind();
  3215. });
  3216. auto se = detail::scope_exit([&] {
  3217. svr.stop();
  3218. thread.join();
  3219. ASSERT_FALSE(svr.is_running());
  3220. });
  3221. svr.wait_until_ready();
  3222. ASSERT_TRUE(svr.is_running());
  3223. pthread_kill(thread.native_handle(), SIGINT);
  3224. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3225. ASSERT_TRUE(svr.is_running());
  3226. }
  3227. #endif
  3228. TEST(RedirectToDifferentPort, Redirect) {
  3229. Server svr1;
  3230. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3231. res.set_content("Hello World!", "text/plain");
  3232. });
  3233. int svr1_port = 0;
  3234. auto thread1 = std::thread([&]() {
  3235. svr1_port = svr1.bind_to_any_port(HOST);
  3236. svr1.listen_after_bind();
  3237. });
  3238. Server svr2;
  3239. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3240. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3241. });
  3242. int svr2_port = 0;
  3243. auto thread2 = std::thread([&]() {
  3244. svr2_port = svr2.bind_to_any_port(HOST);
  3245. svr2.listen_after_bind();
  3246. });
  3247. auto se = detail::scope_exit([&] {
  3248. svr2.stop();
  3249. thread2.join();
  3250. svr1.stop();
  3251. thread1.join();
  3252. ASSERT_FALSE(svr2.is_running());
  3253. ASSERT_FALSE(svr1.is_running());
  3254. });
  3255. svr1.wait_until_ready();
  3256. svr2.wait_until_ready();
  3257. Client cli("localhost", svr2_port);
  3258. cli.set_follow_location(true);
  3259. auto res = cli.Get("/2");
  3260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3261. EXPECT_EQ(StatusCode::OK_200, res->status);
  3262. EXPECT_EQ("Hello World!", res->body);
  3263. }
  3264. // GET /redir on one server redirects to /target on another port, so the
  3265. // client follows it with a new client.
  3266. static Result
  3267. GetThroughRedirectToDifferentPort(Server::Handler target,
  3268. const std::function<void(Client &)> &setup,
  3269. const Headers &headers = Headers()) {
  3270. Server target_svr;
  3271. target_svr.Get("/target", target);
  3272. int target_port = 0;
  3273. auto target_thread = std::thread([&]() {
  3274. target_port = target_svr.bind_to_any_port(HOST);
  3275. target_svr.listen_after_bind();
  3276. });
  3277. Server origin_svr;
  3278. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3279. res.set_redirect(
  3280. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3281. });
  3282. int origin_port = 0;
  3283. auto origin_thread = std::thread([&]() {
  3284. origin_port = origin_svr.bind_to_any_port(HOST);
  3285. origin_svr.listen_after_bind();
  3286. });
  3287. auto se = detail::scope_exit([&] {
  3288. origin_svr.stop();
  3289. origin_thread.join();
  3290. target_svr.stop();
  3291. target_thread.join();
  3292. });
  3293. target_svr.wait_until_ready();
  3294. origin_svr.wait_until_ready();
  3295. Client cli("localhost", origin_port);
  3296. cli.set_follow_location(true);
  3297. setup(cli);
  3298. return cli.Get("/redir", headers);
  3299. }
  3300. static void
  3301. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3302. std::string captured_authorization;
  3303. auto result = GetThroughRedirectToDifferentPort(
  3304. [&](const Request &req, Response &res) {
  3305. captured_authorization = req.get_header_value("Authorization");
  3306. res.set_content("OK", "text/plain");
  3307. },
  3308. set_auth);
  3309. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3310. EXPECT_EQ(StatusCode::OK_200, result->status);
  3311. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3312. EXPECT_TRUE(captured_authorization.empty());
  3313. }
  3314. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3315. TestDoNotForwardCredentialsOnRedirect(
  3316. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3317. }
  3318. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3319. TestDoNotForwardCredentialsOnRedirect(
  3320. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3321. }
  3322. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3323. std::string captured_cookie;
  3324. auto result = GetThroughRedirectToDifferentPort(
  3325. [&](const Request &req, Response &res) {
  3326. captured_cookie = req.get_header_value("Cookie");
  3327. res.set_content("OK", "text/plain");
  3328. },
  3329. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3330. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3331. EXPECT_EQ(StatusCode::OK_200, result->status);
  3332. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3333. EXPECT_TRUE(captured_cookie.empty());
  3334. }
  3335. TEST(RedirectToSamePort, ForwardCookie) {
  3336. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3337. // header so that ordinary session flows keep working.
  3338. Server svr;
  3339. std::string captured_cookie;
  3340. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3341. res.set_redirect("/target", 302);
  3342. });
  3343. svr.Get("/target", [&](const Request &req, Response &res) {
  3344. captured_cookie = req.get_header_value("Cookie");
  3345. res.set_content("OK", "text/plain");
  3346. });
  3347. auto port = svr.bind_to_any_port(HOST);
  3348. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3349. auto se = detail::scope_exit([&] {
  3350. svr.stop();
  3351. thread.join();
  3352. ASSERT_FALSE(svr.is_running());
  3353. });
  3354. svr.wait_until_ready();
  3355. Client cli(HOST, port);
  3356. cli.set_follow_location(true);
  3357. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3358. auto res = cli.Get("/redir", headers);
  3359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3360. EXPECT_EQ(StatusCode::OK_200, res->status);
  3361. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3362. }
  3363. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3364. std::string authorization;
  3365. std::string trace_id;
  3366. auto result = GetThroughRedirectToDifferentPort(
  3367. [&](const Request &req, Response &res) {
  3368. authorization = req.get_header_value("Authorization");
  3369. trace_id = req.get_header_value("X-Trace-Id");
  3370. res.set_content("OK", "text/plain");
  3371. },
  3372. [](Client &cli) {
  3373. cli.set_default_headers(
  3374. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3375. });
  3376. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3377. EXPECT_EQ(StatusCode::OK_200, result->status);
  3378. // Like a header given with the request, a default one goes along unless it
  3379. // carries credentials (RFC 9110 15.4).
  3380. EXPECT_TRUE(authorization.empty());
  3381. EXPECT_EQ("42", trace_id);
  3382. }
  3383. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3384. auto result = GetThroughRedirectToDifferentPort(
  3385. [](const Request &, Response &res) {
  3386. res.set_content(std::string(2048, 'x'), "text/plain");
  3387. },
  3388. [](Client &cli) { cli.set_payload_max_length(1024); });
  3389. EXPECT_FALSE(result);
  3390. }
  3391. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3392. auto result = GetThroughRedirectToDifferentPort(
  3393. [](const Request &req, Response &res) {
  3394. // Answer after a second, or once the client gives up.
  3395. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3396. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3397. }
  3398. res.set_content("late", "text/plain");
  3399. },
  3400. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3401. ASSERT_FALSE(result);
  3402. EXPECT_EQ(Error::Read, result.error());
  3403. }
  3404. #ifdef CPPHTTPLIB_SSL_ENABLED
  3405. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3406. auto result = GetThroughRedirectToDifferentPort(
  3407. [](const Request &, Response &res) {
  3408. res.status = StatusCode::Unauthorized_401;
  3409. res.set_header("WWW-Authenticate",
  3410. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3411. },
  3412. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3413. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3414. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3415. }
  3416. #endif
  3417. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3418. Server svr;
  3419. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3420. // Port number that overflows int — should not crash
  3421. res.set_redirect("http://localhost:99999999999999999999/target");
  3422. });
  3423. auto port = svr.bind_to_any_port(HOST);
  3424. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3425. auto se = detail::scope_exit([&] {
  3426. svr.stop();
  3427. thread.join();
  3428. ASSERT_FALSE(svr.is_running());
  3429. });
  3430. svr.wait_until_ready();
  3431. Client cli(HOST, port);
  3432. cli.set_follow_location(true);
  3433. auto res = cli.Get("/redir");
  3434. // Should fail gracefully, not crash (no valid response due to bad port)
  3435. EXPECT_FALSE(res);
  3436. }
  3437. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3438. Server svr;
  3439. auto port = svr.bind_to_any_port(HOST);
  3440. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3441. // The server's own port followed by junk must not be followed
  3442. res.set_redirect("http://" + std::string(HOST) + ":" +
  3443. std::to_string(port) + "junk/target");
  3444. });
  3445. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3446. res.set_content("target", "text/plain");
  3447. });
  3448. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3449. auto se = detail::scope_exit([&] {
  3450. svr.stop();
  3451. thread.join();
  3452. ASSERT_FALSE(svr.is_running());
  3453. });
  3454. svr.wait_until_ready();
  3455. Client cli(HOST, port);
  3456. cli.set_follow_location(true);
  3457. auto res = cli.Get("/redir");
  3458. EXPECT_FALSE(res);
  3459. }
  3460. TEST(RedirectFromPageWithContent, Redirect) {
  3461. Server svr;
  3462. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3463. res.set_content("___", "text/plain");
  3464. res.set_redirect("/2");
  3465. });
  3466. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3467. res.set_content("Hello World!", "text/plain");
  3468. });
  3469. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3470. auto se = detail::scope_exit([&] {
  3471. svr.stop();
  3472. th.join();
  3473. ASSERT_FALSE(svr.is_running());
  3474. });
  3475. svr.wait_until_ready();
  3476. {
  3477. Client cli("localhost", PORT);
  3478. cli.set_follow_location(true);
  3479. std::string body;
  3480. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3481. body.append(data, data_length);
  3482. return true;
  3483. });
  3484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3485. EXPECT_EQ(StatusCode::OK_200, res->status);
  3486. EXPECT_EQ("Hello World!", body);
  3487. }
  3488. {
  3489. Client cli("localhost", PORT);
  3490. std::string body;
  3491. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3492. body.append(data, data_length);
  3493. return true;
  3494. });
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::Found_302, res->status);
  3497. EXPECT_EQ("___", body);
  3498. }
  3499. }
  3500. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3501. Server svr;
  3502. auto port_str = std::to_string(PORT);
  3503. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3504. auto expected_host = "[::1]:" + port_str;
  3505. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3506. res.set_content("___", "text/plain");
  3507. // res.set_redirect("/2");
  3508. res.set_redirect(redirect_url);
  3509. });
  3510. svr.Get("/2", [&](const Request &req, Response &res) {
  3511. auto host_header = req.headers.find("Host");
  3512. ASSERT_TRUE(host_header != req.headers.end());
  3513. EXPECT_EQ(expected_host, host_header->second);
  3514. res.set_content("Hello World!", "text/plain");
  3515. });
  3516. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3517. auto se = detail::scope_exit([&] {
  3518. svr.stop();
  3519. th.join();
  3520. ASSERT_FALSE(svr.is_running());
  3521. });
  3522. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3523. // actually starts anything, so the condition !svr.is_running() will
  3524. // always remain true, and the loop never stops.
  3525. // This basically counts how many milliseconds have passed since the
  3526. // call to svr.listen(), and if after 5 seconds nothing started yet
  3527. // aborts the test.
  3528. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3529. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3530. ASSERT_LT(milliseconds, 5000U);
  3531. }
  3532. {
  3533. Client cli("::1", PORT);
  3534. cli.set_follow_location(true);
  3535. std::string body;
  3536. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3537. body.append(data, data_length);
  3538. return true;
  3539. });
  3540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3541. EXPECT_EQ(StatusCode::OK_200, res->status);
  3542. EXPECT_EQ("Hello World!", body);
  3543. }
  3544. {
  3545. Client cli("::1", PORT);
  3546. std::string body;
  3547. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3548. body.append(data, data_length);
  3549. return true;
  3550. });
  3551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3552. EXPECT_EQ(StatusCode::Found_302, res->status);
  3553. EXPECT_EQ("___", body);
  3554. }
  3555. }
  3556. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3557. Server svr;
  3558. svr.Get("/foo", [](const Request &req, Response &res) {
  3559. auto a = req.params.find("a");
  3560. if (a != req.params.end()) {
  3561. res.set_content((*a).second, "text/plain");
  3562. res.status = StatusCode::OK_200;
  3563. } else {
  3564. res.status = StatusCode::BadRequest_400;
  3565. }
  3566. });
  3567. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3568. auto se = detail::scope_exit([&] {
  3569. svr.stop();
  3570. thread.join();
  3571. ASSERT_FALSE(svr.is_running());
  3572. });
  3573. svr.wait_until_ready();
  3574. {
  3575. Client cli(HOST, PORT);
  3576. cli.set_path_encode(false);
  3577. auto res = cli.Get("/foo?a=explicitly+encoded");
  3578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3579. EXPECT_EQ(StatusCode::OK_200, res->status);
  3580. // This expects it back with a space, as the `+` won't have been
  3581. // url-encoded, and server-side the params get decoded turning `+`
  3582. // into spaces.
  3583. EXPECT_EQ("explicitly encoded", res->body);
  3584. }
  3585. }
  3586. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3587. // When path encoding is disabled the client must transmit the supplied
  3588. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3589. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3590. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3591. // than a space (0x20). Assert on the raw wire target to catch this.
  3592. Server svr;
  3593. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3594. svr.Get("/foo", [&](const Request &req, Response &res) {
  3595. EXPECT_EQ(expected_target, req.target);
  3596. res.status = StatusCode::OK_200;
  3597. });
  3598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3599. auto se = detail::scope_exit([&] {
  3600. svr.stop();
  3601. thread.join();
  3602. ASSERT_FALSE(svr.is_running());
  3603. });
  3604. svr.wait_until_ready();
  3605. {
  3606. Client cli(HOST, PORT);
  3607. cli.set_path_encode(false);
  3608. auto res = cli.Get(expected_target.c_str());
  3609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3610. EXPECT_EQ(StatusCode::OK_200, res->status);
  3611. }
  3612. }
  3613. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3614. // `open_stream()` used to skip the path encoding that the buffered send
  3615. // path applies, so the same `path` produced different bytes in the request
  3616. // line depending on which API was used. Assert the two agree.
  3617. Server svr;
  3618. std::string target;
  3619. svr.Get(".*", [&](const Request &req, Response &res) {
  3620. target = req.target;
  3621. res.status = StatusCode::OK_200;
  3622. });
  3623. auto port = svr.bind_to_any_port(HOST);
  3624. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3625. auto se = detail::scope_exit([&] {
  3626. svr.stop();
  3627. thread.join();
  3628. ASSERT_FALSE(svr.is_running());
  3629. });
  3630. svr.wait_until_ready();
  3631. struct {
  3632. const char *path;
  3633. const char *expected;
  3634. } cases[] = {
  3635. {"/a b?x=1", "/a%20b?x=1"},
  3636. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3637. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3638. };
  3639. for (const auto &c : cases) {
  3640. Client cli(HOST, port);
  3641. target.clear();
  3642. auto res = cli.Get(c.path);
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3645. auto buffered_target = target;
  3646. target.clear();
  3647. auto handle = cli.open_stream("GET", c.path);
  3648. EXPECT_TRUE(handle.is_valid())
  3649. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3650. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3651. }
  3652. }
  3653. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3654. // The `set_path_encode(false)` contract — transmit the supplied target
  3655. // verbatim — must hold for the streaming API too.
  3656. Server svr;
  3657. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3658. std::string target;
  3659. svr.Get("/foo", [&](const Request &req, Response &res) {
  3660. target = req.target;
  3661. res.status = StatusCode::OK_200;
  3662. });
  3663. auto port = svr.bind_to_any_port(HOST);
  3664. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3665. auto se = detail::scope_exit([&] {
  3666. svr.stop();
  3667. thread.join();
  3668. ASSERT_FALSE(svr.is_running());
  3669. });
  3670. svr.wait_until_ready();
  3671. {
  3672. Client cli(HOST, port);
  3673. cli.set_path_encode(false);
  3674. auto handle = cli.open_stream("GET", expected_target);
  3675. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3676. EXPECT_EQ(expected_target, target);
  3677. }
  3678. }
  3679. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3680. // With path encoding enabled a CR/LF in the target is percent-encoded
  3681. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3682. // write_request_line still backstops `set_path_encode(false)`, which is
  3683. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3684. Server svr;
  3685. // Captured before routing: the decoded path contains a newline, which a
  3686. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3687. std::string target;
  3688. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3689. target = req.target;
  3690. res.status = StatusCode::OK_200;
  3691. return Server::HandlerResponse::Handled;
  3692. });
  3693. auto port = svr.bind_to_any_port(HOST);
  3694. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3695. auto se = detail::scope_exit([&] {
  3696. svr.stop();
  3697. thread.join();
  3698. ASSERT_FALSE(svr.is_running());
  3699. });
  3700. svr.wait_until_ready();
  3701. {
  3702. Client cli(HOST, port);
  3703. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3704. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3705. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3706. }
  3707. }
  3708. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3709. // Every control character is percent-encoded, not just CR/LF, so the target
  3710. // passes the request-target check in write_request_line.
  3711. Server svr;
  3712. std::string target;
  3713. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3714. target = req.target;
  3715. res.status = StatusCode::OK_200;
  3716. return Server::HandlerResponse::Handled;
  3717. });
  3718. auto port = svr.bind_to_any_port(HOST);
  3719. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3720. auto se = detail::scope_exit([&] {
  3721. svr.stop();
  3722. thread.join();
  3723. ASSERT_FALSE(svr.is_running());
  3724. });
  3725. svr.wait_until_ready();
  3726. {
  3727. Client cli(HOST, port);
  3728. auto res = cli.Get("/a\tb\x1b\x7f");
  3729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3730. EXPECT_EQ("/a%09b%1B%7F", target);
  3731. }
  3732. }
  3733. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3734. // Nothing may reach the wire: a raw CR/LF target would split the request
  3735. // line and inject headers.
  3736. Server svr;
  3737. // Pre-routing so that "not called" means nothing reached the server at all,
  3738. // rather than merely failing to match a handler pattern.
  3739. auto handler_called = false;
  3740. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3741. handler_called = true;
  3742. res.status = StatusCode::OK_200;
  3743. return Server::HandlerResponse::Handled;
  3744. });
  3745. auto port = svr.bind_to_any_port(HOST);
  3746. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3747. auto se = detail::scope_exit([&] {
  3748. svr.stop();
  3749. thread.join();
  3750. ASSERT_FALSE(svr.is_running());
  3751. });
  3752. svr.wait_until_ready();
  3753. {
  3754. Client cli(HOST, port);
  3755. cli.set_path_encode(false);
  3756. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3757. EXPECT_FALSE(handle.is_valid());
  3758. EXPECT_EQ(Error::Write, handle.error);
  3759. EXPECT_FALSE(handler_called);
  3760. }
  3761. }
  3762. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3763. // Which of the two branches runs is decided by whether the query component
  3764. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3765. // an empty query and must still fall back to building one from
  3766. // `req.params`, while a non-empty query must win over `req.params`.
  3767. Server svr;
  3768. std::string target;
  3769. svr.Get("/foo", [&](const Request &req, Response &res) {
  3770. target = req.target;
  3771. res.status = StatusCode::OK_200;
  3772. });
  3773. auto port = svr.bind_to_any_port(HOST);
  3774. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3775. auto se = detail::scope_exit([&] {
  3776. svr.stop();
  3777. thread.join();
  3778. ASSERT_FALSE(svr.is_running());
  3779. });
  3780. svr.wait_until_ready();
  3781. {
  3782. // Trailing `?` -> empty query component -> `req.params` is used.
  3783. Client cli(HOST, port);
  3784. Request req;
  3785. req.method = "GET";
  3786. req.path = "/foo?";
  3787. req.params.emplace("a", "1");
  3788. target.clear();
  3789. auto res = cli.send(req);
  3790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3791. EXPECT_EQ("/foo?a=1", target);
  3792. }
  3793. {
  3794. // Non-empty query in `req.path` -> `req.params` is not appended.
  3795. Client cli(HOST, port);
  3796. Request req;
  3797. req.method = "GET";
  3798. req.path = "/foo?b=2";
  3799. req.params.emplace("a", "1");
  3800. target.clear();
  3801. auto res = cli.send(req);
  3802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3803. EXPECT_EQ("/foo?b=2", target);
  3804. }
  3805. }
  3806. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3807. Server svr;
  3808. svr.Get("/", [](const Request &req, Response &) {
  3809. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3810. });
  3811. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3812. auto se = detail::scope_exit([&] {
  3813. svr.stop();
  3814. thread.join();
  3815. ASSERT_FALSE(svr.is_running());
  3816. });
  3817. svr.wait_until_ready();
  3818. {
  3819. Client cli(HOST, PORT);
  3820. cli.set_path_encode(false);
  3821. auto res = cli.Get("/?something=%0A");
  3822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3823. EXPECT_EQ(StatusCode::OK_200, res->status);
  3824. }
  3825. }
  3826. TEST(BindServerTest, BindDualStack) {
  3827. Server svr;
  3828. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3829. res.set_content("Hello World!", "text/plain");
  3830. });
  3831. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3832. auto se = detail::scope_exit([&] {
  3833. svr.stop();
  3834. thread.join();
  3835. ASSERT_FALSE(svr.is_running());
  3836. });
  3837. svr.wait_until_ready();
  3838. {
  3839. Client cli("127.0.0.1", PORT);
  3840. auto res = cli.Get("/1");
  3841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3842. EXPECT_EQ(StatusCode::OK_200, res->status);
  3843. EXPECT_EQ("Hello World!", res->body);
  3844. }
  3845. {
  3846. Client cli("::1", PORT);
  3847. auto res = cli.Get("/1");
  3848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3849. EXPECT_EQ(StatusCode::OK_200, res->status);
  3850. EXPECT_EQ("Hello World!", res->body);
  3851. }
  3852. }
  3853. TEST(BindServerTest, BindAndListenSeparately) {
  3854. Server svr;
  3855. int port = svr.bind_to_any_port("0.0.0.0");
  3856. ASSERT_TRUE(svr.is_valid());
  3857. ASSERT_TRUE(port > 0);
  3858. svr.stop();
  3859. }
  3860. // Reports whether anything is still listening on a loopback port. A plain
  3861. // connect() is used instead of a Client request because a socket left bound by
  3862. // mistake accepts the connection into its backlog and never answers, which
  3863. // would hang the test instead of failing it.
  3864. static bool is_loopback_port_accepting(int port) {
  3865. sockaddr_in addr{};
  3866. addr.sin_family = AF_INET;
  3867. addr.sin_port = htons(static_cast<uint16_t>(port));
  3868. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3869. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3870. EXPECT_NE(sock, INVALID_SOCKET);
  3871. if (sock == INVALID_SOCKET) { return false; }
  3872. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3873. static_cast<socklen_t>(sizeof(addr)));
  3874. detail::close_socket(sock);
  3875. return ret == 0;
  3876. }
  3877. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3878. Server svr;
  3879. auto port = svr.bind_to_any_port("127.0.0.1");
  3880. ASSERT_TRUE(port > 0);
  3881. svr.stop();
  3882. // bind_to_any_port() already called listen(2), so until stop() closed the
  3883. // descriptor the port kept accepting connections into the backlog. ASSERT
  3884. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3885. // below blocks forever in the accept loop.
  3886. ASSERT_FALSE(is_loopback_port_accepting(port));
  3887. // Nothing is left to accept on, so listen_after_bind() must report failure
  3888. // instead of returning success without ever serving.
  3889. EXPECT_FALSE(svr.listen_after_bind());
  3890. // The failed listen marks the server decommissioned, so a waiter returns
  3891. // instead of spinning forever.
  3892. svr.wait_until_ready();
  3893. }
  3894. #ifdef CPPHTTPLIB_SSL_ENABLED
  3895. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3896. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3897. CLIENT_CA_CERT_DIR);
  3898. int port = svr.bind_to_any_port("0.0.0.0");
  3899. ASSERT_TRUE(svr.is_valid());
  3900. ASSERT_TRUE(port > 0);
  3901. svr.stop();
  3902. }
  3903. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3904. // or a rejected CustomRoute() registration would not stop the server binding.
  3905. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3907. CLIENT_CA_CERT_DIR);
  3908. ASSERT_TRUE(svr.is_valid());
  3909. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3910. EXPECT_FALSE(svr.is_valid());
  3911. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3912. }
  3913. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3914. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3915. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3916. int port = svr.bind_to_any_port("0.0.0.0");
  3917. ASSERT_TRUE(svr.is_valid());
  3918. ASSERT_TRUE(port > 0);
  3919. svr.stop();
  3920. }
  3921. TEST(BindServerTest, UpdateCertsPem) {
  3922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3923. int port = svr.bind_to_any_port("0.0.0.0");
  3924. ASSERT_TRUE(svr.is_valid());
  3925. ASSERT_TRUE(port > 0);
  3926. // Read PEM files
  3927. std::string cert_pem, key_pem, ca_pem;
  3928. read_file(SERVER_CERT_FILE, cert_pem);
  3929. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3930. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3931. // Update server certificates using PEM API
  3932. ASSERT_TRUE(
  3933. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3934. ASSERT_TRUE(svr.is_valid());
  3935. svr.stop();
  3936. }
  3937. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3938. // Start server with client CA (enables client auth)
  3939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3940. ASSERT_TRUE(svr.is_valid());
  3941. bool handler_called = false;
  3942. svr.Get("/test", [&](const Request &req, Response &res) {
  3943. handler_called = true;
  3944. // Verify client certificate is present
  3945. auto cert = req.peer_cert();
  3946. EXPECT_TRUE(static_cast<bool>(cert));
  3947. res.set_content("ok", "text/plain");
  3948. });
  3949. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3950. auto se = detail::scope_exit([&] {
  3951. svr.stop();
  3952. t.join();
  3953. ASSERT_FALSE(svr.is_running());
  3954. });
  3955. svr.wait_until_ready();
  3956. // Read PEM files
  3957. std::string cert_pem, key_pem, ca_pem;
  3958. read_file(SERVER_CERT_FILE, cert_pem);
  3959. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3960. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3961. // Update server certificates and client CA using PEM API while server running
  3962. ASSERT_TRUE(
  3963. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3964. // Connect with client certificate
  3965. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3966. cli.enable_server_certificate_verification(false);
  3967. cli.set_connection_timeout(30);
  3968. auto res = cli.Get("/test");
  3969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3970. ASSERT_EQ(StatusCode::OK_200, res->status);
  3971. ASSERT_TRUE(handler_called);
  3972. EXPECT_EQ("ok", res->body);
  3973. }
  3974. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3976. ASSERT_TRUE(svr.is_valid());
  3977. svr.Get("/test", [](const Request &, Response &res) {
  3978. res.set_content("ok", "text/plain");
  3979. });
  3980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3981. auto se = detail::scope_exit([&] {
  3982. svr.stop();
  3983. t.join();
  3984. ASSERT_FALSE(svr.is_running());
  3985. });
  3986. svr.wait_until_ready();
  3987. // A connection that sends no ClientHello keeps its handshake in progress,
  3988. // once the server has had a moment to start it.
  3989. auto error = Error::Success;
  3990. auto sock = detail::create_client_socket(
  3991. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3992. /*connection_timeout_sec=*/5, 0,
  3993. /*read_timeout_sec=*/5, 0,
  3994. /*write_timeout_sec=*/5, 0, std::string(), error);
  3995. ASSERT_NE(INVALID_SOCKET, sock);
  3996. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3997. std::string cert_pem, key_pem;
  3998. read_file(SERVER_CERT_FILE, cert_pem);
  3999. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4000. auto update = std::async(std::launch::async, [&]() {
  4001. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4002. });
  4003. EXPECT_EQ(std::future_status::timeout,
  4004. update.wait_for(std::chrono::milliseconds(200)));
  4005. detail::close_socket(sock);
  4006. EXPECT_TRUE(update.get());
  4007. SSLClient cli(HOST, PORT);
  4008. cli.enable_server_certificate_verification(false);
  4009. auto res = cli.Get("/test");
  4010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4011. EXPECT_EQ(StatusCode::OK_200, res->status);
  4012. }
  4013. #endif
  4014. TEST(ErrorHandlerTest, ContentLength) {
  4015. Server svr;
  4016. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4017. res.status = StatusCode::OK_200;
  4018. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4019. "text/html"); // <= Content-Length still 13
  4020. });
  4021. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4022. res.set_content("Hello World!\n", "text/plain");
  4023. res.status = 524;
  4024. });
  4025. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4026. auto se = detail::scope_exit([&] {
  4027. svr.stop();
  4028. thread.join();
  4029. ASSERT_FALSE(svr.is_running());
  4030. });
  4031. svr.wait_until_ready();
  4032. {
  4033. Client cli(HOST, PORT);
  4034. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4036. EXPECT_EQ(StatusCode::OK_200, res->status);
  4037. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4038. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4039. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4040. }
  4041. }
  4042. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4043. TEST(ExceptionTest, WithoutExceptionHandler) {
  4044. Server svr;
  4045. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4046. throw std::runtime_error("exception...");
  4047. });
  4048. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4049. throw std::runtime_error("exception\r\n...");
  4050. });
  4051. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4052. auto se = detail::scope_exit([&] {
  4053. svr.stop();
  4054. listen_thread.join();
  4055. ASSERT_FALSE(svr.is_running());
  4056. });
  4057. svr.wait_until_ready();
  4058. Client cli("localhost", PORT);
  4059. {
  4060. auto res = cli.Get("/exception");
  4061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4062. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4063. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4064. }
  4065. {
  4066. auto res = cli.Get("/unknown");
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4069. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4070. }
  4071. }
  4072. TEST(ExceptionTest, WithExceptionHandler) {
  4073. Server svr;
  4074. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4075. std::exception_ptr ep) {
  4076. EXPECT_FALSE(ep == nullptr);
  4077. try {
  4078. std::rethrow_exception(ep);
  4079. } catch (std::exception &e) {
  4080. EXPECT_EQ("abc", std::string(e.what()));
  4081. } catch (...) {}
  4082. res.status = StatusCode::InternalServerError_500;
  4083. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4084. "text/html"); // <= Content-Length still 13 at this point
  4085. });
  4086. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4087. res.set_content("Hello World!\n", "text/plain");
  4088. throw std::runtime_error("abc");
  4089. });
  4090. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4091. auto se = detail::scope_exit([&] {
  4092. svr.stop();
  4093. thread.join();
  4094. ASSERT_FALSE(svr.is_running());
  4095. });
  4096. svr.wait_until_ready();
  4097. for (size_t i = 0; i < 10; i++) {
  4098. Client cli(HOST, PORT);
  4099. for (size_t j = 0; j < 100; j++) {
  4100. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4102. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4103. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4104. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4105. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4106. }
  4107. cli.set_keep_alive(true);
  4108. for (size_t j = 0; j < 100; j++) {
  4109. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4111. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4112. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4113. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4114. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4115. }
  4116. }
  4117. }
  4118. TEST(ExceptionTest, AndErrorHandler) {
  4119. Server svr;
  4120. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4121. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4122. });
  4123. svr.set_exception_handler(
  4124. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4125. EXPECT_FALSE(ep == nullptr);
  4126. try {
  4127. std::rethrow_exception(ep);
  4128. } catch (std::exception &e) {
  4129. res.set_content(e.what(), "text/html");
  4130. } catch (...) {}
  4131. res.status = StatusCode::InternalServerError_500;
  4132. });
  4133. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4134. throw std::runtime_error("EXCEPTION");
  4135. });
  4136. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4137. res.set_content("ERROR", "text/html");
  4138. res.status = StatusCode::InternalServerError_500;
  4139. });
  4140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4141. auto se = detail::scope_exit([&] {
  4142. svr.stop();
  4143. thread.join();
  4144. ASSERT_FALSE(svr.is_running());
  4145. });
  4146. svr.wait_until_ready();
  4147. Client cli(HOST, PORT);
  4148. {
  4149. auto res = cli.Get("/exception");
  4150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4151. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4152. EXPECT_EQ("EXCEPTION", res->body);
  4153. }
  4154. {
  4155. auto res = cli.Get("/error");
  4156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4157. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4158. EXPECT_EQ("ERROR", res->body);
  4159. }
  4160. {
  4161. auto res = cli.Get("/invalid");
  4162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4163. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4164. EXPECT_EQ("NOT_FOUND", res->body);
  4165. }
  4166. }
  4167. #endif
  4168. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4169. // process_request() wraps only routing() in a try/catch, so an exception from
  4170. // any other user callback used to unwind into the task queue - which does not
  4171. // catch - and terminate the process. Each test below runs the server on a
  4172. // single worker thread: a guard that catches the exception but still loses the
  4173. // thread would otherwise be hidden by a spare worker serving the follow-up
  4174. // request. Note that a regression here aborts the whole test binary rather
  4175. // than failing one test.
  4176. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4177. Server svr;
  4178. svr.new_task_queue = [] { return new ThreadPool(1); };
  4179. std::atomic<int> reported{0};
  4180. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4181. if (err == Error::UserCallbackException) { reported++; }
  4182. });
  4183. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4184. res.set_content_provider(
  4185. 1024, "text/plain",
  4186. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4187. sink.write("hello", 5);
  4188. throw std::runtime_error("from the content provider");
  4189. });
  4190. });
  4191. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4192. res.set_content("ok", "text/plain");
  4193. });
  4194. auto port = svr.bind_to_any_port(HOST);
  4195. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4196. auto se = detail::scope_exit([&] {
  4197. svr.stop();
  4198. listen_thread.join();
  4199. ASSERT_FALSE(svr.is_running());
  4200. });
  4201. svr.wait_until_ready();
  4202. {
  4203. Client cli(HOST, port);
  4204. cli.set_read_timeout(5, 0);
  4205. EXPECT_FALSE(cli.Get("/throw"));
  4206. }
  4207. EXPECT_TRUE(svr.is_running());
  4208. EXPECT_EQ(1, reported.load());
  4209. // A request on a fresh connection is still served.
  4210. {
  4211. Client cli(HOST, port);
  4212. auto res = cli.Get("/ok");
  4213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4214. EXPECT_EQ(StatusCode::OK_200, res->status);
  4215. EXPECT_EQ("ok", res->body);
  4216. }
  4217. }
  4218. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4219. Server svr;
  4220. svr.new_task_queue = [] { return new ThreadPool(1); };
  4221. std::atomic<bool> should_throw{true};
  4222. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4223. res.set_content("hi", "text/plain");
  4224. });
  4225. svr.set_post_routing_handler(
  4226. [&](const Request & /*req*/, Response & /*res*/) {
  4227. if (should_throw) {
  4228. throw std::runtime_error("from the post-routing handler");
  4229. }
  4230. });
  4231. auto port = svr.bind_to_any_port(HOST);
  4232. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4233. auto se = detail::scope_exit([&] {
  4234. svr.stop();
  4235. listen_thread.join();
  4236. ASSERT_FALSE(svr.is_running());
  4237. });
  4238. svr.wait_until_ready();
  4239. {
  4240. Client cli(HOST, port);
  4241. cli.set_read_timeout(5, 0);
  4242. EXPECT_FALSE(cli.Get("/hi"));
  4243. }
  4244. EXPECT_TRUE(svr.is_running());
  4245. should_throw = false;
  4246. {
  4247. Client cli(HOST, port);
  4248. auto res = cli.Get("/hi");
  4249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4250. EXPECT_EQ(StatusCode::OK_200, res->status);
  4251. EXPECT_EQ("hi", res->body);
  4252. }
  4253. }
  4254. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4255. // The guard reports the caught exception through the error logger, which is
  4256. // a user callback too. A logger that throws has to be contained as well, or
  4257. // the process would terminate from inside the catch.
  4258. Server svr;
  4259. svr.new_task_queue = [] { return new ThreadPool(1); };
  4260. std::atomic<int> reported{0};
  4261. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4262. if (err == Error::UserCallbackException) {
  4263. reported++;
  4264. throw std::runtime_error("from the error logger");
  4265. }
  4266. });
  4267. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4268. res.set_content_provider(
  4269. 1024, "text/plain",
  4270. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4271. sink.write("hello", 5);
  4272. throw std::runtime_error("from the content provider");
  4273. });
  4274. });
  4275. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4276. res.set_content("ok", "text/plain");
  4277. });
  4278. auto port = svr.bind_to_any_port(HOST);
  4279. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4280. auto se = detail::scope_exit([&] {
  4281. svr.stop();
  4282. listen_thread.join();
  4283. ASSERT_FALSE(svr.is_running());
  4284. });
  4285. svr.wait_until_ready();
  4286. {
  4287. Client cli(HOST, port);
  4288. cli.set_read_timeout(5, 0);
  4289. EXPECT_FALSE(cli.Get("/throw"));
  4290. }
  4291. EXPECT_TRUE(svr.is_running());
  4292. EXPECT_EQ(1, reported.load());
  4293. {
  4294. Client cli(HOST, port);
  4295. auto res = cli.Get("/ok");
  4296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. EXPECT_EQ("ok", res->body);
  4299. }
  4300. }
  4301. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4302. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4303. // so the exception unwinds through the ws::WebSocket object on its way to
  4304. // the guard. None of the HTTP cases above cross that.
  4305. Server svr;
  4306. svr.new_task_queue = [] { return new ThreadPool(1); };
  4307. std::atomic<int> reported{0};
  4308. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4309. if (err == Error::UserCallbackException) { reported++; }
  4310. });
  4311. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4312. throw std::runtime_error("from the WebSocket handler");
  4313. });
  4314. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4315. res.set_content("ok", "text/plain");
  4316. });
  4317. auto port = svr.bind_to_any_port(HOST);
  4318. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4319. auto se = detail::scope_exit([&] {
  4320. svr.stop();
  4321. listen_thread.join();
  4322. ASSERT_FALSE(svr.is_running());
  4323. });
  4324. svr.wait_until_ready();
  4325. {
  4326. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4327. "/ws");
  4328. auto res = client.connect();
  4329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4330. // The server dropped the connection instead of dying.
  4331. std::string msg;
  4332. EXPECT_FALSE(client.read(msg));
  4333. client.close();
  4334. }
  4335. EXPECT_TRUE(svr.is_running());
  4336. EXPECT_EQ(1, reported.load());
  4337. {
  4338. Client cli(HOST, port);
  4339. auto res = cli.Get("/ok");
  4340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4341. EXPECT_EQ(StatusCode::OK_200, res->status);
  4342. EXPECT_EQ("ok", res->body);
  4343. }
  4344. }
  4345. #ifdef CPPHTTPLIB_SSL_ENABLED
  4346. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4347. // SSLServer::process_and_close_socket() is a separate overload with its own
  4348. // guard, so it is exercised on its own.
  4349. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4350. ASSERT_TRUE(svr.is_valid());
  4351. svr.new_task_queue = [] { return new ThreadPool(1); };
  4352. std::atomic<int> reported{0};
  4353. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4354. if (err == Error::UserCallbackException) { reported++; }
  4355. });
  4356. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4357. res.set_content_provider(
  4358. 1024, "text/plain",
  4359. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4360. sink.write("hello", 5);
  4361. throw std::runtime_error("from the content provider");
  4362. });
  4363. });
  4364. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4365. res.set_content("ok", "text/plain");
  4366. });
  4367. auto port = svr.bind_to_any_port(HOST);
  4368. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4369. auto se = detail::scope_exit([&] {
  4370. svr.stop();
  4371. listen_thread.join();
  4372. ASSERT_FALSE(svr.is_running());
  4373. });
  4374. svr.wait_until_ready();
  4375. {
  4376. SSLClient cli(HOST, port);
  4377. cli.enable_server_certificate_verification(false);
  4378. cli.set_read_timeout(5, 0);
  4379. EXPECT_FALSE(cli.Get("/throw"));
  4380. }
  4381. EXPECT_TRUE(svr.is_running());
  4382. EXPECT_EQ(1, reported.load());
  4383. {
  4384. SSLClient cli(HOST, port);
  4385. cli.enable_server_certificate_verification(false);
  4386. auto res = cli.Get("/ok");
  4387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4388. EXPECT_EQ(StatusCode::OK_200, res->status);
  4389. EXPECT_EQ("ok", res->body);
  4390. }
  4391. }
  4392. #endif
  4393. #endif
  4394. TEST(NoContentTest, ContentLength) {
  4395. Server svr;
  4396. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4397. res.status = StatusCode::NoContent_204;
  4398. });
  4399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4400. auto se = detail::scope_exit([&] {
  4401. svr.stop();
  4402. thread.join();
  4403. ASSERT_FALSE(svr.is_running());
  4404. });
  4405. svr.wait_until_ready();
  4406. {
  4407. Client cli(HOST, PORT);
  4408. auto res = cli.Get("/hi");
  4409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4410. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4411. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4412. }
  4413. }
  4414. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4415. #ifdef CPPHTTPLIB_SSL_ENABLED
  4416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4417. ASSERT_TRUE(svr.is_valid());
  4418. #else
  4419. Server svr;
  4420. #endif
  4421. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4422. if (req.path == "/routing_handler") {
  4423. res.set_header("PRE_ROUTING", "on");
  4424. res.set_content("Routing Handler", "text/plain");
  4425. return httplib::Server::HandlerResponse::Handled;
  4426. }
  4427. return httplib::Server::HandlerResponse::Unhandled;
  4428. });
  4429. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4430. res.set_content("Error", "text/html");
  4431. });
  4432. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4433. if (req.path == "/routing_handler") {
  4434. res.set_header("POST_ROUTING", "on");
  4435. }
  4436. });
  4437. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4438. res.set_content("Hello World!\n", "text/plain");
  4439. });
  4440. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4441. auto se = detail::scope_exit([&] {
  4442. svr.stop();
  4443. thread.join();
  4444. ASSERT_FALSE(svr.is_running());
  4445. });
  4446. svr.wait_until_ready();
  4447. {
  4448. #ifdef CPPHTTPLIB_SSL_ENABLED
  4449. SSLClient cli(HOST, PORT);
  4450. cli.enable_server_certificate_verification(false);
  4451. #else
  4452. Client cli(HOST, PORT);
  4453. #endif
  4454. auto res = cli.Get("/routing_handler");
  4455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4456. EXPECT_EQ(StatusCode::OK_200, res->status);
  4457. EXPECT_EQ("Routing Handler", res->body);
  4458. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4459. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4460. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4461. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4462. }
  4463. {
  4464. #ifdef CPPHTTPLIB_SSL_ENABLED
  4465. SSLClient cli(HOST, PORT);
  4466. cli.enable_server_certificate_verification(false);
  4467. #else
  4468. Client cli(HOST, PORT);
  4469. #endif
  4470. auto res = cli.Get("/hi");
  4471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. EXPECT_EQ("Hello World!\n", res->body);
  4474. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4475. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4476. }
  4477. {
  4478. #ifdef CPPHTTPLIB_SSL_ENABLED
  4479. SSLClient cli(HOST, PORT);
  4480. cli.enable_server_certificate_verification(false);
  4481. #else
  4482. Client cli(HOST, PORT);
  4483. #endif
  4484. auto res = cli.Get("/aaa");
  4485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4487. EXPECT_EQ("Error", res->body);
  4488. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4489. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4490. }
  4491. }
  4492. TEST(RequestHandlerTest, PreRequestHandler) {
  4493. auto route_path = "/user/:user";
  4494. Server svr;
  4495. svr.Get("/hi", [](const Request &, Response &res) {
  4496. res.set_content("hi", "text/plain");
  4497. });
  4498. svr.Get(route_path, [](const Request &req, Response &res) {
  4499. res.set_content(req.path_params.at("user"), "text/plain");
  4500. });
  4501. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4502. if (req.matched_route == route_path) {
  4503. auto user = req.path_params.at("user");
  4504. if (user != "john") {
  4505. res.status = StatusCode::Forbidden_403;
  4506. res.set_content("error", "text/html");
  4507. return Server::HandlerResponse::Handled;
  4508. }
  4509. }
  4510. return Server::HandlerResponse::Unhandled;
  4511. });
  4512. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4513. auto se = detail::scope_exit([&] {
  4514. svr.stop();
  4515. thread.join();
  4516. ASSERT_FALSE(svr.is_running());
  4517. });
  4518. svr.wait_until_ready();
  4519. Client cli(HOST, PORT);
  4520. {
  4521. auto res = cli.Get("/hi");
  4522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4523. EXPECT_EQ(StatusCode::OK_200, res->status);
  4524. EXPECT_EQ("hi", res->body);
  4525. }
  4526. {
  4527. auto res = cli.Get("/user/john");
  4528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4529. EXPECT_EQ(StatusCode::OK_200, res->status);
  4530. EXPECT_EQ("john", res->body);
  4531. }
  4532. {
  4533. auto res = cli.Get("/user/invalid-user");
  4534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4535. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4536. EXPECT_EQ("error", res->body);
  4537. }
  4538. }
  4539. // The pre-request handler must run before the request body is read, so a
  4540. // rejected request never forces the server to buffer a (potentially large)
  4541. // body. Here the posted body is larger than the payload limit: if the body
  4542. // were read first the server would answer 413, but because the pre-request
  4543. // handler runs first it answers 403 and the body is never read.
  4544. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4545. Server svr;
  4546. svr.set_payload_max_length(8);
  4547. auto handler_ran = false;
  4548. svr.Post("/reject", [&](const Request &req, Response &res) {
  4549. handler_ran = true;
  4550. res.set_content(req.body, "text/plain");
  4551. });
  4552. svr.Post("/accept", [](const Request &req, Response &res) {
  4553. res.set_content(req.body, "text/plain");
  4554. });
  4555. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4556. if (req.matched_route == "/reject") {
  4557. res.status = StatusCode::Forbidden_403;
  4558. res.set_content("denied", "text/plain");
  4559. return Server::HandlerResponse::Handled;
  4560. }
  4561. return Server::HandlerResponse::Unhandled;
  4562. });
  4563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4564. auto se = detail::scope_exit([&] {
  4565. svr.stop();
  4566. thread.join();
  4567. ASSERT_FALSE(svr.is_running());
  4568. });
  4569. svr.wait_until_ready();
  4570. Client cli(HOST, PORT);
  4571. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4572. // rejects with 403 before the body is read, so 413 is never reached.
  4573. {
  4574. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4576. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4577. EXPECT_EQ("denied", res->body);
  4578. EXPECT_FALSE(handler_ran);
  4579. }
  4580. // An approved route still reads the body and enforces the payload limit.
  4581. {
  4582. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4584. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4585. }
  4586. }
  4587. TEST(UserDataTest, BasicOperations) {
  4588. httplib::UserData ud;
  4589. // Initially empty
  4590. EXPECT_FALSE(ud.has("key"));
  4591. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4592. // set and get
  4593. ud.set("key", 42);
  4594. EXPECT_TRUE(ud.has("key"));
  4595. auto *p = ud.get<int>("key");
  4596. ASSERT_NE(nullptr, p);
  4597. EXPECT_EQ(42, *p);
  4598. // Type mismatch → nullptr
  4599. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4600. // Overwrite with different type
  4601. ud.set("key", std::string("hello"));
  4602. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4603. auto *s = ud.get<std::string>("key");
  4604. ASSERT_NE(nullptr, s);
  4605. EXPECT_EQ("hello", *s);
  4606. // erase
  4607. ud.erase("key");
  4608. EXPECT_FALSE(ud.has("key"));
  4609. // clear
  4610. ud.set("a", 1);
  4611. ud.set("b", 2);
  4612. ud.clear();
  4613. EXPECT_FALSE(ud.has("a"));
  4614. EXPECT_FALSE(ud.has("b"));
  4615. }
  4616. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4617. struct AuthCtx {
  4618. std::string user_id;
  4619. };
  4620. Server svr;
  4621. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4622. res.user_data.set("auth", AuthCtx{"alice"});
  4623. return Server::HandlerResponse::Unhandled;
  4624. });
  4625. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4626. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4627. ASSERT_NE(nullptr, ctx);
  4628. res.set_content("Hello " + ctx->user_id, "text/plain");
  4629. });
  4630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4631. auto se = detail::scope_exit([&] {
  4632. svr.stop();
  4633. thread.join();
  4634. ASSERT_FALSE(svr.is_running());
  4635. });
  4636. svr.wait_until_ready();
  4637. Client cli(HOST, PORT);
  4638. auto res = cli.Get("/me");
  4639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4640. EXPECT_EQ(StatusCode::OK_200, res->status);
  4641. EXPECT_EQ("Hello alice", res->body);
  4642. }
  4643. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4644. struct RoleCtx {
  4645. std::string role;
  4646. };
  4647. Server svr;
  4648. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4649. res.user_data.set("role", RoleCtx{"admin"});
  4650. return Server::HandlerResponse::Unhandled;
  4651. });
  4652. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4653. auto *ctx = res.user_data.get<RoleCtx>("role");
  4654. ASSERT_NE(nullptr, ctx);
  4655. res.set_content(ctx->role, "text/plain");
  4656. });
  4657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4658. auto se = detail::scope_exit([&] {
  4659. svr.stop();
  4660. thread.join();
  4661. ASSERT_FALSE(svr.is_running());
  4662. });
  4663. svr.wait_until_ready();
  4664. Client cli(HOST, PORT);
  4665. auto res = cli.Get("/role");
  4666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("admin", res->body);
  4669. }
  4670. TEST(InvalidFormatTest, StatusCode) {
  4671. Server svr;
  4672. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4673. res.set_content("Hello World!\n", "text/plain");
  4674. res.status = 9999; // Status should be a three-digit code...
  4675. });
  4676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4677. auto se = detail::scope_exit([&] {
  4678. svr.stop();
  4679. thread.join();
  4680. ASSERT_FALSE(svr.is_running());
  4681. });
  4682. svr.wait_until_ready();
  4683. {
  4684. Client cli(HOST, PORT);
  4685. auto res = cli.Get("/hi");
  4686. ASSERT_FALSE(res);
  4687. }
  4688. }
  4689. TEST(URLFragmentTest, WithFragment) {
  4690. Server svr;
  4691. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4692. EXPECT_TRUE(req.target == "/hi");
  4693. });
  4694. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4695. auto se = detail::scope_exit([&] {
  4696. svr.stop();
  4697. thread.join();
  4698. ASSERT_FALSE(svr.is_running());
  4699. });
  4700. svr.wait_until_ready();
  4701. {
  4702. Client cli(HOST, PORT);
  4703. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4704. EXPECT_TRUE(res);
  4705. EXPECT_EQ(StatusCode::OK_200, res->status);
  4706. res = cli.Get("/hi%23key1=val1=key2=val2");
  4707. EXPECT_TRUE(res);
  4708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4709. }
  4710. }
  4711. TEST(HeaderWriter, SetHeaderWriter) {
  4712. Server svr;
  4713. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4714. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4715. return detail::write_headers(strm, hdrs);
  4716. });
  4717. svr.Get("/hi", [](const Request &req, Response &res) {
  4718. auto it = req.headers.find("CustomClientHeader");
  4719. EXPECT_TRUE(it != req.headers.end());
  4720. EXPECT_EQ(it->second, "CustomClientValue");
  4721. res.set_content("Hello World!\n", "text/plain");
  4722. });
  4723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4724. auto se = detail::scope_exit([&] {
  4725. svr.stop();
  4726. thread.join();
  4727. ASSERT_FALSE(svr.is_running());
  4728. });
  4729. svr.wait_until_ready();
  4730. {
  4731. Client cli(HOST, PORT);
  4732. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4733. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4734. return detail::write_headers(strm, hdrs);
  4735. });
  4736. auto res = cli.Get("/hi");
  4737. EXPECT_TRUE(res);
  4738. EXPECT_EQ(StatusCode::OK_200, res->status);
  4739. auto it = res->headers.find("CustomServerHeader");
  4740. EXPECT_TRUE(it != res->headers.end());
  4741. EXPECT_EQ(it->second, "CustomServerValue");
  4742. }
  4743. }
  4744. class ServerTest : public ::testing::Test {
  4745. protected:
  4746. ServerTest()
  4747. : cli_(HOST, PORT)
  4748. #ifdef CPPHTTPLIB_SSL_ENABLED
  4749. ,
  4750. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4751. #endif
  4752. {
  4753. #ifdef CPPHTTPLIB_SSL_ENABLED
  4754. cli_.enable_server_certificate_verification(false);
  4755. #endif
  4756. // Allow LARGE_DATA (100MB) responses
  4757. cli_.set_payload_max_length(200 * 1024 * 1024);
  4758. }
  4759. virtual void SetUp() {
  4760. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4761. svr_.set_payload_max_length(200 * 1024 * 1024);
  4762. svr_.set_mount_point("/", "./www");
  4763. svr_.set_mount_point("/mount", "./www2");
  4764. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4765. svr_.Get("/hi",
  4766. [&](const Request & /*req*/, Response &res) {
  4767. res.set_content("Hello World!", "text/plain");
  4768. })
  4769. .Get("/file_content",
  4770. [&](const Request & /*req*/, Response &res) {
  4771. res.set_file_content("./www/dir/test.html");
  4772. })
  4773. .Get("/file_content_with_content_type",
  4774. [&](const Request & /*req*/, Response &res) {
  4775. res.set_file_content("./www/file", "text/plain");
  4776. })
  4777. .Get("/invalid_file_content",
  4778. [&](const Request & /*req*/, Response &res) {
  4779. res.set_file_content("./www/dir/invalid_file_path");
  4780. })
  4781. .Get("/http_response_splitting",
  4782. [&](const Request & /*req*/, Response &res) {
  4783. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4784. EXPECT_EQ(0U, res.headers.size());
  4785. EXPECT_FALSE(res.has_header("a"));
  4786. res.set_header("a", "1\nSet-Cookie: a=1");
  4787. EXPECT_EQ(0U, res.headers.size());
  4788. EXPECT_FALSE(res.has_header("a"));
  4789. res.set_header("a", "1\rSet-Cookie: a=1");
  4790. EXPECT_EQ(0U, res.headers.size());
  4791. EXPECT_FALSE(res.has_header("a"));
  4792. res.set_header("a\r\nb", "0");
  4793. EXPECT_EQ(0U, res.headers.size());
  4794. EXPECT_FALSE(res.has_header("a"));
  4795. res.set_header("a\rb", "0");
  4796. EXPECT_EQ(0U, res.headers.size());
  4797. EXPECT_FALSE(res.has_header("a"));
  4798. res.set_header("a\nb", "0");
  4799. EXPECT_EQ(0U, res.headers.size());
  4800. EXPECT_FALSE(res.has_header("a"));
  4801. res.set_redirect("1\r\nSet-Cookie: a=1");
  4802. EXPECT_EQ(0U, res.headers.size());
  4803. EXPECT_FALSE(res.has_header("Location"));
  4804. })
  4805. .Get("/slow",
  4806. [&](const Request & /*req*/, Response &res) {
  4807. std::this_thread::sleep_for(std::chrono::seconds(4));
  4808. res.set_content("slow", "text/plain");
  4809. })
  4810. #if 0
  4811. .Post("/slowpost",
  4812. [&](const Request & /*req*/, Response &res) {
  4813. std::this_thread::sleep_for(std::chrono::seconds(2));
  4814. res.set_content("slow", "text/plain");
  4815. })
  4816. #endif
  4817. .Get("/remote_addr",
  4818. [&](const Request &req, Response &res) {
  4819. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4820. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4821. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4822. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4823. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4824. #endif
  4825. res.set_content(req.remote_addr, "text/plain");
  4826. })
  4827. .Get("/local_addr",
  4828. [&](const Request &req, Response &res) {
  4829. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4830. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4831. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4832. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4833. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4834. #endif
  4835. auto local_addr = req.local_addr;
  4836. auto local_port = std::to_string(req.local_port);
  4837. res.set_content(local_addr.append(":").append(local_port),
  4838. "text/plain");
  4839. })
  4840. .Get("/endwith%",
  4841. [&](const Request & /*req*/, Response &res) {
  4842. res.set_content("Hello World!", "text/plain");
  4843. })
  4844. .Get("/a\\+\\+b",
  4845. [&](const Request &req, Response &res) {
  4846. ASSERT_TRUE(req.has_param("a +b"));
  4847. auto val = req.get_param_value("a +b");
  4848. res.set_content(val, "text/plain");
  4849. })
  4850. .Get("/", [&](const Request & /*req*/,
  4851. Response &res) { res.set_redirect("/hi"); })
  4852. .Post("/1",
  4853. [](const Request & /*req*/, Response &res) {
  4854. res.set_redirect("/2", StatusCode::SeeOther_303);
  4855. })
  4856. .Get("/2",
  4857. [](const Request & /*req*/, Response &res) {
  4858. res.set_content("redirected.", "text/plain");
  4859. res.status = StatusCode::OK_200;
  4860. })
  4861. .Post("/person",
  4862. [&](const Request &req, Response &res) {
  4863. if (req.has_param("name") && req.has_param("note")) {
  4864. persons_[req.get_param_value("name")] =
  4865. req.get_param_value("note");
  4866. } else {
  4867. res.status = StatusCode::BadRequest_400;
  4868. }
  4869. })
  4870. .Put("/person",
  4871. [&](const Request &req, Response &res) {
  4872. if (req.has_param("name") && req.has_param("note")) {
  4873. persons_[req.get_param_value("name")] =
  4874. req.get_param_value("note");
  4875. } else {
  4876. res.status = StatusCode::BadRequest_400;
  4877. }
  4878. })
  4879. .Get("/person/(.*)",
  4880. [&](const Request &req, Response &res) {
  4881. string name = req.matches[1];
  4882. if (persons_.find(name) != persons_.end()) {
  4883. auto note = persons_[name];
  4884. res.set_content(note, "text/plain");
  4885. } else {
  4886. res.status = StatusCode::NotFound_404;
  4887. }
  4888. })
  4889. .Delete("/person",
  4890. [&](const Request &req, Response &res) {
  4891. if (req.has_param("name")) {
  4892. string name = req.get_param_value("name");
  4893. if (persons_.find(name) != persons_.end()) {
  4894. persons_.erase(name);
  4895. res.set_content("DELETED", "text/plain");
  4896. } else {
  4897. res.status = StatusCode::NotFound_404;
  4898. }
  4899. } else {
  4900. res.status = StatusCode::BadRequest_400;
  4901. }
  4902. })
  4903. .Post("/x-www-form-urlencoded-json",
  4904. [&](const Request &req, Response &res) {
  4905. auto json = req.get_param_value("json");
  4906. ASSERT_EQ(JSON_DATA, json);
  4907. res.set_content(json, "appliation/json");
  4908. res.status = StatusCode::OK_200;
  4909. })
  4910. .Get("/streamed-chunked",
  4911. [&](const Request & /*req*/, Response &res) {
  4912. res.set_chunked_content_provider(
  4913. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4914. sink.os << "123";
  4915. sink.os << "456";
  4916. sink.os << "789";
  4917. sink.done();
  4918. return true;
  4919. });
  4920. })
  4921. .Get("/streamed-chunked-with-prohibited-trailer",
  4922. [&](const Request & /*req*/, Response &res) {
  4923. auto i = new int(0);
  4924. // Declare both a prohibited trailer (Content-Length) and an
  4925. // allowed one
  4926. res.set_header("Trailer", "Content-Length, X-Allowed");
  4927. res.set_chunked_content_provider(
  4928. "text/plain",
  4929. [i](size_t /*offset*/, DataSink &sink) {
  4930. switch (*i) {
  4931. case 0: sink.os << "123"; break;
  4932. case 1: sink.os << "456"; break;
  4933. case 2: sink.os << "789"; break;
  4934. case 3: {
  4935. sink.done_with_trailer(
  4936. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4937. } break;
  4938. }
  4939. (*i)++;
  4940. return true;
  4941. },
  4942. [i](bool success) {
  4943. EXPECT_TRUE(success);
  4944. delete i;
  4945. });
  4946. })
  4947. .Get("/streamed-chunked2",
  4948. [&](const Request & /*req*/, Response &res) {
  4949. auto i = new int(0);
  4950. res.set_chunked_content_provider(
  4951. "text/plain",
  4952. [i](size_t /*offset*/, DataSink &sink) {
  4953. switch (*i) {
  4954. case 0: sink.os << "123"; break;
  4955. case 1: sink.os << "456"; break;
  4956. case 2: sink.os << "789"; break;
  4957. case 3: sink.done(); break;
  4958. }
  4959. (*i)++;
  4960. return true;
  4961. },
  4962. [i](bool success) {
  4963. EXPECT_TRUE(success);
  4964. delete i;
  4965. });
  4966. })
  4967. .Get("/streamed-chunked-with-trailer",
  4968. [&](const Request & /*req*/, Response &res) {
  4969. auto i = new int(0);
  4970. res.set_header("Trailer", "Dummy1, Dummy2");
  4971. res.set_chunked_content_provider(
  4972. "text/plain",
  4973. [i](size_t /*offset*/, DataSink &sink) {
  4974. switch (*i) {
  4975. case 0: sink.os << "123"; break;
  4976. case 1: sink.os << "456"; break;
  4977. case 2: sink.os << "789"; break;
  4978. case 3: {
  4979. sink.done_with_trailer(
  4980. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4981. } break;
  4982. }
  4983. (*i)++;
  4984. return true;
  4985. },
  4986. [i](bool success) {
  4987. EXPECT_TRUE(success);
  4988. delete i;
  4989. });
  4990. })
  4991. .Get("/streamed",
  4992. [&](const Request & /*req*/, Response &res) {
  4993. res.set_content_provider(
  4994. 6, "text/plain",
  4995. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4996. sink.os << (offset < 3 ? "a" : "b");
  4997. return true;
  4998. });
  4999. })
  5000. .Get("/streamed-without-length",
  5001. [&](const Request & /*req*/, Response &res) {
  5002. auto data = new std::string("abcdefg");
  5003. res.set_content_provider(
  5004. "text/plain",
  5005. [data](size_t offset, DataSink &sink) {
  5006. if (offset < data->size()) {
  5007. sink.os << data->substr(offset);
  5008. }
  5009. sink.done();
  5010. return true;
  5011. },
  5012. [data](bool success) {
  5013. EXPECT_TRUE(success);
  5014. delete data;
  5015. });
  5016. })
  5017. .Get("/streamed-with-range",
  5018. [&](const Request &req, Response &res) {
  5019. auto data = new std::string("abcdefg");
  5020. // An explicit status keeps the server from picking the 206 it
  5021. // would otherwise choose for a ranged request, so the response
  5022. // is not a partial representation.
  5023. auto status = req.get_param_value("status");
  5024. if (status == "200") {
  5025. res.status = StatusCode::OK_200;
  5026. } else if (status == "403") {
  5027. res.status = StatusCode::Forbidden_403;
  5028. }
  5029. res.set_content_provider(
  5030. data->size(), "text/plain",
  5031. [data](size_t offset, size_t length, DataSink &sink) {
  5032. size_t DATA_CHUNK_SIZE = 4;
  5033. const auto &d = *data;
  5034. auto out_len =
  5035. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5036. auto ret =
  5037. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5038. EXPECT_TRUE(ret);
  5039. return true;
  5040. },
  5041. [data, &req](bool success) {
  5042. EXPECT_EQ(success, !req.has_param("error"));
  5043. delete data;
  5044. });
  5045. })
  5046. .Get("/streamed-cancel",
  5047. [&](const Request & /*req*/, Response &res) {
  5048. res.set_content_provider(
  5049. size_t(-1), "text/plain",
  5050. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5051. sink.os << "data_chunk";
  5052. return true;
  5053. });
  5054. })
  5055. .Get("/regex-with-delimiter",
  5056. [&](const Request &req, Response & /*res*/) {
  5057. ASSERT_TRUE(req.has_param("key"));
  5058. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5059. })
  5060. .Get("/with-range",
  5061. [&](const Request & /*req*/, Response &res) {
  5062. res.set_content("abcdefg", "text/plain");
  5063. })
  5064. .Get("/test-start-time",
  5065. [&](const Request &req, Response & /*res*/) {
  5066. EXPECT_NE(req.start_time_,
  5067. std::chrono::steady_clock::time_point::min());
  5068. })
  5069. .Get("/with-range-customized-response",
  5070. [&](const Request & /*req*/, Response &res) {
  5071. res.status = StatusCode::BadRequest_400;
  5072. res.set_content(JSON_DATA, "application/json");
  5073. })
  5074. .Post("/chunked",
  5075. [&](const Request &req, Response & /*res*/) {
  5076. EXPECT_EQ(req.body, "dechunked post body");
  5077. })
  5078. .Post("/large-chunked",
  5079. [&](const Request &req, Response & /*res*/) {
  5080. std::string expected(6 * 30 * 1024u, 'a');
  5081. EXPECT_EQ(req.body, expected);
  5082. })
  5083. .Post("/multipart",
  5084. [&](const Request &req, Response & /*res*/) {
  5085. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5086. req.form.get_field_count("text2") +
  5087. req.form.get_field_count("file3") +
  5088. req.form.get_field_count("file4"));
  5089. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5090. req.form.get_file_count("file2"));
  5091. ASSERT_TRUE(!req.form.has_file("???"));
  5092. ASSERT_TRUE(!req.form.has_field("???"));
  5093. ASSERT_TRUE(req.body.empty());
  5094. {
  5095. const auto &text = req.form.get_field("text1");
  5096. EXPECT_EQ("text default", text);
  5097. }
  5098. {
  5099. const auto &text = req.form.get_field("text2");
  5100. EXPECT_EQ("aωb", text);
  5101. }
  5102. {
  5103. const auto &file = req.form.get_file("file1");
  5104. EXPECT_EQ("hello.txt", file.filename);
  5105. EXPECT_EQ("text/plain", file.content_type);
  5106. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5107. }
  5108. {
  5109. const auto &file = req.form.get_file("file2");
  5110. EXPECT_EQ("world.json", file.filename);
  5111. EXPECT_EQ("application/json", file.content_type);
  5112. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5113. }
  5114. {
  5115. const auto &text = req.form.get_field("file3");
  5116. EXPECT_EQ(0u, text.size());
  5117. }
  5118. {
  5119. const auto &text = req.form.get_field("file4");
  5120. EXPECT_EQ(0u, text.size());
  5121. }
  5122. })
  5123. .Post("/multipart/multi_file_values",
  5124. [&](const Request &req, Response & /*res*/) {
  5125. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5126. req.form.get_field_count("multi_text1"));
  5127. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5128. ASSERT_TRUE(!req.form.has_file("???"));
  5129. ASSERT_TRUE(!req.form.has_field("???"));
  5130. ASSERT_TRUE(req.body.empty());
  5131. {
  5132. const auto &text = req.form.get_field("text");
  5133. EXPECT_EQ("default text", text);
  5134. }
  5135. {
  5136. const auto &text1_values = req.form.get_fields("multi_text1");
  5137. EXPECT_EQ(2u, text1_values.size());
  5138. EXPECT_EQ("aaaaa", text1_values[0]);
  5139. EXPECT_EQ("bbbbb", text1_values[1]);
  5140. }
  5141. {
  5142. const auto &file1_values = req.form.get_files("multi_file1");
  5143. EXPECT_EQ(2u, file1_values.size());
  5144. auto file1 = file1_values[0];
  5145. EXPECT_EQ(file1.filename, "hello.txt");
  5146. EXPECT_EQ(file1.content_type, "text/plain");
  5147. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5148. auto file2 = file1_values[1];
  5149. EXPECT_EQ(file2.filename, "world.json");
  5150. EXPECT_EQ(file2.content_type, "application/json");
  5151. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5152. }
  5153. })
  5154. .Post("/empty",
  5155. [&](const Request &req, Response &res) {
  5156. EXPECT_EQ(req.body, "");
  5157. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5158. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5159. res.set_content("empty", "text/plain");
  5160. })
  5161. .Post("/empty-no-content-type",
  5162. [&](const Request &req, Response &res) {
  5163. EXPECT_EQ(req.body, "");
  5164. EXPECT_FALSE(req.has_header("Content-Type"));
  5165. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5166. res.set_content("empty-no-content-type", "text/plain");
  5167. })
  5168. .Post("/path-only",
  5169. [&](const Request &req, Response &res) {
  5170. EXPECT_EQ(req.body, "");
  5171. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5172. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5173. res.set_content("path-only", "text/plain");
  5174. })
  5175. .Post("/path-headers-only",
  5176. [&](const Request &req, Response &res) {
  5177. EXPECT_EQ(req.body, "");
  5178. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5179. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5180. EXPECT_EQ("world", req.get_header_value("hello"));
  5181. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5182. res.set_content("path-headers-only", "text/plain");
  5183. })
  5184. .Post("/post-large",
  5185. [&](const Request &req, Response &res) {
  5186. EXPECT_EQ(req.body, LARGE_DATA);
  5187. res.set_content(req.body, "text/plain");
  5188. })
  5189. .Post("/post-loopback",
  5190. [&](const Request &, Response &res,
  5191. ContentReader const &content_reader) {
  5192. std::string body;
  5193. content_reader([&](const char *data, size_t data_length) {
  5194. body.append(data, data_length);
  5195. return true;
  5196. });
  5197. res.set_content(body, "text/plain");
  5198. })
  5199. .Put("/put-loopback",
  5200. [&](const Request &, Response &res,
  5201. ContentReader const &content_reader) {
  5202. std::string body;
  5203. content_reader([&](const char *data, size_t data_length) {
  5204. body.append(data, data_length);
  5205. return true;
  5206. });
  5207. res.set_content(body, "text/plain");
  5208. })
  5209. .Patch("/patch-loopback",
  5210. [&](const Request &, Response &res,
  5211. ContentReader const &content_reader) {
  5212. std::string body;
  5213. content_reader([&](const char *data, size_t data_length) {
  5214. body.append(data, data_length);
  5215. return true;
  5216. });
  5217. res.set_content(body, "text/plain");
  5218. })
  5219. .Put("/empty-no-content-type",
  5220. [&](const Request &req, Response &res) {
  5221. EXPECT_EQ(req.body, "");
  5222. EXPECT_FALSE(req.has_header("Content-Type"));
  5223. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5224. res.set_content("empty-no-content-type", "text/plain");
  5225. })
  5226. .Put("/put",
  5227. [&](const Request &req, Response &res) {
  5228. EXPECT_EQ(req.body, "PUT");
  5229. res.set_content(req.body, "text/plain");
  5230. })
  5231. .Put("/put-large",
  5232. [&](const Request &req, Response &res) {
  5233. EXPECT_EQ(req.body, LARGE_DATA);
  5234. res.set_content(req.body, "text/plain");
  5235. })
  5236. .Patch("/patch",
  5237. [&](const Request &req, Response &res) {
  5238. EXPECT_EQ(req.body, "PATCH");
  5239. res.set_content(req.body, "text/plain");
  5240. })
  5241. .Delete("/delete",
  5242. [&](const Request & /*req*/, Response &res) {
  5243. res.set_content("DELETE", "text/plain");
  5244. })
  5245. .Delete("/delete-body",
  5246. [&](const Request &req, Response &res) {
  5247. EXPECT_EQ(req.body, "content");
  5248. res.set_content(req.body, "text/plain");
  5249. })
  5250. .Options(R"(\*)",
  5251. [&](const Request & /*req*/, Response &res) {
  5252. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5253. })
  5254. .CustomRoute("PROPFIND", "/dav/:id",
  5255. [&](const Request &req, Response &res) {
  5256. res.set_header("x-body-size",
  5257. std::to_string(req.body.size()));
  5258. res.set_header("x-matched-route", req.matched_route);
  5259. res.set_header("x-dav-id", req.path_params.at("id"));
  5260. res.status = StatusCode::MultiStatus_207;
  5261. res.set_content(req.body, "application/xml");
  5262. })
  5263. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5264. [&](const Request &req, Response &res) {
  5265. res.set_header("x-dav-match", req.matches[1]);
  5266. res.status = StatusCode::MultiStatus_207;
  5267. })
  5268. .CustomRoute("MKCOL", "/dav-mkcol",
  5269. [&](const Request &req, Response &res) {
  5270. EXPECT_TRUE(req.body.empty());
  5271. res.status = StatusCode::Created_201;
  5272. })
  5273. .CustomRoute(
  5274. "REPORT", "/dav-report",
  5275. [&](const Request & /*req*/, Response &res,
  5276. const ContentReader &content_reader) {
  5277. std::string body;
  5278. content_reader([&](const char *data, size_t data_length) {
  5279. body.append(data, data_length);
  5280. return true;
  5281. });
  5282. res.set_header("x-body-size", std::to_string(body.size()));
  5283. res.status = StatusCode::MultiStatus_207;
  5284. res.set_content(body, "application/xml");
  5285. })
  5286. .Get("/request-target",
  5287. [&](const Request &req, Response & /*res*/) {
  5288. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5289. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5290. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5291. })
  5292. .Get("/long-query-value",
  5293. [&](const Request &req, Response & /*res*/) {
  5294. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5295. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5296. })
  5297. .Get("/too-long-query-value",
  5298. [&](const Request &req, Response & /*res*/) {
  5299. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5300. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5301. })
  5302. .Get("/array-param",
  5303. [&](const Request &req, Response & /*res*/) {
  5304. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5305. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5306. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5307. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5308. })
  5309. .Get("/array-param-values",
  5310. [&](const Request &req, Response & /*res*/) {
  5311. auto values = req.get_param_values("array");
  5312. EXPECT_EQ(3u, values.size());
  5313. EXPECT_EQ("value1", values[0]);
  5314. EXPECT_EQ("value2", values[1]);
  5315. EXPECT_EQ("value3", values[2]);
  5316. auto empty = req.get_param_values("nonexistent");
  5317. EXPECT_TRUE(empty.empty());
  5318. })
  5319. .Post("/validate-no-multiple-headers",
  5320. [&](const Request &req, Response & /*res*/) {
  5321. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5322. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5323. })
  5324. .Post("/content_receiver",
  5325. [&](const Request &req, Response &res,
  5326. const ContentReader &content_reader) {
  5327. if (req.is_multipart_form_data()) {
  5328. std::vector<FormData> items;
  5329. content_reader(
  5330. [&](const FormData &file) {
  5331. items.push_back(file);
  5332. return true;
  5333. },
  5334. [&](const char *data, size_t data_length) {
  5335. items.back().content.append(data, data_length);
  5336. return true;
  5337. });
  5338. EXPECT_EQ(5u, items.size());
  5339. {
  5340. const auto &file = get_file_value(items, "text1");
  5341. EXPECT_TRUE(file.filename.empty());
  5342. EXPECT_EQ("text default", file.content);
  5343. }
  5344. {
  5345. const auto &file = get_file_value(items, "text2");
  5346. EXPECT_TRUE(file.filename.empty());
  5347. EXPECT_EQ("aωb", file.content);
  5348. }
  5349. {
  5350. const auto &file = get_file_value(items, "file1");
  5351. EXPECT_EQ("hello.txt", file.filename);
  5352. EXPECT_EQ("text/plain", file.content_type);
  5353. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5354. }
  5355. {
  5356. const auto &file = get_file_value(items, "file2");
  5357. EXPECT_EQ("world.json", file.filename);
  5358. EXPECT_EQ("application/json", file.content_type);
  5359. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5360. }
  5361. {
  5362. const auto &file = get_file_value(items, "file3");
  5363. EXPECT_TRUE(file.filename.empty());
  5364. EXPECT_EQ("application/octet-stream", file.content_type);
  5365. EXPECT_EQ(0u, file.content.size());
  5366. }
  5367. } else {
  5368. std::string body;
  5369. content_reader([&](const char *data, size_t data_length) {
  5370. EXPECT_EQ(7U, data_length);
  5371. body.append(data, data_length);
  5372. return true;
  5373. });
  5374. EXPECT_EQ(body, "content");
  5375. res.set_content(body, "text/plain");
  5376. }
  5377. })
  5378. .Put("/content_receiver",
  5379. [&](const Request & /*req*/, Response &res,
  5380. const ContentReader &content_reader) {
  5381. std::string body;
  5382. content_reader([&](const char *data, size_t data_length) {
  5383. body.append(data, data_length);
  5384. return true;
  5385. });
  5386. EXPECT_EQ(body, "content");
  5387. res.set_content(body, "text/plain");
  5388. })
  5389. .Patch("/content_receiver",
  5390. [&](const Request & /*req*/, Response &res,
  5391. const ContentReader &content_reader) {
  5392. std::string body;
  5393. content_reader([&](const char *data, size_t data_length) {
  5394. body.append(data, data_length);
  5395. return true;
  5396. });
  5397. EXPECT_EQ(body, "content");
  5398. res.set_content(body, "text/plain");
  5399. })
  5400. .Post("/query-string-and-body",
  5401. [&](const Request &req, Response & /*res*/) {
  5402. ASSERT_TRUE(req.has_param("key"));
  5403. EXPECT_EQ(req.get_param_value("key"), "value");
  5404. EXPECT_EQ(req.body, "content");
  5405. })
  5406. .Get("/last-request",
  5407. [&](const Request &req, Response & /*res*/) {
  5408. EXPECT_EQ("close", req.get_header_value("Connection"));
  5409. })
  5410. .Get(R"(/redirect/(\d+))",
  5411. [&](const Request &req, Response &res) {
  5412. auto num = std::stoi(req.matches[1]) + 1;
  5413. std::string url = "/redirect/" + std::to_string(num);
  5414. res.set_redirect(url);
  5415. })
  5416. .Post("/binary",
  5417. [&](const Request &req, Response &res) {
  5418. EXPECT_EQ(4U, req.body.size());
  5419. EXPECT_EQ("application/octet-stream",
  5420. req.get_header_value("Content-Type"));
  5421. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5422. res.set_content(req.body, "application/octet-stream");
  5423. })
  5424. .Put("/binary",
  5425. [&](const Request &req, Response &res) {
  5426. EXPECT_EQ(4U, req.body.size());
  5427. EXPECT_EQ("application/octet-stream",
  5428. req.get_header_value("Content-Type"));
  5429. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5430. res.set_content(req.body, "application/octet-stream");
  5431. })
  5432. .Patch("/binary",
  5433. [&](const Request &req, Response &res) {
  5434. EXPECT_EQ(4U, req.body.size());
  5435. EXPECT_EQ("application/octet-stream",
  5436. req.get_header_value("Content-Type"));
  5437. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5438. res.set_content(req.body, "application/octet-stream");
  5439. })
  5440. .Delete("/binary",
  5441. [&](const Request &req, Response &res) {
  5442. EXPECT_EQ(4U, req.body.size());
  5443. EXPECT_EQ("application/octet-stream",
  5444. req.get_header_value("Content-Type"));
  5445. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5446. res.set_content(req.body, "application/octet-stream");
  5447. })
  5448. .Get("/issue1772",
  5449. [&](const Request & /*req*/, Response &res) {
  5450. res.status = 401;
  5451. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5452. })
  5453. .Delete("/issue609",
  5454. [](const httplib::Request &, httplib::Response &res,
  5455. const httplib::ContentReader &) {
  5456. res.set_content("ok", "text/plain");
  5457. })
  5458. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5459. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5460. .Get("/compress",
  5461. [&](const Request & /*req*/, Response &res) {
  5462. res.set_content(
  5463. "12345678901234567890123456789012345678901234567890123456789"
  5464. "01234567890123456789012345678901234567890",
  5465. "text/plain");
  5466. })
  5467. .Get("/compress-with-charset",
  5468. [&](const Request & /*req*/, Response &res) {
  5469. res.set_content(
  5470. "12345678901234567890123456789012345678901234567890123456789"
  5471. "01234567890123456789012345678901234567890",
  5472. "application/json; charset=utf-8");
  5473. })
  5474. .Get("/nocompress",
  5475. [&](const Request & /*req*/, Response &res) {
  5476. res.set_content(
  5477. "12345678901234567890123456789012345678901234567890123456789"
  5478. "01234567890123456789012345678901234567890",
  5479. "application/octet-stream");
  5480. })
  5481. .Post("/compress-multipart",
  5482. [&](const Request &req, Response & /*res*/) {
  5483. EXPECT_EQ(2u, req.form.fields.size());
  5484. ASSERT_TRUE(!req.form.has_field("???"));
  5485. {
  5486. const auto &text = req.form.get_field("key1");
  5487. EXPECT_EQ("test", text);
  5488. }
  5489. {
  5490. const auto &text = req.form.get_field("key2");
  5491. EXPECT_EQ("--abcdefg123", text);
  5492. }
  5493. })
  5494. #endif
  5495. ;
  5496. persons_["john"] = "programmer";
  5497. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5498. svr_.wait_until_ready();
  5499. }
  5500. virtual void TearDown() {
  5501. svr_.stop();
  5502. if (!request_threads_.empty()) {
  5503. std::this_thread::sleep_for(std::chrono::seconds(1));
  5504. for (auto &t : request_threads_) {
  5505. t.join();
  5506. }
  5507. }
  5508. t_.join();
  5509. }
  5510. map<string, string> persons_;
  5511. #ifdef CPPHTTPLIB_SSL_ENABLED
  5512. SSLClient cli_;
  5513. SSLServer svr_;
  5514. #else
  5515. Client cli_;
  5516. Server svr_;
  5517. #endif
  5518. thread t_;
  5519. std::vector<thread> request_threads_;
  5520. };
  5521. TEST_F(ServerTest, GetMethod200) {
  5522. auto res = cli_.Get("/hi");
  5523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5524. EXPECT_EQ("HTTP/1.1", res->version);
  5525. EXPECT_EQ(StatusCode::OK_200, res->status);
  5526. EXPECT_EQ("OK", res->reason);
  5527. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5528. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5529. EXPECT_EQ("Hello World!", res->body);
  5530. }
  5531. TEST_F(ServerTest, GetEmptyFile) {
  5532. auto res = cli_.Get("/empty_file");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ(StatusCode::OK_200, res->status);
  5535. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5536. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5537. EXPECT_EQ("", res->body);
  5538. }
  5539. TEST_F(ServerTest, GetFileContent) {
  5540. auto res = cli_.Get("/file_content");
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. EXPECT_EQ(StatusCode::OK_200, res->status);
  5543. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5544. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5545. EXPECT_EQ("test.html", res->body);
  5546. }
  5547. TEST_F(ServerTest, GetFileContentWithRange) {
  5548. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5550. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5551. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5552. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5553. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5554. EXPECT_EQ("est", res->body);
  5555. }
  5556. TEST_F(ServerTest, GetFileContentWithContentType) {
  5557. auto res = cli_.Get("/file_content_with_content_type");
  5558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5559. EXPECT_EQ(StatusCode::OK_200, res->status);
  5560. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5561. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5562. EXPECT_EQ("file\n", res->body);
  5563. }
  5564. TEST_F(ServerTest, GetInvalidFileContent) {
  5565. auto res = cli_.Get("/invalid_file_content");
  5566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5567. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5568. }
  5569. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5570. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5572. EXPECT_EQ("HTTP/1.1", res->version);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5575. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5576. EXPECT_EQ("Hello World!", res->body);
  5577. }
  5578. TEST_F(ServerTest, GetMethod302) {
  5579. auto res = cli_.Get("/");
  5580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5581. EXPECT_EQ(StatusCode::Found_302, res->status);
  5582. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5583. }
  5584. TEST_F(ServerTest, GetMethod302Redirect) {
  5585. cli_.set_follow_location(true);
  5586. auto res = cli_.Get("/");
  5587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. EXPECT_EQ("Hello World!", res->body);
  5590. EXPECT_EQ("/hi", res->location);
  5591. }
  5592. TEST_F(ServerTest, GetMethod404) {
  5593. auto res = cli_.Get("/invalid");
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5596. }
  5597. TEST_F(ServerTest, HeadMethod200) {
  5598. auto res = cli_.Head("/hi");
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::OK_200, res->status);
  5601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. EXPECT_TRUE(res->body.empty());
  5603. }
  5604. TEST_F(ServerTest, HeadMethod200Static) {
  5605. auto res = cli_.Head("/mount/dir/index.html");
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. EXPECT_EQ(StatusCode::OK_200, res->status);
  5608. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5609. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5610. EXPECT_TRUE(res->body.empty());
  5611. }
  5612. TEST_F(ServerTest, HeadMethod404) {
  5613. auto res = cli_.Head("/invalid");
  5614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5616. EXPECT_TRUE(res->body.empty());
  5617. }
  5618. TEST_F(ServerTest, GetMethodPersonJohn) {
  5619. auto res = cli_.Get("/person/john");
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. EXPECT_EQ(StatusCode::OK_200, res->status);
  5622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5623. EXPECT_EQ("programmer", res->body);
  5624. }
  5625. TEST_F(ServerTest, PostMethod1) {
  5626. auto res = cli_.Get("/person/john1");
  5627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5628. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5629. res = cli_.Post("/person", "name=john1&note=coder",
  5630. "application/x-www-form-urlencoded");
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. ASSERT_EQ(StatusCode::OK_200, res->status);
  5633. res = cli_.Get("/person/john1");
  5634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5635. ASSERT_EQ(StatusCode::OK_200, res->status);
  5636. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5637. ASSERT_EQ("coder", res->body);
  5638. }
  5639. TEST_F(ServerTest, PostMethod2) {
  5640. auto res = cli_.Get("/person/john2");
  5641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5642. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5643. Params params;
  5644. params.emplace("name", "john2");
  5645. params.emplace("note", "coder");
  5646. res = cli_.Post("/person", params);
  5647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5648. ASSERT_EQ(StatusCode::OK_200, res->status);
  5649. res = cli_.Get("/person/john2");
  5650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5651. ASSERT_EQ(StatusCode::OK_200, res->status);
  5652. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5653. ASSERT_EQ("coder", res->body);
  5654. }
  5655. TEST_F(ServerTest, PutMethod3) {
  5656. auto res = cli_.Get("/person/john3");
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5659. Params params;
  5660. params.emplace("name", "john3");
  5661. params.emplace("note", "coder");
  5662. res = cli_.Put("/person", params);
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::OK_200, res->status);
  5665. res = cli_.Get("/person/john3");
  5666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5667. ASSERT_EQ(StatusCode::OK_200, res->status);
  5668. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5669. ASSERT_EQ("coder", res->body);
  5670. }
  5671. TEST_F(ServerTest, DeleteMethod1) {
  5672. auto res = cli_.Get("/person/john4");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5675. Params params;
  5676. params.emplace("name", "john4");
  5677. params.emplace("note", "coder");
  5678. res = cli_.Post("/person", params);
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. ASSERT_EQ(StatusCode::OK_200, res->status);
  5681. res = cli_.Get("/person/john4");
  5682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5683. ASSERT_EQ(StatusCode::OK_200, res->status);
  5684. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5685. ASSERT_EQ("coder", res->body);
  5686. Params delete_params;
  5687. delete_params.emplace("name", "john4");
  5688. res = cli_.Delete("/person", delete_params);
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ("DELETED", res->body);
  5692. res = cli_.Get("/person/john4");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5695. }
  5696. TEST_F(ServerTest, DeleteMethod2) {
  5697. auto res = cli_.Get("/person/john5");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5700. Params params;
  5701. params.emplace("name", "john5");
  5702. params.emplace("note", "developer");
  5703. res = cli_.Post("/person", params);
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. ASSERT_EQ(StatusCode::OK_200, res->status);
  5706. res = cli_.Get("/person/john5");
  5707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5708. ASSERT_EQ(StatusCode::OK_200, res->status);
  5709. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5710. ASSERT_EQ("developer", res->body);
  5711. Params delete_params;
  5712. delete_params.emplace("name", "john5");
  5713. Headers headers;
  5714. headers.emplace("Custom-Header", "test-value");
  5715. res = cli_.Delete("/person", headers, delete_params);
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. ASSERT_EQ(StatusCode::OK_200, res->status);
  5718. ASSERT_EQ("DELETED", res->body);
  5719. res = cli_.Get("/person/john5");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5722. }
  5723. TEST_F(ServerTest, DeleteMethod3) {
  5724. auto res = cli_.Get("/person/john6");
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5727. Params params;
  5728. params.emplace("name", "john6");
  5729. params.emplace("note", "tester");
  5730. res = cli_.Post("/person", params);
  5731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5732. ASSERT_EQ(StatusCode::OK_200, res->status);
  5733. res = cli_.Get("/person/john6");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. ASSERT_EQ(StatusCode::OK_200, res->status);
  5736. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5737. ASSERT_EQ("tester", res->body);
  5738. Params delete_params;
  5739. delete_params.emplace("name", "john6");
  5740. Headers headers;
  5741. headers.emplace("Custom-Header", "test-value");
  5742. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5744. ASSERT_EQ(StatusCode::OK_200, res->status);
  5745. ASSERT_EQ("DELETED", res->body);
  5746. res = cli_.Get("/person/john6");
  5747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5748. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5749. }
  5750. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5751. Params params;
  5752. params.emplace("json", JSON_DATA);
  5753. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. ASSERT_EQ(StatusCode::OK_200, res->status);
  5756. ASSERT_EQ(JSON_DATA, res->body);
  5757. }
  5758. TEST_F(ServerTest, PostEmptyContent) {
  5759. auto res = cli_.Post("/empty", "", "text/plain");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. ASSERT_EQ(StatusCode::OK_200, res->status);
  5762. ASSERT_EQ("empty", res->body);
  5763. }
  5764. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5765. auto res = cli_.Post("/empty-no-content-type");
  5766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5767. ASSERT_EQ(StatusCode::OK_200, res->status);
  5768. ASSERT_EQ("empty-no-content-type", res->body);
  5769. }
  5770. TEST_F(ServerTest, PostPathOnly) {
  5771. auto res = cli_.Post("/path-only");
  5772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5773. ASSERT_EQ(StatusCode::OK_200, res->status);
  5774. ASSERT_EQ("path-only", res->body);
  5775. }
  5776. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5777. auto res = cli_.Post("/path-headers-only",
  5778. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. ASSERT_EQ(StatusCode::OK_200, res->status);
  5781. ASSERT_EQ("path-headers-only", res->body);
  5782. }
  5783. TEST_F(ServerTest, PostLarge) {
  5784. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. ASSERT_EQ(StatusCode::OK_200, res->status);
  5787. EXPECT_EQ(LARGE_DATA, res->body);
  5788. }
  5789. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5790. auto res = cli_.Put("/empty-no-content-type");
  5791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5792. ASSERT_EQ(StatusCode::OK_200, res->status);
  5793. ASSERT_EQ("empty-no-content-type", res->body);
  5794. }
  5795. TEST_F(ServerTest, GetMethodDir) {
  5796. auto res = cli_.Get("/dir/");
  5797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5798. EXPECT_EQ(StatusCode::OK_200, res->status);
  5799. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5800. auto body = R"(<html>
  5801. <head>
  5802. </head>
  5803. <body>
  5804. <a href="/dir/test.html">Test</a>
  5805. <a href="/hi">hi</a>
  5806. </body>
  5807. </html>
  5808. )";
  5809. EXPECT_EQ(body, res->body);
  5810. }
  5811. TEST_F(ServerTest, GetMethodDirTest) {
  5812. auto res = cli_.Get("/dir/test.html");
  5813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5814. EXPECT_EQ(StatusCode::OK_200, res->status);
  5815. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5816. EXPECT_EQ("test.html", res->body);
  5817. }
  5818. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5819. auto res = cli_.Get("/dir/../dir/test.html");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::OK_200, res->status);
  5822. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5823. EXPECT_EQ("test.html", res->body);
  5824. }
  5825. TEST_F(ServerTest, GetMethodInvalidPath) {
  5826. auto res = cli_.Get("/dir/../test.html");
  5827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5828. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5829. }
  5830. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5831. auto res = cli_.Get("/../www/dir/test.html");
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5834. }
  5835. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5836. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5838. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5839. }
  5840. TEST_F(ServerTest, GetMethodDirMountTest) {
  5841. auto res = cli_.Get("/mount/dir/test.html");
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. EXPECT_EQ(StatusCode::OK_200, res->status);
  5844. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5845. EXPECT_EQ("test.html", res->body);
  5846. }
  5847. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5848. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5850. EXPECT_EQ(StatusCode::OK_200, res->status);
  5851. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5852. EXPECT_EQ("test.html", res->body);
  5853. }
  5854. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5855. auto res = cli_.Get("/mount/dir/../test.html");
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5858. }
  5859. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5860. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5862. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5863. }
  5864. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5865. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5868. }
  5869. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5870. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5872. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5873. }
  5874. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5875. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5877. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5878. }
  5879. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5880. auto res = cli_.Get("/mount/dir");
  5881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5882. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5883. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5884. }
  5885. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5886. auto res = cli_.Get("//dir");
  5887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5888. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5889. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5890. }
  5891. TEST_F(ServerTest, PostMethod303) {
  5892. auto res = cli_.Post("/1", "body", "text/plain");
  5893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5894. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5895. EXPECT_EQ("/2", res->get_header_value("Location"));
  5896. }
  5897. TEST_F(ServerTest, PostMethod303Redirect) {
  5898. cli_.set_follow_location(true);
  5899. auto res = cli_.Post("/1", "body", "text/plain");
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::OK_200, res->status);
  5902. EXPECT_EQ("redirected.", res->body);
  5903. EXPECT_EQ("/2", res->location);
  5904. }
  5905. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5906. auto res = cli_.Get("/dir/test.abcde");
  5907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5908. EXPECT_EQ(StatusCode::OK_200, res->status);
  5909. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5910. EXPECT_EQ("abcde", res->body);
  5911. }
  5912. TEST_F(ServerTest, StaticFileRange) {
  5913. auto res =
  5914. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5917. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5918. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5919. EXPECT_EQ(true, res->has_header("Content-Range"));
  5920. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5921. EXPECT_EQ(std::string("cd"), res->body);
  5922. }
  5923. TEST_F(ServerTest, StaticFileRanges) {
  5924. auto res = cli_.Get("/dir/test.abcde",
  5925. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5928. EXPECT_TRUE(
  5929. res->get_header_value("Content-Type")
  5930. .find(
  5931. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5932. 0);
  5933. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5934. }
  5935. TEST_F(ServerTest, StaticFileRangeHead) {
  5936. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5939. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5940. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5941. EXPECT_EQ(true, res->has_header("Content-Range"));
  5942. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5943. }
  5944. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5945. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5948. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5949. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5950. EXPECT_EQ(true, res->has_header("Content-Range"));
  5951. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5952. res->get_header_value("Content-Range"));
  5953. EXPECT_EQ("LAST\n", res->body);
  5954. }
  5955. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5956. auto res =
  5957. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5959. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5960. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5961. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5962. EXPECT_EQ(true, res->has_header("Content-Range"));
  5963. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5964. }
  5965. TEST_F(ServerTest, StaticFileBigFile) {
  5966. auto res = cli_.Get("/dir/1MB.txt");
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. EXPECT_EQ(StatusCode::OK_200, res->status);
  5969. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5970. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5971. }
  5972. TEST_F(ServerTest, InvalidBaseDirMount) {
  5973. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5974. }
  5975. TEST_F(ServerTest, Binary) {
  5976. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5977. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5978. "application/octet-stream");
  5979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5980. ASSERT_EQ(StatusCode::OK_200, res->status);
  5981. ASSERT_EQ(4U, res->body.size());
  5982. res = cli_.Put("/binary", binary.data(), binary.size(),
  5983. "application/octet-stream");
  5984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5985. ASSERT_EQ(StatusCode::OK_200, res->status);
  5986. ASSERT_EQ(4U, res->body.size());
  5987. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5988. "application/octet-stream");
  5989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5990. ASSERT_EQ(StatusCode::OK_200, res->status);
  5991. ASSERT_EQ(4U, res->body.size());
  5992. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5993. "application/octet-stream");
  5994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5995. ASSERT_EQ(StatusCode::OK_200, res->status);
  5996. ASSERT_EQ(4U, res->body.size());
  5997. }
  5998. TEST_F(ServerTest, BinaryString) {
  5999. auto binary = std::string("\x00\x01\x02\x03", 4);
  6000. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. ASSERT_EQ(StatusCode::OK_200, res->status);
  6003. ASSERT_EQ(4U, res->body.size());
  6004. res = cli_.Put("/binary", binary, "application/octet-stream");
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. ASSERT_EQ(StatusCode::OK_200, res->status);
  6007. ASSERT_EQ(4U, res->body.size());
  6008. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. ASSERT_EQ(StatusCode::OK_200, res->status);
  6011. ASSERT_EQ(4U, res->body.size());
  6012. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6014. ASSERT_EQ(StatusCode::OK_200, res->status);
  6015. ASSERT_EQ(4U, res->body.size());
  6016. }
  6017. TEST_F(ServerTest, EmptyRequest) {
  6018. auto res = cli_.Get("");
  6019. ASSERT_TRUE(!res);
  6020. EXPECT_EQ(Error::Connection, res.error());
  6021. }
  6022. TEST_F(ServerTest, LongRequest) {
  6023. std::string request;
  6024. for (size_t i = 0; i < 545; i++) {
  6025. request += "/TooLongRequest";
  6026. }
  6027. request += "OK";
  6028. auto res = cli_.Get(request.c_str());
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6031. }
  6032. TEST_F(ServerTest, TooLongRequest) {
  6033. std::string request;
  6034. for (size_t i = 0; i < 546; i++) {
  6035. request += "/TooLongRequest";
  6036. }
  6037. request += "_NG";
  6038. auto start = std::chrono::high_resolution_clock::now();
  6039. cli_.set_keep_alive(true);
  6040. auto res = cli_.Get(request.c_str());
  6041. auto end = std::chrono::high_resolution_clock::now();
  6042. auto elapsed =
  6043. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6044. .count();
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6047. EXPECT_LE(elapsed, 1000);
  6048. EXPECT_EQ("close", res->get_header_value("Connection"));
  6049. EXPECT_FALSE(cli_.is_socket_open());
  6050. }
  6051. TEST_F(ServerTest, AlmostTooLongRequest) {
  6052. // test for #2046 - URI length check shouldn't include other content on req
  6053. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6054. // leading /, space, HTTP/1.1)
  6055. std::string request =
  6056. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6057. auto res = cli_.Get(request.c_str());
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6060. }
  6061. TEST_F(ServerTest, LongHeader) {
  6062. Request req;
  6063. req.method = "GET";
  6064. req.path = "/hi";
  6065. std::string host_and_port;
  6066. host_and_port += HOST;
  6067. host_and_port += ":";
  6068. host_and_port += std::to_string(PORT);
  6069. req.headers.emplace("Host", host_and_port.c_str());
  6070. req.headers.emplace("Accept", "*/*");
  6071. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6072. req.headers.emplace(
  6073. "Header-Name",
  6074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6082. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6083. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6084. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6085. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6102. "@@@@@@@@@@@@@@@@");
  6103. auto res = std::make_shared<Response>();
  6104. auto error = Error::Success;
  6105. auto ret = cli_.send(req, *res, error);
  6106. ASSERT_TRUE(ret);
  6107. EXPECT_EQ(StatusCode::OK_200, res->status);
  6108. }
  6109. TEST_F(ServerTest, LongQueryValue) {
  6110. auto start = std::chrono::high_resolution_clock::now();
  6111. cli_.set_keep_alive(true);
  6112. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6113. auto end = std::chrono::high_resolution_clock::now();
  6114. auto elapsed =
  6115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6116. .count();
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6119. EXPECT_LE(elapsed, 1000);
  6120. EXPECT_EQ("close", res->get_header_value("Connection"));
  6121. EXPECT_FALSE(cli_.is_socket_open());
  6122. }
  6123. TEST_F(ServerTest, TooLongQueryValue) {
  6124. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6125. ASSERT_FALSE(res);
  6126. EXPECT_EQ(Error::Read, res.error());
  6127. }
  6128. TEST_F(ServerTest, TooLongHeader) {
  6129. Request req;
  6130. req.method = "GET";
  6131. req.path = "/hi";
  6132. std::string host_and_port;
  6133. host_and_port += HOST;
  6134. host_and_port += ":";
  6135. host_and_port += std::to_string(PORT);
  6136. req.headers.emplace("Host", host_and_port.c_str());
  6137. req.headers.emplace("Accept", "*/*");
  6138. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6139. req.headers.emplace(
  6140. "Header-Name",
  6141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6169. "@@@@@@@@@@@@@@@@@");
  6170. auto res = std::make_shared<Response>();
  6171. auto error = Error::Success;
  6172. auto ret = cli_.send(req, *res, error);
  6173. ASSERT_TRUE(ret);
  6174. EXPECT_EQ(StatusCode::OK_200, res->status);
  6175. }
  6176. TEST_F(ServerTest, HeaderCountAtLimit) {
  6177. // Test with headers just under the 100 limit
  6178. httplib::Headers headers;
  6179. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6180. // This should keep us just under the 100 header limit
  6181. for (int i = 0; i < 95; i++) {
  6182. std::string name = "X-Test-Header-" + std::to_string(i);
  6183. std::string value = "value" + std::to_string(i);
  6184. headers.emplace(name, value);
  6185. }
  6186. // This should work fine as we're under the limit
  6187. auto res = cli_.Get("/hi", headers);
  6188. EXPECT_TRUE(res);
  6189. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6190. }
  6191. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6192. // Test with many headers to exceed the 100 limit
  6193. httplib::Headers headers;
  6194. // Add 150 headers to definitely exceed the 100 limit
  6195. for (int i = 0; i < 150; i++) {
  6196. std::string name = "X-Test-Header-" + std::to_string(i);
  6197. std::string value = "value" + std::to_string(i);
  6198. headers.emplace(name, value);
  6199. }
  6200. // This should fail due to exceeding header count limit
  6201. cli_.set_keep_alive(true);
  6202. auto res = cli_.Get("/hi", headers);
  6203. // The server should respond with 400 Bad Request
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6206. EXPECT_EQ("close", res->get_header_value("Connection"));
  6207. EXPECT_FALSE(cli_.is_socket_open());
  6208. }
  6209. TEST_F(ServerTest, PercentEncoding) {
  6210. auto res = cli_.Get("/e%6edwith%");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. EXPECT_EQ(StatusCode::OK_200, res->status);
  6213. }
  6214. TEST_F(ServerTest, PercentEncodingUnicode) {
  6215. auto res = cli_.Get("/e%u006edwith%");
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. EXPECT_EQ(StatusCode::OK_200, res->status);
  6218. }
  6219. TEST_F(ServerTest, InvalidPercentEncoding) {
  6220. auto res = cli_.Get("/%endwith%");
  6221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6223. }
  6224. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6225. auto res = cli_.Get("/%uendwith%");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6228. }
  6229. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6230. auto res = cli_.Get("/hello?aaa=bbb%");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6233. }
  6234. TEST_F(ServerTest, PlusSignEncoding) {
  6235. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::OK_200, res->status);
  6238. EXPECT_EQ("a +b", res->body);
  6239. }
  6240. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6241. // This test simulates a potential DoS attack using many headers
  6242. // to verify our security fix prevents memory exhaustion
  6243. httplib::Headers attack_headers;
  6244. // Attempt to add many headers like an attacker would (200 headers to far
  6245. // exceed limit)
  6246. for (int i = 0; i < 200; i++) {
  6247. std::string name = "X-Attack-Header-" + std::to_string(i);
  6248. std::string value = "attack_payload_" + std::to_string(i);
  6249. attack_headers.emplace(name, value);
  6250. }
  6251. // Try to POST with excessive headers
  6252. cli_.set_keep_alive(true);
  6253. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6254. // Should either fail or return 400 Bad Request due to security limit
  6255. if (res) {
  6256. // If we get a response, it should be 400 Bad Request
  6257. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6258. EXPECT_EQ("close", res->get_header_value("Connection"));
  6259. }
  6260. EXPECT_FALSE(cli_.is_socket_open());
  6261. }
  6262. TEST_F(ServerTest, MultipartFormData) {
  6263. UploadFormDataItems items = {
  6264. {"text1", "text default", "", ""},
  6265. {"text2", "aωb", "", ""},
  6266. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6267. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6268. {"file3", "", "", "application/octet-stream"},
  6269. {"file4", "", "", " application/json tmp-string "}};
  6270. auto res = cli_.Post("/multipart", items);
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. EXPECT_EQ(StatusCode::OK_200, res->status);
  6273. }
  6274. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6275. UploadFormDataItems items = {
  6276. {"text", "default text", "", ""},
  6277. {"multi_text1", "aaaaa", "", ""},
  6278. {"multi_text1", "bbbbb", "", ""},
  6279. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6280. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6281. "application/json"},
  6282. };
  6283. auto res = cli_.Post("/multipart/multi_file_values", items);
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::OK_200, res->status);
  6286. }
  6287. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6288. auto res = cli_.Get("/hi");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6292. EXPECT_EQ("Hello World!", res->body);
  6293. }
  6294. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6295. Request req;
  6296. req.method = "POST";
  6297. req.path = "/chunked";
  6298. std::string host_and_port;
  6299. host_and_port += HOST;
  6300. host_and_port += ":";
  6301. host_and_port += std::to_string(PORT);
  6302. req.headers.emplace("Host", host_and_port.c_str());
  6303. req.headers.emplace("Accept", "*/*");
  6304. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6305. req.headers.emplace("Content-Type", "text/plain");
  6306. req.headers.emplace("Content-Length", "0");
  6307. req.headers.emplace(
  6308. "Transfer-Encoding",
  6309. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6310. // Client does not chunk, so make a chunked body manually.
  6311. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6312. auto res = std::make_shared<Response>();
  6313. auto error = Error::Success;
  6314. auto ret = cli_.send(req, *res, error);
  6315. ASSERT_TRUE(ret);
  6316. EXPECT_EQ(StatusCode::OK_200, res->status);
  6317. }
  6318. template <typename ClientT>
  6319. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6320. int expected_status) {
  6321. Request req;
  6322. req.method = "POST";
  6323. req.path = "/chunked";
  6324. std::string host_and_port;
  6325. host_and_port += HOST;
  6326. host_and_port += ":";
  6327. host_and_port += std::to_string(PORT);
  6328. req.headers.emplace("Host", host_and_port.c_str());
  6329. req.headers.emplace("Content-Length", "0");
  6330. req.headers.emplace("Transfer-Encoding", "chunked");
  6331. req.body = body;
  6332. auto res = std::make_shared<Response>();
  6333. auto error = Error::Success;
  6334. ASSERT_TRUE(cli.send(req, *res, error));
  6335. EXPECT_EQ(expected_status, res->status);
  6336. }
  6337. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6338. // rather than treat them as valid lengths.
  6339. template <typename ClientT>
  6340. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6341. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6342. }
  6343. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6344. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6345. }
  6346. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6347. expect_chunked_body_rejected(
  6348. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6349. }
  6350. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6351. // chunk-size line carries no CR, LF or other control character ahead of its
  6352. // terminator. Such a line must be refused rather than read as extension text.
  6353. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6354. expect_chunked_body_rejected(
  6355. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6356. }
  6357. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6358. expect_chunked_body_rejected(
  6359. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6360. }
  6361. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6362. expect_chunked_body_rejected(
  6363. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6364. }
  6365. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6366. // The literal stays split: a hex escape consumes every hex digit that
  6367. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6368. expect_chunked_body_rejected(
  6369. cli_, "4;a\x01"
  6370. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6371. }
  6372. TEST_F(ServerTest, AcceptsChunkExtension) {
  6373. expect_chunked_body_status(cli_,
  6374. "4;name=value\r\ndech\r\n"
  6375. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6376. "0;last\r\n\r\n",
  6377. StatusCode::OK_200);
  6378. }
  6379. TEST_F(ServerTest, GetStreamed2) {
  6380. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6383. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6384. EXPECT_EQ(true, res->has_header("Content-Range"));
  6385. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6386. EXPECT_EQ(std::string("ab"), res->body);
  6387. }
  6388. TEST_F(ServerTest, GetStreamed) {
  6389. auto res = cli_.Get("/streamed");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6393. EXPECT_EQ(std::string("aaabbb"), res->body);
  6394. }
  6395. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6396. auto res = cli_.Get("/streamed-without-length",
  6397. Headers{make_range_header({{0, -1}})});
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. EXPECT_EQ(StatusCode::OK_200, res->status);
  6400. EXPECT_EQ(false, res->has_header("Content-Length"));
  6401. EXPECT_EQ(false, res->has_header("Content-Range"));
  6402. EXPECT_EQ(std::string("abcdefg"), res->body);
  6403. }
  6404. TEST_F(ServerTest, GetStreamedWithRange1) {
  6405. auto res =
  6406. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6408. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6409. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6410. EXPECT_EQ(true, res->has_header("Content-Range"));
  6411. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6412. EXPECT_EQ(std::string("def"), res->body);
  6413. }
  6414. TEST_F(ServerTest, GetStreamedWithRange2) {
  6415. auto res =
  6416. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6419. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6420. EXPECT_EQ(true, res->has_header("Content-Range"));
  6421. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6422. EXPECT_EQ(std::string("bcdefg"), res->body);
  6423. }
  6424. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6425. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6427. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6428. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6429. EXPECT_EQ(true, res->has_header("Content-Range"));
  6430. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6431. EXPECT_EQ(std::string("efg"), res->body);
  6432. }
  6433. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6434. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6435. // the entire representation.
  6436. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6437. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6440. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6441. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6442. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6443. }
  6444. }
  6445. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6446. auto res =
  6447. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6450. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6451. EXPECT_EQ(false, res->has_header("Content-Range"));
  6452. EXPECT_EQ(0U, res->body.size());
  6453. }
  6454. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6455. // Only a 206 is served as a partial representation. Under any other status
  6456. // `apply_ranges()` reported the full content length, so the body must match
  6457. // that header, and the content provider must never be asked for an offset
  6458. // outside the representation.
  6459. auto check = [&](int status, const char *range) {
  6460. auto path =
  6461. std::string("/streamed-with-range?status=") + std::to_string(status);
  6462. auto ctx = path + " Range: " + range;
  6463. auto res = cli_.Get(path, Headers{{"Range", range}});
  6464. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6465. EXPECT_EQ(status, res->status) << ctx;
  6466. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6467. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6468. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6469. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6470. };
  6471. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6472. check(403, "bytes=3-5");
  6473. // The offset is far past the representation.
  6474. check(403, "bytes=100000-100200");
  6475. // `first_pos` is still -1 here, and the bounds asserts in
  6476. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6477. check(403, "bytes=-3");
  6478. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6479. // multipart branch would have written one that is empty.
  6480. check(403, "bytes=1-2, 4-5");
  6481. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6482. // covers the whole representation.
  6483. check(200, "bytes=3-5");
  6484. check(200, "bytes=1-2, 4-5");
  6485. }
  6486. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6487. auto res =
  6488. cli_.Get("/streamed-with-range",
  6489. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6490. "92233720368547758079223372036854775807"}});
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6493. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6494. EXPECT_EQ(false, res->has_header("Content-Range"));
  6495. EXPECT_EQ(0U, res->body.size());
  6496. }
  6497. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6498. auto res = cli_.Get(
  6499. "/with-range",
  6500. Headers{{"Range",
  6501. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6502. {"Accept-Encoding", ""}});
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6505. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6506. EXPECT_EQ(true, res->has_header("Content-Range"));
  6507. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6508. EXPECT_EQ(std::string("abcdefg"), res->body);
  6509. }
  6510. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6511. auto res = cli_.Get("/with-range", Headers{
  6512. {"Range", "bytes=0-"},
  6513. {"Accept-Encoding", ""},
  6514. });
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6517. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6518. EXPECT_EQ(true, res->has_header("Content-Range"));
  6519. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6520. EXPECT_EQ(std::string("abcdefg"), res->body);
  6521. }
  6522. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6523. auto res = cli_.Get("/streamed-with-range",
  6524. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6526. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6527. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6528. EXPECT_EQ(false, res->has_header("Content-Range"));
  6529. EXPECT_EQ(267U, res->body.size());
  6530. // Check that both range contents are present
  6531. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6532. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6533. // Check that Content-Range headers are present for both ranges
  6534. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6535. std::string::npos);
  6536. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6537. std::string::npos);
  6538. }
  6539. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6540. Ranges ranges;
  6541. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6542. ranges.emplace_back(0, -1);
  6543. }
  6544. auto res = cli_.Get("/streamed-with-range?error",
  6545. Headers{{make_range_header(ranges)}});
  6546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6547. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6548. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6549. EXPECT_EQ(false, res->has_header("Content-Range"));
  6550. EXPECT_EQ(0U, res->body.size());
  6551. }
  6552. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6553. auto res = cli_.Get("/streamed-with-range",
  6554. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6556. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6557. EXPECT_EQ(5U, res->body.size());
  6558. // Check that overlapping ranges are coalesced into a single range
  6559. EXPECT_EQ("bcdef", res->body);
  6560. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6561. // Should be single range, not multipart
  6562. EXPECT_TRUE(res->has_header("Content-Range"));
  6563. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6564. }
  6565. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6566. auto res = cli_.Get("/streamed-with-range",
  6567. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6570. EXPECT_EQ(268U, res->body.size());
  6571. // Check that both range contents are present
  6572. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6573. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6574. // Check that Content-Range headers are present for both ranges
  6575. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6576. std::string::npos);
  6577. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6578. std::string::npos);
  6579. }
  6580. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6581. auto res = cli_.Get("/streamed-with-range",
  6582. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6584. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6585. EXPECT_EQ(269U, res->body.size());
  6586. // Check that both duplicate range contents are present
  6587. size_t first_abc = res->body.find("abc\r\n");
  6588. EXPECT_TRUE(first_abc != std::string::npos);
  6589. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6590. EXPECT_TRUE(second_abc != std::string::npos);
  6591. // Check that Content-Range headers are present for both ranges
  6592. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6593. EXPECT_TRUE(first_range != std::string::npos);
  6594. size_t second_range =
  6595. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6596. EXPECT_TRUE(second_range != std::string::npos);
  6597. }
  6598. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6599. auto res =
  6600. cli_.Get("/streamed-with-range?error",
  6601. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6604. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6605. EXPECT_EQ(false, res->has_header("Content-Range"));
  6606. EXPECT_EQ(0U, res->body.size());
  6607. }
  6608. TEST_F(ServerTest, GetStreamedEndless) {
  6609. uint64_t offset = 0;
  6610. auto res = cli_.Get("/streamed-cancel",
  6611. [&](const char * /*data*/, uint64_t data_length) {
  6612. if (offset < 100) {
  6613. offset += data_length;
  6614. return true;
  6615. }
  6616. return false;
  6617. });
  6618. ASSERT_TRUE(!res);
  6619. EXPECT_EQ(Error::Canceled, res.error());
  6620. }
  6621. TEST_F(ServerTest, ClientStop) {
  6622. std::atomic_size_t count{4};
  6623. std::vector<std::thread> threads;
  6624. for (auto i = count.load(); i != 0; --i) {
  6625. threads.emplace_back([&]() {
  6626. auto res = cli_.Get("/streamed-cancel",
  6627. [&](const char *, uint64_t) { return true; });
  6628. --count;
  6629. ASSERT_TRUE(!res);
  6630. EXPECT_TRUE(res.error() == Error::Canceled ||
  6631. res.error() == Error::Read || res.error() == Error::Write);
  6632. });
  6633. }
  6634. std::this_thread::sleep_for(std::chrono::seconds(2));
  6635. while (count != 0) {
  6636. cli_.stop();
  6637. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6638. }
  6639. for (auto &t : threads) {
  6640. t.join();
  6641. }
  6642. }
  6643. TEST_F(ServerTest, GetWithRange1) {
  6644. auto res = cli_.Get("/with-range", Headers{
  6645. make_range_header({{3, 5}}),
  6646. {"Accept-Encoding", ""},
  6647. });
  6648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6649. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6650. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6651. EXPECT_EQ(true, res->has_header("Content-Range"));
  6652. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6653. EXPECT_EQ(std::string("def"), res->body);
  6654. }
  6655. TEST_F(ServerTest, GetWithRange2) {
  6656. auto res = cli_.Get("/with-range", Headers{
  6657. make_range_header({{1, -1}}),
  6658. {"Accept-Encoding", ""},
  6659. });
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6662. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6663. EXPECT_EQ(true, res->has_header("Content-Range"));
  6664. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6665. EXPECT_EQ(std::string("bcdefg"), res->body);
  6666. }
  6667. TEST_F(ServerTest, GetWithRange3) {
  6668. auto res = cli_.Get("/with-range", Headers{
  6669. make_range_header({{0, 0}}),
  6670. {"Accept-Encoding", ""},
  6671. });
  6672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6673. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6674. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6675. EXPECT_EQ(true, res->has_header("Content-Range"));
  6676. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6677. EXPECT_EQ(std::string("a"), res->body);
  6678. }
  6679. TEST_F(ServerTest, GetWithRange4) {
  6680. auto res = cli_.Get("/with-range", Headers{
  6681. make_range_header({{-1, 2}}),
  6682. {"Accept-Encoding", ""},
  6683. });
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6686. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6687. EXPECT_EQ(true, res->has_header("Content-Range"));
  6688. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6689. EXPECT_EQ(std::string("fg"), res->body);
  6690. }
  6691. TEST_F(ServerTest, GetWithRange5) {
  6692. auto res = cli_.Get("/with-range", Headers{
  6693. make_range_header({{0, 5}}),
  6694. {"Accept-Encoding", ""},
  6695. });
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6698. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6699. EXPECT_EQ(true, res->has_header("Content-Range"));
  6700. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6701. EXPECT_EQ(std::string("abcdef"), res->body);
  6702. }
  6703. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6704. auto res =
  6705. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6708. }
  6709. TEST_F(ServerTest, GetWithRangeMultipart) {
  6710. auto res =
  6711. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6714. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6715. EXPECT_EQ(false, res->has_header("Content-Range"));
  6716. EXPECT_EQ(267U, res->body.size());
  6717. }
  6718. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6719. auto res = cli_.Get("/with-range",
  6720. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6723. }
  6724. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6725. auto res = cli_.Get("/with-range-customized-response",
  6726. Headers{{make_range_header({{1, 2}})}});
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6729. EXPECT_EQ(true, res->has_header("Content-Length"));
  6730. EXPECT_EQ(false, res->has_header("Content-Range"));
  6731. EXPECT_EQ(JSON_DATA, res->body);
  6732. }
  6733. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6734. auto res = cli_.Get("/with-range-customized-response",
  6735. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6737. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6738. EXPECT_EQ(true, res->has_header("Content-Length"));
  6739. EXPECT_EQ(false, res->has_header("Content-Range"));
  6740. EXPECT_EQ(JSON_DATA, res->body);
  6741. }
  6742. TEST_F(ServerTest, Issue1772) {
  6743. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6746. }
  6747. TEST_F(ServerTest, Issue609) {
  6748. auto res = cli_.Delete("/issue609");
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. EXPECT_EQ(std::string("ok"), res->body);
  6752. }
  6753. TEST_F(ServerTest, GetStreamedChunked) {
  6754. auto res = cli_.Get("/streamed-chunked");
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. EXPECT_EQ(StatusCode::OK_200, res->status);
  6757. EXPECT_EQ(std::string("123456789"), res->body);
  6758. }
  6759. TEST_F(ServerTest, GetStreamedChunked2) {
  6760. auto res = cli_.Get("/streamed-chunked2");
  6761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6762. EXPECT_EQ(StatusCode::OK_200, res->status);
  6763. EXPECT_EQ(std::string("123456789"), res->body);
  6764. }
  6765. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6766. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6768. EXPECT_EQ(StatusCode::OK_200, res->status);
  6769. EXPECT_EQ(std::string("123456789"), res->body);
  6770. EXPECT_TRUE(res->has_header("Trailer"));
  6771. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6772. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6773. // Trailers are now stored separately from headers (security fix)
  6774. EXPECT_EQ(2U, res->trailers.size());
  6775. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6776. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6777. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6778. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6779. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6780. // Verify trailers are NOT in headers (security verification)
  6781. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6782. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6783. }
  6784. TEST_F(ServerTest, LargeChunkedPost) {
  6785. Request req;
  6786. req.method = "POST";
  6787. req.path = "/large-chunked";
  6788. std::string host_and_port;
  6789. host_and_port += HOST;
  6790. host_and_port += ":";
  6791. host_and_port += std::to_string(PORT);
  6792. req.headers.emplace("Host", host_and_port.c_str());
  6793. req.headers.emplace("Accept", "*/*");
  6794. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6795. req.headers.emplace("Content-Type", "text/plain");
  6796. req.headers.emplace("Content-Length", "0");
  6797. req.headers.emplace("Transfer-Encoding", "chunked");
  6798. std::string long_string(30 * 1024u, 'a');
  6799. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6800. // Attempt to make a large enough post to exceed OS buffers, to test that
  6801. // the server handles short reads if the full chunk data isn't available.
  6802. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6803. auto res = std::make_shared<Response>();
  6804. auto error = Error::Success;
  6805. auto ret = cli_.send(req, *res, error);
  6806. ASSERT_TRUE(ret);
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. }
  6809. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6810. auto res = cli_.Get("/remote_addr");
  6811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6812. EXPECT_EQ(StatusCode::OK_200, res->status);
  6813. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6814. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6815. }
  6816. TEST_F(ServerTest, GetMethodLocalAddr) {
  6817. auto res = cli_.Get("/local_addr");
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. EXPECT_EQ(StatusCode::OK_200, res->status);
  6820. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6821. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6822. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6823. }
  6824. TEST_F(ServerTest, HTTPResponseSplitting) {
  6825. auto res = cli_.Get("/http_response_splitting");
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. }
  6829. TEST_F(ServerTest, SlowRequest) {
  6830. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6831. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6832. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6833. }
  6834. #if 0
  6835. TEST_F(ServerTest, SlowPost) {
  6836. char buffer[64 * 1024];
  6837. memset(buffer, 0x42, sizeof(buffer));
  6838. auto res = cli_.Post(
  6839. "/slowpost", 64 * 1024 * 1024,
  6840. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6841. auto ret = sink.write(buffer, sizeof(buffer));
  6842. EXPECT_TRUE(ret);
  6843. return true;
  6844. },
  6845. "text/plain");
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::OK_200, res->status);
  6848. }
  6849. TEST_F(ServerTest, SlowPostFail) {
  6850. char buffer[64 * 1024];
  6851. memset(buffer, 0x42, sizeof(buffer));
  6852. cli_.set_write_timeout(std::chrono::seconds(0));
  6853. auto res = cli_.Post(
  6854. "/slowpost", 64 * 1024 * 1024,
  6855. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6856. sink.write(buffer, sizeof(buffer));
  6857. return true;
  6858. },
  6859. "text/plain");
  6860. ASSERT_TRUE(!res);
  6861. EXPECT_EQ(Error::Write, res.error());
  6862. }
  6863. #endif
  6864. TEST_F(ServerTest, Put) {
  6865. auto res = cli_.Put("/put", "PUT", "text/plain");
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("PUT", res->body);
  6869. }
  6870. TEST_F(ServerTest, PutWithContentProvider) {
  6871. auto res = cli_.Put(
  6872. "/put", 3,
  6873. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6874. sink.os << "PUT";
  6875. return true;
  6876. },
  6877. "text/plain");
  6878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6879. EXPECT_EQ(StatusCode::OK_200, res->status);
  6880. EXPECT_EQ("PUT", res->body);
  6881. }
  6882. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6883. auto res = cli_.Post(
  6884. "/post", 42,
  6885. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6886. return false;
  6887. },
  6888. "text/plain");
  6889. ASSERT_TRUE(!res);
  6890. EXPECT_EQ(Error::Canceled, res.error());
  6891. }
  6892. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6893. auto res = cli_.Put(
  6894. "/put",
  6895. [](size_t /*offset*/, DataSink &sink) {
  6896. sink.os << "PUT";
  6897. sink.done();
  6898. return true;
  6899. },
  6900. "text/plain");
  6901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6902. EXPECT_EQ(StatusCode::OK_200, res->status);
  6903. EXPECT_EQ("PUT", res->body);
  6904. }
  6905. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6906. auto res = cli_.Post(
  6907. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6908. "text/plain");
  6909. ASSERT_TRUE(!res);
  6910. EXPECT_EQ(Error::Canceled, res.error());
  6911. }
  6912. TEST_F(ServerTest, PostLoopBack) {
  6913. std::string body;
  6914. auto res = cli_.Post(
  6915. "/post-loopback", 9,
  6916. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6917. EXPECT_EQ(9u, length);
  6918. sink.write("123", 3);
  6919. sink.write("456", 3);
  6920. sink.write("789", 3);
  6921. return true;
  6922. },
  6923. "text/plain",
  6924. [&body](const char *data, size_t data_length) {
  6925. body.append(data, data_length);
  6926. return true;
  6927. });
  6928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6929. EXPECT_EQ(StatusCode::OK_200, res->status);
  6930. EXPECT_EQ("123456789", body);
  6931. }
  6932. TEST_F(ServerTest, PutLoopBack) {
  6933. std::string body;
  6934. auto res = cli_.Put(
  6935. "/put-loopback", 9,
  6936. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6937. EXPECT_EQ(9u, length);
  6938. sink.write("123", 3);
  6939. sink.write("456", 3);
  6940. sink.write("789", 3);
  6941. return true;
  6942. },
  6943. "text/plain",
  6944. [&body](const char *data, size_t data_length) {
  6945. body.append(data, data_length);
  6946. return true;
  6947. });
  6948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6949. EXPECT_EQ(StatusCode::OK_200, res->status);
  6950. EXPECT_EQ("123456789", body);
  6951. }
  6952. TEST_F(ServerTest, PatchLoopBack) {
  6953. std::string body;
  6954. auto res = cli_.Patch(
  6955. "/patch-loopback", 9,
  6956. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6957. EXPECT_EQ(9u, length);
  6958. sink.write("123", 3);
  6959. sink.write("456", 3);
  6960. sink.write("789", 3);
  6961. return true;
  6962. },
  6963. "text/plain",
  6964. [&body](const char *data, size_t data_length) {
  6965. body.append(data, data_length);
  6966. return true;
  6967. });
  6968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6969. EXPECT_EQ(StatusCode::OK_200, res->status);
  6970. EXPECT_EQ("123456789", body);
  6971. }
  6972. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6973. std::string body;
  6974. auto res = cli_.Post(
  6975. "/post-loopback",
  6976. [](size_t /*offset*/, DataSink &sink) {
  6977. sink.write("123", 3);
  6978. sink.write("456", 3);
  6979. sink.write("789", 3);
  6980. sink.done();
  6981. return true;
  6982. },
  6983. "text/plain",
  6984. [&body](const char *data, size_t data_length) {
  6985. body.append(data, data_length);
  6986. return true;
  6987. });
  6988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6989. EXPECT_EQ(StatusCode::OK_200, res->status);
  6990. EXPECT_EQ("123456789", body);
  6991. }
  6992. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6993. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6994. cli_.set_compress(true);
  6995. auto res = cli_.Put(
  6996. "/put", 3,
  6997. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6998. sink.os << "PUT";
  6999. return true;
  7000. },
  7001. "text/plain");
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::OK_200, res->status);
  7004. EXPECT_EQ("PUT", res->body);
  7005. }
  7006. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7007. cli_.set_compress(true);
  7008. auto res = cli_.Post(
  7009. "/post", 42,
  7010. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7011. return false;
  7012. },
  7013. "text/plain");
  7014. ASSERT_TRUE(!res);
  7015. EXPECT_EQ(Error::Canceled, res.error());
  7016. }
  7017. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7018. cli_.set_compress(true);
  7019. auto res = cli_.Put(
  7020. "/put",
  7021. [](size_t /*offset*/, DataSink &sink) {
  7022. sink.os << "PUT";
  7023. sink.done();
  7024. return true;
  7025. },
  7026. "text/plain");
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::OK_200, res->status);
  7029. EXPECT_EQ("PUT", res->body);
  7030. }
  7031. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7032. cli_.set_compress(true);
  7033. auto res = cli_.Post(
  7034. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7035. "text/plain");
  7036. ASSERT_TRUE(!res);
  7037. EXPECT_EQ(Error::Canceled, res.error());
  7038. }
  7039. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7040. cli_.set_compress(true);
  7041. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7043. EXPECT_EQ(StatusCode::OK_200, res->status);
  7044. EXPECT_EQ(LARGE_DATA, res->body);
  7045. }
  7046. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7047. #ifdef CPPHTTPLIB_SSL_ENABLED
  7048. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7049. Client cli(s.c_str());
  7050. cli.enable_server_certificate_verification(false);
  7051. #else
  7052. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7053. Client cli(s.c_str());
  7054. #endif
  7055. cli.set_compress(true);
  7056. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::OK_200, res->status);
  7059. EXPECT_EQ(LARGE_DATA, res->body);
  7060. // The compressed size should be less than a 10th of the original. May vary
  7061. // depending on the zlib library.
  7062. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7063. static_cast<uint64_t>(10 * 1024 * 1024));
  7064. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7065. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7066. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7067. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7068. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7069. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7070. #endif
  7071. }
  7072. TEST_F(ServerTest, PutContentWithDeflate) {
  7073. cli_.set_compress(false);
  7074. Headers headers;
  7075. headers.emplace("Content-Encoding", "deflate");
  7076. // PUT in deflate format:
  7077. auto res = cli_.Put("/put", headers,
  7078. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ("PUT", res->body);
  7082. }
  7083. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7084. Headers headers;
  7085. headers.emplace("Accept-Encoding", "gzip, deflate");
  7086. auto res = cli_.Get("/streamed-chunked", headers);
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::OK_200, res->status);
  7089. EXPECT_EQ(std::string("123456789"), res->body);
  7090. }
  7091. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7092. Headers headers;
  7093. headers.emplace("Accept-Encoding", "gzip, deflate");
  7094. auto res = cli_.Get("/streamed-chunked2", headers);
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::OK_200, res->status);
  7097. EXPECT_EQ(std::string("123456789"), res->body);
  7098. }
  7099. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7100. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. EXPECT_EQ(StatusCode::OK_200, res->status);
  7103. }
  7104. TEST(GzipDecompressor, ChunkedDecompression) {
  7105. std::string data;
  7106. for (size_t i = 0; i < 32 * 1024; ++i) {
  7107. data.push_back(static_cast<char>('a' + i % 26));
  7108. }
  7109. std::string compressed_data;
  7110. {
  7111. httplib::detail::gzip_compressor compressor;
  7112. bool result = compressor.compress(
  7113. data.data(), data.size(),
  7114. /*last=*/true,
  7115. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7116. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7117. compressed_data_size);
  7118. return true;
  7119. });
  7120. ASSERT_TRUE(result);
  7121. }
  7122. std::string decompressed_data;
  7123. {
  7124. httplib::detail::gzip_decompressor decompressor;
  7125. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7126. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7127. size_t chunk_size = 130;
  7128. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7129. chunk_begin += chunk_size) {
  7130. size_t current_chunk_size =
  7131. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7132. bool result = decompressor.decompress(
  7133. compressed_data.data() + chunk_begin, current_chunk_size,
  7134. [&](const char *decompressed_data_chunk,
  7135. size_t decompressed_data_chunk_size) {
  7136. decompressed_data.insert(decompressed_data.size(),
  7137. decompressed_data_chunk,
  7138. decompressed_data_chunk_size);
  7139. return true;
  7140. });
  7141. ASSERT_TRUE(result);
  7142. }
  7143. }
  7144. ASSERT_EQ(data, decompressed_data);
  7145. }
  7146. TEST(GzipDecompressor, DeflateDecompression) {
  7147. std::string original_text = "Raw deflate without gzip";
  7148. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7149. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7150. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7151. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7152. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7153. std::string decompressed_data;
  7154. {
  7155. httplib::detail::gzip_decompressor decompressor;
  7156. bool result = decompressor.decompress(
  7157. compressed_data.data(), compressed_data.size(),
  7158. [&](const char *decompressed_data_chunk,
  7159. size_t decompressed_data_chunk_size) {
  7160. decompressed_data.insert(decompressed_data.size(),
  7161. decompressed_data_chunk,
  7162. decompressed_data_chunk_size);
  7163. return true;
  7164. });
  7165. ASSERT_TRUE(result);
  7166. }
  7167. ASSERT_EQ(original_text, decompressed_data);
  7168. }
  7169. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7170. std::string original_text = "Raw deflate without gzip";
  7171. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7172. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7173. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7174. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7175. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7176. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7177. std::string decompressed_data;
  7178. {
  7179. httplib::detail::gzip_decompressor decompressor;
  7180. bool result = decompressor.decompress(
  7181. compressed_data.data(), compressed_data.size(),
  7182. [&](const char *decompressed_data_chunk,
  7183. size_t decompressed_data_chunk_size) {
  7184. decompressed_data.insert(decompressed_data.size(),
  7185. decompressed_data_chunk,
  7186. decompressed_data_chunk_size);
  7187. return true;
  7188. });
  7189. ASSERT_TRUE(result);
  7190. }
  7191. ASSERT_EQ(original_text, decompressed_data);
  7192. }
  7193. #endif
  7194. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7195. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7196. Headers headers;
  7197. headers.emplace("Accept-Encoding", "br");
  7198. auto res = cli_.Get("/streamed-chunked", headers);
  7199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7200. EXPECT_EQ(StatusCode::OK_200, res->status);
  7201. EXPECT_EQ(std::string("123456789"), res->body);
  7202. }
  7203. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7204. Headers headers;
  7205. headers.emplace("Accept-Encoding", "br");
  7206. auto res = cli_.Get("/streamed-chunked2", headers);
  7207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7208. EXPECT_EQ(StatusCode::OK_200, res->status);
  7209. EXPECT_EQ(std::string("123456789"), res->body);
  7210. }
  7211. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7212. cli_.set_compress(true);
  7213. auto res = cli_.Put(
  7214. "/put", 3,
  7215. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7216. sink.os << "PUT";
  7217. return true;
  7218. },
  7219. "text/plain");
  7220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7221. EXPECT_EQ(StatusCode::OK_200, res->status);
  7222. EXPECT_EQ("PUT", res->body);
  7223. }
  7224. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7225. cli_.set_compress(true);
  7226. auto res = cli_.Put(
  7227. "/put",
  7228. [](size_t /*offset*/, DataSink &sink) {
  7229. sink.os << "PUT";
  7230. sink.done();
  7231. return true;
  7232. },
  7233. "text/plain");
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::OK_200, res->status);
  7236. EXPECT_EQ("PUT", res->body);
  7237. }
  7238. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7239. cli_.set_compress(true);
  7240. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. EXPECT_EQ(StatusCode::OK_200, res->status);
  7243. EXPECT_EQ(LARGE_DATA, res->body);
  7244. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7245. }
  7246. #endif
  7247. TEST_F(ServerTest, Patch) {
  7248. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::OK_200, res->status);
  7251. EXPECT_EQ("PATCH", res->body);
  7252. }
  7253. TEST_F(ServerTest, Delete) {
  7254. auto res = cli_.Delete("/delete");
  7255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7256. EXPECT_EQ(StatusCode::OK_200, res->status);
  7257. EXPECT_EQ("DELETE", res->body);
  7258. }
  7259. TEST_F(ServerTest, DeleteContentReceiver) {
  7260. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. EXPECT_EQ(StatusCode::OK_200, res->status);
  7263. EXPECT_EQ("content", res->body);
  7264. }
  7265. TEST_F(ServerTest, Options) {
  7266. auto res = cli_.Options("*");
  7267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7268. EXPECT_EQ(StatusCode::OK_200, res->status);
  7269. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7270. EXPECT_TRUE(res->body.empty());
  7271. }
  7272. TEST_F(ServerTest, URL) {
  7273. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7275. EXPECT_EQ(StatusCode::OK_200, res->status);
  7276. }
  7277. TEST_F(ServerTest, ArrayParam) {
  7278. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. }
  7282. TEST_F(ServerTest, ArrayParamValues) {
  7283. auto res =
  7284. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. EXPECT_EQ(StatusCode::OK_200, res->status);
  7287. }
  7288. TEST_F(ServerTest, NoMultipleHeaders) {
  7289. Headers headers = {{"Content-Length", "5"}};
  7290. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7291. "text/plain");
  7292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7293. EXPECT_EQ(StatusCode::OK_200, res->status);
  7294. }
  7295. TEST_F(ServerTest, PostContentReceiver) {
  7296. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7298. ASSERT_EQ(StatusCode::OK_200, res->status);
  7299. ASSERT_EQ("content", res->body);
  7300. }
  7301. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7302. UploadFormDataItems items = {
  7303. {"text1", "text default", "", ""},
  7304. {"text2", "aωb", "", ""},
  7305. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7306. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7307. {"file3", "", "", "application/octet-stream"},
  7308. };
  7309. auto res = cli_.Post("/content_receiver", items);
  7310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7311. EXPECT_EQ(StatusCode::OK_200, res->status);
  7312. }
  7313. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7314. UploadFormDataItems items = {
  7315. {"text1", "text default", "", ""},
  7316. {"text2", "aωb", "", ""},
  7317. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7318. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7319. {"file3", "", "", "application/octet-stream"},
  7320. };
  7321. auto boundary = std::string("+++++");
  7322. std::string body;
  7323. for (const auto &item : items) {
  7324. body += "--" + boundary + "\r\n";
  7325. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7326. if (!item.filename.empty()) {
  7327. body += "; filename=\"" + item.filename + "\"";
  7328. }
  7329. body += "\r\n";
  7330. if (!item.content_type.empty()) {
  7331. body += "Content-Type: " + item.content_type + "\r\n";
  7332. }
  7333. body += "\r\n";
  7334. body += item.content + "\r\n";
  7335. }
  7336. body += "--" + boundary + "--\r\n";
  7337. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7338. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ(StatusCode::OK_200, res->status);
  7341. }
  7342. TEST(MultipartFormDataTest, FieldEscaping) {
  7343. Server svr;
  7344. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7345. const ContentReader &content_reader) {
  7346. ASSERT_TRUE(req.is_multipart_form_data());
  7347. std::vector<FormData> received;
  7348. content_reader(
  7349. [&](const FormData &file) {
  7350. received.push_back(file);
  7351. return true;
  7352. },
  7353. [&](const char *data, size_t data_length) {
  7354. received.back().content.append(data, data_length);
  7355. return true;
  7356. });
  7357. // '"', CR and LF in names and filenames are escaped following the
  7358. // WHATWG HTML standard, so each part still parses as a single part
  7359. // with no injected headers. Content types get CR/LF escaped too,
  7360. // while '"' (legal there, e.g. quoted charset) is preserved.
  7361. ASSERT_EQ(4U, received.size());
  7362. EXPECT_EQ("na%22me", received[0].name);
  7363. EXPECT_EQ("quoted name", received[0].content);
  7364. EXPECT_EQ("file", received[1].name);
  7365. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7366. received[1].filename);
  7367. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7368. EXPECT_EQ("injected", received[1].content);
  7369. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7370. EXPECT_EQ("my%22file.txt", received[2].filename);
  7371. EXPECT_EQ("cr lf name", received[2].content);
  7372. EXPECT_EQ("typed", received[3].name);
  7373. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7374. received[3].content_type);
  7375. EXPECT_EQ("typed content", received[3].content);
  7376. });
  7377. auto port = svr.bind_to_any_port("localhost");
  7378. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7379. auto se = detail::scope_exit([&] {
  7380. svr.stop();
  7381. t.join();
  7382. ASSERT_FALSE(svr.is_running());
  7383. });
  7384. svr.wait_until_ready();
  7385. Client cli("localhost", port);
  7386. UploadFormDataItems items = {
  7387. {"na\"me", "quoted name", "", ""},
  7388. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7389. "application/octet-stream"},
  7390. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7391. {"typed", "typed content", "",
  7392. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7393. };
  7394. auto res = cli.Post("/post", items);
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::OK_200, res->status);
  7397. }
  7398. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7399. const UploadFormDataItems items = {
  7400. {"name1", "Content 1", "", ""},
  7401. {"name2", "Content 2", "file2.txt", "text/plain"},
  7402. };
  7403. Server svr;
  7404. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7405. const ContentReader &content_reader) {
  7406. ASSERT_TRUE(req.is_multipart_form_data());
  7407. std::vector<FormData> received;
  7408. content_reader(
  7409. [&](const FormData &file) {
  7410. received.push_back(file);
  7411. return true;
  7412. },
  7413. [&](const char *data, size_t data_length) {
  7414. received.back().content.append(data, data_length);
  7415. return true;
  7416. });
  7417. ASSERT_EQ(2U, received.size());
  7418. EXPECT_EQ("name1", received[0].name);
  7419. EXPECT_EQ("Content 1", received[0].content);
  7420. EXPECT_EQ("name2", received[1].name);
  7421. EXPECT_EQ("Content 2", received[1].content);
  7422. EXPECT_EQ("file2.txt", received[1].filename);
  7423. EXPECT_EQ("text/plain", received[1].content_type);
  7424. });
  7425. auto port = svr.bind_to_any_port("localhost");
  7426. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7427. auto se = detail::scope_exit([&] {
  7428. svr.stop();
  7429. t.join();
  7430. ASSERT_FALSE(svr.is_running());
  7431. });
  7432. svr.wait_until_ready();
  7433. Client cli("localhost", port);
  7434. // Whole-body serialization with a generated boundary
  7435. {
  7436. MultipartFormDataWriter writer;
  7437. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7438. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7439. writer.content_type());
  7440. auto body = writer.serialize(items);
  7441. EXPECT_EQ(body.size(), writer.content_length(items));
  7442. auto res = cli.Post("/post", body, writer.content_type());
  7443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7444. EXPECT_EQ(StatusCode::OK_200, res->status);
  7445. }
  7446. // Per-part framing with a custom boundary via a content provider
  7447. {
  7448. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7449. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7450. MultipartFormDataWriter writer("custom-boundary_123");
  7451. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7452. std::string body;
  7453. for (const auto &item : items) {
  7454. body += writer.item_begin(item);
  7455. body += item.content;
  7456. body += MultipartFormDataWriter::item_end();
  7457. }
  7458. body += writer.finish();
  7459. EXPECT_EQ(body.size(), writer.content_length(items));
  7460. auto res = cli.Post(
  7461. "/post", body.size(),
  7462. [&](size_t offset, size_t length, DataSink &sink) {
  7463. sink.write(body.data() + offset, length);
  7464. return true;
  7465. },
  7466. writer.content_type());
  7467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7468. EXPECT_EQ(StatusCode::OK_200, res->status);
  7469. }
  7470. }
  7471. TEST_F(ServerTest, PostContentReceiverGzip) {
  7472. cli_.set_compress(true);
  7473. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. ASSERT_EQ(StatusCode::OK_200, res->status);
  7476. ASSERT_EQ("content", res->body);
  7477. }
  7478. TEST_F(ServerTest, PutContentReceiver) {
  7479. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. ASSERT_EQ(StatusCode::OK_200, res->status);
  7482. ASSERT_EQ("content", res->body);
  7483. }
  7484. TEST_F(ServerTest, PatchContentReceiver) {
  7485. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7487. ASSERT_EQ(StatusCode::OK_200, res->status);
  7488. ASSERT_EQ("content", res->body);
  7489. }
  7490. template <typename ClientType>
  7491. void TestWithHeadersAndContentReceiver(
  7492. ClientType &cli,
  7493. std::function<Result(ClientType &, const std::string &, const Headers &,
  7494. const std::string &, const std::string &,
  7495. ContentReceiver, DownloadProgress)>
  7496. request_func) {
  7497. Headers headers;
  7498. headers.emplace("X-Custom-Header", "test-value");
  7499. std::string received_body;
  7500. auto res = request_func(
  7501. cli, "/content_receiver", headers, "content", "application/json",
  7502. [&](const char *data, size_t data_length) {
  7503. received_body.append(data, data_length);
  7504. return true;
  7505. },
  7506. nullptr);
  7507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7508. EXPECT_EQ(StatusCode::OK_200, res->status);
  7509. EXPECT_EQ("content", received_body);
  7510. }
  7511. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7512. #ifdef CPPHTTPLIB_SSL_ENABLED
  7513. using ClientT = SSLClient;
  7514. #else
  7515. using ClientT = Client;
  7516. #endif
  7517. TestWithHeadersAndContentReceiver<ClientT>(
  7518. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7519. const std::string &body, const std::string &content_type,
  7520. ContentReceiver receiver, DownloadProgress progress) {
  7521. return cli.Post(path, headers, body, content_type, receiver, progress);
  7522. });
  7523. }
  7524. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7525. #ifdef CPPHTTPLIB_SSL_ENABLED
  7526. using ClientT = SSLClient;
  7527. #else
  7528. using ClientT = Client;
  7529. #endif
  7530. TestWithHeadersAndContentReceiver<ClientT>(
  7531. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7532. const std::string &body, const std::string &content_type,
  7533. ContentReceiver receiver, DownloadProgress progress) {
  7534. return cli.Put(path, headers, body, content_type, receiver, progress);
  7535. });
  7536. }
  7537. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7538. #ifdef CPPHTTPLIB_SSL_ENABLED
  7539. using ClientT = SSLClient;
  7540. #else
  7541. using ClientT = Client;
  7542. #endif
  7543. TestWithHeadersAndContentReceiver<ClientT>(
  7544. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7545. const std::string &body, const std::string &content_type,
  7546. ContentReceiver receiver, DownloadProgress progress) {
  7547. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7548. });
  7549. }
  7550. template <typename ClientType>
  7551. void TestWithHeadersAndContentReceiverWithProgress(
  7552. ClientType &cli,
  7553. std::function<Result(ClientType &, const std::string &, const Headers &,
  7554. const std::string &, const std::string &,
  7555. ContentReceiver, DownloadProgress)>
  7556. request_func) {
  7557. Headers headers;
  7558. headers.emplace("X-Test-Header", "progress-test");
  7559. std::string received_body;
  7560. auto progress_called = false;
  7561. auto res = request_func(
  7562. cli, "/content_receiver", headers, "content", "text/plain",
  7563. [&](const char *data, size_t data_length) {
  7564. received_body.append(data, data_length);
  7565. return true;
  7566. },
  7567. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7568. progress_called = true;
  7569. return true;
  7570. });
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ("content", received_body);
  7574. EXPECT_TRUE(progress_called);
  7575. }
  7576. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7577. #ifdef CPPHTTPLIB_SSL_ENABLED
  7578. using ClientT = SSLClient;
  7579. #else
  7580. using ClientT = Client;
  7581. #endif
  7582. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7583. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7584. const std::string &body, const std::string &content_type,
  7585. ContentReceiver receiver, DownloadProgress progress) {
  7586. return cli.Post(path, headers, body, content_type, receiver, progress);
  7587. });
  7588. }
  7589. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7590. #ifdef CPPHTTPLIB_SSL_ENABLED
  7591. using ClientT = SSLClient;
  7592. #else
  7593. using ClientT = Client;
  7594. #endif
  7595. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7596. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7597. const std::string &body, const std::string &content_type,
  7598. ContentReceiver receiver, DownloadProgress progress) {
  7599. return cli.Put(path, headers, body, content_type, receiver, progress);
  7600. });
  7601. }
  7602. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7603. #ifdef CPPHTTPLIB_SSL_ENABLED
  7604. using ClientT = SSLClient;
  7605. #else
  7606. using ClientT = Client;
  7607. #endif
  7608. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7609. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7610. const std::string &body, const std::string &content_type,
  7611. ContentReceiver receiver, DownloadProgress progress) {
  7612. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7613. });
  7614. }
  7615. template <typename ClientType>
  7616. void TestWithHeadersAndContentReceiverError(
  7617. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7618. const Headers &, const std::string &,
  7619. const std::string &, ContentReceiver)>
  7620. request_func) {
  7621. Headers headers;
  7622. headers.emplace("X-Error-Test", "true");
  7623. std::string received_body;
  7624. auto receiver_failed = false;
  7625. auto res =
  7626. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7627. [&](const char *data, size_t data_length) {
  7628. received_body.append(data, data_length);
  7629. receiver_failed = true;
  7630. return false;
  7631. });
  7632. ASSERT_FALSE(res);
  7633. EXPECT_TRUE(receiver_failed);
  7634. }
  7635. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7636. #ifdef CPPHTTPLIB_SSL_ENABLED
  7637. using ClientT = SSLClient;
  7638. #else
  7639. using ClientT = Client;
  7640. #endif
  7641. TestWithHeadersAndContentReceiverError<ClientT>(
  7642. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7643. const std::string &body, const std::string &content_type,
  7644. ContentReceiver receiver) {
  7645. return cli.Post(path, headers, body, content_type, receiver);
  7646. });
  7647. }
  7648. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7649. #ifdef CPPHTTPLIB_SSL_ENABLED
  7650. using ClientT = SSLClient;
  7651. #else
  7652. using ClientT = Client;
  7653. #endif
  7654. TestWithHeadersAndContentReceiverError<ClientT>(
  7655. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7656. const std::string &body, const std::string &content_type,
  7657. ContentReceiver receiver) {
  7658. return cli.Put(path, headers, body, content_type, receiver);
  7659. });
  7660. }
  7661. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7662. #ifdef CPPHTTPLIB_SSL_ENABLED
  7663. using ClientT = SSLClient;
  7664. #else
  7665. using ClientT = Client;
  7666. #endif
  7667. TestWithHeadersAndContentReceiverError<ClientT>(
  7668. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7669. const std::string &body, const std::string &content_type,
  7670. ContentReceiver receiver) {
  7671. return cli.Patch(path, headers, body, content_type, receiver);
  7672. });
  7673. }
  7674. TEST_F(ServerTest, PostQueryStringAndBody) {
  7675. auto res =
  7676. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7678. ASSERT_EQ(StatusCode::OK_200, res->status);
  7679. }
  7680. TEST_F(ServerTest, HTTP2Magic) {
  7681. Request req;
  7682. req.method = "PRI";
  7683. req.path = "*";
  7684. req.body = "SM";
  7685. auto res = std::make_shared<Response>();
  7686. auto error = Error::Success;
  7687. auto ret = cli_.send(req, *res, error);
  7688. ASSERT_TRUE(ret);
  7689. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7690. }
  7691. TEST_F(ServerTest, KeepAlive) {
  7692. auto res = cli_.Get("/hi");
  7693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7694. EXPECT_EQ(StatusCode::OK_200, res->status);
  7695. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7696. EXPECT_EQ("Hello World!", res->body);
  7697. res = cli_.Get("/hi");
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7701. EXPECT_EQ("Hello World!", res->body);
  7702. res = cli_.Get("/hi");
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::OK_200, res->status);
  7705. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7706. EXPECT_EQ("Hello World!", res->body);
  7707. res = cli_.Get("/not-exist");
  7708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7709. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7710. res = cli_.Post("/empty", "", "text/plain");
  7711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7712. EXPECT_EQ(StatusCode::OK_200, res->status);
  7713. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7714. EXPECT_EQ("empty", res->body);
  7715. EXPECT_EQ("close", res->get_header_value("Connection"));
  7716. res = cli_.Post(
  7717. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7718. "text/plain");
  7719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7720. EXPECT_EQ(StatusCode::OK_200, res->status);
  7721. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7722. EXPECT_EQ("empty", res->body);
  7723. cli_.set_keep_alive(false);
  7724. res = cli_.Get("/last-request");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("close", res->get_header_value("Connection"));
  7728. }
  7729. TEST_F(ServerTest, TooManyRedirect) {
  7730. cli_.set_follow_location(true);
  7731. auto res = cli_.Get("/redirect/0");
  7732. ASSERT_TRUE(!res);
  7733. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7734. }
  7735. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7736. Request req;
  7737. req.method = "FOOBAR";
  7738. req.path = "/hi";
  7739. cli_.set_keep_alive(true);
  7740. auto res = cli_.send(req);
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7743. EXPECT_EQ("close", res->get_header_value("Connection"));
  7744. EXPECT_FALSE(cli_.is_socket_open());
  7745. }
  7746. TEST_F(ServerTest, CustomRouteReadsBody) {
  7747. const std::string xml =
  7748. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7749. Request req;
  7750. req.method = "PROPFIND";
  7751. req.path = "/dav/dir";
  7752. req.set_header("Depth", "1");
  7753. req.body = xml;
  7754. auto res = cli_.send(req);
  7755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7756. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7757. EXPECT_EQ(xml, res->body);
  7758. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7759. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7760. }
  7761. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7762. Request req;
  7763. req.method = "PROPFIND";
  7764. req.path = "/dav/42";
  7765. auto res = cli_.send(req);
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7768. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7769. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7770. }
  7771. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7772. Request req;
  7773. req.method = "PROPFIND";
  7774. req.path = "/dav-re/123";
  7775. auto res = cli_.send(req);
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7778. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7779. }
  7780. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7781. Request req;
  7782. req.method = "MKCOL";
  7783. req.path = "/dav-mkcol";
  7784. auto res = cli_.send(req);
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::Created_201, res->status);
  7787. }
  7788. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7789. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7790. Request req;
  7791. req.method = "REPORT";
  7792. req.path = "/dav-report";
  7793. req.body = xml;
  7794. auto res = cli_.send(req);
  7795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7796. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7797. EXPECT_EQ(xml, res->body);
  7798. }
  7799. // A content reader route must fire even when the request carries no body,
  7800. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7801. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7802. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7803. Request req;
  7804. req.method = "REPORT";
  7805. req.path = "/dav-report";
  7806. auto res = cli_.send(req);
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7809. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7810. }
  7811. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7812. Request req;
  7813. req.method = "PROPFIND";
  7814. req.path = "/not-dav";
  7815. auto res = cli_.send(req);
  7816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7817. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7818. }
  7819. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7820. Request req;
  7821. req.method = "UNLOCK";
  7822. req.path = "/dav/dir";
  7823. cli_.set_keep_alive(true);
  7824. auto res = cli_.send(req);
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7827. EXPECT_EQ("close", res->get_header_value("Connection"));
  7828. EXPECT_FALSE(cli_.is_socket_open());
  7829. }
  7830. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7831. // The mount point serves this path, but only for GET and HEAD.
  7832. auto get_res = cli_.Get("/dir/index.html");
  7833. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7834. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7835. Request req;
  7836. req.method = "PROPFIND";
  7837. req.path = "/dir/index.html";
  7838. auto res = cli_.send(req);
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7841. }
  7842. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7843. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7844. cli_.set_keep_alive(true);
  7845. for (auto i = 0; i < 2; i++) {
  7846. Request req;
  7847. req.method = "PROPFIND";
  7848. req.path = "/dav/dir";
  7849. req.body = xml;
  7850. auto res = cli_.send(req);
  7851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7852. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7853. EXPECT_EQ(xml, res->body);
  7854. EXPECT_TRUE(cli_.is_socket_open());
  7855. }
  7856. // A built-in method must still be served on the same connection.
  7857. cli_.set_keep_alive(false);
  7858. auto res = cli_.Get("/hi");
  7859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7860. EXPECT_EQ(StatusCode::OK_200, res->status);
  7861. EXPECT_EQ("close", res->get_header_value("Connection"));
  7862. }
  7863. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7864. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7865. Request req;
  7866. req.method = "PROPFIND";
  7867. req.path = "/dav/dir";
  7868. req.set_header("Expect", "100-continue");
  7869. req.body = xml;
  7870. auto res = cli_.send(req);
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7873. EXPECT_EQ(xml, res->body);
  7874. }
  7875. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7876. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7877. TEST_F(ServerTest, Gzip) {
  7878. Headers headers;
  7879. headers.emplace("Accept-Encoding", "gzip, deflate");
  7880. auto res = cli_.Get("/compress", headers);
  7881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7882. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7884. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7885. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7886. "7890123456789012345678901234567890",
  7887. res->body);
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. }
  7890. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7891. Headers headers;
  7892. headers.emplace("Accept-Encoding", "gzip, deflate");
  7893. auto res = cli_.Get("/compress-with-charset", headers);
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7896. EXPECT_EQ("application/json; charset=utf-8",
  7897. res->get_header_value("Content-Type"));
  7898. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7899. "7890123456789012345678901234567890",
  7900. res->body);
  7901. EXPECT_EQ(StatusCode::OK_200, res->status);
  7902. }
  7903. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7904. Headers headers;
  7905. headers.emplace("Accept-Encoding", "");
  7906. auto res = cli_.Get("/compress", headers);
  7907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7908. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7909. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7910. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7911. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7912. "7890123456789012345678901234567890",
  7913. res->body);
  7914. EXPECT_EQ(StatusCode::OK_200, res->status);
  7915. }
  7916. TEST_F(ServerTest, GzipWithContentReceiver) {
  7917. Headers headers;
  7918. headers.emplace("Accept-Encoding", "gzip, deflate");
  7919. std::string body;
  7920. auto res = cli_.Get("/compress", headers,
  7921. [&](const char *data, uint64_t data_length) {
  7922. EXPECT_EQ(100U, data_length);
  7923. body.append(data, data_length);
  7924. return true;
  7925. });
  7926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7927. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7929. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7930. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7931. "7890123456789012345678901234567890",
  7932. body);
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7936. Headers headers;
  7937. headers.emplace("Accept-Encoding", "gzip, deflate");
  7938. cli_.set_decompress(false);
  7939. auto res = cli_.Get("/compress", headers);
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7942. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7943. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7944. EXPECT_EQ(33U, res->body.size());
  7945. EXPECT_EQ(StatusCode::OK_200, res->status);
  7946. }
  7947. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7948. Headers headers;
  7949. headers.emplace("Accept-Encoding", "");
  7950. std::string body;
  7951. auto res = cli_.Get("/compress", headers,
  7952. [&](const char *data, uint64_t data_length) {
  7953. EXPECT_EQ(100U, data_length);
  7954. body.append(data, data_length);
  7955. return true;
  7956. });
  7957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7958. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7959. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7960. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7961. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7962. "7890123456789012345678901234567890",
  7963. body);
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. }
  7966. TEST_F(ServerTest, NoGzip) {
  7967. Headers headers;
  7968. headers.emplace("Accept-Encoding", "gzip, deflate");
  7969. auto res = cli_.Get("/nocompress", headers);
  7970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7971. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7972. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7973. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7974. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7975. "7890123456789012345678901234567890",
  7976. res->body);
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. }
  7979. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7980. Headers headers;
  7981. headers.emplace("Accept-Encoding", "gzip, deflate");
  7982. std::string body;
  7983. auto res = cli_.Get("/nocompress", headers,
  7984. [&](const char *data, uint64_t data_length) {
  7985. EXPECT_EQ(100U, data_length);
  7986. body.append(data, data_length);
  7987. return true;
  7988. });
  7989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7990. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7991. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7992. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7993. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7994. "7890123456789012345678901234567890",
  7995. body);
  7996. EXPECT_EQ(StatusCode::OK_200, res->status);
  7997. }
  7998. TEST_F(ServerTest, MultipartFormDataGzip) {
  7999. UploadFormDataItems items = {
  8000. {"key1", "test", "", ""},
  8001. {"key2", "--abcdefg123", "", ""},
  8002. };
  8003. cli_.set_compress(true);
  8004. auto res = cli_.Post("/compress-multipart", items);
  8005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8006. EXPECT_EQ(StatusCode::OK_200, res->status);
  8007. }
  8008. #endif
  8009. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8010. // Static file compression is opt-in, so these run their own server rather than
  8011. // flipping it on for the shared ServerTest fixture, which would silently
  8012. // rewrite what every other static file test is asserting.
  8013. class StaticFileCompressionTest : public ::testing::Test {
  8014. protected:
  8015. void TearDown() override {
  8016. if (t_.joinable()) {
  8017. svr_.stop();
  8018. t_.join();
  8019. }
  8020. }
  8021. int start(const std::function<void(Server &)> &configure = nullptr) {
  8022. // Serves the same tree as a directory of build-time compressed assets
  8023. // would be served: the mount point names the coding the files are already
  8024. // stored in. Registered before "/" so it is the one that matches.
  8025. svr_.set_mount_point("/pre-encoded", "./www",
  8026. {{"Content-Encoding", "gzip"}});
  8027. svr_.set_mount_point("/", "./www");
  8028. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8029. res.set_file_content("./www/dir/index.html", "text/html");
  8030. });
  8031. svr_.Get("/pre-encoded-file-content",
  8032. [](const Request & /*req*/, Response &res) {
  8033. res.set_header("Content-Encoding", "gzip");
  8034. res.set_file_content("./www/dir/index.html", "text/html");
  8035. });
  8036. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8037. res.set_content_provider(
  8038. 6, "text/plain",
  8039. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8040. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8041. return true;
  8042. });
  8043. });
  8044. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8045. res.set_content_provider(
  8046. 1000, "text/plain",
  8047. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8048. if (offset < 100) {
  8049. std::string data(100, 'A');
  8050. sink.write(data.data(), data.size());
  8051. return true;
  8052. }
  8053. std::this_thread::sleep_for(std::chrono::seconds(2));
  8054. std::string data(900, 'B');
  8055. sink.write(data.data(), data.size());
  8056. return true;
  8057. });
  8058. });
  8059. if (configure) { configure(svr_); }
  8060. auto port = svr_.bind_to_any_port(HOST);
  8061. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8062. svr_.wait_until_ready();
  8063. return port;
  8064. }
  8065. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8066. // Every file under ./www except 1MB.txt is smaller than the default
  8067. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8068. // it out of the way.
  8069. static void enable_without_floor(Server &svr) {
  8070. svr.set_static_file_compression(true);
  8071. svr.set_static_file_compression_min_length(0);
  8072. }
  8073. Server svr_;
  8074. std::thread t_;
  8075. };
  8076. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8077. auto port = start();
  8078. Client cli(HOST, port);
  8079. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8081. EXPECT_EQ(StatusCode::OK_200, res->status);
  8082. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8083. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8084. EXPECT_EQ(1048576U, res->body.size());
  8085. }
  8086. TEST_F(StaticFileCompressionTest, MountPoint) {
  8087. auto port = start(enable);
  8088. Client cli(HOST, port);
  8089. cli.set_decompress(false);
  8090. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8092. EXPECT_EQ(StatusCode::OK_200, res->status);
  8093. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8094. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8095. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8096. // The response stays self-delimiting: a length, not a chunked body.
  8097. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8098. EXPECT_EQ(std::to_string(res->body.size()),
  8099. res->get_header_value("Content-Length"));
  8100. EXPECT_LT(res->body.size(), 1048576U);
  8101. EXPECT_FALSE(res->body.empty());
  8102. }
  8103. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8104. auto port = start(enable);
  8105. Client cli(HOST, port);
  8106. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8110. EXPECT_EQ(1048576U, res->body.size());
  8111. }
  8112. TEST_F(StaticFileCompressionTest, FileContent) {
  8113. auto port = start(enable_without_floor);
  8114. Client cli(HOST, port);
  8115. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8117. EXPECT_EQ(StatusCode::OK_200, res->status);
  8118. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8119. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8120. EXPECT_EQ(104U, res->body.size());
  8121. }
  8122. // A handler that serves an already-encoded file names the coding itself. The
  8123. // file-backed path decided its coding from Accept-Encoding and the content
  8124. // type alone, so it compressed the stored bytes a second time and appended a
  8125. // second Content-Encoding field line.
  8126. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8127. auto port = start(enable_without_floor);
  8128. Client cli(HOST, port);
  8129. cli.set_decompress(false);
  8130. auto res = cli.Get("/pre-encoded-file-content",
  8131. Headers{{"Accept-Encoding", "gzip"}});
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8135. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8136. // Vary belongs to a coding the server chose, and it chose none here.
  8137. EXPECT_FALSE(res->has_header("Vary"));
  8138. // The file travels exactly as it is stored on disk.
  8139. EXPECT_EQ(104U, res->body.size());
  8140. }
  8141. // The 1MB file clears the default floor, so this one runs the configuration a
  8142. // deployment would actually have.
  8143. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8144. auto port = start(enable);
  8145. Client cli(HOST, port);
  8146. cli.set_decompress(false);
  8147. auto res =
  8148. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8150. EXPECT_EQ(StatusCode::OK_200, res->status);
  8151. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8152. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8153. EXPECT_FALSE(res->has_header("Vary"));
  8154. EXPECT_EQ(1048576U, res->body.size());
  8155. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8156. }
  8157. TEST_F(StaticFileCompressionTest, Head) {
  8158. auto port = start(enable);
  8159. Client cli(HOST, port);
  8160. cli.set_decompress(false);
  8161. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8162. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8163. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8167. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8168. // HEAD still reports the size a GET would return.
  8169. EXPECT_EQ(get->get_header_value("Content-Length"),
  8170. res->get_header_value("Content-Length"));
  8171. EXPECT_TRUE(res->body.empty());
  8172. }
  8173. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8174. auto port = start(enable);
  8175. Client cli(HOST, port);
  8176. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8177. {"Accept-Encoding", "gzip"}});
  8178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8179. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8180. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8181. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8182. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8183. EXPECT_EQ("cd", res->body);
  8184. }
  8185. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8186. auto port = start(enable);
  8187. Client cli(HOST, port);
  8188. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8190. EXPECT_EQ(StatusCode::OK_200, res->status);
  8191. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8192. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8193. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8194. }
  8195. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8196. auto port = start(enable);
  8197. Client cli(HOST, port);
  8198. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8200. EXPECT_EQ(StatusCode::OK_200, res->status);
  8201. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8202. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8203. EXPECT_TRUE(res->body.empty());
  8204. }
  8205. TEST_F(StaticFileCompressionTest, MinLength) {
  8206. auto port = start(enable);
  8207. Client cli(HOST, port);
  8208. // 104 bytes, well under the default floor. Compressing it would add the
  8209. // gzip header and trailer to a body that already fits in one packet.
  8210. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8214. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8215. }
  8216. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8217. auto port = start([](Server &svr) {
  8218. svr.set_static_file_compression(true);
  8219. svr.set_static_file_compression_min_length(1);
  8220. });
  8221. Client cli(HOST, port);
  8222. cli.set_decompress(false);
  8223. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8226. // A 9-byte file comes back larger than it went in, because gzip's header and
  8227. // trailer outweigh anything deflate can save. That is the end of the range
  8228. // the floor exists to keep out.
  8229. EXPECT_GT(res->body.size(), 9U);
  8230. }
  8231. TEST_F(StaticFileCompressionTest, MaxLength) {
  8232. auto port = start([](Server &svr) {
  8233. svr.set_static_file_compression(true);
  8234. svr.set_static_file_compression_min_length(0);
  8235. svr.set_static_file_compression_max_length(1024);
  8236. });
  8237. Client cli(HOST, port);
  8238. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8239. // defines `small` as a macro on Windows.
  8240. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8241. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8242. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8243. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8244. // Under it: compressed.
  8245. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8246. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8247. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8248. }
  8249. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8250. auto port = start(enable_without_floor);
  8251. Client cli(HOST, port);
  8252. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8253. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8254. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8255. auto identity_etag = identity->get_header_value("ETag");
  8256. ASSERT_FALSE(identity_etag.empty());
  8257. auto gzipped =
  8258. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8259. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8260. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8261. auto gzip_etag = gzipped->get_header_value("ETag");
  8262. ASSERT_FALSE(gzip_etag.empty());
  8263. // Two representations, two validators.
  8264. EXPECT_NE(identity_etag, gzip_etag);
  8265. // Each one revalidates against the request that would produce it...
  8266. auto fresh =
  8267. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8268. {"If-None-Match", gzip_etag}});
  8269. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8270. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8271. auto fresh_identity =
  8272. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8273. {"If-None-Match", identity_etag}});
  8274. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8275. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8276. // ...and not against the other representation.
  8277. auto crossed =
  8278. cli.Get("/dir/index.html",
  8279. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8280. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8281. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8282. }
  8283. // The opt-in covers responses the server reads off disk itself. A caller's own
  8284. // known-length provider keeps its Content-Length and, more importantly, keeps
  8285. // delivering incrementally: routing it through a compressor would hold every
  8286. // write back until zlib's window filled.
  8287. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8288. auto port = start(enable);
  8289. Client cli(HOST, port);
  8290. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8292. EXPECT_EQ(StatusCode::OK_200, res->status);
  8293. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8294. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8295. EXPECT_EQ("aaabbb", res->body);
  8296. }
  8297. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8298. auto port = start(enable);
  8299. Client cli(HOST, port);
  8300. cli.set_read_timeout(1, 0);
  8301. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8302. Headers{{"Accept-Encoding", "gzip"}});
  8303. ASSERT_TRUE(handle.is_valid());
  8304. // The provider writes 100 bytes and then stalls for longer than the read
  8305. // timeout. Those first bytes have to arrive anyway: run the response through
  8306. // a compressor and zlib holds them until its window fills, so the read would
  8307. // come back empty instead.
  8308. char buf[256];
  8309. auto n = handle.read(buf, sizeof(buf));
  8310. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8311. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8312. }
  8313. #endif
  8314. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8315. TEST_F(ServerTest, Brotli) {
  8316. Headers headers;
  8317. headers.emplace("Accept-Encoding", "br");
  8318. auto res = cli_.Get("/compress", headers);
  8319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8320. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8321. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8322. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8323. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8324. "7890123456789012345678901234567890",
  8325. res->body);
  8326. EXPECT_EQ(StatusCode::OK_200, res->status);
  8327. }
  8328. #endif
  8329. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8330. TEST_F(ServerTest, Zstd) {
  8331. Headers headers;
  8332. headers.emplace("Accept-Encoding", "zstd");
  8333. auto res = cli_.Get("/compress", headers);
  8334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8335. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8336. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8337. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8338. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8339. "7890123456789012345678901234567890",
  8340. res->body);
  8341. EXPECT_EQ(StatusCode::OK_200, res->status);
  8342. }
  8343. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8344. Headers headers;
  8345. headers.emplace("Accept-Encoding", "");
  8346. auto res = cli_.Get("/compress", headers);
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8349. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8350. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8351. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8352. "7890123456789012345678901234567890",
  8353. res->body);
  8354. EXPECT_EQ(StatusCode::OK_200, res->status);
  8355. }
  8356. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8357. Headers headers;
  8358. headers.emplace("Accept-Encoding", "zstd");
  8359. std::string body;
  8360. auto res = cli_.Get("/compress", headers,
  8361. [&](const char *data, uint64_t data_length) {
  8362. EXPECT_EQ(100U, data_length);
  8363. body.append(data, data_length);
  8364. return true;
  8365. });
  8366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8367. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8368. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8369. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8370. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8371. "7890123456789012345678901234567890",
  8372. body);
  8373. EXPECT_EQ(StatusCode::OK_200, res->status);
  8374. }
  8375. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8376. Headers headers;
  8377. headers.emplace("Accept-Encoding", "zstd");
  8378. cli_.set_decompress(false);
  8379. auto res = cli_.Get("/compress", headers);
  8380. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8381. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8382. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8383. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8386. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8387. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8388. EXPECT_EQ(StatusCode::OK_200, res->status);
  8389. ASSERT_EQ(26U, res->body.size());
  8390. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8391. 0);
  8392. }
  8393. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8394. Headers headers;
  8395. headers.emplace("Accept-Encoding", "");
  8396. std::string body;
  8397. auto res = cli_.Get("/compress", headers,
  8398. [&](const char *data, uint64_t data_length) {
  8399. EXPECT_EQ(100U, data_length);
  8400. body.append(data, data_length);
  8401. return true;
  8402. });
  8403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8404. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8406. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8407. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8408. "7890123456789012345678901234567890",
  8409. body);
  8410. EXPECT_EQ(StatusCode::OK_200, res->status);
  8411. }
  8412. TEST_F(ServerTest, NoZstd) {
  8413. Headers headers;
  8414. headers.emplace("Accept-Encoding", "zstd");
  8415. auto res = cli_.Get("/nocompress", headers);
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8418. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8419. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8420. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8421. "7890123456789012345678901234567890",
  8422. res->body);
  8423. EXPECT_EQ(StatusCode::OK_200, res->status);
  8424. }
  8425. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8426. Headers headers;
  8427. headers.emplace("Accept-Encoding", "zstd");
  8428. std::string body;
  8429. auto res = cli_.Get("/nocompress", headers,
  8430. [&](const char *data, uint64_t data_length) {
  8431. EXPECT_EQ(100U, data_length);
  8432. body.append(data, data_length);
  8433. return true;
  8434. });
  8435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8436. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8437. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8438. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8439. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8440. "7890123456789012345678901234567890",
  8441. body);
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. }
  8444. // TODO: How to enable zstd ??
  8445. TEST_F(ServerTest, MultipartFormDataZstd) {
  8446. UploadFormDataItems items = {
  8447. {"key1", "test", "", ""},
  8448. {"key2", "--abcdefg123", "", ""},
  8449. };
  8450. Headers headers;
  8451. headers.emplace("Accept-Encoding", "zstd");
  8452. cli_.set_compress(true);
  8453. auto res = cli_.Post("/compress-multipart", headers, items);
  8454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8455. EXPECT_EQ(StatusCode::OK_200, res->status);
  8456. }
  8457. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8458. Headers headers;
  8459. headers.emplace("Accept-Encoding", "zstd");
  8460. cli_.set_compress(true);
  8461. auto res = cli_.Put(
  8462. "/put", headers, 3,
  8463. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8464. sink.os << "PUT";
  8465. return true;
  8466. },
  8467. "text/plain");
  8468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. EXPECT_EQ("PUT", res->body);
  8471. }
  8472. // Pre-compression logging tests
  8473. TEST_F(ServerTest, PreCompressionLogging) {
  8474. // Test data for compression (matches the actual /compress endpoint content)
  8475. const std::string test_content =
  8476. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8477. "3456789012345678901234567890";
  8478. // Variables to capture logging data
  8479. std::string pre_compression_body;
  8480. std::string pre_compression_content_type;
  8481. std::string pre_compression_content_encoding;
  8482. std::string post_compression_body;
  8483. std::string post_compression_content_type;
  8484. std::string post_compression_content_encoding;
  8485. // Set up pre-compression logger
  8486. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8487. const Response &res) {
  8488. pre_compression_body = res.body;
  8489. pre_compression_content_type = res.get_header_value("Content-Type");
  8490. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8491. });
  8492. // Set up post-compression logger
  8493. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8494. post_compression_body = res.body;
  8495. post_compression_content_type = res.get_header_value("Content-Type");
  8496. post_compression_content_encoding =
  8497. res.get_header_value("Content-Encoding");
  8498. });
  8499. // Test with gzip compression
  8500. Headers headers;
  8501. headers.emplace("Accept-Encoding", "gzip");
  8502. auto res = cli_.Get("/compress", headers);
  8503. // Verify response was compressed
  8504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8507. // Verify pre-compression logger captured uncompressed content
  8508. EXPECT_EQ(test_content, pre_compression_body);
  8509. EXPECT_EQ("text/plain", pre_compression_content_type);
  8510. EXPECT_TRUE(pre_compression_content_encoding
  8511. .empty()); // No encoding header before compression
  8512. // Verify post-compression logger captured compressed content
  8513. EXPECT_NE(test_content,
  8514. post_compression_body); // Should be different after compression
  8515. EXPECT_EQ("text/plain", post_compression_content_type);
  8516. EXPECT_EQ("gzip", post_compression_content_encoding);
  8517. // Verify compressed content is smaller
  8518. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8519. }
  8520. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8521. const std::string test_content =
  8522. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8523. "3456789012345678901234567890";
  8524. std::string pre_compression_body;
  8525. std::string post_compression_body;
  8526. svr_.set_pre_compression_logger(
  8527. [&](const Request & /*req*/, const Response &res) {
  8528. pre_compression_body = res.body;
  8529. });
  8530. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8531. post_compression_body = res.body;
  8532. });
  8533. Headers headers;
  8534. headers.emplace("Accept-Encoding", "br");
  8535. auto res = cli_.Get("/compress", headers);
  8536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8537. EXPECT_EQ(StatusCode::OK_200, res->status);
  8538. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8539. // Verify pre-compression content is uncompressed
  8540. EXPECT_EQ(test_content, pre_compression_body);
  8541. // Verify post-compression content is compressed
  8542. EXPECT_NE(test_content, post_compression_body);
  8543. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8544. }
  8545. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8546. const std::string test_content =
  8547. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8548. "3456789012345678901234567890";
  8549. std::string pre_compression_body;
  8550. std::string post_compression_body;
  8551. svr_.set_pre_compression_logger(
  8552. [&](const Request & /*req*/, const Response &res) {
  8553. pre_compression_body = res.body;
  8554. });
  8555. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8556. post_compression_body = res.body;
  8557. });
  8558. // Request without compression (use /nocompress endpoint)
  8559. Headers headers;
  8560. auto res = cli_.Get("/nocompress", headers);
  8561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8562. EXPECT_EQ(StatusCode::OK_200, res->status);
  8563. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8564. // Pre-compression logger should not be called when no compression is applied
  8565. EXPECT_TRUE(
  8566. pre_compression_body.empty()); // Pre-compression logger not called
  8567. EXPECT_EQ(
  8568. test_content,
  8569. post_compression_body); // Post-compression logger captures final content
  8570. }
  8571. TEST_F(ServerTest, LoggerSeesContentLength) {
  8572. size_t logged_content_length = 0;
  8573. std::string logged_content_length_header;
  8574. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8575. logged_content_length = res.content_length_;
  8576. logged_content_length_header = res.get_header_value("Content-Length");
  8577. });
  8578. auto res = cli_.Get("/nocompress");
  8579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8580. EXPECT_EQ(StatusCode::OK_200, res->status);
  8581. EXPECT_EQ(res->body.size(), logged_content_length);
  8582. EXPECT_EQ(std::to_string(logged_content_length),
  8583. logged_content_length_header);
  8584. }
  8585. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8586. const std::string test_content =
  8587. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8588. "3456789012345678901234567890";
  8589. std::string pre_compression_body;
  8590. bool pre_logger_called = false;
  8591. // Set only pre-compression logger
  8592. svr_.set_pre_compression_logger(
  8593. [&](const Request & /*req*/, const Response &res) {
  8594. pre_compression_body = res.body;
  8595. pre_logger_called = true;
  8596. });
  8597. Headers headers;
  8598. headers.emplace("Accept-Encoding", "gzip");
  8599. auto res = cli_.Get("/compress", headers);
  8600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8601. EXPECT_EQ(StatusCode::OK_200, res->status);
  8602. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8603. // Verify pre-compression logger was called
  8604. EXPECT_TRUE(pre_logger_called);
  8605. EXPECT_EQ(test_content, pre_compression_body);
  8606. }
  8607. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8608. {
  8609. // Test with Expect: 100-continue header - success case
  8610. // Server returns 100 Continue, client sends body, server returns 200 OK
  8611. Request req;
  8612. req.method = "POST";
  8613. req.path = "/post-large";
  8614. req.set_header("Expect", "100-continue");
  8615. req.body = LARGE_DATA;
  8616. Response res;
  8617. auto error = Error::Success;
  8618. cli_.set_keep_alive(true);
  8619. auto ret = cli_.send(req, res, error);
  8620. EXPECT_TRUE(ret);
  8621. EXPECT_EQ(StatusCode::OK_200, res.status);
  8622. EXPECT_EQ(LARGE_DATA, res.body);
  8623. }
  8624. {
  8625. // Test with Expect: 100-continue header - error case
  8626. // Client should not send the body when server returns an error
  8627. Request req;
  8628. req.method = "POST";
  8629. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8630. req.set_header("Expect", "100-continue");
  8631. req.body = LARGE_DATA;
  8632. Response res;
  8633. auto error = Error::Success;
  8634. auto start = std::chrono::high_resolution_clock::now();
  8635. cli_.set_keep_alive(true);
  8636. auto ret = cli_.send(req, res, error);
  8637. auto end = std::chrono::high_resolution_clock::now();
  8638. auto elapsed =
  8639. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8640. .count();
  8641. // With Expect: 100-continue, request completes successfully but with error
  8642. EXPECT_TRUE(ret);
  8643. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8644. EXPECT_EQ("close", res.get_header_value("Connection"));
  8645. EXPECT_FALSE(cli_.is_socket_open());
  8646. EXPECT_LE(elapsed, 2000);
  8647. }
  8648. {
  8649. // Send an extra GET request to ensure error recovery without hanging
  8650. Request req;
  8651. req.method = "GET";
  8652. req.path = "/hi";
  8653. auto start = std::chrono::high_resolution_clock::now();
  8654. auto res = cli_.send(req);
  8655. auto end = std::chrono::high_resolution_clock::now();
  8656. auto elapsed =
  8657. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8658. .count();
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. EXPECT_EQ("Hello World!", res->body);
  8662. EXPECT_LE(elapsed, 500);
  8663. }
  8664. }
  8665. TEST(ZstdDecompressor, ChunkedDecompression) {
  8666. std::string data;
  8667. for (size_t i = 0; i < 32 * 1024; ++i) {
  8668. data.push_back(static_cast<char>('a' + i % 26));
  8669. }
  8670. std::string compressed_data;
  8671. {
  8672. httplib::detail::zstd_compressor compressor;
  8673. bool result = compressor.compress(
  8674. data.data(), data.size(),
  8675. /*last=*/true,
  8676. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8677. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8678. compressed_data_size);
  8679. return true;
  8680. });
  8681. ASSERT_TRUE(result);
  8682. }
  8683. std::string decompressed_data;
  8684. {
  8685. httplib::detail::zstd_decompressor decompressor;
  8686. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8687. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8688. size_t chunk_size = 130;
  8689. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8690. chunk_begin += chunk_size) {
  8691. size_t current_chunk_size =
  8692. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8693. bool result = decompressor.decompress(
  8694. compressed_data.data() + chunk_begin, current_chunk_size,
  8695. [&](const char *decompressed_data_chunk,
  8696. size_t decompressed_data_chunk_size) {
  8697. decompressed_data.insert(decompressed_data.size(),
  8698. decompressed_data_chunk,
  8699. decompressed_data_chunk_size);
  8700. return true;
  8701. });
  8702. ASSERT_TRUE(result);
  8703. }
  8704. }
  8705. ASSERT_EQ(data, decompressed_data);
  8706. }
  8707. TEST(ZstdDecompressor, Decompress) {
  8708. std::string original_text = "Compressed with ZSTD";
  8709. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8710. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8711. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8712. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8713. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8714. std::string decompressed_data;
  8715. {
  8716. httplib::detail::zstd_decompressor decompressor;
  8717. bool result = decompressor.decompress(
  8718. compressed_data.data(), compressed_data.size(),
  8719. [&](const char *decompressed_data_chunk,
  8720. size_t decompressed_data_chunk_size) {
  8721. decompressed_data.insert(decompressed_data.size(),
  8722. decompressed_data_chunk,
  8723. decompressed_data_chunk_size);
  8724. return true;
  8725. });
  8726. ASSERT_TRUE(result);
  8727. }
  8728. ASSERT_EQ(original_text, decompressed_data);
  8729. }
  8730. #endif
  8731. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8732. // separate chunks so that the server sees each part in its own read(). Used to
  8733. // place a read boundary at a specific offset of a request body.
  8734. static bool send_request_in_parts(time_t read_timeout_sec,
  8735. const std::vector<std::string> &parts,
  8736. std::string *resp = nullptr,
  8737. int port = PORT) {
  8738. auto error = Error::Success;
  8739. auto client_sock = detail::create_client_socket(
  8740. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8741. /*connection_timeout_sec=*/5, 0,
  8742. /*read_timeout_sec=*/5, 0,
  8743. /*write_timeout_sec=*/5, 0, std::string(), error);
  8744. if (client_sock == INVALID_SOCKET) { return false; }
  8745. auto ret = detail::process_client_socket(
  8746. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8747. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8748. for (size_t i = 0; i < parts.size(); i++) {
  8749. const auto &part = parts[i];
  8750. if (part.size() !=
  8751. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8752. return false;
  8753. }
  8754. if (i + 1 < parts.size()) {
  8755. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8756. }
  8757. }
  8758. char buf[512];
  8759. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8760. while (line_reader.getline()) {
  8761. if (resp) { *resp += line_reader.ptr(); }
  8762. }
  8763. return true;
  8764. });
  8765. detail::close_socket(client_sock);
  8766. return ret;
  8767. }
  8768. // Sends a raw request to a server listening at HOST:PORT.
  8769. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8770. std::string *resp = nullptr, int port = PORT) {
  8771. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8772. }
  8773. #ifdef CPPHTTPLIB_SSL_ENABLED
  8774. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8776. ASSERT_TRUE(svr.is_valid());
  8777. svr.set_read_timeout(1, 0);
  8778. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8779. auto se = detail::scope_exit([&] {
  8780. svr.stop();
  8781. t.join();
  8782. ASSERT_FALSE(svr.is_running());
  8783. });
  8784. svr.wait_until_ready();
  8785. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8786. // keeps each wait well within the read timeout. The server gives up a
  8787. // second in, so the bytes sent after that fail.
  8788. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8789. parts.resize(26, std::string(1, '\0'));
  8790. EXPECT_FALSE(send_request_in_parts(5, parts));
  8791. }
  8792. #endif
  8793. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8794. Server svr;
  8795. std::string header_value;
  8796. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8797. header_value = req.get_header_value("foo");
  8798. res.set_content("ok", "text/plain");
  8799. });
  8800. thread t = thread([&] { svr.listen(HOST, PORT); });
  8801. auto se = detail::scope_exit([&] {
  8802. svr.stop();
  8803. t.join();
  8804. ASSERT_FALSE(svr.is_running());
  8805. });
  8806. svr.wait_until_ready();
  8807. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8808. // like characters are not treated the same - use vertical tab and escape.
  8809. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8810. "foo: \t \v bar \x1B\t \r\n"
  8811. "Connection: close\r\n"
  8812. "\r\n";
  8813. std::string res;
  8814. ASSERT_TRUE(send_request(5, req, &res));
  8815. EXPECT_EQ(header_value, "");
  8816. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8817. }
  8818. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8819. Server svr;
  8820. std::string received;
  8821. svr.Get("/order", [&](const Request &req, Response &res) {
  8822. received = entries_to_string(req.headers);
  8823. res.set_content("ok", "text/plain");
  8824. });
  8825. auto port = svr.bind_to_any_port(HOST);
  8826. thread t = thread([&] { svr.listen_after_bind(); });
  8827. auto se = detail::scope_exit([&] {
  8828. svr.stop();
  8829. t.join();
  8830. ASSERT_FALSE(svr.is_running());
  8831. });
  8832. svr.wait_until_ready();
  8833. const std::string req = "GET /order HTTP/1.1\r\n"
  8834. "X-First: 1\r\n"
  8835. "X-Dup: a\r\n"
  8836. "X-Second: 2\r\n"
  8837. "X-Dup: b\r\n"
  8838. "Connection: close\r\n"
  8839. "\r\n";
  8840. std::string res;
  8841. ASSERT_TRUE(send_request(5, req, &res, port));
  8842. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8843. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8844. }
  8845. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8846. Server svr;
  8847. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8848. res.set_header("Set-Cookie", "first=1");
  8849. res.set_header("X-Between", "y");
  8850. res.set_header("Set-Cookie", "second=2");
  8851. res.set_content("ok", "text/plain");
  8852. });
  8853. auto port = svr.bind_to_any_port(HOST);
  8854. thread t = thread([&] { svr.listen_after_bind(); });
  8855. auto se = detail::scope_exit([&] {
  8856. svr.stop();
  8857. t.join();
  8858. ASSERT_FALSE(svr.is_running());
  8859. });
  8860. svr.wait_until_ready();
  8861. Client cli(HOST, port);
  8862. auto res = cli.Get("/cookies");
  8863. ASSERT_TRUE(res);
  8864. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8865. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8866. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8867. }
  8868. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8869. Server svr;
  8870. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8871. auto i = new int(0);
  8872. res.set_header("Trailer", "X-Safe, X-Reflected");
  8873. res.set_chunked_content_provider(
  8874. "text/plain",
  8875. [i](size_t /*offset*/, DataSink &sink) {
  8876. if (*i == 0) {
  8877. sink.os << "body";
  8878. } else {
  8879. Headers trailer;
  8880. // A valid trailer that must survive.
  8881. trailer.emplace("X-Safe", "safe");
  8882. // Attacker-controlled value carrying CR/LF (response splitting).
  8883. trailer.emplace("X-Reflected",
  8884. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8885. // Attacker-controlled name carrying CR/LF.
  8886. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8887. sink.done_with_trailer(trailer);
  8888. }
  8889. (*i)++;
  8890. return true;
  8891. },
  8892. [i](bool /*success*/) { delete i; });
  8893. });
  8894. thread t = thread([&] { svr.listen(HOST, PORT); });
  8895. auto se = detail::scope_exit([&] {
  8896. svr.stop();
  8897. t.join();
  8898. ASSERT_FALSE(svr.is_running());
  8899. });
  8900. svr.wait_until_ready();
  8901. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8902. "Host: " + HOST +
  8903. "\r\n"
  8904. "Connection: close\r\n"
  8905. "\r\n";
  8906. std::string res;
  8907. ASSERT_TRUE(send_request(5, req, &res));
  8908. // The injected fields must not appear anywhere in the raw response.
  8909. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8910. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8911. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8912. // Invalid trailers are dropped entirely, matching set_header().
  8913. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8914. // The valid trailer still passes through.
  8915. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8916. }
  8917. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8918. Server svr;
  8919. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8920. // res.headers is a public field an application can populate directly,
  8921. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8922. // A valid header that must survive.
  8923. res.headers.emplace("X-Safe", "safe");
  8924. // Attacker-controlled value carrying CR/LF (response splitting).
  8925. res.headers.emplace("X-Reflected",
  8926. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8927. // Attacker-controlled name carrying CR/LF.
  8928. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8929. res.set_content("body", "text/plain");
  8930. });
  8931. thread t = thread([&] { svr.listen(HOST, PORT); });
  8932. auto se = detail::scope_exit([&] {
  8933. svr.stop();
  8934. t.join();
  8935. ASSERT_FALSE(svr.is_running());
  8936. });
  8937. svr.wait_until_ready();
  8938. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8939. "Host: " + HOST +
  8940. "\r\n"
  8941. "Connection: close\r\n"
  8942. "\r\n";
  8943. std::string res;
  8944. ASSERT_TRUE(send_request(5, req, &res));
  8945. // The injected fields must not appear anywhere in the raw response.
  8946. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8947. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8948. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8949. // Invalid headers are dropped entirely, matching set_header().
  8950. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8951. // The valid header still passes through.
  8952. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8953. }
  8954. // Forward declaration: in split builds split.py strips `inline` and moves the
  8955. // definition into httplib.cc, so detail::write_request_line is not visible from
  8956. // the public httplib.h. Re-declaring it here lets the tests link against the
  8957. // symbol in both header-only and split builds.
  8958. namespace httplib {
  8959. namespace detail {
  8960. ssize_t write_request_line(Stream &strm, const std::string &method,
  8961. const std::string &path);
  8962. } // namespace detail
  8963. } // namespace httplib
  8964. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8965. // A well-formed target is written verbatim.
  8966. {
  8967. detail::BufferStream strm;
  8968. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8969. EXPECT_GT(n, 0);
  8970. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8971. }
  8972. // A target carrying CR/LF, SP or other control octets must be rejected
  8973. // before anything reaches the wire, otherwise it splits the request line and
  8974. // injects a header or a whole request.
  8975. const std::string evil_targets[] = {
  8976. "/a\r\nInjected: pwned",
  8977. "/a\rInjected",
  8978. "/a\nInjected",
  8979. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8980. "/a b",
  8981. "/a\tb",
  8982. "/a\x7f",
  8983. };
  8984. for (const auto &evil : evil_targets) {
  8985. detail::BufferStream strm;
  8986. auto n = detail::write_request_line(strm, "GET", evil);
  8987. EXPECT_LT(n, 0);
  8988. EXPECT_TRUE(strm.get_buffer().empty());
  8989. }
  8990. }
  8991. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8992. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8993. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8994. // target reaches write_request. The client must fail cleanly with
  8995. // Error::Write instead of putting a request-line-less, header-injecting
  8996. // request on the wire.
  8997. Server svr;
  8998. svr.Get("/a", [](const Request &, Response &res) {
  8999. res.set_content("ok", "text/plain");
  9000. });
  9001. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9002. auto se = detail::scope_exit([&] {
  9003. svr.stop();
  9004. thread.join();
  9005. ASSERT_FALSE(svr.is_running());
  9006. });
  9007. svr.wait_until_ready();
  9008. {
  9009. Client cli(HOST, PORT);
  9010. cli.set_path_encode(false);
  9011. // The request is rejected before anything is written, so the connection
  9012. // stays silent and the subsequent response read would otherwise block for
  9013. // the full default read timeout. Shorten it -- the assertion is on the
  9014. // error, not the timeout.
  9015. cli.set_read_timeout(1, 0);
  9016. auto res = cli.Get("/a\r\nInjected: pwned");
  9017. EXPECT_FALSE(res);
  9018. EXPECT_EQ(Error::Write, res.error());
  9019. }
  9020. }
  9021. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9022. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9023. // including extension methods.
  9024. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9025. for (const auto &method : good_methods) {
  9026. detail::BufferStream strm;
  9027. auto n = detail::write_request_line(strm, method, "/");
  9028. EXPECT_GT(n, 0);
  9029. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9030. }
  9031. // A method carrying CR/LF would split the request line and smuggle a whole
  9032. // request ahead of the real one. A space or an empty method corrupts the
  9033. // request line. All must be rejected before anything reaches the wire.
  9034. const std::string evil_methods[] = {
  9035. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9036. "GET\r\nInjected: pwned",
  9037. "GET\r",
  9038. "GET\n",
  9039. "GE T",
  9040. "",
  9041. };
  9042. for (const auto &evil : evil_methods) {
  9043. detail::BufferStream strm;
  9044. auto n = detail::write_request_line(strm, evil, "/");
  9045. EXPECT_LT(n, 0);
  9046. EXPECT_TRUE(strm.get_buffer().empty());
  9047. }
  9048. }
  9049. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9050. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9051. // through Client::send must fail with Error::Write and no request, neither
  9052. // the smuggled one nor the real one, may reach the server.
  9053. Server svr;
  9054. std::atomic<int> request_count(0);
  9055. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9056. request_count++;
  9057. res.status = StatusCode::OK_200;
  9058. return Server::HandlerResponse::Handled;
  9059. });
  9060. auto port = svr.bind_to_any_port(HOST);
  9061. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9062. auto se = detail::scope_exit([&] {
  9063. svr.stop();
  9064. thread.join();
  9065. ASSERT_FALSE(svr.is_running());
  9066. });
  9067. svr.wait_until_ready();
  9068. {
  9069. Client cli(HOST, port);
  9070. const std::string evil_methods[] = {
  9071. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9072. "GE T",
  9073. "",
  9074. };
  9075. for (const auto &evil : evil_methods) {
  9076. Request req;
  9077. req.method = evil;
  9078. req.path = "/";
  9079. auto res = cli.send(req);
  9080. EXPECT_FALSE(res);
  9081. EXPECT_EQ(Error::Write, res.error());
  9082. }
  9083. auto handle =
  9084. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9085. EXPECT_FALSE(handle.is_valid());
  9086. EXPECT_EQ(Error::Write, handle.error);
  9087. // A valid request on the same client still goes through.
  9088. auto res = cli.Get("/");
  9089. ASSERT_TRUE(res);
  9090. EXPECT_EQ(StatusCode::OK_200, res->status);
  9091. }
  9092. EXPECT_EQ(1, request_count.load());
  9093. }
  9094. // Sends a raw request and verifies that there isn't a crash or exception.
  9095. static void test_raw_request(const std::string &req,
  9096. std::string *out = nullptr) {
  9097. Server svr;
  9098. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9099. res.set_content("ok", "text/plain");
  9100. });
  9101. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9102. res.set_content("ok", "text/plain");
  9103. });
  9104. svr.Get("/header_field_value_check",
  9105. [&](const Request & /*req*/, Response &res) {
  9106. res.set_content("ok", "text/plain");
  9107. });
  9108. svr.CustomRoute("PROPFIND", "/dav",
  9109. [&](const Request & /*req*/, Response &res) {
  9110. res.status = StatusCode::MultiStatus_207;
  9111. });
  9112. // Server read timeout must be longer than the client read timeout for the
  9113. // bug to reproduce, probably to force the server to process a request
  9114. // without a trailing blank line.
  9115. const time_t client_read_timeout_sec = 1;
  9116. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9117. bool listen_thread_ok = false;
  9118. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9119. auto se = detail::scope_exit([&] {
  9120. svr.stop();
  9121. t.join();
  9122. ASSERT_FALSE(svr.is_running());
  9123. EXPECT_TRUE(listen_thread_ok);
  9124. });
  9125. svr.wait_until_ready();
  9126. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9127. }
  9128. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9129. // A certain header line causes an exception if the header property is parsed
  9130. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9131. test_raw_request(
  9132. "GET /hi HTTP/1.1\r\n"
  9133. " : "
  9134. " "
  9135. " ");
  9136. }
  9137. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9138. // A certain header line causes an exception if the header property *name* is
  9139. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9140. // greedy matcher and requires backtracking when there are a lot of ":"
  9141. // characters.
  9142. // This occurs with libc++ but not libstdc++.
  9143. test_raw_request(
  9144. "GET /hi HTTP/1.1\r\n"
  9145. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9146. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9147. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9148. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9149. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9150. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9151. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9152. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9153. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9154. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9155. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9156. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9157. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9158. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9159. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9160. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9161. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9162. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9163. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9164. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9165. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9166. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9167. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9168. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9169. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9170. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9171. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9172. "&&&%%%");
  9173. }
  9174. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9175. // Make sure this doesn't crash the server.
  9176. // In a previous version of the header line regex, the "\r" rendered the line
  9177. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9178. // a new position where the leading white space ended and the field value
  9179. // began.
  9180. // The crash occurs with libc++ but not libstdc++.
  9181. test_raw_request("GET /hi HTTP/1.1\r\n"
  9182. "a:" +
  9183. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9184. "\r\n"
  9185. "\r\n");
  9186. }
  9187. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9188. // RFC 9112 §6.1
  9189. const char *requests[] = {
  9190. "PUT /put_hi HTTP/1.1\r\n"
  9191. "Content-Length: 0\r\n"
  9192. "Transfer-Encoding: chunked\r\n"
  9193. "\r\n"
  9194. "0\r\n\r\n",
  9195. "PUT /put_hi HTTP/1.0\r\n"
  9196. "Connection: keep-alive\r\n"
  9197. "Transfer-Encoding: chunked\r\n"
  9198. "\r\n"
  9199. "0\r\n\r\n",
  9200. };
  9201. for (auto request : requests) {
  9202. std::string out;
  9203. test_raw_request(request, &out);
  9204. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9205. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9206. }
  9207. }
  9208. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9209. std::string out;
  9210. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9211. "Content-Type: text/plain\r\n"
  9212. "Transfer-Encoding: chunked\r\n"
  9213. "\r\n"
  9214. "nothex\r\n",
  9215. &out);
  9216. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9217. }
  9218. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9219. std::string out;
  9220. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9221. "Content-Type: text/plain\r\n"
  9222. "Transfer-Encoding: chunked\r\n"
  9223. "\r\n"
  9224. "3\r\n"
  9225. "xyz\r\n"
  9226. "NaN\r\n",
  9227. &out);
  9228. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9229. }
  9230. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9231. std::string out;
  9232. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9233. "Content-Type: text/plain\r\n"
  9234. "Transfer-Encoding: chunked\r\n"
  9235. "\r\n"
  9236. // Length is too large for 64 bits.
  9237. "1ffffffffffffffff\r\n"
  9238. "xyz\r\n",
  9239. &out);
  9240. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9241. }
  9242. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9243. test_raw_request("GET /hi HTTP/1.1\r\n"
  9244. "Content-Type: text/plain\r\n\r");
  9245. }
  9246. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9247. std::string out;
  9248. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9249. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9250. }
  9251. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9252. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9253. std::string out;
  9254. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9255. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9256. }
  9257. }
  9258. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9259. std::string out;
  9260. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9261. "Connection: close\r\n\r\n",
  9262. &out);
  9263. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9264. }
  9265. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9266. Server svr;
  9267. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9268. EXPECT_TRUE(!req.remote_addr.empty());
  9269. });
  9270. thread t = thread([&] { svr.listen(HOST, PORT); });
  9271. auto se = detail::scope_exit([&] {
  9272. svr.stop();
  9273. t.join();
  9274. ASSERT_FALSE(svr.is_running());
  9275. });
  9276. svr.wait_until_ready();
  9277. // Send an invalid request line to trigger Bad Request
  9278. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9279. std::string out;
  9280. ASSERT_TRUE(send_request(5, bad_req, &out));
  9281. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9282. }
  9283. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9284. // answered right away rather than blocking on a read that waits for EOF.
  9285. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9286. std::string out;
  9287. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9288. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9289. }
  9290. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9291. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9292. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9293. for (const auto *method : methods) {
  9294. Server svr;
  9295. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9296. EXPECT_FALSE(svr.is_valid()) << method;
  9297. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9298. }
  9299. }
  9300. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9301. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9302. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9303. for (const auto *method : methods) {
  9304. Server svr;
  9305. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9306. EXPECT_FALSE(svr.is_valid()) << method;
  9307. }
  9308. }
  9309. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9310. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9311. "COPY", "MOVE", "LOCK",
  9312. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9313. Server svr;
  9314. for (const auto *method : methods) {
  9315. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9316. }
  9317. EXPECT_TRUE(svr.is_valid());
  9318. }
  9319. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9320. Server svr;
  9321. svr.CustomRoute("POST", "/x",
  9322. [](const Request &, Response &, const ContentReader &) {});
  9323. EXPECT_FALSE(svr.is_valid());
  9324. }
  9325. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9326. Server svr;
  9327. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9328. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9329. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9330. EXPECT_FALSE(svr.is_valid());
  9331. }
  9332. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9333. Server svr;
  9334. auto captured = Error::Success;
  9335. svr.set_error_logger(
  9336. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9337. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9338. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9339. }
  9340. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9341. std::string out;
  9342. std::string request(
  9343. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9344. test_raw_request(request, &out);
  9345. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9346. }
  9347. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9348. std::string out;
  9349. std::string request(
  9350. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9351. test_raw_request(request, &out);
  9352. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9353. }
  9354. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9355. std::string out;
  9356. std::string request(
  9357. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9358. test_raw_request(request, &out);
  9359. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9360. }
  9361. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9362. std::string out;
  9363. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9364. "Test: \r\n\r\n",
  9365. &out);
  9366. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9367. }
  9368. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9369. Server svr;
  9370. std::string x_custom;
  9371. std::string cookie;
  9372. std::string xff;
  9373. std::string x_unicode;
  9374. std::string x_iis;
  9375. svr.Get("/check", [&](const Request &req, Response &res) {
  9376. x_custom = req.get_header_value("X-Custom");
  9377. cookie = req.get_header_value("Cookie");
  9378. xff = req.get_header_value("X-Forwarded-For");
  9379. x_unicode = req.get_header_value("X-Unicode");
  9380. x_iis = req.get_header_value("X-IIS");
  9381. res.set_content("ok", "text/plain");
  9382. });
  9383. thread t = thread([&] { svr.listen(HOST, PORT); });
  9384. auto se = detail::scope_exit([&] {
  9385. svr.stop();
  9386. t.join();
  9387. ASSERT_FALSE(svr.is_running());
  9388. });
  9389. svr.wait_until_ready();
  9390. const std::string req = "GET /check HTTP/1.1\r\n"
  9391. "Host: localhost\r\n"
  9392. "X-Custom: a%0D%0AInjected: b\r\n"
  9393. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9394. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9395. "X-Unicode: %E3%81%82\r\n"
  9396. "X-IIS: %u00E9\r\n"
  9397. "Connection: close\r\n"
  9398. "\r\n";
  9399. std::string res;
  9400. ASSERT_TRUE(send_request(5, req, &res));
  9401. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9402. // Every value must be returned verbatim (wire form), with no decoding.
  9403. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9404. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9405. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9406. EXPECT_EQ("%E3%81%82", x_unicode);
  9407. EXPECT_EQ("%u00E9", x_iis);
  9408. }
  9409. // Applications that previously relied on automatic percent-decoding can
  9410. // reproduce the old behavior by explicitly calling decode_path_component()
  9411. // or, for RFC 3986 conformance, decode_uri_component().
  9412. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9413. Server svr;
  9414. std::string decoded;
  9415. svr.Get("/check", [&](const Request &req, Response &res) {
  9416. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9417. res.set_content("ok", "text/plain");
  9418. });
  9419. thread t = thread([&] { svr.listen(HOST, PORT); });
  9420. auto se = detail::scope_exit([&] {
  9421. svr.stop();
  9422. t.join();
  9423. ASSERT_FALSE(svr.is_running());
  9424. });
  9425. svr.wait_until_ready();
  9426. const std::string req = "GET /check HTTP/1.1\r\n"
  9427. "Host: localhost\r\n"
  9428. "X-Custom: hello%20world\r\n"
  9429. "Connection: close\r\n"
  9430. "\r\n";
  9431. std::string res;
  9432. ASSERT_TRUE(send_request(5, req, &res));
  9433. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9434. EXPECT_EQ("hello world", decoded);
  9435. }
  9436. // Regression test for #2033. Browsers send Referer values that include
  9437. // percent-encoded characters such as %0A inside the URL. Decoding the
  9438. // header value would either trip the post-decode CR/LF/NUL guard (the
  9439. // original bug, returning 400) or, after that guard was relaxed, silently
  9440. // store a literal LF — both unacceptable. The wire form must round-trip.
  9441. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9442. Server svr;
  9443. std::string referer;
  9444. svr.Get("/check", [&](const Request &req, Response &res) {
  9445. referer = req.get_header_value("Referer");
  9446. res.set_content("ok", "text/plain");
  9447. });
  9448. thread t = thread([&] { svr.listen(HOST, PORT); });
  9449. auto se = detail::scope_exit([&] {
  9450. svr.stop();
  9451. t.join();
  9452. ASSERT_FALSE(svr.is_running());
  9453. });
  9454. svr.wait_until_ready();
  9455. const std::string req = "GET /check HTTP/1.1\r\n"
  9456. "Host: localhost\r\n"
  9457. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9458. "Connection: close\r\n"
  9459. "\r\n";
  9460. std::string res;
  9461. ASSERT_TRUE(send_request(5, req, &res));
  9462. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9463. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9464. }
  9465. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9466. Server svr;
  9467. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9468. res.set_header("Cache-Control", "no-cache");
  9469. res.set_chunked_content_provider(
  9470. "text/event-stream", [](size_t offset, DataSink &sink) {
  9471. std::string s = "data:";
  9472. s += std::to_string(offset);
  9473. s += "\n\n";
  9474. auto ret = sink.write(s.data(), s.size());
  9475. EXPECT_TRUE(ret);
  9476. std::this_thread::sleep_for(std::chrono::seconds(1));
  9477. return true;
  9478. });
  9479. });
  9480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9481. svr.wait_until_ready();
  9482. Client client(HOST, PORT);
  9483. const Headers headers = {{"Accept", "text/event-stream"}};
  9484. auto get_thread = std::thread([&client, &headers]() {
  9485. auto res = client.Get(
  9486. "/events", headers,
  9487. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9488. });
  9489. auto se = detail::scope_exit([&] {
  9490. svr.stop();
  9491. get_thread.join();
  9492. listen_thread.join();
  9493. ASSERT_FALSE(svr.is_running());
  9494. });
  9495. // Give GET time to get a few messages.
  9496. std::this_thread::sleep_for(std::chrono::seconds(2));
  9497. }
  9498. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9499. httplib::Server svr;
  9500. svr.Post("/hi",
  9501. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9502. res.status = StatusCode::OK_200;
  9503. });
  9504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9505. svr.wait_until_ready();
  9506. Client cli(HOST, PORT);
  9507. auto res = cli.Post("/hi", "data", "text/plain");
  9508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9509. EXPECT_EQ(StatusCode::OK_200, res->status);
  9510. svr.stop();
  9511. thread.join();
  9512. ASSERT_FALSE(svr.is_running());
  9513. res = cli.Post("/hi", "data", "text/plain");
  9514. ASSERT_FALSE(res);
  9515. }
  9516. TEST(ServerStopTest, ListenFailure) {
  9517. Server svr;
  9518. auto t = thread([&]() {
  9519. auto ret = svr.listen("????", PORT);
  9520. EXPECT_FALSE(ret);
  9521. });
  9522. svr.wait_until_ready();
  9523. svr.stop();
  9524. t.join();
  9525. }
  9526. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9527. TEST(ServerStopTest, Decommision) {
  9528. Server svr;
  9529. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9530. for (int i = 0; i < 4; i++) {
  9531. auto is_even = !(i % 2);
  9532. std::thread t{[&] {
  9533. try {
  9534. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9535. if (is_even) {
  9536. throw std::runtime_error("Some thing that happens to go wrong.");
  9537. }
  9538. svr.listen(HOST, PORT);
  9539. } catch (...) { svr.decommission(); }
  9540. }};
  9541. svr.wait_until_ready();
  9542. // Server is up
  9543. {
  9544. Client cli(HOST, PORT);
  9545. auto res = cli.Get("/hi");
  9546. if (is_even) {
  9547. EXPECT_FALSE(res);
  9548. } else {
  9549. EXPECT_TRUE(res);
  9550. EXPECT_EQ("hi...", res->body);
  9551. }
  9552. }
  9553. svr.stop();
  9554. t.join();
  9555. // Server is down...
  9556. {
  9557. Client cli(HOST, PORT);
  9558. auto res = cli.Get("/hi");
  9559. EXPECT_FALSE(res);
  9560. }
  9561. }
  9562. }
  9563. #endif
  9564. // Helper function for string body upload progress tests
  9565. template <typename SetupHandler, typename ClientCall>
  9566. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9567. ClientCall &&client_call,
  9568. const string &body) {
  9569. Server svr;
  9570. setup_handler(svr);
  9571. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9572. auto se = detail::scope_exit([&] {
  9573. svr.stop();
  9574. t.join();
  9575. });
  9576. svr.wait_until_ready();
  9577. Client cli(HOST, PORT);
  9578. vector<uint64_t> progress_values;
  9579. bool progress_called = false;
  9580. auto res =
  9581. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9582. progress_values.push_back(current);
  9583. progress_called = true;
  9584. return true;
  9585. });
  9586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9587. EXPECT_EQ(200, res->status);
  9588. EXPECT_TRUE(progress_called);
  9589. }
  9590. TEST(UploadProgressTest, PostStringBodyBasic) {
  9591. TestStringBodyUploadProgress(
  9592. [](Server &svr) {
  9593. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9594. res.set_content("received", "text/plain");
  9595. });
  9596. },
  9597. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9598. return cli.Post("/test", body, "text/plain", progress_callback);
  9599. },
  9600. "test data for upload progress");
  9601. }
  9602. TEST(UploadProgressTest, PutStringBodyBasic) {
  9603. TestStringBodyUploadProgress(
  9604. [](Server &svr) {
  9605. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9606. res.set_content("put received", "text/plain");
  9607. });
  9608. },
  9609. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9610. return cli.Put("/test", body, "text/plain", progress_callback);
  9611. },
  9612. "put test data for upload progress");
  9613. }
  9614. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9615. TestStringBodyUploadProgress(
  9616. [](Server &svr) {
  9617. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9618. res.set_content("patch received", "text/plain");
  9619. });
  9620. },
  9621. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9622. return cli.Patch("/test", body, "text/plain", progress_callback);
  9623. },
  9624. "patch test data for upload progress");
  9625. }
  9626. // Helper function for content provider upload progress tests
  9627. template <typename SetupHandler, typename ClientCall>
  9628. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9629. ClientCall &&client_call) {
  9630. Server svr;
  9631. setup_handler(svr);
  9632. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9633. auto se = detail::scope_exit([&] {
  9634. svr.stop();
  9635. t.join();
  9636. });
  9637. svr.wait_until_ready();
  9638. Client cli(HOST, PORT);
  9639. vector<uint64_t> progress_values;
  9640. auto res =
  9641. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9642. progress_values.push_back(current);
  9643. return true;
  9644. });
  9645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9646. EXPECT_EQ(200, res->status);
  9647. EXPECT_FALSE(progress_values.empty());
  9648. }
  9649. TEST(UploadProgressTest, PostContentProviderProgress) {
  9650. TestContentProviderUploadProgress(
  9651. [](Server &svr) {
  9652. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9653. res.set_content("provider received", "text/plain");
  9654. });
  9655. },
  9656. [](Client &cli, UploadProgress progress_callback) {
  9657. return cli.Post(
  9658. "/test", 10,
  9659. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9660. sink.os << "test data";
  9661. return true;
  9662. },
  9663. "text/plain", progress_callback);
  9664. });
  9665. }
  9666. // Helper function for multipart upload progress tests
  9667. template <typename SetupHandler, typename ClientCall>
  9668. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9669. ClientCall &&client_call,
  9670. const string &endpoint) {
  9671. Server svr;
  9672. setup_handler(svr);
  9673. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9674. auto se = detail::scope_exit([&] {
  9675. svr.stop();
  9676. t.join();
  9677. });
  9678. svr.wait_until_ready();
  9679. Client cli(HOST, PORT);
  9680. vector<uint64_t> progress_values;
  9681. UploadFormDataItems items = {
  9682. {"field1", "value1", "", ""},
  9683. {"field2", "longer value for progress tracking test", "", ""},
  9684. {"file1", "file content data for upload progress", "test.txt",
  9685. "text/plain"}};
  9686. auto res = client_call(cli, endpoint, items,
  9687. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9688. progress_values.push_back(current);
  9689. return true;
  9690. });
  9691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9692. EXPECT_EQ(200, res->status);
  9693. EXPECT_FALSE(progress_values.empty());
  9694. }
  9695. TEST(UploadProgressTest, PostMultipartProgress) {
  9696. TestMultipartUploadProgress(
  9697. [](Server &svr) {
  9698. svr.Post("/multipart", [](const Request &req, Response &res) {
  9699. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9700. res.set_content("multipart received", "text/plain");
  9701. });
  9702. },
  9703. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9704. UploadProgress progress_callback) {
  9705. return cli.Post(endpoint, items, progress_callback);
  9706. },
  9707. "/multipart");
  9708. }
  9709. // Helper function for basic download progress tests
  9710. template <typename SetupHandler, typename ClientCall>
  9711. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9712. ClientCall &&client_call, const string &endpoint,
  9713. size_t expected_content_size) {
  9714. Server svr;
  9715. setup_handler(svr);
  9716. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9717. auto se = detail::scope_exit([&] {
  9718. svr.stop();
  9719. t.join();
  9720. });
  9721. svr.wait_until_ready();
  9722. Client cli(HOST, PORT);
  9723. vector<uint64_t> progress_values;
  9724. auto res = client_call(cli, endpoint,
  9725. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9726. progress_values.push_back(current);
  9727. return true;
  9728. });
  9729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9730. EXPECT_EQ(200, res->status);
  9731. EXPECT_FALSE(progress_values.empty());
  9732. EXPECT_EQ(expected_content_size, res->body.size());
  9733. }
  9734. TEST(DownloadProgressTest, GetBasic) {
  9735. TestBasicDownloadProgress(
  9736. [](Server &svr) {
  9737. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9738. string content(1000, 'D');
  9739. res.set_content(content, "text/plain");
  9740. });
  9741. },
  9742. [](Client &cli, const string &endpoint,
  9743. DownloadProgress progress_callback) {
  9744. return cli.Get(endpoint, progress_callback);
  9745. },
  9746. "/download", 1000u);
  9747. }
  9748. // Helper function for content receiver download progress tests
  9749. template <typename SetupHandler, typename ClientCall>
  9750. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9751. ClientCall &&client_call,
  9752. const string &endpoint,
  9753. size_t expected_content_size) {
  9754. Server svr;
  9755. setup_handler(svr);
  9756. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9757. auto se = detail::scope_exit([&] {
  9758. svr.stop();
  9759. t.join();
  9760. });
  9761. svr.wait_until_ready();
  9762. Client cli(HOST, PORT);
  9763. vector<uint64_t> progress_values;
  9764. string received_body;
  9765. auto res = client_call(
  9766. cli, endpoint,
  9767. [&](const char *data, size_t data_length) -> bool {
  9768. received_body.append(data, data_length);
  9769. return true;
  9770. },
  9771. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9772. progress_values.push_back(current);
  9773. return true;
  9774. });
  9775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9776. EXPECT_EQ(200, res->status);
  9777. EXPECT_FALSE(progress_values.empty());
  9778. EXPECT_EQ(expected_content_size, received_body.size());
  9779. EXPECT_TRUE(res->body.empty());
  9780. }
  9781. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9782. TestContentReceiverDownloadProgress(
  9783. [](Server &svr) {
  9784. svr.Get("/download-receiver",
  9785. [](const Request & /*req*/, Response &res) {
  9786. string content(2000, 'R');
  9787. res.set_content(content, "text/plain");
  9788. });
  9789. },
  9790. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9791. DownloadProgress progress_callback) {
  9792. return cli.Get(endpoint, content_receiver, progress_callback);
  9793. },
  9794. "/download-receiver", 2000u);
  9795. }
  9796. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9797. // A provider reaching a pass with nothing to hand over - an empty buffer
  9798. // popped off a queue, say - must not be taken to mean the body is finished.
  9799. // It used to end the loop with the terminating chunk unwritten while the
  9800. // server still considered the response complete, so the peer waited for an
  9801. // end that never arrived.
  9802. Server svr;
  9803. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9804. auto step = std::make_shared<int>(0);
  9805. res.set_chunked_content_provider("text/plain",
  9806. [step](size_t /*offset*/, DataSink &sink) {
  9807. switch ((*step)++) {
  9808. case 0: sink.write("", 0); break;
  9809. case 1: sink.write("hello", 5); break;
  9810. default: sink.done(); break;
  9811. }
  9812. return true;
  9813. });
  9814. });
  9815. auto port = svr.bind_to_any_port(HOST);
  9816. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9817. auto listen_se = detail::scope_exit([&] {
  9818. svr.stop();
  9819. listen_thread.join();
  9820. ASSERT_FALSE(svr.is_running());
  9821. });
  9822. svr.wait_until_ready();
  9823. Client cli(HOST, port);
  9824. // Without the fix the body is never terminated, so bound the wait rather
  9825. // than letting the test hang on the default read timeout.
  9826. cli.set_read_timeout(5, 0);
  9827. auto res = cli.Get("/stream");
  9828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9829. EXPECT_EQ(StatusCode::OK_200, res->status);
  9830. EXPECT_EQ("hello", res->body);
  9831. }
  9832. TEST(StreamingTest, NoContentLengthStreaming) {
  9833. Server svr;
  9834. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9835. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9836. if (offset < 6) {
  9837. sink.os << (offset < 3 ? "a" : "b");
  9838. } else {
  9839. sink.done();
  9840. }
  9841. return true;
  9842. });
  9843. });
  9844. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9845. auto listen_se = detail::scope_exit([&] {
  9846. svr.stop();
  9847. listen_thread.join();
  9848. ASSERT_FALSE(svr.is_running());
  9849. });
  9850. svr.wait_until_ready();
  9851. Client client(HOST, PORT);
  9852. auto get_thread = std::thread([&client]() {
  9853. std::string s;
  9854. auto res =
  9855. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9856. s += std::string(data, len);
  9857. return true;
  9858. });
  9859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9860. EXPECT_EQ(StatusCode::OK_200, res->status);
  9861. EXPECT_EQ("aaabbb", s);
  9862. });
  9863. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9864. // Give GET time to get a few messages.
  9865. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9866. }
  9867. TEST(MountTest, Unmount) {
  9868. Server svr;
  9869. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9870. auto se = detail::scope_exit([&] {
  9871. svr.stop();
  9872. listen_thread.join();
  9873. ASSERT_FALSE(svr.is_running());
  9874. });
  9875. svr.wait_until_ready();
  9876. Client cli("localhost", PORT);
  9877. svr.set_mount_point("/mount2", "./www2");
  9878. auto res = cli.Get("/");
  9879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9881. res = cli.Get("/mount2/dir/test.html");
  9882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9883. EXPECT_EQ(StatusCode::OK_200, res->status);
  9884. svr.set_mount_point("/", "./www");
  9885. res = cli.Get("/dir/");
  9886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9887. EXPECT_EQ(StatusCode::OK_200, res->status);
  9888. svr.remove_mount_point("/");
  9889. res = cli.Get("/dir/");
  9890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9891. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9892. svr.remove_mount_point("/mount2");
  9893. res = cli.Get("/mount2/dir/test.html");
  9894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9895. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9896. }
  9897. TEST(MountTest, PathSegmentBoundary) {
  9898. Server svr;
  9899. svr.set_mount_point("/mount2", "./www2");
  9900. svr.set_mount_point("/", "./www");
  9901. auto port = svr.bind_to_any_port(HOST);
  9902. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9903. auto se = detail::scope_exit([&] {
  9904. svr.stop();
  9905. listen_thread.join();
  9906. ASSERT_FALSE(svr.is_running());
  9907. });
  9908. svr.wait_until_ready();
  9909. Client cli(HOST, port);
  9910. auto res = cli.Get("/mount2/dir/test.html");
  9911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9912. EXPECT_EQ(StatusCode::OK_200, res->status);
  9913. // "/mount2" must not match part-way through a path segment.
  9914. res = cli.Get("/mount2dir/test.html");
  9915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9917. // A mount point ending in '/' keeps matching every path below it.
  9918. res = cli.Get("/dir/test.html");
  9919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9920. EXPECT_EQ(StatusCode::OK_200, res->status);
  9921. }
  9922. TEST(MountTest, Redicect) {
  9923. Server svr;
  9924. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9925. auto se = detail::scope_exit([&] {
  9926. svr.stop();
  9927. listen_thread.join();
  9928. ASSERT_FALSE(svr.is_running());
  9929. });
  9930. svr.set_mount_point("/", "./www");
  9931. svr.wait_until_ready();
  9932. Client cli("localhost", PORT);
  9933. auto res = cli.Get("/dir/");
  9934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9935. EXPECT_EQ(StatusCode::OK_200, res->status);
  9936. res = cli.Get("/dir");
  9937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9938. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9939. res = cli.Get("/file");
  9940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9941. EXPECT_EQ(StatusCode::OK_200, res->status);
  9942. res = cli.Get("/file/");
  9943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9944. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9945. cli.set_follow_location(true);
  9946. res = cli.Get("/dir");
  9947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9948. EXPECT_EQ(StatusCode::OK_200, res->status);
  9949. }
  9950. TEST(MountTest, MultibytesPathName) {
  9951. Server svr;
  9952. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9953. auto se = detail::scope_exit([&] {
  9954. svr.stop();
  9955. listen_thread.join();
  9956. ASSERT_FALSE(svr.is_running());
  9957. });
  9958. svr.set_mount_point("/", "./www");
  9959. svr.wait_until_ready();
  9960. Client cli("localhost", PORT);
  9961. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9963. EXPECT_EQ(StatusCode::OK_200, res->status);
  9964. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9965. }
  9966. #ifdef _WIN32
  9967. // Issue #2435: mmap::open() must succeed even when another handle holds
  9968. // the file open for writing (e.g. an active log file).
  9969. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9970. const char *path = "mmap_concurrent_writer_test.txt";
  9971. const char *content = "hello";
  9972. {
  9973. std::ofstream f(path, std::ios::binary);
  9974. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9975. }
  9976. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9977. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9978. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9979. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9980. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9981. detail::mmap m(path);
  9982. ASSERT_TRUE(m.is_open());
  9983. EXPECT_EQ(strlen(content), m.size());
  9984. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9985. }
  9986. #endif
  9987. #ifndef _WIN32
  9988. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9989. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9990. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9991. TEST(MmapTest, FailedMappingIsNotOpen) {
  9992. const char *path = "./mmap_failed_mapping_test_dir";
  9993. ASSERT_EQ(0, ::mkdir(path, 0755));
  9994. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9995. detail::mmap m(path);
  9996. EXPECT_FALSE(m.is_open());
  9997. EXPECT_EQ(0U, m.size());
  9998. EXPECT_NE(static_cast<const void *>(m.data()),
  9999. static_cast<const void *>(MAP_FAILED));
  10000. }
  10001. #endif
  10002. TEST(KeepAliveTest, ReadTimeout) {
  10003. Server svr;
  10004. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10005. std::this_thread::sleep_for(std::chrono::seconds(2));
  10006. res.set_content("a", "text/plain");
  10007. });
  10008. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10009. res.set_content("b", "text/plain");
  10010. });
  10011. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10012. auto se = detail::scope_exit([&] {
  10013. svr.stop();
  10014. listen_thread.join();
  10015. ASSERT_FALSE(svr.is_running());
  10016. });
  10017. svr.wait_until_ready();
  10018. Client cli("localhost", PORT);
  10019. cli.set_keep_alive(true);
  10020. cli.set_read_timeout(std::chrono::seconds(1));
  10021. auto resa = cli.Get("/a");
  10022. ASSERT_FALSE(resa);
  10023. EXPECT_EQ(Error::Read, resa.error());
  10024. auto resb = cli.Get("/b");
  10025. ASSERT_TRUE(resb);
  10026. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10027. EXPECT_EQ("b", resb->body);
  10028. }
  10029. TEST(KeepAliveTest, MaxCount) {
  10030. size_t keep_alive_max_count = 3;
  10031. Server svr;
  10032. svr.set_keep_alive_max_count(keep_alive_max_count);
  10033. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10034. res.set_content("Hello World!", "text/plain");
  10035. });
  10036. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. listen_thread.join();
  10040. ASSERT_FALSE(svr.is_running());
  10041. });
  10042. svr.wait_until_ready();
  10043. Client cli(HOST, PORT);
  10044. cli.set_keep_alive(true);
  10045. for (size_t i = 0; i < 5; i++) {
  10046. auto result = cli.Get("/hi");
  10047. ASSERT_TRUE(result);
  10048. EXPECT_EQ(StatusCode::OK_200, result->status);
  10049. if (i == keep_alive_max_count - 1) {
  10050. EXPECT_EQ("close", result->get_header_value("Connection"));
  10051. } else {
  10052. EXPECT_FALSE(result->has_header("Connection"));
  10053. }
  10054. }
  10055. }
  10056. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10057. // can pull the next one into the server's buffer. The server must serve it
  10058. // without waiting for the socket to become readable again. The keep-alive
  10059. // timeout outlasts the client's read timeout, so a request left waiting for it
  10060. // shows up as a missing response.
  10061. static void serve_pipelining_routes(Server &svr,
  10062. const std::function<void(int)> &client) {
  10063. svr.set_keep_alive_timeout(5);
  10064. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10065. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10066. });
  10067. svr.Post("/echo", [](const Request &req, Response &res) {
  10068. res.set_content("echo " + req.body, "text/plain");
  10069. });
  10070. auto port = svr.bind_to_any_port(HOST);
  10071. thread t = thread([&] { svr.listen_after_bind(); });
  10072. auto se = detail::scope_exit([&] {
  10073. svr.stop();
  10074. t.join();
  10075. });
  10076. svr.wait_until_ready();
  10077. client(port);
  10078. }
  10079. static std::string
  10080. send_pipelined_requests(const std::vector<std::string> &parts) {
  10081. Server svr;
  10082. std::string res;
  10083. serve_pipelining_routes(svr, [&](int port) {
  10084. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10085. });
  10086. return res;
  10087. }
  10088. static void expect_in_order(const std::string &res,
  10089. const std::vector<std::string> &bodies) {
  10090. size_t pos = 0;
  10091. for (const auto &body : bodies) {
  10092. pos = res.find(body, pos);
  10093. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10094. pos += body.size();
  10095. }
  10096. }
  10097. TEST(KeepAliveTest, PipelinedRequests) {
  10098. auto res = send_pipelined_requests(
  10099. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10100. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10101. "Content-Length: 4\r\n\r\nbody"
  10102. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10103. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10104. }
  10105. // The second request starts in the server's buffer and ends on the socket.
  10106. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10107. auto res =
  10108. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10109. "GET /hi/2 HTTP/1.1\r\nHo",
  10110. "st: localhost\r\nConnection: close\r\n\r\n"});
  10111. expect_in_order(res, {"hi 1", "hi 2"});
  10112. }
  10113. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10114. // CRLF after a body does not turn into a 400 for the next request.
  10115. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10116. auto res = send_pipelined_requests(
  10117. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10118. "Content-Length: 4\r\n\r\nbody\r\n"
  10119. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10120. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10121. expect_in_order(res, {"echo body", "hi 2"});
  10122. }
  10123. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10124. // must not be served as the next request.
  10125. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10126. auto res = send_pipelined_requests(
  10127. {"INVALID REQUEST LINE\r\n\r\n"
  10128. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10129. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10130. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10131. }
  10132. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10133. // Over TLS, the next request is held by the TLS library as already decrypted
  10134. // data rather than on the socket.
  10135. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10136. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10137. std::string res;
  10138. serve_pipelining_routes(svr, [&](int port) {
  10139. auto error = Error::Success;
  10140. auto sock = detail::create_client_socket(
  10141. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10142. /*connection_timeout_sec=*/5, 0,
  10143. /*read_timeout_sec=*/2, 0,
  10144. /*write_timeout_sec=*/5, 0, std::string(), error);
  10145. ASSERT_NE(INVALID_SOCKET, sock);
  10146. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10147. auto ctx = SSL_CTX_new(TLS_client_method());
  10148. auto ssl = SSL_new(ctx);
  10149. auto ssl_se = detail::scope_exit([&] {
  10150. SSL_free(ssl);
  10151. SSL_CTX_free(ctx);
  10152. });
  10153. SSL_set_fd(ssl, static_cast<int>(sock));
  10154. ASSERT_EQ(1, SSL_connect(ssl));
  10155. // One write, so all three requests arrive in one TLS record
  10156. const std::string req =
  10157. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10158. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10159. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10160. ASSERT_EQ(static_cast<int>(req.size()),
  10161. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10162. char buf[512];
  10163. int n;
  10164. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10165. res.append(buf, static_cast<size_t>(n));
  10166. }
  10167. });
  10168. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10169. }
  10170. #endif
  10171. TEST(KeepAliveTest, Issue1041) {
  10172. Server svr;
  10173. svr.set_keep_alive_timeout(3);
  10174. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10175. res.set_content("Hello World!", "text/plain");
  10176. });
  10177. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10178. auto se = detail::scope_exit([&] {
  10179. svr.stop();
  10180. listen_thread.join();
  10181. ASSERT_FALSE(svr.is_running());
  10182. });
  10183. svr.wait_until_ready();
  10184. Client cli(HOST, PORT);
  10185. cli.set_keep_alive(true);
  10186. auto result = cli.Get("/hi");
  10187. ASSERT_TRUE(result);
  10188. EXPECT_EQ(StatusCode::OK_200, result->status);
  10189. std::this_thread::sleep_for(std::chrono::seconds(5));
  10190. result = cli.Get("/hi");
  10191. ASSERT_TRUE(result);
  10192. EXPECT_EQ(StatusCode::OK_200, result->status);
  10193. }
  10194. TEST(KeepAliveTest, Issue1959) {
  10195. Server svr;
  10196. svr.set_keep_alive_timeout(5);
  10197. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10198. res.set_content("a", "text/plain");
  10199. });
  10200. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10201. auto se = detail::scope_exit([&] {
  10202. if (!svr.is_running()) return;
  10203. svr.stop();
  10204. listen_thread.join();
  10205. ASSERT_FALSE(svr.is_running());
  10206. });
  10207. svr.wait_until_ready();
  10208. Client cli("localhost", PORT);
  10209. cli.set_keep_alive(true);
  10210. using namespace std::chrono;
  10211. auto start = steady_clock::now();
  10212. cli.Get("/a");
  10213. svr.stop();
  10214. listen_thread.join();
  10215. auto end = steady_clock::now();
  10216. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10217. EXPECT_LT(elapsed, 5000);
  10218. }
  10219. #ifdef CPPHTTPLIB_SSL_ENABLED
  10220. TEST(KeepAliveTest, SSLClientReconnection) {
  10221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10222. ASSERT_TRUE(svr.is_valid());
  10223. svr.set_keep_alive_timeout(1);
  10224. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10225. res.set_content("Hello World!", "text/plain");
  10226. });
  10227. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10228. auto se = detail::scope_exit([&] {
  10229. svr.stop();
  10230. listen_thread.join();
  10231. ASSERT_FALSE(svr.is_running());
  10232. });
  10233. svr.wait_until_ready();
  10234. SSLClient cli(HOST, PORT);
  10235. cli.enable_server_certificate_verification(false);
  10236. cli.set_keep_alive(true);
  10237. auto result = cli.Get("/hi");
  10238. ASSERT_TRUE(result);
  10239. EXPECT_EQ(StatusCode::OK_200, result->status);
  10240. result = cli.Get("/hi");
  10241. ASSERT_TRUE(result);
  10242. EXPECT_EQ(StatusCode::OK_200, result->status);
  10243. std::this_thread::sleep_for(std::chrono::seconds(2));
  10244. // Recoonect
  10245. result = cli.Get("/hi");
  10246. ASSERT_TRUE(result);
  10247. EXPECT_EQ(StatusCode::OK_200, result->status);
  10248. result = cli.Get("/hi");
  10249. ASSERT_TRUE(result);
  10250. EXPECT_EQ(StatusCode::OK_200, result->status);
  10251. }
  10252. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10254. ASSERT_TRUE(svr.is_valid());
  10255. svr.set_keep_alive_timeout(1);
  10256. std::string content = "reconnect";
  10257. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10258. res.set_content("Hello World!", "text/plain");
  10259. });
  10260. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10261. auto se = detail::scope_exit([&] {
  10262. svr.stop();
  10263. listen_thread.join();
  10264. ASSERT_FALSE(svr.is_running());
  10265. });
  10266. svr.wait_until_ready();
  10267. SSLClient cli(HOST, PORT);
  10268. cli.enable_server_certificate_verification(false);
  10269. cli.set_keep_alive(true);
  10270. auto result = cli.Post(
  10271. "/hi", content.size(),
  10272. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10273. sink.write(content.c_str(), content.size());
  10274. return true;
  10275. },
  10276. "text/plain");
  10277. ASSERT_TRUE(result);
  10278. EXPECT_EQ(200, result->status);
  10279. std::this_thread::sleep_for(std::chrono::seconds(2));
  10280. // Recoonect
  10281. result = cli.Post(
  10282. "/hi", content.size(),
  10283. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10284. sink.write(content.c_str(), content.size());
  10285. return true;
  10286. },
  10287. "text/plain");
  10288. ASSERT_TRUE(result);
  10289. EXPECT_EQ(200, result->status);
  10290. result = cli.Post(
  10291. "/hi", content.size(),
  10292. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10293. sink.write(content.c_str(), content.size());
  10294. return true;
  10295. },
  10296. "text/plain");
  10297. ASSERT_TRUE(result);
  10298. EXPECT_EQ(200, result->status);
  10299. }
  10300. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10301. using namespace httplib::tls;
  10302. {
  10303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10304. ASSERT_TRUE(svr.is_valid());
  10305. svr.Get("/sni", [&](const Request &req, Response &res) {
  10306. std::string expected = req.sni();
  10307. EXPECT_EQ(expected, req.get_param_value("expected"));
  10308. res.set_content("ok", "text/plain");
  10309. });
  10310. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10311. auto se = detail::scope_exit([&] {
  10312. svr.stop();
  10313. listen_thread.join();
  10314. ASSERT_FALSE(svr.is_running());
  10315. });
  10316. svr.wait_until_ready();
  10317. {
  10318. SSLClient cli("localhost", PORT);
  10319. cli.enable_server_certificate_verification(false);
  10320. auto res = cli.Get("/sni?expected=localhost");
  10321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10322. }
  10323. {
  10324. SSLClient cli("::1", PORT);
  10325. cli.enable_server_certificate_verification(false);
  10326. auto res = cli.Get("/sni?expected=");
  10327. // NOTE: This may fail if the server is listening on IPv4 only
  10328. // (e.g., when localhost resolves to 127.0.0.1 only)
  10329. if (res) {
  10330. EXPECT_EQ(StatusCode::OK_200, res->status);
  10331. } else {
  10332. EXPECT_EQ(Error::Connection, res.error());
  10333. }
  10334. }
  10335. }
  10336. }
  10337. #endif
  10338. TEST(ClientProblemDetectionTest, ContentProvider) {
  10339. Server svr;
  10340. size_t content_length = 1024 * 1024;
  10341. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10342. res.set_content_provider(
  10343. content_length, "text/plain",
  10344. [&](size_t offset, size_t length, DataSink &sink) {
  10345. auto out_len = std::min(length, static_cast<size_t>(1024));
  10346. std::string out(out_len, '@');
  10347. sink.write(out.data(), out_len);
  10348. return offset < 4096;
  10349. },
  10350. [](bool success) { ASSERT_FALSE(success); });
  10351. });
  10352. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10353. res.set_content_provider(
  10354. 0, "text/plain",
  10355. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10356. EXPECT_TRUE(false);
  10357. return true;
  10358. },
  10359. [](bool success) { ASSERT_FALSE(success); });
  10360. });
  10361. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10362. auto se = detail::scope_exit([&] {
  10363. svr.stop();
  10364. listen_thread.join();
  10365. ASSERT_FALSE(svr.is_running());
  10366. });
  10367. svr.wait_until_ready();
  10368. Client cli("localhost", PORT);
  10369. {
  10370. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10371. size_t /*data_length*/) { return false; });
  10372. ASSERT_FALSE(res);
  10373. }
  10374. {
  10375. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10376. size_t /*data_length*/) { return false; });
  10377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10378. }
  10379. }
  10380. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10381. // A provider that reports success without writing anything and without
  10382. // calling done() used to be handed the same offset and length again on every
  10383. // pass, so it spun for as long as the peer stayed connected.
  10384. Server svr;
  10385. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10386. res.set_content("ok", "text/plain");
  10387. });
  10388. auto port = svr.bind_to_any_port(HOST);
  10389. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10390. auto se = detail::scope_exit([&] {
  10391. svr.stop();
  10392. listen_thread.join();
  10393. ASSERT_FALSE(svr.is_running());
  10394. });
  10395. svr.wait_until_ready();
  10396. std::atomic<int> call_count{0};
  10397. Client cli(HOST, port);
  10398. auto res = cli.Post(
  10399. "/", 1024,
  10400. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10401. // Give up after enough passes to show the spin, so that losing the
  10402. // check below fails this test instead of hanging it.
  10403. return ++call_count < 100;
  10404. },
  10405. "text/plain");
  10406. ASSERT_FALSE(res);
  10407. EXPECT_EQ(Error::Write, res.error());
  10408. EXPECT_EQ(1, call_count.load());
  10409. }
  10410. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10411. // A writer only has to assign `write`. The other three used to be left as
  10412. // empty std::functions, so a provider calling one threw
  10413. // std::bad_function_call out of the thread running it and took the whole
  10414. // process down.
  10415. DataSink sink;
  10416. std::string written;
  10417. sink.write = [&](const char *data, size_t data_len) {
  10418. written.append(data, data_len);
  10419. return true;
  10420. };
  10421. EXPECT_TRUE(sink.is_writable());
  10422. sink.done();
  10423. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10424. EXPECT_TRUE(written.empty());
  10425. }
  10426. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10427. // A sink that cannot carry trailers still has to finish.
  10428. DataSink sink;
  10429. auto done_count = 0;
  10430. sink.done = [&]() { done_count++; };
  10431. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10432. EXPECT_EQ(1, done_count);
  10433. }
  10434. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10435. Server svr;
  10436. const std::string body(4096, 'x');
  10437. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10438. res.set_content_provider(body.size(), "text/plain",
  10439. [&](size_t offset, size_t length, DataSink &sink) {
  10440. sink.write(body.data() + offset, length);
  10441. sink.done();
  10442. return true;
  10443. });
  10444. });
  10445. auto port = svr.bind_to_any_port(HOST);
  10446. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10447. auto se = detail::scope_exit([&] {
  10448. svr.stop();
  10449. listen_thread.join();
  10450. ASSERT_FALSE(svr.is_running());
  10451. });
  10452. svr.wait_until_ready();
  10453. Client cli(HOST, port);
  10454. auto res = cli.Get("/");
  10455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10456. EXPECT_EQ(StatusCode::OK_200, res->status);
  10457. EXPECT_EQ(body, res->body);
  10458. }
  10459. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10460. Server svr;
  10461. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10462. res.set_content_provider(
  10463. 1024, "text/plain",
  10464. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10465. sink.write("hello", 5);
  10466. sink.done(); // short of the 1024 bytes the response promised
  10467. return true;
  10468. });
  10469. });
  10470. auto port = svr.bind_to_any_port(HOST);
  10471. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10472. auto se = detail::scope_exit([&] {
  10473. svr.stop();
  10474. listen_thread.join();
  10475. ASSERT_FALSE(svr.is_running());
  10476. });
  10477. svr.wait_until_ready();
  10478. Client cli(HOST, port);
  10479. cli.set_read_timeout(5, 0);
  10480. // The response is short of its Content-Length, so the client cannot read a
  10481. // complete body. What matters is that this returns at all: a no-op done()
  10482. // would leave the writer looping over a provider that never makes progress.
  10483. auto res = cli.Get("/");
  10484. EXPECT_FALSE(res);
  10485. }
  10486. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10487. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10488. // The compressed path builds the whole body before connecting, so this
  10489. // fails client-side and never reaches a server.
  10490. Client cli(HOST, PORT);
  10491. cli.set_compress(true);
  10492. auto res = cli.Post(
  10493. "/", 1024,
  10494. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10495. sink.write("hello", 5);
  10496. sink.done(); // short of the 1024 bytes the request announced
  10497. return true;
  10498. },
  10499. "text/plain");
  10500. ASSERT_FALSE(res);
  10501. EXPECT_EQ(Error::Write, res.error());
  10502. }
  10503. #endif
  10504. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10505. Server svr;
  10506. svr.set_error_handler([](Request const &, Response &res) -> void {
  10507. res.set_chunked_content_provider(
  10508. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10509. sink.os << "hello";
  10510. sink.os << "world";
  10511. sink.done();
  10512. return true;
  10513. });
  10514. });
  10515. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10516. auto se = detail::scope_exit([&] {
  10517. svr.stop();
  10518. listen_thread.join();
  10519. ASSERT_FALSE(svr.is_running());
  10520. });
  10521. svr.wait_until_ready();
  10522. Client cli("localhost", PORT);
  10523. auto res = cli.Get("/");
  10524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10526. EXPECT_EQ("helloworld", res->body);
  10527. }
  10528. // A body set after a content provider must replace it, not be sent through it.
  10529. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10530. Server svr;
  10531. svr.set_mount_point("/", "./www");
  10532. svr.set_file_request_handler([](const Request &req, Response &res) {
  10533. if (req.path == "/dir/test.html") {
  10534. res.status = StatusCode::Forbidden_403;
  10535. res.set_content(std::string(5000, 'D'), "text/plain");
  10536. } else if (req.path == "/file") {
  10537. res.status = StatusCode::Forbidden_403;
  10538. res.body = "Denied";
  10539. }
  10540. });
  10541. auto port = svr.bind_to_any_port(HOST);
  10542. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10543. auto se = detail::scope_exit([&] {
  10544. svr.stop();
  10545. t.join();
  10546. ASSERT_FALSE(svr.is_running());
  10547. });
  10548. svr.wait_until_ready();
  10549. Client cli(HOST, port);
  10550. {
  10551. auto res = cli.Get("/dir/test.html");
  10552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10553. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10554. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10555. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10556. }
  10557. {
  10558. auto res = cli.Get("/file");
  10559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10560. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10561. EXPECT_EQ("Denied", res->body);
  10562. }
  10563. {
  10564. auto res = cli.Get("/dir/index.html");
  10565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10566. EXPECT_EQ(StatusCode::OK_200, res->status);
  10567. EXPECT_EQ(0U, res->body.find("<html>"));
  10568. }
  10569. }
  10570. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10571. Server svr;
  10572. std::vector<bool> released;
  10573. std::mutex released_mutex;
  10574. auto releaser = [&](bool success) {
  10575. std::lock_guard<std::mutex> guard(released_mutex);
  10576. released.push_back(success);
  10577. };
  10578. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10579. return sink.write(&"hello"[offset], length);
  10580. };
  10581. svr.Get("/sized", [&](const Request &, Response &res) {
  10582. res.status = StatusCode::NotFound_404;
  10583. res.set_content_provider(5, "text/plain", provider, releaser);
  10584. });
  10585. svr.Get("/chunked", [&](const Request &, Response &res) {
  10586. res.status = StatusCode::ServiceUnavailable_503;
  10587. res.set_chunked_content_provider(
  10588. "text/plain",
  10589. [](size_t, DataSink &sink) {
  10590. sink.os << "chunk";
  10591. sink.done();
  10592. return true;
  10593. },
  10594. releaser);
  10595. });
  10596. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10597. res.set_content_provider(5, "text/plain", provider, releaser);
  10598. throw std::runtime_error("after the provider");
  10599. });
  10600. svr.set_error_handler([](const Request &req, Response &res) {
  10601. // Leave the exception handler's content to it.
  10602. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10603. res.set_content(std::string(1000, 'E'), "text/html");
  10604. return Server::HandlerResponse::Handled;
  10605. });
  10606. svr.set_exception_handler(
  10607. [](const Request &, Response &res, std::exception_ptr) {
  10608. res.status = StatusCode::InternalServerError_500;
  10609. res.set_content(std::string(1000, 'X'), "text/html");
  10610. });
  10611. auto port = svr.bind_to_any_port(HOST);
  10612. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10613. auto se = detail::scope_exit([&] {
  10614. svr.stop();
  10615. t.join();
  10616. ASSERT_FALSE(svr.is_running());
  10617. });
  10618. svr.wait_until_ready();
  10619. Client cli(HOST, port);
  10620. {
  10621. auto res = cli.Get("/sized");
  10622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10624. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10625. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10626. }
  10627. {
  10628. auto res = cli.Get("/chunked");
  10629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10630. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10631. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10632. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10633. }
  10634. {
  10635. auto res = cli.Get("/throw");
  10636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10637. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10638. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10639. }
  10640. std::lock_guard<std::mutex> guard(released_mutex);
  10641. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10642. }
  10643. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10644. Server svr;
  10645. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10646. return sink.write(&"abc"[offset], length);
  10647. };
  10648. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10649. res.set_file_content("./www/dir/test.html");
  10650. res.set_content("body", "text/plain");
  10651. });
  10652. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10653. res.set_content(std::string(100, 'B'), "text/plain");
  10654. res.set_file_content("./www/dir/test.html");
  10655. });
  10656. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10657. res.set_content(std::string(100, 'B'), "text/plain");
  10658. res.set_content_provider(3, "text/plain", abc);
  10659. });
  10660. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10661. res.set_content_provider(3, "text/plain", abc);
  10662. res.set_content(std::string(100, 'B'), "text/plain");
  10663. });
  10664. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10665. res.set_content_provider(3, "text/plain", abc);
  10666. res.body = "direct";
  10667. });
  10668. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10669. res.set_file_content("./www/dir/test.html");
  10670. res.body = "direct";
  10671. });
  10672. auto port = svr.bind_to_any_port(HOST);
  10673. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10674. auto se = detail::scope_exit([&] {
  10675. svr.stop();
  10676. t.join();
  10677. ASSERT_FALSE(svr.is_running());
  10678. });
  10679. svr.wait_until_ready();
  10680. Client cli(HOST, port);
  10681. auto expect_body = [&](const char *path, const std::string &body) {
  10682. // Uncompressed, so Content-Length can be compared with the body.
  10683. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10684. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10685. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10686. EXPECT_EQ(body, res->body) << path;
  10687. EXPECT_EQ(std::to_string(body.size()),
  10688. res->get_header_value("Content-Length"))
  10689. << path;
  10690. };
  10691. expect_body("/file-then-body", "body");
  10692. expect_body("/body-then-file", "test.html");
  10693. expect_body("/body-then-provider", "abc");
  10694. expect_body("/provider-then-body", std::string(100, 'B'));
  10695. expect_body("/provider-then-direct-body", "direct");
  10696. expect_body("/file-then-direct-body", "direct");
  10697. // Ranges are checked against the body, not the dropped provider.
  10698. {
  10699. auto res = cli.Get("/provider-then-direct-body",
  10700. Headers{{make_range_header({{1, 2}})}});
  10701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10702. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10703. EXPECT_EQ("ir", res->body);
  10704. }
  10705. {
  10706. auto res = cli.Get("/file-then-direct-body",
  10707. Headers{{make_range_header({{7, 8}})}});
  10708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10709. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10710. }
  10711. }
  10712. // Forward declaration (see the base64_encode note).
  10713. namespace httplib {
  10714. namespace detail {
  10715. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10716. const std::string &content_type,
  10717. EncodingType encoding);
  10718. } // namespace detail
  10719. } // namespace httplib
  10720. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10721. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10722. ASSERT_TRUE(mm->is_open());
  10723. Response res;
  10724. detail::set_file_content_provider(res, mm, "text/html",
  10725. detail::EncodingType::None);
  10726. std::string out;
  10727. DataSink sink;
  10728. sink.write = [&](const char *d, size_t l) {
  10729. out.append(d, l);
  10730. return true;
  10731. };
  10732. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10733. EXPECT_EQ("test.html", out);
  10734. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10735. EXPECT_EQ("test.html", out);
  10736. }
  10737. TEST(LongPollingTest, ClientCloseDetection) {
  10738. Server svr;
  10739. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10740. res.set_chunked_content_provider(
  10741. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10742. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10743. sink.os << "hello";
  10744. auto count = 10;
  10745. while (count > 0 && sink.is_writable()) {
  10746. this_thread::sleep_for(chrono::milliseconds(10));
  10747. count--;
  10748. }
  10749. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10750. return true;
  10751. });
  10752. });
  10753. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10754. auto se = detail::scope_exit([&] {
  10755. svr.stop();
  10756. listen_thread.join();
  10757. ASSERT_FALSE(svr.is_running());
  10758. });
  10759. svr.wait_until_ready();
  10760. Client cli("localhost", PORT);
  10761. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10762. EXPECT_EQ("hello", string(data, data_length));
  10763. return false; // close the socket immediately.
  10764. });
  10765. ASSERT_FALSE(res);
  10766. }
  10767. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10768. Server svr;
  10769. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10770. res.set_chunked_content_provider(
  10771. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10772. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10773. sink.os << "hello";
  10774. EXPECT_TRUE(sink.os.good());
  10775. // Wait for the client to close the connection
  10776. auto count = 10;
  10777. while (count > 0 && sink.is_writable()) {
  10778. this_thread::sleep_for(chrono::milliseconds(10));
  10779. count--;
  10780. }
  10781. // After client disconnect, write repeatedly until the socket
  10782. // write actually fails (small writes may be absorbed by the
  10783. // kernel buffer)
  10784. std::string chunk(1024, 'x');
  10785. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10786. sink.os << chunk;
  10787. }
  10788. EXPECT_TRUE(sink.os.fail());
  10789. return true;
  10790. });
  10791. });
  10792. auto port = svr.bind_to_any_port("localhost");
  10793. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10794. auto se = detail::scope_exit([&] {
  10795. svr.stop();
  10796. listen_thread.join();
  10797. ASSERT_FALSE(svr.is_running());
  10798. });
  10799. svr.wait_until_ready();
  10800. Client cli("localhost", port);
  10801. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10802. EXPECT_EQ("hello", string(data, data_length));
  10803. return false; // close the socket immediately.
  10804. });
  10805. ASSERT_FALSE(res);
  10806. }
  10807. TEST(GetWithParametersTest, GetWithParameters) {
  10808. Server svr;
  10809. svr.Get("/", [&](const Request &req, Response &) {
  10810. EXPECT_EQ("world", req.get_param_value("hello"));
  10811. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10812. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10813. });
  10814. svr.Get("/params", [&](const Request &req, Response &) {
  10815. EXPECT_EQ("world", req.get_param_value("hello"));
  10816. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10817. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10818. });
  10819. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10820. EXPECT_EQ("resource-id", req.matches[1]);
  10821. EXPECT_EQ("foo", req.get_param_value("param1"));
  10822. EXPECT_EQ("bar", req.get_param_value("param2"));
  10823. });
  10824. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10825. EXPECT_EQ("user-id", req.path_params.at("id"));
  10826. EXPECT_EQ("foo", req.get_param_value("param1"));
  10827. EXPECT_EQ("bar", req.get_param_value("param2"));
  10828. });
  10829. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10830. auto se = detail::scope_exit([&] {
  10831. svr.stop();
  10832. listen_thread.join();
  10833. ASSERT_FALSE(svr.is_running());
  10834. });
  10835. svr.wait_until_ready();
  10836. {
  10837. Client cli(HOST, PORT);
  10838. Params params;
  10839. params.emplace("hello", "world");
  10840. params.emplace("hello2", "world2");
  10841. params.emplace("hello3", "world3");
  10842. auto res = cli.Get("/", params, Headers{});
  10843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10844. EXPECT_EQ(StatusCode::OK_200, res->status);
  10845. }
  10846. {
  10847. Client cli(HOST, PORT);
  10848. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10850. EXPECT_EQ(StatusCode::OK_200, res->status);
  10851. }
  10852. {
  10853. Client cli(HOST, PORT);
  10854. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10856. EXPECT_EQ(StatusCode::OK_200, res->status);
  10857. }
  10858. {
  10859. Client cli(HOST, PORT);
  10860. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10862. EXPECT_EQ(StatusCode::OK_200, res->status);
  10863. }
  10864. }
  10865. TEST(GetWithParametersTest, GetWithParameters2) {
  10866. Server svr;
  10867. svr.Get("/", [&](const Request &req, Response &res) {
  10868. auto text = req.get_param_value("hello");
  10869. res.set_content(text, "text/plain");
  10870. });
  10871. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", 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. Client cli("localhost", PORT);
  10879. Params params;
  10880. params.emplace("hello", "world");
  10881. std::string body;
  10882. auto res = cli.Get("/", params, Headers{},
  10883. [&](const char *data, size_t data_length) {
  10884. body.append(data, data_length);
  10885. return true;
  10886. });
  10887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10888. EXPECT_EQ(StatusCode::OK_200, res->status);
  10889. EXPECT_EQ("world", body);
  10890. }
  10891. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10892. Server svr;
  10893. svr.Get("/search", [&](const Request &req, Response &res) {
  10894. auto q = req.get_param_value("q");
  10895. res.set_content(q, "text/plain");
  10896. });
  10897. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10898. auto se = detail::scope_exit([&] {
  10899. svr.stop();
  10900. listen_thread.join();
  10901. ASSERT_FALSE(svr.is_running());
  10902. });
  10903. svr.wait_until_ready();
  10904. Client cli("localhost", PORT);
  10905. // Verify that Get(path, params) works without requiring Headers argument
  10906. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10908. EXPECT_EQ(StatusCode::OK_200, res->status);
  10909. EXPECT_EQ("cpp-httplib", res->body);
  10910. }
  10911. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10912. auto host = "httpbingo.org";
  10913. auto path = std::string{"/range/32"};
  10914. #ifdef CPPHTTPLIB_SSL_ENABLED
  10915. SSLClient cli(host);
  10916. #else
  10917. Client cli(host);
  10918. #endif
  10919. cli.set_default_headers({make_range_header({{1, 10}})});
  10920. cli.set_connection_timeout(5);
  10921. {
  10922. auto res = cli.Get(path);
  10923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10924. EXPECT_EQ("bcdefghijk", res->body);
  10925. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10926. }
  10927. {
  10928. auto res = cli.Get(path);
  10929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10930. EXPECT_EQ("bcdefghijk", res->body);
  10931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10932. }
  10933. }
  10934. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10935. Server svr;
  10936. svr.set_default_headers({{"Hello", "World"}});
  10937. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10938. res.set_content("ok", "text/plain");
  10939. });
  10940. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10941. auto se = detail::scope_exit([&] {
  10942. svr.stop();
  10943. listen_thread.join();
  10944. ASSERT_FALSE(svr.is_running());
  10945. });
  10946. svr.wait_until_ready();
  10947. Client cli("localhost", PORT);
  10948. auto res = cli.Get("/");
  10949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10950. EXPECT_EQ(StatusCode::OK_200, res->status);
  10951. EXPECT_EQ("ok", res->body);
  10952. EXPECT_EQ("World", res->get_header_value("Hello"));
  10953. }
  10954. #ifdef CPPHTTPLIB_SSL_ENABLED
  10955. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10956. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10957. ASSERT_TRUE(svr.is_valid());
  10958. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10959. std::this_thread::sleep_for(std::chrono::seconds(2));
  10960. res.set_content("a", "text/plain");
  10961. });
  10962. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10963. res.set_content("b", "text/plain");
  10964. });
  10965. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10966. auto se = detail::scope_exit([&] {
  10967. svr.stop();
  10968. listen_thread.join();
  10969. ASSERT_FALSE(svr.is_running());
  10970. });
  10971. svr.wait_until_ready();
  10972. SSLClient cli("localhost", PORT);
  10973. cli.enable_server_certificate_verification(false);
  10974. cli.set_keep_alive(true);
  10975. cli.set_read_timeout(std::chrono::seconds(1));
  10976. auto resa = cli.Get("/a");
  10977. ASSERT_TRUE(!resa);
  10978. EXPECT_EQ(Error::Read, resa.error());
  10979. auto resb = cli.Get("/b");
  10980. ASSERT_TRUE(resb);
  10981. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10982. EXPECT_EQ("b", resb->body);
  10983. }
  10984. // Closing an idle keep-alive connection sends close_notify and returns. The
  10985. // server must not wait for the client's close_notify: an idle client never
  10986. // sends one, so the worker would be held until the read timeout expires, and
  10987. // stop() would wait for it.
  10988. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10989. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10990. ASSERT_TRUE(svr.is_valid());
  10991. svr.set_keep_alive_timeout(1);
  10992. svr.set_read_timeout(10, 0);
  10993. svr.Get("/", [](const Request &, Response &res) {
  10994. res.set_content("ok", "text/plain");
  10995. });
  10996. auto port = svr.bind_to_any_port(HOST);
  10997. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10998. auto se = detail::scope_exit([&] {
  10999. if (listen_thread.joinable()) {
  11000. svr.stop();
  11001. listen_thread.join();
  11002. }
  11003. });
  11004. svr.wait_until_ready();
  11005. SSLClient cli(HOST, port);
  11006. cli.enable_server_certificate_verification(false);
  11007. cli.set_keep_alive(true);
  11008. auto res = cli.Get("/");
  11009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11010. EXPECT_EQ(StatusCode::OK_200, res->status);
  11011. // Stay idle past the keep-alive timeout so the server closes the connection.
  11012. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11013. auto start = std::chrono::steady_clock::now();
  11014. svr.stop();
  11015. listen_thread.join();
  11016. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11017. std::chrono::steady_clock::now() - start)
  11018. .count();
  11019. EXPECT_LT(elapsed, 3000);
  11020. }
  11021. #endif
  11022. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11023. protected:
  11024. ServerTestWithAI_PASSIVE()
  11025. : cli_(HOST, PORT)
  11026. #ifdef CPPHTTPLIB_SSL_ENABLED
  11027. ,
  11028. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11029. #endif
  11030. {
  11031. #ifdef CPPHTTPLIB_SSL_ENABLED
  11032. cli_.enable_server_certificate_verification(false);
  11033. #endif
  11034. }
  11035. virtual void SetUp() {
  11036. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11037. res.set_content("Hello World!", "text/plain");
  11038. });
  11039. t_ = thread(
  11040. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11041. svr_.wait_until_ready();
  11042. }
  11043. virtual void TearDown() {
  11044. svr_.stop();
  11045. t_.join();
  11046. }
  11047. #ifdef CPPHTTPLIB_SSL_ENABLED
  11048. SSLClient cli_;
  11049. SSLServer svr_;
  11050. #else
  11051. Client cli_;
  11052. Server svr_;
  11053. #endif
  11054. thread t_;
  11055. };
  11056. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11057. auto res = cli_.Get("/hi");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. EXPECT_EQ(StatusCode::OK_200, res->status);
  11060. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11061. EXPECT_EQ("Hello World!", res->body);
  11062. }
  11063. class ServerUpDownTest : public ::testing::Test {
  11064. protected:
  11065. ServerUpDownTest() : cli_(HOST, PORT) {}
  11066. virtual void SetUp() {
  11067. t_ = thread([&]() {
  11068. svr_.bind_to_any_port(HOST);
  11069. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11070. ASSERT_TRUE(svr_.listen_after_bind());
  11071. });
  11072. svr_.wait_until_ready();
  11073. }
  11074. virtual void TearDown() {
  11075. svr_.stop();
  11076. t_.join();
  11077. }
  11078. Client cli_;
  11079. Server svr_;
  11080. thread t_;
  11081. };
  11082. TEST_F(ServerUpDownTest, QuickStartStop) {
  11083. // Should not crash, especially when run with
  11084. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11085. }
  11086. class PayloadMaxLengthTest : public ::testing::Test {
  11087. protected:
  11088. PayloadMaxLengthTest()
  11089. : cli_(HOST, PORT)
  11090. #ifdef CPPHTTPLIB_SSL_ENABLED
  11091. ,
  11092. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11093. #endif
  11094. {
  11095. #ifdef CPPHTTPLIB_SSL_ENABLED
  11096. cli_.enable_server_certificate_verification(false);
  11097. #endif
  11098. }
  11099. virtual void SetUp() {
  11100. svr_.set_payload_max_length(8);
  11101. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11102. res.set_content("test", "text/plain");
  11103. });
  11104. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11105. svr_.wait_until_ready();
  11106. }
  11107. virtual void TearDown() {
  11108. svr_.stop();
  11109. t_.join();
  11110. }
  11111. #ifdef CPPHTTPLIB_SSL_ENABLED
  11112. SSLClient cli_;
  11113. SSLServer svr_;
  11114. #else
  11115. Client cli_;
  11116. Server svr_;
  11117. #endif
  11118. thread t_;
  11119. };
  11120. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11121. auto res = cli_.Post("/test", "123456789", "text/plain");
  11122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11123. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11124. res = cli_.Post("/test", "12345678", "text/plain");
  11125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11126. EXPECT_EQ(StatusCode::OK_200, res->status);
  11127. }
  11128. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11129. // Test chunked encoding with payload exceeding the 8-byte limit
  11130. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11131. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11133. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11134. }
  11135. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11136. // Test chunked encoding with payload within the 8-byte limit
  11137. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11138. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11140. EXPECT_EQ(StatusCode::OK_200, res->status);
  11141. }
  11142. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11143. // Test using send_request to send chunked data exceeding payload limit
  11144. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11145. "Host: " +
  11146. std::string(HOST) + ":" + std::to_string(PORT) +
  11147. "\r\n"
  11148. "Transfer-Encoding: chunked\r\n"
  11149. "Connection: close\r\n"
  11150. "\r\n"
  11151. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11152. "0123456789\r\n"
  11153. "0\r\n" // End chunk
  11154. "\r\n";
  11155. std::string response;
  11156. bool result = send_request(1, chunked_request, &response);
  11157. if (!result) {
  11158. // If send_request fails, it might be because the server closed the
  11159. // connection due to payload limit enforcement, which is acceptable
  11160. SUCCEED()
  11161. << "Server rejected oversized chunked request (connection closed)";
  11162. } else {
  11163. // If we got a response, check if it's an error response or connection was
  11164. // closed early Short response length indicates connection was closed due to
  11165. // payload limit
  11166. if (response.length() <= 10) {
  11167. SUCCEED() << "Server closed connection for oversized chunked request";
  11168. } else {
  11169. // Check for error status codes
  11170. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11171. response.find("Payload Too Large") != std::string::npos ||
  11172. response.find("400") != std::string::npos);
  11173. }
  11174. }
  11175. }
  11176. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11177. // Test request without Content-Length header exceeding payload limit
  11178. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11179. "Host: " +
  11180. std::string(HOST) + ":" +
  11181. std::to_string(PORT) +
  11182. "\r\n"
  11183. "Connection: close\r\n"
  11184. "\r\n";
  11185. // Add payload exceeding the 8-byte limit
  11186. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11187. request_without_content_length += large_payload;
  11188. std::string response;
  11189. bool result = send_request(1, request_without_content_length, &response);
  11190. if (!result) {
  11191. // If send_request fails, server likely closed connection due to payload
  11192. // limit
  11193. SUCCEED() << "Server rejected oversized request without Content-Length "
  11194. "(connection closed)";
  11195. } else {
  11196. // Check if server responded with error or closed connection early
  11197. if (response.length() <= 10) {
  11198. SUCCEED() << "Server closed connection for oversized request without "
  11199. "Content-Length";
  11200. } else {
  11201. // Check for error status codes
  11202. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11203. response.find("Payload Too Large") != std::string::npos ||
  11204. response.find("400") != std::string::npos);
  11205. }
  11206. }
  11207. }
  11208. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11209. // Test request without Content-Length header within payload limit
  11210. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11211. "Host: " +
  11212. std::string(HOST) + ":" +
  11213. std::to_string(PORT) +
  11214. "\r\n"
  11215. "Connection: close\r\n"
  11216. "\r\n";
  11217. // Add payload within the 8-byte limit
  11218. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11219. request_without_content_length += small_payload;
  11220. std::string response;
  11221. bool result = send_request(1, request_without_content_length, &response);
  11222. // For requests without Content-Length, the server may have different behavior
  11223. // The key is that it should not reject due to payload limit for small
  11224. // payloads
  11225. if (result) {
  11226. // Check for any HTTP response (success or error, but not connection closed)
  11227. if (response.length() > 10) {
  11228. SUCCEED()
  11229. << "Server processed request without Content-Length within limit";
  11230. } else {
  11231. // Short response might indicate connection closed, which is acceptable
  11232. SUCCEED() << "Server closed connection for request without "
  11233. "Content-Length (acceptable behavior)";
  11234. }
  11235. } else {
  11236. // Connection failure might be due to protocol requirements
  11237. SUCCEED() << "Connection issue with request without Content-Length "
  11238. "(environment-specific)";
  11239. }
  11240. }
  11241. class LargePayloadMaxLengthTest : public ::testing::Test {
  11242. protected:
  11243. LargePayloadMaxLengthTest()
  11244. : cli_(HOST, PORT)
  11245. #ifdef CPPHTTPLIB_SSL_ENABLED
  11246. ,
  11247. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11248. #endif
  11249. {
  11250. #ifdef CPPHTTPLIB_SSL_ENABLED
  11251. cli_.enable_server_certificate_verification(false);
  11252. #endif
  11253. }
  11254. virtual void SetUp() {
  11255. // Set 10MB payload limit
  11256. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11257. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11258. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11259. res.set_content("Large payload test", "text/plain");
  11260. });
  11261. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11262. svr_.wait_until_ready();
  11263. }
  11264. virtual void TearDown() {
  11265. svr_.stop();
  11266. t_.join();
  11267. }
  11268. #ifdef CPPHTTPLIB_SSL_ENABLED
  11269. SSLClient cli_;
  11270. SSLServer svr_;
  11271. #else
  11272. Client cli_;
  11273. Server svr_;
  11274. #endif
  11275. thread t_;
  11276. };
  11277. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11278. // Test chunked encoding with payload within 10MB limit
  11279. std::string medium_payload(5 * 1024 * 1024,
  11280. 'A'); // 5MB payload, within 10MB limit
  11281. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11283. EXPECT_EQ(StatusCode::OK_200, res->status);
  11284. }
  11285. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11286. // Test chunked encoding with payload exceeding 10MB limit
  11287. std::string large_payload(12 * 1024 * 1024,
  11288. 'B'); // 12MB payload, exceeds 10MB limit
  11289. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11290. // Server may either return 413 or close the connection
  11291. if (res) {
  11292. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11293. } else {
  11294. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11295. }
  11296. }
  11297. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11298. // Test request without Content-Length header within 10MB limit
  11299. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11300. "Host: " +
  11301. std::string(HOST) + ":" +
  11302. std::to_string(PORT) +
  11303. "\r\n"
  11304. "Connection: close\r\n"
  11305. "\r\n";
  11306. // Add 1MB payload (within 10MB limit)
  11307. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11308. request_without_content_length += medium_payload;
  11309. std::string response;
  11310. bool result = send_request(5, request_without_content_length, &response);
  11311. if (result) {
  11312. // Should get a proper HTTP response for payloads within limit
  11313. if (response.length() > 10) {
  11314. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11315. "10MB limit";
  11316. } else {
  11317. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11318. "Content-Length)";
  11319. }
  11320. } else {
  11321. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11322. }
  11323. }
  11324. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11325. // Test request without Content-Length header exceeding 10MB limit
  11326. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11327. "Host: " +
  11328. std::string(HOST) + ":" +
  11329. std::to_string(PORT) +
  11330. "\r\n"
  11331. "Connection: close\r\n"
  11332. "\r\n";
  11333. // Add 12MB payload (exceeds 10MB limit)
  11334. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11335. request_without_content_length += large_payload;
  11336. std::string response;
  11337. bool result = send_request(10, request_without_content_length, &response);
  11338. if (!result) {
  11339. // Server should close connection due to payload limit
  11340. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11341. "(connection closed)";
  11342. } else {
  11343. // Check for error response
  11344. if (response.length() <= 10) {
  11345. SUCCEED()
  11346. << "Server closed connection for 12MB request exceeding 10MB limit";
  11347. } else {
  11348. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11349. response.find("Payload Too Large") != std::string::npos ||
  11350. response.find("400") != std::string::npos);
  11351. }
  11352. }
  11353. }
  11354. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11355. Server svr;
  11356. svr.Get("/", [](const Request &, Response &res) {
  11357. // Claims far more than it sends, then drops the connection.
  11358. res.set_content_provider(size_t(1) << 41, "text/plain",
  11359. [](size_t, size_t, DataSink &sink) {
  11360. sink.write("abc", 3);
  11361. return false;
  11362. });
  11363. });
  11364. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11365. auto se = detail::scope_exit([&] {
  11366. svr.stop();
  11367. thread.join();
  11368. ASSERT_FALSE(svr.is_running());
  11369. });
  11370. svr.wait_until_ready();
  11371. Client cli(HOST, PORT);
  11372. cli.set_payload_max_length(0);
  11373. EXPECT_FALSE(cli.Get("/"));
  11374. }
  11375. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11376. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11377. // path.
  11378. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11379. Server svr;
  11380. const size_t LIMIT = 64 * 1024; // 64KB
  11381. svr.set_payload_max_length(LIMIT);
  11382. size_t total = 0;
  11383. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11384. const ContentReader &content_reader) {
  11385. content_reader([&](const char * /*data*/, size_t len) {
  11386. total += len;
  11387. return true;
  11388. });
  11389. res.status = 200;
  11390. res.set_content("stream_ok", "text/plain");
  11391. });
  11392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11393. auto se = detail::scope_exit([&] {
  11394. svr.stop();
  11395. thread.join();
  11396. ASSERT_FALSE(svr.is_running());
  11397. });
  11398. svr.wait_until_ready();
  11399. // Prepare 256KB raw data and gzip-compress it
  11400. std::string raw(256 * 1024, 'A');
  11401. std::string gz;
  11402. {
  11403. z_stream zs{};
  11404. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11405. Z_DEFAULT_STRATEGY);
  11406. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11407. zs.avail_in = static_cast<uInt>(raw.size());
  11408. char outbuf[4096];
  11409. int ret;
  11410. do {
  11411. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11412. zs.avail_out = sizeof(outbuf);
  11413. ret = deflate(&zs, Z_FINISH);
  11414. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11415. } while (ret != Z_STREAM_END);
  11416. deflateEnd(&zs);
  11417. }
  11418. Client cli(HOST, PORT);
  11419. cli.set_connection_timeout(std::chrono::seconds(5));
  11420. Headers headers = {{"Content-Encoding", "gzip"}};
  11421. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11422. "application/octet-stream");
  11423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11424. // Server must reject oversized decompressed payloads with 413.
  11425. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11426. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11427. EXPECT_LE(total, LIMIT);
  11428. }
  11429. #ifndef CPPHTTPLIB_SSL_ENABLED
  11430. // For a request with neither Content-Length nor Transfer-Encoding, the
  11431. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11432. // compressed wire bytes straight to the ContentReader without ever routing
  11433. // them through the decompressor, so payload_max_length_ only bounded the
  11434. // compressed size on the wire, not the decompressed size.
  11435. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11436. Server svr;
  11437. const size_t LIMIT = 64 * 1024; // 64KB
  11438. svr.set_payload_max_length(LIMIT);
  11439. size_t total = 0;
  11440. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11441. const ContentReader &content_reader) {
  11442. content_reader([&](const char * /*data*/, size_t len) {
  11443. total += len;
  11444. return true;
  11445. });
  11446. res.status = 200;
  11447. res.set_content("stream_ok", "text/plain");
  11448. });
  11449. auto port = svr.bind_to_any_port(HOST);
  11450. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11451. auto se = detail::scope_exit([&] {
  11452. svr.stop();
  11453. thread.join();
  11454. ASSERT_FALSE(svr.is_running());
  11455. });
  11456. svr.wait_until_ready();
  11457. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11458. // StreamingGzipDecompression test above.
  11459. std::string raw(256 * 1024, 'A');
  11460. std::string gz;
  11461. {
  11462. httplib::detail::gzip_compressor compressor;
  11463. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11464. [&](const char *chunk, size_t len) {
  11465. gz.append(chunk, len);
  11466. return true;
  11467. });
  11468. ASSERT_TRUE(result);
  11469. }
  11470. // Send the gzip body over raw TCP with neither Content-Length nor
  11471. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11472. // kicks in.
  11473. std::string req = "POST /stream HTTP/1.1\r\n"
  11474. "Host: " +
  11475. std::string(HOST) + ":" + std::to_string(port) +
  11476. "\r\n"
  11477. "Content-Encoding: gzip\r\n"
  11478. "Connection: close\r\n"
  11479. "\r\n" +
  11480. gz;
  11481. std::string response;
  11482. ASSERT_TRUE(send_request(5, req, &response, port));
  11483. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11484. EXPECT_LE(total, LIMIT);
  11485. }
  11486. #endif
  11487. #endif
  11488. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11489. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11490. // the payload must be passed through untouched instead of being rejected.
  11491. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11492. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11493. Server svr;
  11494. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11495. res.set_content(body, "image/jpeg");
  11496. res.set_header("Content-Encoding", "UTF-8");
  11497. });
  11498. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11499. res.set_content(body, "image/jpeg");
  11500. res.set_header("Content-Encoding", "identity");
  11501. });
  11502. svr.Post("/echo", [](const Request &req, Response &res) {
  11503. res.set_content(req.body, "image/jpeg");
  11504. });
  11505. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11506. auto se = detail::scope_exit([&] {
  11507. svr.stop();
  11508. t.join();
  11509. ASSERT_FALSE(svr.is_running());
  11510. });
  11511. svr.wait_until_ready();
  11512. Client cli(HOST, PORT);
  11513. {
  11514. auto res = cli.Get("/image");
  11515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11516. EXPECT_EQ(StatusCode::OK_200, res->status);
  11517. EXPECT_EQ(body, res->body);
  11518. }
  11519. {
  11520. auto res = cli.Get("/identity");
  11521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11522. EXPECT_EQ(StatusCode::OK_200, res->status);
  11523. EXPECT_EQ(body, res->body);
  11524. }
  11525. {
  11526. // The same applies to a request body reaching the server.
  11527. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11528. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11530. EXPECT_EQ(StatusCode::OK_200, res->status);
  11531. EXPECT_EQ(body, res->body);
  11532. }
  11533. }
  11534. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11535. // gzip-encoded response even when the build has no zlib support.
  11536. static const char GZIPPED_HELLO_WORLD[] = {
  11537. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11538. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11539. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11540. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11541. // A content coding is a whole token, not something the field value merely
  11542. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11543. // as "fibre" look like Brotli, and turned a multi-coding value like
  11544. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11545. // it was never meant to see.
  11546. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11547. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11548. Server svr;
  11549. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11550. res.set_content(body, "image/jpeg");
  11551. res.set_header("Content-Encoding", "fibre");
  11552. });
  11553. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11554. res.set_content(body, "image/jpeg");
  11555. res.set_header("Content-Encoding", "gzip, br");
  11556. });
  11557. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11558. res.set_content(body, "image/jpeg");
  11559. res.set_header("Content-Encoding", "x-zstd-ish");
  11560. });
  11561. auto port = svr.bind_to_any_port(HOST);
  11562. thread t = thread([&]() { svr.listen_after_bind(); });
  11563. auto se = detail::scope_exit([&] {
  11564. svr.stop();
  11565. t.join();
  11566. ASSERT_FALSE(svr.is_running());
  11567. });
  11568. svr.wait_until_ready();
  11569. Client cli(HOST, port);
  11570. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11571. auto res = cli.Get(path);
  11572. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11573. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11574. // Not a coding we recognize, so the payload comes back untouched
  11575. EXPECT_EQ(body, res->body) << path;
  11576. }
  11577. }
  11578. // A content coding cpp-httplib recognizes but was not built with must be
  11579. // reported as such. Handing the still-compressed payload back to the caller
  11580. // would silently corrupt it.
  11581. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11582. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11583. Server svr;
  11584. // "image/jpeg" keeps the server from applying a content coding of its own,
  11585. // so the hand-crafted Content-Encoding below survives.
  11586. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11587. res.set_content(gzipped, "image/jpeg");
  11588. res.set_header("Content-Encoding", "gzip");
  11589. });
  11590. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11591. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11592. res.set_content(gzipped, "image/jpeg");
  11593. res.set_header("Content-Encoding", "GZIP");
  11594. });
  11595. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11596. auto se = detail::scope_exit([&] {
  11597. svr.stop();
  11598. t.join();
  11599. ASSERT_FALSE(svr.is_running());
  11600. });
  11601. svr.wait_until_ready();
  11602. Client cli(HOST, PORT);
  11603. {
  11604. auto res = cli.Get("/gzipped");
  11605. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11607. EXPECT_EQ("Hello World!", res->body);
  11608. #else
  11609. ASSERT_FALSE(res);
  11610. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11611. #endif
  11612. }
  11613. {
  11614. // open_stream() must behave the same way.
  11615. auto handle = cli.open_stream("GET", "/gzipped");
  11616. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11617. ASSERT_TRUE(handle.is_valid());
  11618. std::string received;
  11619. char buf[256];
  11620. ssize_t n;
  11621. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11622. received.append(buf, static_cast<size_t>(n));
  11623. }
  11624. EXPECT_EQ("Hello World!", received);
  11625. #else
  11626. EXPECT_FALSE(handle.is_valid());
  11627. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11628. #endif
  11629. }
  11630. {
  11631. // A differently-cased coding must not be mistaken for an unknown one, or
  11632. // the body would be handed back still compressed.
  11633. auto res = cli.Get("/gzipped-uppercase");
  11634. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11636. EXPECT_EQ("Hello World!", res->body);
  11637. #else
  11638. ASSERT_FALSE(res);
  11639. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11640. #endif
  11641. }
  11642. }
  11643. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11644. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11645. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11646. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11647. // body a second time and appending a second Content-Encoding field line, so
  11648. // clients that decode one coding per listed value handed back raw gzip bytes.
  11649. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11650. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11651. Server svr;
  11652. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11653. // keeps the server from applying a coding of its own.
  11654. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11655. res.set_content(gzipped, "text/plain");
  11656. res.set_header("Content-Encoding", "gzip");
  11657. });
  11658. auto port = svr.bind_to_any_port(HOST);
  11659. thread t = thread([&]() { svr.listen_after_bind(); });
  11660. auto se = detail::scope_exit([&] {
  11661. svr.stop();
  11662. t.join();
  11663. ASSERT_FALSE(svr.is_running());
  11664. });
  11665. svr.wait_until_ready();
  11666. Client cli(HOST, port);
  11667. Headers headers = {{"Accept-Encoding", "gzip"}};
  11668. auto res = cli.Get("/pre-gzipped", headers);
  11669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11670. EXPECT_EQ(StatusCode::OK_200, res->status);
  11671. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11672. EXPECT_EQ("Hello World!", res->body);
  11673. }
  11674. // A chunked provider settles its coding where the headers are written and
  11675. // reuses it at write time. Both ends of that have to hold: a handler's own
  11676. // Content-Encoding suppresses the coding, and a response without one is still
  11677. // compressed as it always was.
  11678. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11679. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11680. const std::string plain = "Hello World! Hello World! Hello World!";
  11681. Server svr;
  11682. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11683. res.set_header("Content-Encoding", "gzip");
  11684. res.set_chunked_content_provider(
  11685. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11686. sink.write(gzipped.data(), gzipped.size());
  11687. sink.done();
  11688. return true;
  11689. });
  11690. });
  11691. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11692. res.set_chunked_content_provider(
  11693. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11694. sink.write(plain.data(), plain.size());
  11695. sink.done();
  11696. return true;
  11697. });
  11698. });
  11699. auto port = svr.bind_to_any_port(HOST);
  11700. thread t = thread([&]() { svr.listen_after_bind(); });
  11701. auto se = detail::scope_exit([&] {
  11702. svr.stop();
  11703. t.join();
  11704. ASSERT_FALSE(svr.is_running());
  11705. });
  11706. svr.wait_until_ready();
  11707. Client cli(HOST, port);
  11708. Headers headers = {{"Accept-Encoding", "gzip"}};
  11709. {
  11710. auto res = cli.Get("/pre-gzipped", headers);
  11711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11712. EXPECT_EQ(StatusCode::OK_200, res->status);
  11713. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11714. EXPECT_EQ("Hello World!", res->body);
  11715. }
  11716. {
  11717. auto res = cli.Get("/negotiated", headers);
  11718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11719. EXPECT_EQ(StatusCode::OK_200, res->status);
  11720. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11721. EXPECT_EQ(plain, res->body);
  11722. }
  11723. }
  11724. #endif
  11725. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11726. // the same message as the comma-joined one, so both have to be read the same
  11727. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11728. // single gzip coding, and a body the sender says was encoded twice was handed
  11729. // back after one pass, still compressed but presented as decoded.
  11730. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11731. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11732. Server svr;
  11733. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11734. res.set_content(body, "image/jpeg");
  11735. res.headers.emplace("Content-Encoding", "gzip");
  11736. res.headers.emplace("Content-Encoding", "gzip");
  11737. });
  11738. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11739. res.set_content(body, "image/jpeg");
  11740. res.set_header("Content-Encoding", "gzip, gzip");
  11741. });
  11742. auto port = svr.bind_to_any_port(HOST);
  11743. thread t = thread([&]() { svr.listen_after_bind(); });
  11744. auto se = detail::scope_exit([&] {
  11745. svr.stop();
  11746. t.join();
  11747. ASSERT_FALSE(svr.is_running());
  11748. });
  11749. svr.wait_until_ready();
  11750. Client cli(HOST, port);
  11751. // Two codings is not something cpp-httplib decodes, so both representations
  11752. // take the pass-through path rather than one of them being gunzipped once.
  11753. for (const char *path : {"/split", "/joined"}) {
  11754. auto res = cli.Get(path);
  11755. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11756. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11757. EXPECT_EQ(body, res->body) << path;
  11758. }
  11759. }
  11760. // Regression test for DoS vulnerability: a malicious server sending a response
  11761. // without Content-Length header must not cause unbounded memory consumption on
  11762. // the client side. The client should stop reading after a reasonable limit,
  11763. // similar to the server-side set_payload_max_length protection.
  11764. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11765. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11766. #ifndef _WIN32
  11767. signal(SIGPIPE, SIG_IGN);
  11768. #endif
  11769. auto server_thread = std::thread([] {
  11770. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11771. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11772. default_socket_options(srv);
  11773. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11774. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11775. sockaddr_in addr{};
  11776. addr.sin_family = AF_INET;
  11777. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11778. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11779. int opt = 1;
  11780. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11781. #ifdef _WIN32
  11782. reinterpret_cast<const char *>(&opt),
  11783. #else
  11784. &opt,
  11785. #endif
  11786. sizeof(opt));
  11787. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11788. ::listen(srv, 1);
  11789. sockaddr_in cli_addr{};
  11790. socklen_t cli_len = sizeof(cli_addr);
  11791. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11792. if (cli != INVALID_SOCKET) {
  11793. char buf[4096];
  11794. ::recv(cli, buf, sizeof(buf), 0);
  11795. // Malicious response: no Content-Length, no chunked encoding
  11796. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11797. "Connection: close\r\n"
  11798. "\r\n";
  11799. ::send(cli,
  11800. #ifdef _WIN32
  11801. static_cast<const char *>(response_header.c_str()),
  11802. static_cast<int>(response_header.size()),
  11803. #else
  11804. response_header.c_str(), response_header.size(),
  11805. #endif
  11806. 0);
  11807. // Send 10MB of data
  11808. std::string chunk(64 * 1024, 'A');
  11809. size_t total_sent = 0;
  11810. while (total_sent < MALICIOUS_DATA_SIZE) {
  11811. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11812. auto sent = ::send(cli,
  11813. #ifdef _WIN32
  11814. static_cast<const char *>(chunk.c_str()),
  11815. static_cast<int>(to_send),
  11816. #else
  11817. chunk.c_str(), to_send,
  11818. #endif
  11819. 0);
  11820. if (sent <= 0) break;
  11821. total_sent += static_cast<size_t>(sent);
  11822. }
  11823. detail::close_socket(cli);
  11824. }
  11825. detail::close_socket(srv);
  11826. });
  11827. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11828. size_t total_read = 0;
  11829. {
  11830. Client cli("127.0.0.1", PORT + 2);
  11831. cli.set_read_timeout(5, 0);
  11832. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11833. auto stream = cli.open_stream("GET", "/malicious");
  11834. ASSERT_TRUE(stream.is_valid());
  11835. char buffer[64 * 1024];
  11836. ssize_t n;
  11837. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11838. total_read += static_cast<size_t>(n);
  11839. }
  11840. } // StreamHandle and Client destroyed here, closing the socket
  11841. server_thread.join();
  11842. // With set_payload_max_length, the client must stop reading before consuming
  11843. // all 10MB. The read loop should be cut off at or near the configured limit.
  11844. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11845. << "Client read " << total_read << " bytes, exceeding the configured "
  11846. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11847. }
  11848. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11849. // the entire response body without truncation.
  11850. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11851. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11852. #ifndef _WIN32
  11853. signal(SIGPIPE, SIG_IGN);
  11854. #endif
  11855. auto server_thread = std::thread([] {
  11856. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11857. default_socket_options(srv);
  11858. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11859. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11860. sockaddr_in addr{};
  11861. addr.sin_family = AF_INET;
  11862. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11863. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11864. int opt = 1;
  11865. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11866. #ifdef _WIN32
  11867. reinterpret_cast<const char *>(&opt),
  11868. #else
  11869. &opt,
  11870. #endif
  11871. sizeof(opt));
  11872. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11873. ::listen(srv, 1);
  11874. sockaddr_in cli_addr{};
  11875. socklen_t cli_len = sizeof(cli_addr);
  11876. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11877. if (cli != INVALID_SOCKET) {
  11878. char buf[4096];
  11879. ::recv(cli, buf, sizeof(buf), 0);
  11880. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11881. "Connection: close\r\n"
  11882. "\r\n";
  11883. ::send(cli,
  11884. #ifdef _WIN32
  11885. static_cast<const char *>(response_header.c_str()),
  11886. static_cast<int>(response_header.size()),
  11887. #else
  11888. response_header.c_str(), response_header.size(),
  11889. #endif
  11890. 0);
  11891. std::string chunk(64 * 1024, 'A');
  11892. size_t total_sent = 0;
  11893. while (total_sent < DATA_SIZE) {
  11894. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11895. auto sent = ::send(cli,
  11896. #ifdef _WIN32
  11897. static_cast<const char *>(chunk.c_str()),
  11898. static_cast<int>(to_send),
  11899. #else
  11900. chunk.c_str(), to_send,
  11901. #endif
  11902. 0);
  11903. if (sent <= 0) break;
  11904. total_sent += static_cast<size_t>(sent);
  11905. }
  11906. #ifdef _WIN32
  11907. ::shutdown(cli, SD_SEND);
  11908. #else
  11909. ::shutdown(cli, SHUT_WR);
  11910. #endif
  11911. // Drain until the client closes its end, ensuring all data is delivered
  11912. char drain[1024];
  11913. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11914. detail::close_socket(cli);
  11915. }
  11916. detail::close_socket(srv);
  11917. });
  11918. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11919. size_t total_read = 0;
  11920. {
  11921. Client cli("127.0.0.1", PORT + 2);
  11922. cli.set_read_timeout(5, 0);
  11923. cli.set_payload_max_length(0); // 0 means no limit
  11924. auto stream = cli.open_stream("GET", "/data");
  11925. ASSERT_TRUE(stream.is_valid());
  11926. char buffer[64 * 1024];
  11927. ssize_t n;
  11928. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11929. total_read += static_cast<size_t>(n);
  11930. }
  11931. }
  11932. server_thread.join();
  11933. EXPECT_EQ(total_read, DATA_SIZE)
  11934. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11935. << " bytes without truncation, but only read " << total_read << " bytes.";
  11936. }
  11937. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11938. // enormous Content-Length must not cause the client to pre-allocate a huge
  11939. // response body buffer. The reservation is capped at payload_max_length_, and
  11940. // the read itself fails when the body exceeds the limit.
  11941. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11942. #ifndef _WIN32
  11943. signal(SIGPIPE, SIG_IGN);
  11944. #endif
  11945. auto server_thread = std::thread([] {
  11946. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11947. default_socket_options(srv);
  11948. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11949. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11950. sockaddr_in addr{};
  11951. addr.sin_family = AF_INET;
  11952. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11953. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11954. int opt = 1;
  11955. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11956. #ifdef _WIN32
  11957. reinterpret_cast<const char *>(&opt),
  11958. #else
  11959. &opt,
  11960. #endif
  11961. sizeof(opt));
  11962. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11963. ::listen(srv, 1);
  11964. sockaddr_in cli_addr{};
  11965. socklen_t cli_len = sizeof(cli_addr);
  11966. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11967. if (cli != INVALID_SOCKET) {
  11968. char buf[4096];
  11969. ::recv(cli, buf, sizeof(buf), 0);
  11970. // Malicious response: claim a 20GB body but send only a tiny payload.
  11971. std::string response = "HTTP/1.1 200 OK\r\n"
  11972. "Content-Length: 20000000000\r\n"
  11973. "\r\n"
  11974. "abc";
  11975. ::send(cli,
  11976. #ifdef _WIN32
  11977. static_cast<const char *>(response.c_str()),
  11978. static_cast<int>(response.size()),
  11979. #else
  11980. response.c_str(), response.size(),
  11981. #endif
  11982. 0);
  11983. detail::close_socket(cli);
  11984. }
  11985. detail::close_socket(srv);
  11986. });
  11987. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11988. {
  11989. Client cli("127.0.0.1", PORT + 2);
  11990. cli.set_read_timeout(5, 0);
  11991. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11992. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11993. // (server claims more bytes than payload_max_length permits), but it must
  11994. // not exhaust memory before getting there.
  11995. auto res = cli.Get("/malicious");
  11996. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11997. }
  11998. server_thread.join();
  11999. }
  12000. // Verify that content_receiver bypasses the default payload_max_length,
  12001. // allowing streaming downloads larger than 100MB without requiring an explicit
  12002. // set_payload_max_length call.
  12003. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12004. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12005. #ifndef _WIN32
  12006. signal(SIGPIPE, SIG_IGN);
  12007. #endif
  12008. auto server_thread = std::thread([] {
  12009. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12010. default_socket_options(srv);
  12011. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12012. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12013. sockaddr_in addr{};
  12014. addr.sin_family = AF_INET;
  12015. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12016. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12017. int opt = 1;
  12018. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12019. #ifdef _WIN32
  12020. reinterpret_cast<const char *>(&opt),
  12021. #else
  12022. &opt,
  12023. #endif
  12024. sizeof(opt));
  12025. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12026. ::listen(srv, 1);
  12027. sockaddr_in cli_addr{};
  12028. socklen_t cli_len = sizeof(cli_addr);
  12029. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12030. if (cli != INVALID_SOCKET) {
  12031. char buf[4096];
  12032. ::recv(cli, buf, sizeof(buf), 0);
  12033. // Response with Content-Length larger than default 100MB limit
  12034. auto content_length = std::to_string(DATA_SIZE);
  12035. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12036. "Content-Length: " +
  12037. content_length +
  12038. "\r\n"
  12039. "Connection: close\r\n"
  12040. "\r\n";
  12041. ::send(cli,
  12042. #ifdef _WIN32
  12043. static_cast<const char *>(response_header.c_str()),
  12044. static_cast<int>(response_header.size()),
  12045. #else
  12046. response_header.c_str(), response_header.size(),
  12047. #endif
  12048. 0);
  12049. std::string chunk(64 * 1024, 'A');
  12050. size_t total_sent = 0;
  12051. while (total_sent < DATA_SIZE) {
  12052. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12053. auto sent = ::send(cli,
  12054. #ifdef _WIN32
  12055. static_cast<const char *>(chunk.c_str()),
  12056. static_cast<int>(to_send),
  12057. #else
  12058. chunk.c_str(), to_send,
  12059. #endif
  12060. 0);
  12061. if (sent <= 0) break;
  12062. total_sent += static_cast<size_t>(sent);
  12063. }
  12064. detail::close_socket(cli);
  12065. }
  12066. detail::close_socket(srv);
  12067. });
  12068. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12069. size_t total_received = 0;
  12070. {
  12071. Client cli("127.0.0.1", PORT + 2);
  12072. cli.set_read_timeout(10, 0);
  12073. // Do NOT call set_payload_max_length — use the default 100MB limit
  12074. auto res =
  12075. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12076. total_received += data_length;
  12077. return true;
  12078. });
  12079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12080. EXPECT_EQ(StatusCode::OK_200, res->status);
  12081. }
  12082. server_thread.join();
  12083. EXPECT_EQ(total_received, DATA_SIZE)
  12084. << "With content_receiver, the client should read all " << DATA_SIZE
  12085. << " bytes despite the default 100MB payload_max_length, but only read "
  12086. << total_received << " bytes.";
  12087. }
  12088. // Verify that an explicit set_payload_max_length smaller than the response is
  12089. // enforced even when a content_receiver is used.
  12090. TEST(ClientVulnerabilityTest,
  12091. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12092. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12093. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12094. #ifndef _WIN32
  12095. signal(SIGPIPE, SIG_IGN);
  12096. #endif
  12097. auto server_thread = std::thread([] {
  12098. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12099. default_socket_options(srv);
  12100. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12101. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12102. sockaddr_in addr{};
  12103. addr.sin_family = AF_INET;
  12104. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12105. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12106. int opt = 1;
  12107. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12108. #ifdef _WIN32
  12109. reinterpret_cast<const char *>(&opt),
  12110. #else
  12111. &opt,
  12112. #endif
  12113. sizeof(opt));
  12114. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12115. ::listen(srv, 1);
  12116. sockaddr_in cli_addr{};
  12117. socklen_t cli_len = sizeof(cli_addr);
  12118. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12119. if (cli != INVALID_SOCKET) {
  12120. char buf[4096];
  12121. ::recv(cli, buf, sizeof(buf), 0);
  12122. auto content_length = std::to_string(DATA_SIZE);
  12123. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12124. "Content-Length: " +
  12125. content_length +
  12126. "\r\n"
  12127. "Connection: close\r\n"
  12128. "\r\n";
  12129. ::send(cli,
  12130. #ifdef _WIN32
  12131. static_cast<const char *>(response_header.c_str()),
  12132. static_cast<int>(response_header.size()),
  12133. #else
  12134. response_header.c_str(), response_header.size(),
  12135. #endif
  12136. 0);
  12137. std::string chunk(64 * 1024, 'A');
  12138. size_t total_sent = 0;
  12139. while (total_sent < DATA_SIZE) {
  12140. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12141. auto sent = ::send(cli,
  12142. #ifdef _WIN32
  12143. static_cast<const char *>(chunk.c_str()),
  12144. static_cast<int>(to_send),
  12145. #else
  12146. chunk.c_str(), to_send,
  12147. #endif
  12148. 0);
  12149. if (sent <= 0) break;
  12150. total_sent += static_cast<size_t>(sent);
  12151. }
  12152. detail::close_socket(cli);
  12153. }
  12154. detail::close_socket(srv);
  12155. });
  12156. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12157. size_t total_received = 0;
  12158. {
  12159. Client cli("127.0.0.1", PORT + 2);
  12160. cli.set_read_timeout(10, 0);
  12161. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12162. auto res =
  12163. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12164. total_received += data_length;
  12165. return true;
  12166. });
  12167. // Should fail because 200MB exceeds the explicit 150MB limit
  12168. EXPECT_FALSE(res);
  12169. }
  12170. server_thread.join();
  12171. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12172. << "Client with content_receiver should respect the explicit "
  12173. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12174. << total_received << " bytes.";
  12175. }
  12176. // Verify that an explicit set_payload_max_length larger than the response
  12177. // allows the content_receiver to read all data successfully.
  12178. TEST(ClientVulnerabilityTest,
  12179. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12180. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12181. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12182. #ifndef _WIN32
  12183. signal(SIGPIPE, SIG_IGN);
  12184. #endif
  12185. auto server_thread = std::thread([] {
  12186. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12187. default_socket_options(srv);
  12188. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12189. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12190. sockaddr_in addr{};
  12191. addr.sin_family = AF_INET;
  12192. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12193. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12194. int opt = 1;
  12195. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12196. #ifdef _WIN32
  12197. reinterpret_cast<const char *>(&opt),
  12198. #else
  12199. &opt,
  12200. #endif
  12201. sizeof(opt));
  12202. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12203. ::listen(srv, 1);
  12204. sockaddr_in cli_addr{};
  12205. socklen_t cli_len = sizeof(cli_addr);
  12206. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12207. if (cli != INVALID_SOCKET) {
  12208. char buf[4096];
  12209. ::recv(cli, buf, sizeof(buf), 0);
  12210. auto content_length = std::to_string(DATA_SIZE);
  12211. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12212. "Content-Length: " +
  12213. content_length +
  12214. "\r\n"
  12215. "Connection: close\r\n"
  12216. "\r\n";
  12217. ::send(cli,
  12218. #ifdef _WIN32
  12219. static_cast<const char *>(response_header.c_str()),
  12220. static_cast<int>(response_header.size()),
  12221. #else
  12222. response_header.c_str(), response_header.size(),
  12223. #endif
  12224. 0);
  12225. std::string chunk(64 * 1024, 'A');
  12226. size_t total_sent = 0;
  12227. while (total_sent < DATA_SIZE) {
  12228. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12229. auto sent = ::send(cli,
  12230. #ifdef _WIN32
  12231. static_cast<const char *>(chunk.c_str()),
  12232. static_cast<int>(to_send),
  12233. #else
  12234. chunk.c_str(), to_send,
  12235. #endif
  12236. 0);
  12237. if (sent <= 0) break;
  12238. total_sent += static_cast<size_t>(sent);
  12239. }
  12240. #ifdef _WIN32
  12241. ::shutdown(cli, SD_SEND);
  12242. #else
  12243. ::shutdown(cli, SHUT_WR);
  12244. #endif
  12245. char drain[1024];
  12246. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12247. detail::close_socket(cli);
  12248. }
  12249. detail::close_socket(srv);
  12250. });
  12251. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12252. size_t total_received = 0;
  12253. {
  12254. Client cli("127.0.0.1", PORT + 2);
  12255. cli.set_read_timeout(10, 0);
  12256. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12257. auto res =
  12258. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12259. total_received += data_length;
  12260. return true;
  12261. });
  12262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12263. EXPECT_EQ(StatusCode::OK_200, res->status);
  12264. }
  12265. server_thread.join();
  12266. EXPECT_EQ(total_received, DATA_SIZE)
  12267. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12268. << " bytes (larger than " << DATA_SIZE
  12269. << " bytes response), content_receiver should read all data, but only "
  12270. "read "
  12271. << total_received << " bytes.";
  12272. }
  12273. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12274. // Regression test for "zip bomb" attack on the client side: a malicious server
  12275. // sends a small gzip-compressed response that decompresses to a huge payload.
  12276. // The client must enforce payload_max_length on the decompressed size.
  12277. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12278. constexpr size_t DECOMPRESSED_SIZE =
  12279. 10 * 1024 * 1024; // 10MB after decompression
  12280. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12281. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12282. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12283. std::string compressed;
  12284. {
  12285. httplib::detail::gzip_compressor compressor;
  12286. bool ok =
  12287. compressor.compress(uncompressed.data(), uncompressed.size(),
  12288. /*last=*/true, [&](const char *buf, size_t len) {
  12289. compressed.append(buf, len);
  12290. return true;
  12291. });
  12292. ASSERT_TRUE(ok);
  12293. }
  12294. // Sanity: compressed data should be much smaller than the decompressed size
  12295. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12296. #ifndef _WIN32
  12297. signal(SIGPIPE, SIG_IGN);
  12298. #endif
  12299. // Set up the listening socket in the main thread so the server is guaranteed
  12300. // to be ready before the client connects (eliminates race condition).
  12301. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12302. default_socket_options(srv);
  12303. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12304. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12305. sockaddr_in addr{};
  12306. addr.sin_family = AF_INET;
  12307. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12308. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12309. int opt = 1;
  12310. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12311. #ifdef _WIN32
  12312. reinterpret_cast<const char *>(&opt),
  12313. #else
  12314. &opt,
  12315. #endif
  12316. sizeof(opt));
  12317. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12318. ASSERT_EQ(0, ::listen(srv, 1));
  12319. auto server_thread = std::thread([&compressed, srv] {
  12320. sockaddr_in cli_addr{};
  12321. socklen_t cli_len = sizeof(cli_addr);
  12322. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12323. if (cli != INVALID_SOCKET) {
  12324. // Read the full HTTP request (until \r\n\r\n)
  12325. char buf[4096];
  12326. size_t total = 0;
  12327. while (total < sizeof(buf)) {
  12328. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12329. if (n <= 0) break;
  12330. total += static_cast<size_t>(n);
  12331. // Check for end of headers
  12332. if (total >= 4) {
  12333. std::string req(buf, total);
  12334. if (req.find("\r\n\r\n") != std::string::npos) break;
  12335. }
  12336. }
  12337. // Malicious response: gzip-compressed body, no Content-Length
  12338. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12339. "Content-Encoding: gzip\r\n"
  12340. "Connection: close\r\n"
  12341. "\r\n";
  12342. ::send(cli,
  12343. #ifdef _WIN32
  12344. static_cast<const char *>(response_header.c_str()),
  12345. static_cast<int>(response_header.size()),
  12346. #else
  12347. response_header.c_str(), response_header.size(),
  12348. #endif
  12349. 0);
  12350. // Send the compressed payload (small on the wire, huge when decompressed)
  12351. size_t total_sent = 0;
  12352. while (total_sent < compressed.size()) {
  12353. auto to_send = std::min(compressed.size() - total_sent,
  12354. static_cast<size_t>(64 * 1024));
  12355. auto sent =
  12356. ::send(cli,
  12357. #ifdef _WIN32
  12358. static_cast<const char *>(compressed.c_str() + total_sent),
  12359. static_cast<int>(to_send),
  12360. #else
  12361. compressed.c_str() + total_sent, to_send,
  12362. #endif
  12363. 0);
  12364. if (sent <= 0) break;
  12365. total_sent += static_cast<size_t>(sent);
  12366. }
  12367. detail::close_socket(cli);
  12368. }
  12369. });
  12370. auto se = detail::scope_exit([&] {
  12371. detail::close_socket(srv);
  12372. server_thread.join();
  12373. });
  12374. size_t total_decompressed = 0;
  12375. {
  12376. Client cli("127.0.0.1", PORT + 3);
  12377. cli.set_read_timeout(5, 0);
  12378. cli.set_decompress(true);
  12379. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12380. auto stream = cli.open_stream("GET", "/zipbomb");
  12381. ASSERT_TRUE(stream.is_valid());
  12382. char buffer[64 * 1024];
  12383. ssize_t n;
  12384. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12385. total_decompressed += static_cast<size_t>(n);
  12386. }
  12387. }
  12388. // The decompressed size must be capped by payload_max_length. Without
  12389. // protection, the client would decompress the full 10MB from a tiny
  12390. // compressed payload, enabling a zip bomb DoS attack.
  12391. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12392. << "Client decompressed " << total_decompressed
  12393. << " bytes from a gzip response. The decompressed size should be "
  12394. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12395. }
  12396. #endif
  12397. TEST(HostAndPortPropertiesTest, NoSSL) {
  12398. httplib::Client cli("www.google.com", 1234);
  12399. ASSERT_EQ("www.google.com", cli.host());
  12400. ASSERT_EQ(1234, cli.port());
  12401. }
  12402. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12403. httplib::Client cli("www.google.com:1234");
  12404. ASSERT_EQ("www.google.com", cli.host());
  12405. ASSERT_EQ(1234, cli.port());
  12406. }
  12407. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12408. // Port number that overflows int — should not crash, client becomes invalid
  12409. httplib::Client cli("http://www.google.com:99999999999999999999");
  12410. ASSERT_FALSE(cli.is_valid());
  12411. }
  12412. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12413. // Port 99999 exceeds valid range (1-65535) — should not crash
  12414. httplib::Client cli("http://www.google.com:99999");
  12415. ASSERT_FALSE(cli.is_valid());
  12416. auto res = cli.Get("/");
  12417. EXPECT_FALSE(res);
  12418. EXPECT_EQ(Error::Connection, res.error());
  12419. }
  12420. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12421. httplib::Client cli("http://www.google.com:80abc");
  12422. ASSERT_FALSE(cli.is_valid());
  12423. }
  12424. #ifdef CPPHTTPLIB_SSL_ENABLED
  12425. TEST(HostAndPortPropertiesTest, SSL) {
  12426. httplib::SSLClient cli("www.google.com");
  12427. ASSERT_EQ("www.google.com", cli.host());
  12428. ASSERT_EQ(443, cli.port());
  12429. }
  12430. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12431. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12432. std::string cert;
  12433. read_file(CA_CERT_FILE, cert);
  12434. httplib::SSLClient httplib_client("www.google.com");
  12435. // Load CA store first time
  12436. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12437. // Load CA store second time (update)
  12438. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12439. // Verify client is still valid and can make connections
  12440. httplib_client.enable_server_certificate_verification(true);
  12441. auto res = httplib_client.Get("/");
  12442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12443. // Google may return 200 or 301 depending on various factors
  12444. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12445. res->status == StatusCode::MovedPermanently_301);
  12446. }
  12447. TEST(SSLClientTest, ServerNameIndication_Online) {
  12448. auto host = "httpbingo.org";
  12449. auto path = std::string{"/get"};
  12450. SSLClient cli(host, 443);
  12451. auto res = cli.Get(path);
  12452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12453. ASSERT_EQ(StatusCode::OK_200, res->status);
  12454. }
  12455. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12456. // Use a site that will cause SSL verification failure due to self-signed cert
  12457. SSLClient cli("self-signed.badssl.com", 443);
  12458. cli.enable_server_certificate_verification(true);
  12459. auto res = cli.Get("/");
  12460. ASSERT_TRUE(!res);
  12461. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12462. // Verify backend error is captured for SSLServerVerification
  12463. // This occurs when certificate verification fails
  12464. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12465. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12466. EXPECT_NE(0UL, res.ssl_backend_error());
  12467. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12468. // For OpenSSL, ssl_error is 0 for verification errors
  12469. EXPECT_EQ(0, res.ssl_error());
  12470. #if !defined(_WIN32) || \
  12471. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12472. // On non-Windows or when Windows Schannel is disabled, the error comes
  12473. // from OpenSSL's verification
  12474. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12475. res.ssl_backend_error());
  12476. #endif
  12477. #endif
  12478. }
  12479. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12480. // Use a site where hostname doesn't match the certificate
  12481. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12482. SSLClient cli("wrong.host.badssl.com", 443);
  12483. cli.enable_server_certificate_verification(true);
  12484. cli.enable_server_hostname_verification(true);
  12485. auto res = cli.Get("/");
  12486. ASSERT_TRUE(!res);
  12487. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12488. // Verify backend error is captured for hostname verification failure
  12489. EXPECT_NE(0UL, res.ssl_backend_error());
  12490. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12491. // For OpenSSL, ssl_error is 0 for verification errors
  12492. EXPECT_EQ(0, res.ssl_error());
  12493. #if !defined(_WIN32) || \
  12494. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12495. // On non-Windows or when Windows Schannel is disabled, the error comes
  12496. // from OpenSSL's hostname verification
  12497. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12498. res.ssl_backend_error());
  12499. #endif
  12500. #endif
  12501. }
  12502. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12503. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12504. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12505. SSLClient cli("www.google.com", 443);
  12506. cli.enable_server_certificate_verification(true);
  12507. auto res = cli.Get("/");
  12508. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12509. }
  12510. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12511. SSLClient cli("www.google.com", 443);
  12512. cli.enable_server_certificate_verification(true);
  12513. cli.enable_windows_certificate_verification(false);
  12514. auto res = cli.Get("/");
  12515. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12516. }
  12517. // The server sends an intermediate cross-signed by a root Windows trusts,
  12518. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12519. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12520. SSLClient cli("accounts.spotify.com", 443);
  12521. auto res = cli.Get("/");
  12522. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12523. << " ssl_backend_error=" << res.ssl_backend_error();
  12524. }
  12525. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12526. // policy status, which no backend reports for a self-signed certificate.
  12527. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12528. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12529. ASSERT_TRUE(svr.is_valid());
  12530. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12531. auto se = detail::scope_exit([&] {
  12532. svr.stop();
  12533. t.join();
  12534. ASSERT_FALSE(svr.is_running());
  12535. });
  12536. svr.wait_until_ready();
  12537. SSLClient cli("127.0.0.1", PORT);
  12538. cli.set_connection_timeout(30);
  12539. auto res = cli.Get("/");
  12540. ASSERT_FALSE(res);
  12541. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12542. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12543. }
  12544. #endif
  12545. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12546. Client cli("https://google.com");
  12547. auto res = cli.Get("/");
  12548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12549. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12550. }
  12551. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12552. SSLClient cli("google.com");
  12553. cli.set_ca_cert_path(CA_CERT_FILE);
  12554. auto res = cli.Get("/");
  12555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12556. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12557. }
  12558. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12559. SSLClient cli("google.com");
  12560. cli.enable_server_certificate_verification(true);
  12561. cli.set_ca_cert_path("hello");
  12562. auto res = cli.Get("/");
  12563. ASSERT_TRUE(!res);
  12564. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12565. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12566. // should be set
  12567. EXPECT_EQ(0, res.ssl_error());
  12568. // Verify backend error is captured for SSLLoadingCerts
  12569. // This error occurs when loading CA certificates fails
  12570. EXPECT_NE(0UL, res.ssl_backend_error());
  12571. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12572. // OpenSSL specific error codes:
  12573. // > openssl errstr 0x80000002
  12574. // error:80000002:system library::No such file or directory
  12575. // > openssl errstr 0xA000126
  12576. // error:0A000126:SSL routines::unexpected eof while reading
  12577. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12578. res.ssl_backend_error() == 0xA000126);
  12579. #endif
  12580. }
  12581. TEST(SSLClientTest, ServerCertificateVerification4) {
  12582. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12583. ASSERT_TRUE(svr.is_valid());
  12584. svr.Get("/test", [&](const Request &, Response &res) {
  12585. res.set_content("test", "text/plain");
  12586. svr.stop();
  12587. ASSERT_TRUE(true);
  12588. });
  12589. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12590. auto se = detail::scope_exit([&] {
  12591. t.join();
  12592. ASSERT_FALSE(svr.is_running());
  12593. });
  12594. svr.wait_until_ready();
  12595. SSLClient cli("127.0.0.1", PORT);
  12596. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12597. cli.enable_server_certificate_verification(true);
  12598. cli.set_connection_timeout(30);
  12599. auto res = cli.Get("/test");
  12600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12601. ASSERT_EQ(StatusCode::OK_200, res->status);
  12602. }
  12603. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12604. std::string cert;
  12605. read_file(CA_CERT_FILE, cert);
  12606. SSLClient cli("google.com");
  12607. cli.load_ca_cert_store(cert.data(), cert.size());
  12608. const auto res = cli.Get("/");
  12609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12610. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12611. }
  12612. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12613. // clang-format off
  12614. static constexpr char cert[] =
  12615. "GlobalSign Root CA\n"
  12616. "==================\n"
  12617. "-----BEGIN CERTIFICATE-----\n"
  12618. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12619. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12620. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12621. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12622. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12623. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12624. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12625. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12626. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12627. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12628. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12629. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12630. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12631. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12632. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12633. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12634. "-----END CERTIFICATE-----\n";
  12635. // clang-format on
  12636. SSLClient cli("google.com");
  12637. cli.load_ca_cert_store(cert, sizeof(cert));
  12638. const auto res = cli.Get("/");
  12639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12640. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12641. }
  12642. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12643. SSLClient cli("www.youtube.com");
  12644. cli.set_ca_cert_path(CA_CERT_FILE);
  12645. cli.enable_server_certificate_verification(true);
  12646. cli.set_follow_location(true);
  12647. auto res = cli.Get("/");
  12648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12649. ASSERT_EQ(StatusCode::OK_200, res->status);
  12650. }
  12651. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12652. SSLClient cli("wWw.YouTube.Com");
  12653. cli.set_ca_cert_path(CA_CERT_FILE);
  12654. cli.enable_server_certificate_verification(true);
  12655. cli.enable_server_hostname_verification(true);
  12656. cli.set_follow_location(true);
  12657. auto res = cli.Get("/");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. ASSERT_EQ(StatusCode::OK_200, res->status);
  12660. }
  12661. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12662. SSLClient cli("gOoGlE.COm");
  12663. cli.enable_server_certificate_verification(true);
  12664. cli.enable_server_hostname_verification(true);
  12665. cli.set_follow_location(true);
  12666. auto res = cli.Get("/");
  12667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12668. ASSERT_EQ(StatusCode::OK_200, res->status);
  12669. }
  12670. TEST(SSLClientTest, Issue2004_Online) {
  12671. Client client("https://google.com");
  12672. client.set_follow_location(true);
  12673. auto res = client.Get("/");
  12674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12675. ASSERT_EQ(StatusCode::OK_200, res->status);
  12676. auto body = res->body;
  12677. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12678. }
  12679. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12680. // Create SSLClient with invalid cert/key to make is_valid() return false
  12681. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12682. "nonexistent_key.pem");
  12683. // is_valid() should be false due to cert loading failure
  12684. ASSERT_FALSE(cli.is_valid());
  12685. auto res = cli.Get("/");
  12686. ASSERT_FALSE(res);
  12687. EXPECT_EQ(Error::SSLConnection, res.error());
  12688. }
  12689. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12690. // Test for Issue #2251: SSL error not properly reported when client cert
  12691. // and key paths are swapped or mismatched
  12692. // This simulates the scenario where user accidentally swaps the cert and key
  12693. // files
  12694. // Using client cert file as private key and vice versa (completely wrong)
  12695. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12696. // Should fail validation due to cert/key mismatch
  12697. ASSERT_FALSE(cli.is_valid());
  12698. // Attempt to make a request should fail with proper error
  12699. auto res = cli.Get("/");
  12700. ASSERT_FALSE(res);
  12701. EXPECT_EQ(Error::SSLConnection, res.error());
  12702. // SSL error should be recorded in the Result object (this is the key fix for
  12703. // Issue #2251)
  12704. auto backend_error = res.ssl_backend_error();
  12705. EXPECT_NE(0u, backend_error);
  12706. }
  12707. // Tests cert/key mismatch detection at the TLS context level
  12708. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12709. // Test that using mismatched cert/key causes connection failure.
  12710. // We verify this at the SSLClient level rather than through internal
  12711. // TLS API functions.
  12712. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12713. cli.enable_server_certificate_verification(false);
  12714. cli.set_connection_timeout(2);
  12715. // The mismatch should cause a connection or handshake error
  12716. auto res = cli.Get("/test");
  12717. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12718. // Either way, the request should fail
  12719. EXPECT_FALSE(res);
  12720. }
  12721. #endif
  12722. #if 0
  12723. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12724. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12725. ASSERT_TRUE(cli != nullptr);
  12726. cli->set_address_family(AF_INET6);
  12727. cli->set_interface("en0");
  12728. auto res = cli->Get("/get");
  12729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12730. ASSERT_EQ(StatusCode::OK_200, res->status);
  12731. }
  12732. #endif
  12733. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12734. #ifdef CPPHTTPLIB_SSL_ENABLED
  12735. void ClientCertPresent(
  12736. const std::string &client_cert_file,
  12737. const std::string &client_private_key_file,
  12738. const std::string &client_encrypted_private_key_pass = std::string()) {
  12739. using namespace httplib::tls;
  12740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12741. CLIENT_CA_CERT_DIR);
  12742. ASSERT_TRUE(svr.is_valid());
  12743. svr.Get("/test", [&](const Request &req, Response &res) {
  12744. res.set_content("test", "text/plain");
  12745. auto cert = req.peer_cert();
  12746. ASSERT_TRUE(static_cast<bool>(cert));
  12747. std::string common_name = cert.subject_cn();
  12748. EXPECT_EQ("Common Name", common_name);
  12749. });
  12750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12751. auto se = detail::scope_exit([&] {
  12752. svr.stop();
  12753. t.join();
  12754. ASSERT_FALSE(svr.is_running());
  12755. });
  12756. svr.wait_until_ready();
  12757. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12758. client_encrypted_private_key_pass);
  12759. cli.enable_server_certificate_verification(false);
  12760. cli.set_connection_timeout(30);
  12761. auto res = cli.Get("/test");
  12762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12763. ASSERT_EQ(StatusCode::OK_200, res->status);
  12764. }
  12765. TEST(SSLClientServerTest, ClientCertPresent) {
  12766. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12767. }
  12768. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12769. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12770. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12771. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12772. }
  12773. // PEM memory-based constructor tests (works with all TLS backends)
  12774. void PemMemoryClientCertPresent(
  12775. const std::string &client_cert_file,
  12776. const std::string &client_private_key_file,
  12777. const std::string &client_encrypted_private_key_pass = std::string()) {
  12778. // Read PEM files into memory
  12779. std::string server_cert_pem, server_key_pem;
  12780. std::string client_ca_pem;
  12781. std::string client_cert_pem, client_key_pem;
  12782. read_file(SERVER_CERT_FILE, server_cert_pem);
  12783. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12784. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12785. read_file(client_cert_file, client_cert_pem);
  12786. read_file(client_private_key_file, client_key_pem);
  12787. // Create server with PEM memory
  12788. SSLServer::PemMemory server_pem = {
  12789. server_cert_pem.c_str(),
  12790. server_cert_pem.size(),
  12791. server_key_pem.c_str(),
  12792. server_key_pem.size(),
  12793. client_ca_pem.c_str(),
  12794. client_ca_pem.size(),
  12795. nullptr // no password for server key
  12796. };
  12797. SSLServer svr(server_pem);
  12798. ASSERT_TRUE(svr.is_valid());
  12799. svr.Get("/test", [&](const Request &, Response &res) {
  12800. res.set_content("test", "text/plain");
  12801. });
  12802. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12803. auto se = detail::scope_exit([&] {
  12804. svr.stop();
  12805. t.join();
  12806. ASSERT_FALSE(svr.is_running());
  12807. });
  12808. svr.wait_until_ready();
  12809. // Create client with PEM memory
  12810. const char *password = client_encrypted_private_key_pass.empty()
  12811. ? nullptr
  12812. : client_encrypted_private_key_pass.c_str();
  12813. SSLClient::PemMemory client_pem = {
  12814. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12815. client_key_pem.size(), password};
  12816. SSLClient cli(HOST, PORT, client_pem);
  12817. cli.enable_server_certificate_verification(false);
  12818. cli.set_connection_timeout(30);
  12819. auto res = cli.Get("/test");
  12820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12821. ASSERT_EQ(StatusCode::OK_200, res->status);
  12822. }
  12823. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12824. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12825. }
  12826. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12827. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12828. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12829. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12830. }
  12831. TEST(SSLClientServerTest, ClientCertMissing) {
  12832. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12833. CLIENT_CA_CERT_DIR);
  12834. ASSERT_TRUE(svr.is_valid());
  12835. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12836. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12837. auto se = detail::scope_exit([&] {
  12838. svr.stop();
  12839. t.join();
  12840. ASSERT_FALSE(svr.is_running());
  12841. });
  12842. svr.wait_until_ready();
  12843. SSLClient cli(HOST, PORT);
  12844. cli.set_connection_timeout(30);
  12845. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12846. // the chain check on Windows, so the result does not depend on the order.
  12847. cli.enable_server_hostname_verification(false);
  12848. auto res = cli.Get("/test");
  12849. ASSERT_TRUE(!res);
  12850. // When client cert is missing and server requires it, connection fails
  12851. // Error type depends on backend implementation
  12852. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12853. res.error() == Error::SSLConnection);
  12854. // Verify backend error is captured
  12855. // Note: This test may have different error codes depending on the exact
  12856. // verification failure
  12857. EXPECT_NE(0UL, res.ssl_backend_error());
  12858. }
  12859. TEST(SSLClientServerTest, TrustDirOptional) {
  12860. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12861. ASSERT_TRUE(svr.is_valid());
  12862. svr.Get("/test", [&](const Request &, Response &res) {
  12863. res.set_content("test", "text/plain");
  12864. });
  12865. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12866. auto se = detail::scope_exit([&] {
  12867. svr.stop();
  12868. t.join();
  12869. ASSERT_FALSE(svr.is_running());
  12870. });
  12871. svr.wait_until_ready();
  12872. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12873. cli.enable_server_certificate_verification(false);
  12874. cli.set_connection_timeout(30);
  12875. auto res = cli.Get("/test");
  12876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12877. ASSERT_EQ(StatusCode::OK_200, res->status);
  12878. }
  12879. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12880. class NoListenSSLServer : public SSLServer {
  12881. public:
  12882. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12883. const char *client_ca_cert_file_path,
  12884. const char *client_ca_cert_dir_path = nullptr)
  12885. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12886. client_ca_cert_dir_path),
  12887. stop_(false) {}
  12888. std::atomic_bool stop_;
  12889. private:
  12890. bool process_and_close_socket(socket_t /*sock*/) override {
  12891. // Don't create SSL context
  12892. while (!stop_.load()) {
  12893. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12894. }
  12895. return true;
  12896. }
  12897. };
  12898. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12899. CLIENT_CA_CERT_FILE);
  12900. ASSERT_TRUE(svr.is_valid());
  12901. svr.Get("/test", [&](const Request &, Response &res) {
  12902. res.set_content("test", "text/plain");
  12903. });
  12904. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12905. auto se = detail::scope_exit([&] {
  12906. svr.stop_ = true;
  12907. svr.stop();
  12908. t.join();
  12909. ASSERT_FALSE(svr.is_running());
  12910. });
  12911. svr.wait_until_ready();
  12912. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12913. cli.enable_server_certificate_verification(false);
  12914. cli.set_connection_timeout(1);
  12915. auto res = cli.Get("/test");
  12916. ASSERT_TRUE(!res);
  12917. EXPECT_EQ(Error::SSLConnection, res.error());
  12918. // Timeout results in WantRead error code (maps to backend-specific value)
  12919. EXPECT_NE(0, res.ssl_error());
  12920. }
  12921. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12922. // Test SSLServer with client certificate verification using the standard
  12923. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12924. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12925. CLIENT_CA_CERT_DIR);
  12926. ASSERT_TRUE(svr.is_valid());
  12927. svr.Get("/test", [&](const Request &req, Response &res) {
  12928. res.set_content("test", "text/plain");
  12929. auto cert = req.peer_cert();
  12930. ASSERT_TRUE(static_cast<bool>(cert));
  12931. auto common_name = cert.subject_cn();
  12932. EXPECT_EQ("Common Name", common_name);
  12933. });
  12934. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12935. auto se = detail::scope_exit([&] {
  12936. svr.stop();
  12937. t.join();
  12938. ASSERT_FALSE(svr.is_running());
  12939. });
  12940. svr.wait_until_ready();
  12941. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12942. cli.enable_server_certificate_verification(false);
  12943. cli.set_connection_timeout(30);
  12944. auto res = cli.Get("/test");
  12945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12946. ASSERT_EQ(StatusCode::OK_200, res->status);
  12947. }
  12948. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12949. // Verifies that wildcard matching and exact matching work consistently
  12950. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12951. using namespace httplib::tls;
  12952. // We need a running server to test against
  12953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12954. ASSERT_TRUE(svr.is_valid());
  12955. svr.Get("/test", [](const Request &, Response &res) {
  12956. res.set_content("ok", "text/plain");
  12957. });
  12958. thread t([&]() { svr.listen(HOST, PORT); });
  12959. auto se = detail::scope_exit([&] {
  12960. svr.stop();
  12961. t.join();
  12962. });
  12963. svr.wait_until_ready();
  12964. bool verify_callback_called = false;
  12965. bool verify_result_wrong = false;
  12966. SSLClient cli(HOST, PORT);
  12967. cli.enable_server_certificate_verification(true);
  12968. cli.set_ca_cert_path(CA_CERT_FILE);
  12969. cli.set_connection_timeout(5);
  12970. // Note: Test certificate has CN="Common Name", not "localhost"
  12971. bool verify_result_cn = false;
  12972. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12973. verify_callback_called = true;
  12974. if (!ctx.cert) return false;
  12975. // Test 1: "Common Name" should match (our test server cert CN)
  12976. verify_result_cn = ctx.check_hostname("Common Name");
  12977. // Test 2: wrong hostname should not match
  12978. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12979. return true; // Accept for the purpose of this test
  12980. });
  12981. auto res = cli.Get("/test");
  12982. // The request may succeed or fail depending on cert configuration
  12983. // but the callback should have been called
  12984. ASSERT_TRUE(verify_callback_called)
  12985. << "Verify callback should have been called";
  12986. // CN="Common Name" should match our test certificate
  12987. //
  12988. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12989. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12990. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12991. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12992. // <openssl/base.h>, which is included transitively when
  12993. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12994. #if defined(OPENSSL_IS_BORINGSSL)
  12995. EXPECT_FALSE(verify_result_cn)
  12996. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12997. #else
  12998. EXPECT_TRUE(verify_result_cn)
  12999. << "verify_hostname should match 'Common Name' (certificate CN)";
  13000. #endif
  13001. // Wrong hostname should not match
  13002. EXPECT_FALSE(verify_result_wrong)
  13003. << "verify_hostname should not match 'wronghost.example.com'";
  13004. }
  13005. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13006. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13007. // X509_check_ip behavior and must hold for every backend.
  13008. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13009. using namespace httplib::tls;
  13010. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13011. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13012. ASSERT_TRUE(svr.is_valid());
  13013. svr.Get("/test", [](const Request &, Response &res) {
  13014. res.set_content("ok", "text/plain");
  13015. });
  13016. thread t([&]() { svr.listen(HOST, PORT); });
  13017. auto se = detail::scope_exit([&] {
  13018. svr.stop();
  13019. t.join();
  13020. });
  13021. svr.wait_until_ready();
  13022. bool verify_callback_called = false;
  13023. bool ip_matched_via_cn = true;
  13024. SSLClient cli(HOST, PORT);
  13025. cli.enable_server_certificate_verification(true);
  13026. cli.set_ca_cert_path(CA_CERT_FILE);
  13027. cli.set_connection_timeout(5);
  13028. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13029. verify_callback_called = true;
  13030. if (!ctx.cert) return false;
  13031. // The IP appears only in the CN, so it must NOT be accepted.
  13032. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13033. return true; // Accept for the purpose of this test
  13034. });
  13035. cli.Get("/test");
  13036. ASSERT_TRUE(verify_callback_called)
  13037. << "Verify callback should have been called";
  13038. EXPECT_FALSE(ip_matched_via_cn)
  13039. << "An IP host must not be authenticated via the certificate CN";
  13040. }
  13041. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13042. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13043. using namespace httplib::tls;
  13044. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13045. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13046. ASSERT_TRUE(svr.is_valid());
  13047. svr.Get("/test", [](const Request &, Response &res) {
  13048. res.set_content("ok", "text/plain");
  13049. });
  13050. thread t([&]() { svr.listen(HOST, PORT); });
  13051. auto se = detail::scope_exit([&] {
  13052. svr.stop();
  13053. t.join();
  13054. });
  13055. svr.wait_until_ready();
  13056. bool verify_callback_called = false;
  13057. bool san_matched = false;
  13058. bool wrong_ipv6_matched = true;
  13059. bool cn_ipv6_matched = true;
  13060. SSLClient cli(HOST, PORT);
  13061. cli.enable_server_certificate_verification(true);
  13062. cli.set_ca_cert_path(CA_CERT_FILE);
  13063. cli.set_connection_timeout(5);
  13064. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13065. verify_callback_called = true;
  13066. if (!ctx.cert) return false;
  13067. // Matches the IPv6 iPAddress SAN.
  13068. san_matched = ctx.check_hostname("2001:db8::1");
  13069. // A different IPv6 address must not match.
  13070. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13071. // "::1" lives only in the CN, so it must not be accepted.
  13072. cn_ipv6_matched = ctx.check_hostname("::1");
  13073. return true; // Accept for the purpose of this test
  13074. });
  13075. cli.Get("/test");
  13076. ASSERT_TRUE(verify_callback_called)
  13077. << "Verify callback should have been called";
  13078. EXPECT_TRUE(san_matched)
  13079. << "verify_hostname should match an IPv6 iPAddress SAN";
  13080. EXPECT_FALSE(wrong_ipv6_matched)
  13081. << "verify_hostname should not match a non-matching IPv6 address";
  13082. EXPECT_FALSE(cn_ipv6_matched)
  13083. << "An IPv6 host must not be authenticated via the certificate CN";
  13084. }
  13085. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13086. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13087. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13088. using namespace httplib::tls;
  13089. // SANs: DNS:a.zz, IP:42.46.122.122
  13090. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13091. ASSERT_TRUE(svr.is_valid());
  13092. svr.Get("/test", [](const Request &, Response &res) {
  13093. res.set_content("ok", "text/plain");
  13094. });
  13095. auto port = svr.bind_to_any_port(HOST);
  13096. thread t([&]() { svr.listen_after_bind(); });
  13097. auto se = detail::scope_exit([&] {
  13098. svr.stop();
  13099. t.join();
  13100. });
  13101. svr.wait_until_ready();
  13102. bool verify_callback_called = false;
  13103. bool dns_san_matched = false;
  13104. bool ip_san_matched = false;
  13105. bool ip_matched_via_dns_san = true;
  13106. bool dns_matched_via_ip_san = true;
  13107. SSLClient cli(HOST, port);
  13108. cli.enable_server_certificate_verification(true);
  13109. cli.set_ca_cert_path(CA_CERT_FILE);
  13110. cli.set_connection_timeout(5);
  13111. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13112. verify_callback_called = true;
  13113. if (!ctx.cert) return false;
  13114. dns_san_matched = ctx.check_hostname("a.zz");
  13115. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13116. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13117. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13118. return true; // Accept for the purpose of this test
  13119. });
  13120. cli.Get("/test");
  13121. ASSERT_TRUE(verify_callback_called)
  13122. << "Verify callback should have been called";
  13123. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13124. EXPECT_TRUE(ip_san_matched)
  13125. << "verify_hostname should match an iPAddress SAN";
  13126. EXPECT_FALSE(ip_matched_via_dns_san)
  13127. << "An IP host must not be authenticated via a dNSName SAN";
  13128. EXPECT_FALSE(dns_matched_via_ip_san)
  13129. << "A DNS host must not be authenticated via an iPAddress SAN";
  13130. }
  13131. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13132. // "www.*.example.test" names one host and not every host under example.test.
  13133. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13134. using namespace httplib::tls;
  13135. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13136. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13137. ASSERT_TRUE(svr.is_valid());
  13138. svr.Get("/test", [](const Request &, Response &res) {
  13139. res.set_content("ok", "text/plain");
  13140. });
  13141. auto port = svr.bind_to_any_port(HOST);
  13142. thread t([&]() { svr.listen_after_bind(); });
  13143. auto se = detail::scope_exit([&] {
  13144. svr.stop();
  13145. t.join();
  13146. });
  13147. svr.wait_until_ready();
  13148. bool verify_callback_called = false;
  13149. bool leftmost_wildcard_matched = false;
  13150. bool wildcard_spanned_labels = true;
  13151. bool inner_wildcard_matched = true;
  13152. SSLClient cli(HOST, port);
  13153. cli.enable_server_certificate_verification(true);
  13154. cli.set_ca_cert_path(CA_CERT_FILE);
  13155. cli.set_connection_timeout(5);
  13156. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13157. verify_callback_called = true;
  13158. if (!ctx.cert) return false;
  13159. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13160. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13161. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13162. return true; // Accept for the purpose of this test
  13163. });
  13164. cli.Get("/test");
  13165. ASSERT_TRUE(verify_callback_called)
  13166. << "Verify callback should have been called";
  13167. EXPECT_TRUE(leftmost_wildcard_matched)
  13168. << "A leftmost wildcard should match a single label";
  13169. EXPECT_FALSE(wildcard_spanned_labels)
  13170. << "A wildcard label must not match more than one label";
  13171. EXPECT_FALSE(inner_wildcard_matched)
  13172. << "A wildcard outside the leftmost label must not be honoured";
  13173. }
  13174. // sans() must report each SAN entry under its own type.
  13175. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13176. using namespace httplib::tls;
  13177. // SANs: DNS:a.zz, IP:42.46.122.122
  13178. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13179. ASSERT_TRUE(svr.is_valid());
  13180. svr.Get("/test", [](const Request &, Response &res) {
  13181. res.set_content("ok", "text/plain");
  13182. });
  13183. auto port = svr.bind_to_any_port(HOST);
  13184. thread t([&]() { svr.listen_after_bind(); });
  13185. auto se = detail::scope_exit([&] {
  13186. svr.stop();
  13187. t.join();
  13188. });
  13189. svr.wait_until_ready();
  13190. bool verify_callback_called = false;
  13191. std::vector<SanEntry> sans;
  13192. SSLClient cli(HOST, port);
  13193. cli.enable_server_certificate_verification(true);
  13194. cli.set_ca_cert_path(CA_CERT_FILE);
  13195. cli.set_connection_timeout(5);
  13196. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13197. verify_callback_called = true;
  13198. if (!ctx.cert) return false;
  13199. sans = ctx.sans();
  13200. return true; // Accept for the purpose of this test
  13201. });
  13202. cli.Get("/test");
  13203. ASSERT_TRUE(verify_callback_called)
  13204. << "Verify callback should have been called";
  13205. auto has_san = [&](SanType type, const std::string &value) {
  13206. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13207. return san.type == type && san.value == value;
  13208. });
  13209. };
  13210. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13211. << "sans() should report the dNSName SAN";
  13212. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13213. << "sans() should report the iPAddress SAN";
  13214. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13215. << "sans() must not report the dNSName SAN as an address";
  13216. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13217. << "sans() must not report the iPAddress SAN as a DNS name";
  13218. }
  13219. #endif
  13220. // mbedTLS-specific callback constructor test
  13221. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13222. #ifdef CPPHTTPLIB_SSL_ENABLED
  13223. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13225. ASSERT_TRUE(svr.is_valid());
  13226. // Set up a handler to verify client certificate is present
  13227. bool client_cert_verified = false;
  13228. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13229. // Verify that client certificate was provided
  13230. client_cert_verified = true;
  13231. res.set_content("success", "text/plain");
  13232. });
  13233. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13234. auto se = detail::scope_exit([&] {
  13235. svr.stop();
  13236. t.join();
  13237. ASSERT_FALSE(svr.is_running());
  13238. });
  13239. svr.wait_until_ready();
  13240. // Client with certificate
  13241. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13242. cli.enable_server_certificate_verification(false);
  13243. cli.set_connection_timeout(30);
  13244. auto res = cli.Get("/test");
  13245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13246. ASSERT_EQ(StatusCode::OK_200, res->status);
  13247. ASSERT_TRUE(client_cert_verified);
  13248. EXPECT_EQ("success", res->body);
  13249. }
  13250. #endif
  13251. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13252. // backends
  13253. #ifdef CPPHTTPLIB_SSL_ENABLED
  13254. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13255. using namespace httplib::tls;
  13256. // Test that when client CA cert file is provided,
  13257. // the server properly requests and validates client certificates
  13258. // Create a server with client authentication
  13259. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13260. ASSERT_TRUE(svr.is_valid());
  13261. bool handler_called = false;
  13262. svr.Get("/test", [&](const Request &req, Response &res) {
  13263. handler_called = true;
  13264. // Verify that a client certificate was provided
  13265. auto cert = req.peer_cert();
  13266. ASSERT_TRUE(static_cast<bool>(cert));
  13267. // Get the issuer name
  13268. std::string issuer_str = cert.issuer_name();
  13269. ASSERT_FALSE(issuer_str.empty());
  13270. // The client certificate should be issued by our test CA
  13271. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13272. res.set_content("authenticated", "text/plain");
  13273. });
  13274. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13275. auto se = detail::scope_exit([&] {
  13276. svr.stop();
  13277. t.join();
  13278. ASSERT_FALSE(svr.is_running());
  13279. });
  13280. svr.wait_until_ready();
  13281. // Connect with a client certificate issued by the CA
  13282. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13283. cli.enable_server_certificate_verification(false);
  13284. cli.set_connection_timeout(30);
  13285. auto res = cli.Get("/test");
  13286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13287. ASSERT_EQ(StatusCode::OK_200, res->status);
  13288. ASSERT_TRUE(handler_called);
  13289. EXPECT_EQ("authenticated", res->body);
  13290. }
  13291. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13292. using namespace httplib::tls;
  13293. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13294. ASSERT_TRUE(svr.is_valid());
  13295. svr.Get("/test", [](const Request &, Response &res) {
  13296. res.set_content("ok", "text/plain");
  13297. });
  13298. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13299. auto se = detail::scope_exit([&] {
  13300. svr.stop();
  13301. t.join();
  13302. });
  13303. svr.wait_until_ready();
  13304. SSLClient cli(HOST, PORT);
  13305. cli.enable_server_certificate_verification(false);
  13306. cli.set_connection_timeout(30);
  13307. bool cert_checked = false;
  13308. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13309. if (ctx.cert) {
  13310. auto sans = ctx.sans();
  13311. // Test certificate may or may not have SANs - just verify the API
  13312. // works If SANs exist, verify the types are valid
  13313. for (const auto &san : sans) {
  13314. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13315. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13316. san.type == SanType::OTHER);
  13317. EXPECT_FALSE(san.value.empty());
  13318. }
  13319. cert_checked = true;
  13320. }
  13321. return true;
  13322. });
  13323. auto res = cli.Get("/test");
  13324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13325. EXPECT_TRUE(cert_checked);
  13326. }
  13327. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13328. using namespace httplib::tls;
  13329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13330. ASSERT_TRUE(svr.is_valid());
  13331. svr.Get("/test", [](const Request &, Response &res) {
  13332. res.set_content("ok", "text/plain");
  13333. });
  13334. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13335. auto se = detail::scope_exit([&] {
  13336. svr.stop();
  13337. t.join();
  13338. });
  13339. svr.wait_until_ready();
  13340. SSLClient cli(HOST, PORT);
  13341. cli.enable_server_certificate_verification(false);
  13342. cli.set_connection_timeout(30);
  13343. bool validity_checked = false;
  13344. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13345. if (ctx.cert) {
  13346. time_t not_before = 0, not_after = 0;
  13347. bool result = ctx.validity(not_before, not_after);
  13348. EXPECT_TRUE(result);
  13349. // Verify that not_before < now < not_after for a valid cert
  13350. time_t now = time(nullptr);
  13351. EXPECT_LT(not_before, now);
  13352. EXPECT_GT(not_after, now);
  13353. validity_checked = true;
  13354. }
  13355. return true;
  13356. });
  13357. auto res = cli.Get("/test");
  13358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13359. EXPECT_TRUE(validity_checked);
  13360. }
  13361. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13362. using namespace httplib::tls;
  13363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13364. ASSERT_TRUE(svr.is_valid());
  13365. svr.Get("/test", [](const Request &, Response &res) {
  13366. res.set_content("ok", "text/plain");
  13367. });
  13368. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13369. auto se = detail::scope_exit([&] {
  13370. svr.stop();
  13371. t.join();
  13372. });
  13373. svr.wait_until_ready();
  13374. SSLClient cli(HOST, PORT);
  13375. cli.enable_server_certificate_verification(false);
  13376. cli.set_connection_timeout(30);
  13377. bool serial_checked = false;
  13378. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13379. if (ctx.cert) {
  13380. std::string serial = ctx.serial();
  13381. EXPECT_FALSE(serial.empty());
  13382. // Serial should be a hex string
  13383. for (char c : serial) {
  13384. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13385. (c >= 'a' && c <= 'f'));
  13386. }
  13387. serial_checked = true;
  13388. }
  13389. return true;
  13390. });
  13391. auto res = cli.Get("/test");
  13392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13393. EXPECT_TRUE(serial_checked);
  13394. }
  13395. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13396. // Test 1: Valid CA file - no error should be recorded
  13397. {
  13398. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13399. CLIENT_CA_CERT_FILE);
  13400. ASSERT_TRUE(svr.is_valid());
  13401. // With valid setup, last_ssl_error should be 0
  13402. EXPECT_EQ(0, svr.ssl_last_error());
  13403. }
  13404. // Test 2: Invalid CA file content
  13405. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13406. {
  13407. // Create a temporary file with completely invalid content
  13408. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13409. {
  13410. std::ofstream ofs(temp_invalid_ca);
  13411. ofs << "This is not a certificate file at all\n";
  13412. ofs << "Just plain text content\n";
  13413. }
  13414. // Create server with invalid CA file
  13415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13416. // Clean up temporary file
  13417. std::remove(temp_invalid_ca);
  13418. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13419. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13420. // Note: SSL_CTX_load_verify_locations typically fails first,
  13421. // but our error handling code path is still exercised
  13422. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13423. }
  13424. }
  13425. TEST(VerifyCallbackTest, VerifyContextFields) {
  13426. using namespace httplib::tls;
  13427. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13428. ASSERT_TRUE(svr.is_valid());
  13429. svr.Get("/test", [](const Request &, Response &res) {
  13430. res.set_content("ok", "text/plain");
  13431. });
  13432. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13433. auto se = detail::scope_exit([&] {
  13434. svr.stop();
  13435. t.join();
  13436. });
  13437. svr.wait_until_ready();
  13438. SSLClient cli(HOST, PORT);
  13439. cli.enable_server_certificate_verification(false);
  13440. cli.set_connection_timeout(30);
  13441. int callback_count = 0;
  13442. bool saw_leaf_cert = false;
  13443. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13444. if (ctx.cert) {
  13445. callback_count++;
  13446. // We should see at least one certificate (the leaf)
  13447. std::string cn = ctx.subject_cn();
  13448. if (!cn.empty()) { saw_leaf_cert = true; }
  13449. // Verify context fields are populated
  13450. EXPECT_NE(ctx.session, nullptr);
  13451. EXPECT_GE(ctx.depth, 0);
  13452. }
  13453. return true;
  13454. });
  13455. auto res = cli.Get("/test");
  13456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13457. EXPECT_GT(callback_count, 0);
  13458. EXPECT_TRUE(saw_leaf_cert);
  13459. }
  13460. // A verifier belongs to the client that set it, not to the thread that set it.
  13461. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13462. using namespace httplib::tls;
  13463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13464. ASSERT_TRUE(svr.is_valid());
  13465. svr.Get("/test", [](const Request &, Response &res) {
  13466. res.set_content("ok", "text/plain");
  13467. });
  13468. auto port = svr.bind_to_any_port(HOST);
  13469. thread t([&]() { svr.listen_after_bind(); });
  13470. auto se = detail::scope_exit([&] {
  13471. svr.stop();
  13472. t.join();
  13473. });
  13474. svr.wait_until_ready();
  13475. auto rejecting_calls = 0;
  13476. SSLClient rejecting(HOST, port);
  13477. rejecting.enable_server_certificate_verification(false);
  13478. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13479. rejecting_calls++;
  13480. return false;
  13481. });
  13482. auto accepting_calls = 0;
  13483. SSLClient accepting(HOST, port);
  13484. accepting.enable_server_certificate_verification(false);
  13485. // Set on another thread than the requests below.
  13486. thread([&]() {
  13487. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13488. accepting_calls++;
  13489. return true;
  13490. });
  13491. }).join();
  13492. // Requested on another thread than the verifier was set on.
  13493. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13494. EXPECT_GT(rejecting_calls, 0);
  13495. auto res = accepting.Get("/test");
  13496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13497. EXPECT_GT(accepting_calls, 0);
  13498. }
  13499. // VerifyContext::session is the same handle the other tls:: functions take.
  13500. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13501. using namespace httplib::tls;
  13502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13503. ASSERT_TRUE(svr.is_valid());
  13504. svr.Get("/test", [](const Request &, Response &res) {
  13505. res.set_content("ok", "text/plain");
  13506. });
  13507. auto port = svr.bind_to_any_port(HOST);
  13508. thread t([&]() { svr.listen_after_bind(); });
  13509. auto se = detail::scope_exit([&] {
  13510. svr.stop();
  13511. t.join();
  13512. });
  13513. svr.wait_until_ready();
  13514. SSLClient cli(HOST, port);
  13515. cli.enable_server_certificate_verification(false);
  13516. session_t verifier_session = nullptr;
  13517. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13518. verifier_session = ctx.session;
  13519. return true;
  13520. });
  13521. session_t session_verifier_session = nullptr;
  13522. cli.set_session_verifier([&](session_t session) {
  13523. session_verifier_session = session;
  13524. return SSLVerifierResponse::NoDecisionMade;
  13525. });
  13526. auto res = cli.Get("/test");
  13527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13528. EXPECT_NE(nullptr, verifier_session);
  13529. EXPECT_EQ(session_verifier_session, verifier_session);
  13530. }
  13531. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13532. using httplib::tls::TlsError;
  13533. // Test that verify_error_to_string returns empty for success
  13534. std::string success_str = TlsError::verify_error_to_string(0);
  13535. EXPECT_TRUE(success_str.empty());
  13536. // Test that verify_error_to_string returns non-empty for error codes
  13537. // Using a common error code (certificate expired)
  13538. std::string error_str =
  13539. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13540. EXPECT_FALSE(error_str.empty());
  13541. }
  13542. TEST(SessionVerifierTest, CertificateAccepted) {
  13543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13544. ASSERT_TRUE(svr.is_valid());
  13545. svr.Get("/test", [](const Request &, Response &res) {
  13546. res.set_content("ok", "text/plain");
  13547. });
  13548. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13549. auto se = detail::scope_exit([&] {
  13550. svr.stop();
  13551. t.join();
  13552. });
  13553. svr.wait_until_ready();
  13554. SSLClient cli(HOST, PORT);
  13555. cli.enable_server_certificate_verification(false);
  13556. cli.set_connection_timeout(30);
  13557. bool callback_called = false;
  13558. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13559. EXPECT_NE(session, nullptr);
  13560. callback_called = true;
  13561. return SSLVerifierResponse::CertificateAccepted;
  13562. });
  13563. auto res = cli.Get("/test");
  13564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13565. EXPECT_EQ(200, res->status);
  13566. EXPECT_TRUE(callback_called);
  13567. }
  13568. TEST(SessionVerifierTest, CertificateRejected) {
  13569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13570. ASSERT_TRUE(svr.is_valid());
  13571. svr.Get("/test", [](const Request &, Response &res) {
  13572. res.set_content("ok", "text/plain");
  13573. });
  13574. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13575. auto se = detail::scope_exit([&] {
  13576. svr.stop();
  13577. t.join();
  13578. });
  13579. svr.wait_until_ready();
  13580. SSLClient cli(HOST, PORT);
  13581. cli.enable_server_certificate_verification(false);
  13582. cli.set_connection_timeout(30);
  13583. bool callback_called = false;
  13584. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13585. EXPECT_NE(session, nullptr);
  13586. callback_called = true;
  13587. return SSLVerifierResponse::CertificateRejected;
  13588. });
  13589. auto res = cli.Get("/test");
  13590. EXPECT_FALSE(res);
  13591. EXPECT_TRUE(callback_called);
  13592. }
  13593. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13594. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13595. ASSERT_TRUE(svr.is_valid());
  13596. svr.Get("/test", [](const Request &, Response &res) {
  13597. res.set_content("ok", "text/plain");
  13598. });
  13599. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13600. auto se = detail::scope_exit([&] {
  13601. svr.stop();
  13602. t.join();
  13603. });
  13604. svr.wait_until_ready();
  13605. // NoDecisionMade with verification disabled should succeed (no default check)
  13606. SSLClient cli(HOST, PORT);
  13607. cli.enable_server_certificate_verification(false);
  13608. cli.set_connection_timeout(30);
  13609. bool callback_called = false;
  13610. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13611. EXPECT_NE(session, nullptr);
  13612. callback_called = true;
  13613. return SSLVerifierResponse::NoDecisionMade;
  13614. });
  13615. auto res = cli.Get("/test");
  13616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13617. EXPECT_EQ(200, res->status);
  13618. EXPECT_TRUE(callback_called);
  13619. }
  13620. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13622. ASSERT_TRUE(svr.is_valid());
  13623. svr.Get("/test", [](const Request &, Response &res) {
  13624. res.set_content("ok", "text/plain");
  13625. });
  13626. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13627. auto se = detail::scope_exit([&] {
  13628. svr.stop();
  13629. t.join();
  13630. });
  13631. svr.wait_until_ready();
  13632. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13633. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13634. // so we only check that the request fails, not whether the callback was
  13635. // called.
  13636. SSLClient cli(HOST, PORT);
  13637. cli.enable_server_certificate_verification(true);
  13638. cli.set_connection_timeout(30);
  13639. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13640. EXPECT_NE(session, nullptr);
  13641. return SSLVerifierResponse::NoDecisionMade;
  13642. });
  13643. auto res = cli.Get("/test");
  13644. EXPECT_FALSE(res);
  13645. }
  13646. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13647. // Test SSL server using PemMemory constructor with client CA certificates
  13648. // Read PEM files
  13649. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13650. read_file(SERVER_CERT_FILE, server_cert_pem);
  13651. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13652. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13653. // Create SSLServer with PemMemory constructor including client CA
  13654. SSLServer::PemMemory server_pem = {
  13655. server_cert_pem.c_str(),
  13656. server_cert_pem.size(),
  13657. server_key_pem.c_str(),
  13658. server_key_pem.size(),
  13659. client_ca_pem.c_str(),
  13660. client_ca_pem.size(),
  13661. nullptr // no password for server key
  13662. };
  13663. SSLServer svr(server_pem);
  13664. ASSERT_TRUE(svr.is_valid());
  13665. // No SSL error should be recorded for valid setup
  13666. EXPECT_EQ(0, svr.ssl_last_error());
  13667. // Set up server endpoints
  13668. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13669. res.set_content("ok", "text/plain");
  13670. });
  13671. // Start server in a thread
  13672. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13673. svr.wait_until_ready();
  13674. // Connect with client certificate (using constructor with paths)
  13675. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13676. cli.enable_server_certificate_verification(false);
  13677. auto res = cli.Get("/test-pem-ca");
  13678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13679. EXPECT_EQ(200, res->status);
  13680. EXPECT_EQ("ok", res->body);
  13681. svr.stop();
  13682. server_thread.join();
  13683. }
  13684. #endif
  13685. #ifdef _WIN32
  13686. TEST(CleanupTest, WSACleanup) {
  13687. int ret = WSACleanup();
  13688. ASSERT_EQ(0, ret);
  13689. }
  13690. #endif
  13691. #ifndef CPPHTTPLIB_SSL_ENABLED
  13692. TEST(NoSSLSupport, SimpleInterface) {
  13693. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13694. }
  13695. #endif
  13696. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13697. TEST(InvalidScheme, SimpleInterface) {
  13698. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13699. }
  13700. #endif
  13701. TEST(NoScheme, SimpleInterface) {
  13702. Client cli("yahoo.com:80");
  13703. ASSERT_TRUE(cli.is_valid());
  13704. }
  13705. TEST(SendAPI, SimpleInterface_Online) {
  13706. Client cli("http://yahoo.com");
  13707. Request req;
  13708. req.method = "GET";
  13709. req.path = "/";
  13710. auto res = cli.send(req);
  13711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13712. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13713. }
  13714. TEST(SendAPI, WithParamsInRequest) {
  13715. Server svr;
  13716. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13717. EXPECT_TRUE(req.has_param("test"));
  13718. EXPECT_EQ("test_value", req.get_param_value("test"));
  13719. });
  13720. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13721. auto se = detail::scope_exit([&] {
  13722. svr.stop();
  13723. t.join();
  13724. ASSERT_FALSE(svr.is_running());
  13725. });
  13726. svr.wait_until_ready();
  13727. Client cli(HOST, PORT);
  13728. {
  13729. Request req;
  13730. req.method = "GET";
  13731. req.path = "/";
  13732. req.params.emplace("test", "test_value");
  13733. auto res = cli.send(req);
  13734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13735. }
  13736. {
  13737. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13739. }
  13740. }
  13741. TEST(ClientImplMethods, GetSocketTest) {
  13742. httplib::Server svr;
  13743. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13744. res.status = StatusCode::OK_200;
  13745. });
  13746. auto port = svr.bind_to_any_port("127.0.0.1");
  13747. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13748. auto se = detail::scope_exit([&] {
  13749. svr.stop();
  13750. thread.join();
  13751. ASSERT_FALSE(svr.is_running());
  13752. });
  13753. svr.wait_until_ready();
  13754. {
  13755. httplib::Client cli("127.0.0.1", port);
  13756. cli.set_keep_alive(true);
  13757. // Use the behavior of cpp-httplib of opening the connection
  13758. // only when the first request happens. If that changes,
  13759. // this test would be obsolete.
  13760. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13761. // This also implicitly tests the server. But other tests would fail much
  13762. // earlier than this one to be considered.
  13763. auto res = cli.Get("/");
  13764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13765. EXPECT_EQ(StatusCode::OK_200, res->status);
  13766. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13767. }
  13768. }
  13769. #ifdef CPPHTTPLIB_SSL_ENABLED
  13770. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13771. Client cli("http://yahoo.com");
  13772. auto res = cli.Get("/");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13775. cli.set_follow_location(true);
  13776. res = cli.Get("/");
  13777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13778. EXPECT_EQ(StatusCode::OK_200, res->status);
  13779. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13780. }
  13781. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13782. Client cli("https://yahoo.com");
  13783. auto res = cli.Get("/");
  13784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13785. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13786. cli.set_follow_location(true);
  13787. res = cli.Get("/");
  13788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13789. EXPECT_EQ(StatusCode::OK_200, res->status);
  13790. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13791. }
  13792. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13793. Client cli("https://yahoo.com");
  13794. auto res = cli.Get("/");
  13795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13796. ASSERT_FALSE(!res);
  13797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13798. ASSERT_FALSE(res == nullptr);
  13799. ASSERT_TRUE(res != nullptr);
  13800. EXPECT_EQ(Error::Success, res.error());
  13801. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13802. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13803. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13804. cli.set_follow_location(true);
  13805. res = cli.Get("/");
  13806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13807. EXPECT_EQ(Error::Success, res.error());
  13808. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13809. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13810. EXPECT_EQ(StatusCode::OK_200, res->status);
  13811. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13812. }
  13813. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13814. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13815. Client cli("https://cdnjs.cloudflare.com");
  13816. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13817. Headers{{"Accept-Encoding", "br"}});
  13818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13819. EXPECT_EQ(StatusCode::OK_200, res->status);
  13820. EXPECT_EQ(287630U, res->body.size());
  13821. EXPECT_EQ("application/javascript; charset=utf-8",
  13822. res->get_header_value("Content-Type"));
  13823. }
  13824. #endif
  13825. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13826. #undef REDIR_HOST // Silence compiler warning
  13827. #define REDIR_HOST "https://httpbingo.org"
  13828. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13829. Client cli(REDIR_HOST);
  13830. cli.set_follow_location(true);
  13831. auto res =
  13832. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13834. EXPECT_EQ(StatusCode::OK_200, res->status);
  13835. }
  13836. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13837. Client cli(REDIR_HOST);
  13838. cli.set_follow_location(true);
  13839. Params params;
  13840. params.emplace("url", "http://example.com");
  13841. params.emplace("status_code", "302");
  13842. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13844. EXPECT_EQ(StatusCode::OK_200, res->status);
  13845. }
  13846. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13847. Client cli(REDIR_HOST);
  13848. cli.set_follow_location(true);
  13849. Params params;
  13850. params.emplace("url", "http://example.com");
  13851. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13853. EXPECT_EQ(StatusCode::OK_200, res->status);
  13854. }
  13855. TEST(HttpToHttpsRedirectTest, CertFile) {
  13856. auto ssl_port = PORT + 1;
  13857. Server svr;
  13858. ASSERT_TRUE(svr.is_valid());
  13859. svr.Get("/index", [&](const Request &, Response &res) {
  13860. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13861. "/index");
  13862. svr.stop();
  13863. });
  13864. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13865. ASSERT_TRUE(ssl_svr.is_valid());
  13866. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13867. res.set_content("test", "text/plain");
  13868. ssl_svr.stop();
  13869. });
  13870. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13871. thread t2 =
  13872. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13873. auto se = detail::scope_exit([&] {
  13874. t2.join();
  13875. t.join();
  13876. ASSERT_FALSE(svr.is_running());
  13877. });
  13878. svr.wait_until_ready();
  13879. ssl_svr.wait_until_ready();
  13880. Client cli("127.0.0.1", PORT);
  13881. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13882. cli.enable_server_certificate_verification(true);
  13883. cli.set_follow_location(true);
  13884. cli.set_connection_timeout(30);
  13885. auto res = cli.Get("/index");
  13886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13887. ASSERT_EQ(StatusCode::OK_200, res->status);
  13888. }
  13889. TEST(SSLClientRedirectTest, CertFile) {
  13890. auto ssl_port = PORT + 1;
  13891. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13892. ASSERT_TRUE(ssl_svr1.is_valid());
  13893. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13894. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13895. "/index");
  13896. ssl_svr1.stop();
  13897. });
  13898. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13899. ASSERT_TRUE(ssl_svr2.is_valid());
  13900. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13901. res.set_content("test", "text/plain");
  13902. ssl_svr2.stop();
  13903. });
  13904. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13905. thread t2 =
  13906. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13907. auto se = detail::scope_exit([&] {
  13908. t2.join();
  13909. t.join();
  13910. ASSERT_FALSE(ssl_svr1.is_running());
  13911. });
  13912. ssl_svr1.wait_until_ready();
  13913. ssl_svr2.wait_until_ready();
  13914. SSLClient cli("127.0.0.1", PORT);
  13915. std::string cert;
  13916. read_file(SERVER_CERT2_FILE, cert);
  13917. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13918. cli.enable_server_certificate_verification(true);
  13919. cli.set_follow_location(true);
  13920. cli.set_connection_timeout(30);
  13921. auto res = cli.Get("/index");
  13922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13923. ASSERT_EQ(StatusCode::OK_200, res->status);
  13924. }
  13925. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13926. // another port, so the client follows it with a new client.
  13927. static Result GetThroughTlsRedirectToDifferentPort(
  13928. const std::function<void(SSLClient &)> &setup,
  13929. const char *target_cert = SERVER_CERT2_FILE) {
  13930. auto ssl_port = PORT + 1;
  13931. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13932. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13933. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13934. "/index");
  13935. });
  13936. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13937. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13938. res.set_content("test", "text/plain");
  13939. });
  13940. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13941. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13942. auto se = detail::scope_exit([&] {
  13943. ssl_svr2.stop();
  13944. ssl_svr1.stop();
  13945. t2.join();
  13946. t.join();
  13947. });
  13948. ssl_svr1.wait_until_ready();
  13949. ssl_svr2.wait_until_ready();
  13950. SSLClient cli("127.0.0.1", PORT);
  13951. cli.set_follow_location(true);
  13952. cli.set_connection_timeout(30);
  13953. setup(cli);
  13954. return cli.Get("/index");
  13955. }
  13956. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13957. auto calls = 0;
  13958. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13959. cli.enable_server_certificate_verification(false);
  13960. // Accept the first server only.
  13961. cli.set_session_verifier([&](tls::session_t) {
  13962. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13963. : SSLVerifierResponse::CertificateRejected;
  13964. });
  13965. });
  13966. EXPECT_FALSE(res);
  13967. EXPECT_EQ(2, calls);
  13968. }
  13969. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13970. std::string pinned;
  13971. auto res = GetThroughTlsRedirectToDifferentPort(
  13972. [&](SSLClient &cli) {
  13973. cli.enable_server_certificate_verification(false);
  13974. // Pin the first certificate seen.
  13975. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13976. if (pinned.empty()) { pinned = ctx.serial(); }
  13977. return ctx.serial() == pinned;
  13978. });
  13979. },
  13980. // A certificate other than the first server's.
  13981. SERVER_CERT_FILE);
  13982. EXPECT_FALSE(res);
  13983. EXPECT_FALSE(pinned.empty());
  13984. }
  13985. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13986. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13987. std::string cert;
  13988. read_file(SERVER_CERT2_FILE, cert);
  13989. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13990. });
  13991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13992. EXPECT_EQ(StatusCode::OK_200, res->status);
  13993. }
  13994. #endif
  13995. #ifdef CPPHTTPLIB_SSL_ENABLED
  13996. // Test that set_ca_cert_store() skips system certs (consistent with
  13997. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13998. // should be trusted - system certs should NOT be loaded.
  13999. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14000. // Load a specific cert that is NOT a system CA cert
  14001. std::string cert;
  14002. read_file(SERVER_CERT2_FILE, cert);
  14003. SSLClient cli("google.com");
  14004. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14005. cli.enable_server_certificate_verification(true);
  14006. // This should FAIL because:
  14007. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14008. // 2. System certs should NOT be loaded when custom store is set
  14009. // If system certs WERE loaded, this would succeed
  14010. auto res = cli.Get("/");
  14011. ASSERT_FALSE(res);
  14012. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14013. }
  14014. // Same as above, but through the native store handle path. Regression test:
  14015. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14016. // merged system certs into the user-provided store.
  14017. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14018. std::string cert;
  14019. read_file(SERVER_CERT2_FILE, cert);
  14020. SSLClient cli("google.com");
  14021. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14022. cli.enable_server_certificate_verification(true);
  14023. auto res = cli.Get("/");
  14024. ASSERT_FALSE(res);
  14025. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14026. }
  14027. // A custom store set via the native handle must still verify a server whose
  14028. // cert it does contain.
  14029. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14030. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14031. ASSERT_TRUE(svr.is_valid());
  14032. svr.Get("/test", [&](const Request &, Response &res) {
  14033. res.set_content("test", "text/plain");
  14034. });
  14035. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14036. auto se = detail::scope_exit([&] {
  14037. svr.stop();
  14038. t.join();
  14039. ASSERT_FALSE(svr.is_running());
  14040. });
  14041. svr.wait_until_ready();
  14042. SSLClient cli("127.0.0.1", PORT);
  14043. std::string cert;
  14044. read_file(SERVER_CERT2_FILE, cert);
  14045. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14046. cli.enable_server_certificate_verification(true);
  14047. cli.set_connection_timeout(30);
  14048. auto res = cli.Get("/test");
  14049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14050. ASSERT_EQ(StatusCode::OK_200, res->status);
  14051. }
  14052. // CA certs loaded through the universal Client must be transferred to the
  14053. // client created internally for following an HTTPS redirect. Regression test:
  14054. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14055. // the CA data for redirect transfer.
  14056. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14057. auto ssl_port = PORT + 1;
  14058. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14059. ASSERT_TRUE(ssl_svr1.is_valid());
  14060. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14061. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14062. "/index");
  14063. });
  14064. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14065. ASSERT_TRUE(ssl_svr2.is_valid());
  14066. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14067. res.set_content("test", "text/plain");
  14068. });
  14069. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14070. thread t2 =
  14071. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14072. auto se = detail::scope_exit([&] {
  14073. ssl_svr2.stop();
  14074. ssl_svr1.stop();
  14075. t2.join();
  14076. t.join();
  14077. ASSERT_FALSE(ssl_svr1.is_running());
  14078. });
  14079. ssl_svr1.wait_until_ready();
  14080. ssl_svr2.wait_until_ready();
  14081. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14082. std::string cert;
  14083. read_file(SERVER_CERT2_FILE, cert);
  14084. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14085. cli.enable_server_certificate_verification(true);
  14086. cli.set_follow_location(true);
  14087. cli.set_connection_timeout(30);
  14088. auto res = cli.Get("/index");
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. ASSERT_EQ(StatusCode::OK_200, res->status);
  14091. }
  14092. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14093. // so a host signed by a system CA verifies even though a custom CA is set
  14094. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14095. std::string cert;
  14096. read_file(SERVER_CERT2_FILE, cert);
  14097. SSLClient cli("google.com");
  14098. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14099. cli.enable_system_ca(true);
  14100. cli.enable_server_certificate_verification(true);
  14101. auto res = cli.Get("/");
  14102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14103. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14104. }
  14105. // The custom CA remains effective when combined with the system CA
  14106. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14107. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14108. ASSERT_TRUE(svr.is_valid());
  14109. svr.Get("/test", [&](const Request &, Response &res) {
  14110. res.set_content("test", "text/plain");
  14111. });
  14112. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14113. auto se = detail::scope_exit([&] {
  14114. svr.stop();
  14115. t.join();
  14116. ASSERT_FALSE(svr.is_running());
  14117. });
  14118. svr.wait_until_ready();
  14119. SSLClient cli("127.0.0.1", PORT);
  14120. std::string cert;
  14121. read_file(SERVER_CERT2_FILE, cert);
  14122. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14123. cli.enable_system_ca(true);
  14124. cli.enable_server_certificate_verification(true);
  14125. cli.set_connection_timeout(30);
  14126. auto res = cli.Get("/test");
  14127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14128. ASSERT_EQ(StatusCode::OK_200, res->status);
  14129. }
  14130. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14131. // skip chain verification entirely (only the certificate identity was
  14132. // checked), so a server presenting an untrusted certificate with a matching
  14133. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14134. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14135. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14136. ASSERT_TRUE(svr.is_valid());
  14137. svr.Get("/test", [&](const Request &, Response &res) {
  14138. res.set_content("test", "text/plain");
  14139. });
  14140. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14141. auto se = detail::scope_exit([&] {
  14142. svr.stop();
  14143. t.join();
  14144. ASSERT_FALSE(svr.is_running());
  14145. });
  14146. svr.wait_until_ready();
  14147. SSLClient cli("127.0.0.1", PORT);
  14148. std::string cert;
  14149. // A trusted CA that did not sign the server certificate. The server cert
  14150. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14151. // this connection.
  14152. read_file(CLIENT_CA_CERT_FILE, cert);
  14153. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14154. cli.enable_server_certificate_verification(true);
  14155. cli.set_connection_timeout(30);
  14156. auto res = cli.Get("/test");
  14157. ASSERT_FALSE(res);
  14158. }
  14159. // enable_system_ca(false) prevents system CA loading entirely
  14160. TEST(SSLClientTest, DisableSystemCa_Online) {
  14161. SSLClient cli("google.com");
  14162. cli.enable_system_ca(false);
  14163. cli.enable_server_certificate_verification(true);
  14164. auto res = cli.Get("/");
  14165. ASSERT_FALSE(res);
  14166. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14167. // itself when the CA chain is empty
  14168. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14169. res.error() == Error::SSLConnection);
  14170. }
  14171. // The universal Client forwards enable_system_ca()
  14172. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14173. std::string cert;
  14174. read_file(SERVER_CERT2_FILE, cert);
  14175. Client cli("https://google.com");
  14176. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14177. cli.enable_system_ca(true);
  14178. cli.enable_server_certificate_verification(true);
  14179. auto res = cli.Get("/");
  14180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14181. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14182. }
  14183. // The system CA policy must carry over to the client created internally for
  14184. // following a cross-host HTTPS redirect
  14185. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14186. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14187. ASSERT_TRUE(svr.is_valid());
  14188. svr.Get("/index", [&](const Request &, Response &res) {
  14189. res.set_redirect("https://www.google.com/");
  14190. });
  14191. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14192. auto se = detail::scope_exit([&] {
  14193. svr.stop();
  14194. t.join();
  14195. ASSERT_FALSE(svr.is_running());
  14196. });
  14197. svr.wait_until_ready();
  14198. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14199. std::string cert;
  14200. read_file(SERVER_CERT2_FILE, cert);
  14201. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14202. cli.enable_system_ca(true);
  14203. cli.enable_server_certificate_verification(true);
  14204. cli.set_follow_location(true);
  14205. cli.set_connection_timeout(30);
  14206. // Receiving any response proves the redirect client completed the TLS
  14207. // handshake with a system-CA-signed host
  14208. auto res = cli.Get("/index");
  14209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14210. }
  14211. TEST(MultipartFormDataTest, LargeData) {
  14212. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14213. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14214. const ContentReader &content_reader) {
  14215. if (req.is_multipart_form_data()) {
  14216. std::vector<FormData> items;
  14217. content_reader(
  14218. [&](const FormData &file) {
  14219. items.push_back(file);
  14220. return true;
  14221. },
  14222. [&](const char *data, size_t data_length) {
  14223. items.back().content.append(data, data_length);
  14224. return true;
  14225. });
  14226. EXPECT_TRUE(std::string(items[0].name) == "document");
  14227. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14228. EXPECT_TRUE(items[0].filename == "2MB_data");
  14229. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14230. EXPECT_TRUE(items[1].name == "hello");
  14231. EXPECT_TRUE(items[1].content == "world");
  14232. EXPECT_TRUE(items[1].filename == "");
  14233. EXPECT_TRUE(items[1].content_type == "");
  14234. } else {
  14235. std::string body;
  14236. content_reader([&](const char *data, size_t data_length) {
  14237. body.append(data, data_length);
  14238. return true;
  14239. });
  14240. }
  14241. });
  14242. auto port = svr.bind_to_any_port(HOST);
  14243. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14244. auto se = detail::scope_exit([&] {
  14245. svr.stop();
  14246. t.join();
  14247. ASSERT_FALSE(svr.is_running());
  14248. });
  14249. svr.wait_until_ready();
  14250. {
  14251. std::string data(1024 * 1024 * 2, '.');
  14252. std::stringstream buffer;
  14253. buffer << data;
  14254. SSLClient cli(HOST, port);
  14255. cli.enable_server_certificate_verification(false);
  14256. UploadFormDataItems items{
  14257. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14258. {"hello", "world", "", ""},
  14259. };
  14260. auto res = cli.Post("/post", items);
  14261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14262. ASSERT_EQ(StatusCode::OK_200, res->status);
  14263. }
  14264. }
  14265. TEST(MultipartFormDataTest, DataProviderItems) {
  14266. std::random_device seed_gen;
  14267. std::mt19937 random(seed_gen());
  14268. std::string rand1;
  14269. rand1.resize(1000);
  14270. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14271. std::string rand2;
  14272. rand2.resize(3000);
  14273. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14274. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14275. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14276. const ContentReader &content_reader) {
  14277. ASSERT_FALSE(req.is_multipart_form_data());
  14278. std::string body;
  14279. content_reader([&](const char *data, size_t data_length) {
  14280. body.append(data, data_length);
  14281. return true;
  14282. });
  14283. EXPECT_EQ(body, "");
  14284. });
  14285. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14286. const ContentReader &content_reader) {
  14287. ASSERT_TRUE(req.is_multipart_form_data());
  14288. std::vector<FormData> items;
  14289. content_reader(
  14290. [&](const FormData &file) {
  14291. items.push_back(file);
  14292. return true;
  14293. },
  14294. [&](const char *data, size_t data_length) {
  14295. items.back().content.append(data, data_length);
  14296. return true;
  14297. });
  14298. ASSERT_TRUE(items.size() == 2);
  14299. EXPECT_EQ(std::string(items[0].name), "name1");
  14300. EXPECT_EQ(items[0].content, "Testing123");
  14301. EXPECT_EQ(items[0].filename, "filename1");
  14302. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14303. EXPECT_EQ(items[1].name, "name2");
  14304. EXPECT_EQ(items[1].content, "Testing456");
  14305. EXPECT_EQ(items[1].filename, "");
  14306. EXPECT_EQ(items[1].content_type, "");
  14307. });
  14308. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14309. const ContentReader &content_reader) {
  14310. ASSERT_TRUE(req.is_multipart_form_data());
  14311. std::vector<FormData> items;
  14312. content_reader(
  14313. [&](const FormData &file) {
  14314. items.push_back(file);
  14315. return true;
  14316. },
  14317. [&](const char *data, size_t data_length) {
  14318. items.back().content.append(data, data_length);
  14319. return true;
  14320. });
  14321. ASSERT_TRUE(items.size() == 2);
  14322. EXPECT_EQ(items[0].name, "name3");
  14323. EXPECT_EQ(items[0].content, rand1);
  14324. EXPECT_EQ(items[0].filename, "filename3");
  14325. EXPECT_EQ(items[0].content_type, "");
  14326. EXPECT_EQ(items[1].name, "name4");
  14327. EXPECT_EQ(items[1].content, rand2);
  14328. EXPECT_EQ(items[1].filename, "filename4");
  14329. EXPECT_EQ(items[1].content_type, "");
  14330. });
  14331. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14332. const ContentReader &content_reader) {
  14333. ASSERT_TRUE(req.is_multipart_form_data());
  14334. std::vector<FormData> items;
  14335. content_reader(
  14336. [&](const FormData &file) {
  14337. items.push_back(file);
  14338. return true;
  14339. },
  14340. [&](const char *data, size_t data_length) {
  14341. items.back().content.append(data, data_length);
  14342. return true;
  14343. });
  14344. ASSERT_TRUE(items.size() == 4);
  14345. EXPECT_EQ(std::string(items[0].name), "name1");
  14346. EXPECT_EQ(items[0].content, "Testing123");
  14347. EXPECT_EQ(items[0].filename, "filename1");
  14348. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14349. EXPECT_EQ(items[1].name, "name2");
  14350. EXPECT_EQ(items[1].content, "Testing456");
  14351. EXPECT_EQ(items[1].filename, "");
  14352. EXPECT_EQ(items[1].content_type, "");
  14353. EXPECT_EQ(items[2].name, "name3");
  14354. EXPECT_EQ(items[2].content, rand1);
  14355. EXPECT_EQ(items[2].filename, "filename3");
  14356. EXPECT_EQ(items[2].content_type, "");
  14357. EXPECT_EQ(items[3].name, "name4");
  14358. EXPECT_EQ(items[3].content, rand2);
  14359. EXPECT_EQ(items[3].filename, "filename4");
  14360. EXPECT_EQ(items[3].content_type, "");
  14361. });
  14362. auto port = svr.bind_to_any_port("localhost");
  14363. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14364. auto se = detail::scope_exit([&] {
  14365. svr.stop();
  14366. t.join();
  14367. ASSERT_FALSE(svr.is_running());
  14368. });
  14369. svr.wait_until_ready();
  14370. {
  14371. SSLClient cli("localhost", port);
  14372. cli.enable_server_certificate_verification(false);
  14373. UploadFormDataItems items{
  14374. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14375. {"name2", "Testing456", "", ""}, // not a file
  14376. };
  14377. {
  14378. auto res = cli.Post("/post-none", {}, {}, {});
  14379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14380. ASSERT_EQ(StatusCode::OK_200, res->status);
  14381. }
  14382. FormDataProviderItems providers;
  14383. {
  14384. auto res =
  14385. cli.Post("/post-items", {}, items, providers); // empty providers
  14386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14387. ASSERT_EQ(StatusCode::OK_200, res->status);
  14388. }
  14389. providers.push_back({"name3",
  14390. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14391. // test the offset is given correctly at each step
  14392. if (!offset)
  14393. sink.os.write(rand1.data(), 30);
  14394. else if (offset == 30)
  14395. sink.os.write(rand1.data() + 30, 300);
  14396. else if (offset == 330)
  14397. sink.os.write(rand1.data() + 330, 670);
  14398. else if (offset == rand1.size())
  14399. sink.done();
  14400. return true;
  14401. },
  14402. "filename3",
  14403. {}});
  14404. providers.push_back({"name4",
  14405. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14406. // test the offset is given correctly at each step
  14407. if (!offset)
  14408. sink.os.write(rand2.data(), 2000);
  14409. else if (offset == 2000)
  14410. sink.os.write(rand2.data() + 2000, 1);
  14411. else if (offset == 2001)
  14412. sink.os.write(rand2.data() + 2001, 999);
  14413. else if (offset == rand2.size())
  14414. sink.done();
  14415. return true;
  14416. },
  14417. "filename4",
  14418. {}});
  14419. {
  14420. auto res = cli.Post("/post-providers", {}, {}, providers);
  14421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14422. ASSERT_EQ(StatusCode::OK_200, res->status);
  14423. }
  14424. {
  14425. auto res = cli.Post("/post-both", {}, items, providers);
  14426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14427. ASSERT_EQ(StatusCode::OK_200, res->status);
  14428. }
  14429. }
  14430. }
  14431. TEST(MultipartFormDataTest, BadHeader) {
  14432. Server svr;
  14433. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14434. res.set_content("ok", "text/plain");
  14435. });
  14436. thread t = thread([&] { svr.listen(HOST, PORT); });
  14437. auto se = detail::scope_exit([&] {
  14438. svr.stop();
  14439. t.join();
  14440. ASSERT_FALSE(svr.is_running());
  14441. });
  14442. svr.wait_until_ready();
  14443. const std::string body =
  14444. "This is the preamble. It is to be ignored, though it\r\n"
  14445. "is a handy place for composition agents to include an\r\n"
  14446. "explanatory note to non-MIME conformant readers.\r\n"
  14447. "\r\n"
  14448. "\r\n"
  14449. "--simple boundary\r\n"
  14450. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14451. ": BAD...\r\n"
  14452. "\r\n"
  14453. "value1\r\n"
  14454. "--simple boundary\r\n"
  14455. "Content-Disposition: form-data; name=\"field2\"; "
  14456. "filename=\"example.txt\"\r\n"
  14457. "\r\n"
  14458. "value2\r\n"
  14459. "--simple boundary--\r\n"
  14460. "This is the epilogue. It is also to be ignored.\r\n";
  14461. std::string content_type =
  14462. R"(multipart/form-data; boundary="simple boundary")";
  14463. Client cli(HOST, PORT);
  14464. auto res = cli.Post("/post", body, content_type.c_str());
  14465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14466. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14467. }
  14468. TEST(MultipartFormDataTest, WithPreamble) {
  14469. Server svr;
  14470. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14471. res.set_content("ok", "text/plain");
  14472. });
  14473. thread t = thread([&] { svr.listen(HOST, PORT); });
  14474. auto se = detail::scope_exit([&] {
  14475. svr.stop();
  14476. t.join();
  14477. ASSERT_FALSE(svr.is_running());
  14478. });
  14479. svr.wait_until_ready();
  14480. const std::string body =
  14481. "This is the preamble. It is to be ignored, though it\r\n"
  14482. "is a handy place for composition agents to include an\r\n"
  14483. "explanatory note to non-MIME conformant readers.\r\n"
  14484. "\r\n"
  14485. "\r\n"
  14486. "--simple boundary\r\n"
  14487. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14488. "\r\n"
  14489. "value1\r\n"
  14490. "--simple boundary\r\n"
  14491. "Content-Disposition: form-data; name=\"field2\"; "
  14492. "filename=\"example.txt\"\r\n"
  14493. "\r\n"
  14494. "value2\r\n"
  14495. "--simple boundary--\r\n"
  14496. "This is the epilogue. It is also to be ignored.\r\n";
  14497. std::string content_type =
  14498. R"(multipart/form-data; boundary="simple boundary")";
  14499. Client cli(HOST, PORT);
  14500. auto res = cli.Post("/post", body, content_type.c_str());
  14501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14502. EXPECT_EQ(StatusCode::OK_200, res->status);
  14503. }
  14504. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14505. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14506. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14507. const ContentReader &content_reader) {
  14508. if (req.is_multipart_form_data()) {
  14509. std::vector<FormData> items;
  14510. content_reader(
  14511. [&](const FormData &file) {
  14512. items.push_back(file);
  14513. return true;
  14514. },
  14515. [&](const char *data, size_t data_length) {
  14516. items.back().content.append(data, data_length);
  14517. return true;
  14518. });
  14519. EXPECT_TRUE(std::string(items[0].name) == "document");
  14520. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14521. EXPECT_TRUE(items[0].filename == "2MB_data");
  14522. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14523. EXPECT_TRUE(items[1].name == "hello");
  14524. EXPECT_TRUE(items[1].content == "world");
  14525. EXPECT_TRUE(items[1].filename == "");
  14526. EXPECT_TRUE(items[1].content_type == "");
  14527. } else {
  14528. std::string body;
  14529. content_reader([&](const char *data, size_t data_length) {
  14530. body.append(data, data_length);
  14531. return true;
  14532. });
  14533. }
  14534. });
  14535. auto port = svr.bind_to_any_port("localhost");
  14536. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14537. auto se = detail::scope_exit([&] {
  14538. svr.stop();
  14539. t.join();
  14540. ASSERT_FALSE(svr.is_running());
  14541. });
  14542. svr.wait_until_ready();
  14543. {
  14544. std::string data(1024 * 1024 * 2, '.');
  14545. std::stringstream buffer;
  14546. buffer << data;
  14547. SSLClient cli("localhost", port);
  14548. cli.enable_server_certificate_verification(false);
  14549. UploadFormDataItems items{
  14550. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14551. {"hello", "world", "", ""},
  14552. };
  14553. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14555. ASSERT_EQ(StatusCode::OK_200, res->status);
  14556. }
  14557. }
  14558. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14559. std::string data(1024 * 1024 * 2, '&');
  14560. std::stringstream buffer;
  14561. buffer << data;
  14562. Client cli("https://localhost:8080");
  14563. UploadFormDataItems items{
  14564. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14565. {"hello", "world", "", ""},
  14566. };
  14567. for (const char &c : " \t\r\n") {
  14568. auto res =
  14569. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14570. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14571. ASSERT_FALSE(res);
  14572. }
  14573. }
  14574. TEST(MultipartFormDataTest, PutFormData) {
  14575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14576. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14577. const ContentReader &content_reader) {
  14578. if (req.is_multipart_form_data()) {
  14579. std::vector<FormData> items;
  14580. content_reader(
  14581. [&](const FormData &file) {
  14582. items.push_back(file);
  14583. return true;
  14584. },
  14585. [&](const char *data, size_t data_length) {
  14586. items.back().content.append(data, data_length);
  14587. return true;
  14588. });
  14589. EXPECT_TRUE(std::string(items[0].name) == "document");
  14590. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14591. EXPECT_TRUE(items[0].filename == "2MB_data");
  14592. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14593. EXPECT_TRUE(items[1].name == "hello");
  14594. EXPECT_TRUE(items[1].content == "world");
  14595. EXPECT_TRUE(items[1].filename == "");
  14596. EXPECT_TRUE(items[1].content_type == "");
  14597. } else {
  14598. std::string body;
  14599. content_reader([&](const char *data, size_t data_length) {
  14600. body.append(data, data_length);
  14601. return true;
  14602. });
  14603. }
  14604. });
  14605. auto port = svr.bind_to_any_port("localhost");
  14606. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14607. auto se = detail::scope_exit([&] {
  14608. svr.stop();
  14609. t.join();
  14610. ASSERT_FALSE(svr.is_running());
  14611. });
  14612. svr.wait_until_ready();
  14613. {
  14614. std::string data(1024 * 1024 * 2, '&');
  14615. std::stringstream buffer;
  14616. buffer << data;
  14617. SSLClient cli("localhost", port);
  14618. cli.enable_server_certificate_verification(false);
  14619. UploadFormDataItems items{
  14620. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14621. {"hello", "world", "", ""},
  14622. };
  14623. auto res = cli.Put("/put", items);
  14624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14625. ASSERT_EQ(StatusCode::OK_200, res->status);
  14626. }
  14627. }
  14628. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14630. svr.Put("/put_customboundary",
  14631. [&](const Request &req, const Response & /*res*/,
  14632. const ContentReader &content_reader) {
  14633. if (req.is_multipart_form_data()) {
  14634. std::vector<FormData> items;
  14635. content_reader(
  14636. [&](const FormData &file) {
  14637. items.push_back(file);
  14638. return true;
  14639. },
  14640. [&](const char *data, size_t data_length) {
  14641. items.back().content.append(data, data_length);
  14642. return true;
  14643. });
  14644. EXPECT_TRUE(std::string(items[0].name) == "document");
  14645. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14646. EXPECT_TRUE(items[0].filename == "2MB_data");
  14647. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14648. EXPECT_TRUE(items[1].name == "hello");
  14649. EXPECT_TRUE(items[1].content == "world");
  14650. EXPECT_TRUE(items[1].filename == "");
  14651. EXPECT_TRUE(items[1].content_type == "");
  14652. } else {
  14653. std::string body;
  14654. content_reader([&](const char *data, size_t data_length) {
  14655. body.append(data, data_length);
  14656. return true;
  14657. });
  14658. }
  14659. });
  14660. auto port = svr.bind_to_any_port("localhost");
  14661. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14662. auto se = detail::scope_exit([&] {
  14663. svr.stop();
  14664. t.join();
  14665. ASSERT_FALSE(svr.is_running());
  14666. });
  14667. svr.wait_until_ready();
  14668. {
  14669. std::string data(1024 * 1024 * 2, '&');
  14670. std::stringstream buffer;
  14671. buffer << data;
  14672. SSLClient cli("localhost", port);
  14673. cli.enable_server_certificate_verification(false);
  14674. UploadFormDataItems items{
  14675. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14676. {"hello", "world", "", ""},
  14677. };
  14678. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14680. ASSERT_EQ(StatusCode::OK_200, res->status);
  14681. }
  14682. }
  14683. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14684. std::string data(1024 * 1024 * 2, '&');
  14685. std::stringstream buffer;
  14686. buffer << data;
  14687. Client cli("https://localhost:8080");
  14688. cli.enable_server_certificate_verification(false);
  14689. UploadFormDataItems items{
  14690. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14691. {"hello", "world", "", ""},
  14692. };
  14693. for (const char &c : " \t\r\n") {
  14694. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14695. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14696. ASSERT_FALSE(res);
  14697. }
  14698. }
  14699. TEST(MultipartFormDataTest, AlternateFilename) {
  14700. auto handled = false;
  14701. Server svr;
  14702. svr.Post("/test", [&](const Request &req, Response &res) {
  14703. ASSERT_EQ(2u, req.form.files.size());
  14704. ASSERT_EQ(1u, req.form.fields.size());
  14705. // Test files
  14706. const auto &file1 = req.form.get_file("file1");
  14707. ASSERT_EQ("file1", file1.name);
  14708. ASSERT_EQ("A.txt", file1.filename);
  14709. ASSERT_EQ("text/plain", file1.content_type);
  14710. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14711. const auto &file2 = req.form.get_file("file2");
  14712. ASSERT_EQ("file2", file2.name);
  14713. ASSERT_EQ("a.html", file2.filename);
  14714. ASSERT_EQ("text/html", file2.content_type);
  14715. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14716. file2.content);
  14717. // Test text field
  14718. const auto &text = req.form.get_field("text");
  14719. ASSERT_EQ("text default", text);
  14720. res.set_content("ok", "text/plain");
  14721. handled = true;
  14722. });
  14723. thread t = thread([&] { svr.listen(HOST, PORT); });
  14724. auto se = detail::scope_exit([&] {
  14725. svr.stop();
  14726. t.join();
  14727. ASSERT_FALSE(svr.is_running());
  14728. ASSERT_TRUE(handled);
  14729. });
  14730. svr.wait_until_ready();
  14731. auto req = "POST /test HTTP/1.1\r\n"
  14732. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14733. "Content-Length: 399\r\n"
  14734. "\r\n"
  14735. "----------\r\n"
  14736. "Content-Disposition: form-data; name=\"text\"\r\n"
  14737. "\r\n"
  14738. "text default\r\n"
  14739. "----------\r\n"
  14740. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14741. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14742. "Content-Type: text/plain\r\n"
  14743. "\r\n"
  14744. "Content of a.txt.\r\n"
  14745. "\r\n"
  14746. "----------\r\n"
  14747. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14748. "\"a.html\"\r\n"
  14749. "Content-Type: text/html\r\n"
  14750. "\r\n"
  14751. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14752. "\r\n"
  14753. "------------\r\n";
  14754. ASSERT_TRUE(send_request(1, req));
  14755. }
  14756. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14757. auto handled = false;
  14758. Server svr;
  14759. svr.Post("/test", [&](const Request &req, Response &res) {
  14760. // Case-insensitive "utf-8''" prefix with a long value
  14761. const auto &file = req.form.get_file("file1");
  14762. ASSERT_EQ("file1", file.name);
  14763. // 8000 chars exercises both the Content-Disposition parser and the
  14764. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14765. // Prior to the fix, std::regex_match on this header would cause O(N)
  14766. // stack recursion in libstdc++, leading to SIGSEGV.
  14767. std::string expected_filename(8000, 'A');
  14768. ASSERT_EQ(expected_filename, file.filename);
  14769. res.set_content("ok", "text/plain");
  14770. handled = true;
  14771. });
  14772. thread t = thread([&] { svr.listen(HOST, PORT); });
  14773. auto se = detail::scope_exit([&] {
  14774. svr.stop();
  14775. t.join();
  14776. ASSERT_FALSE(svr.is_running());
  14777. ASSERT_TRUE(handled);
  14778. });
  14779. svr.wait_until_ready();
  14780. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14781. // Regression test for GHSA-qq6v-r583-3h69
  14782. std::string long_filename(8000, 'A');
  14783. std::string body = "----------\r\n"
  14784. "Content-Disposition: form-data; name=\"file1\"; "
  14785. "filename*=\"Utf-8''" +
  14786. long_filename +
  14787. "\"\r\n"
  14788. "\r\n"
  14789. "hello\r\n"
  14790. "------------\r\n";
  14791. auto req = "POST /test HTTP/1.1\r\n"
  14792. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14793. "Content-Length: " +
  14794. std::to_string(body.size()) + "\r\n\r\n" + body;
  14795. ASSERT_TRUE(send_request(1, req));
  14796. }
  14797. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14798. auto handled = false;
  14799. Server svr;
  14800. svr.Post("/test", [&](const Request &req, Response &) {
  14801. ASSERT_EQ(2u, req.form.fields.size());
  14802. const auto &text1 = req.form.get_field("text1");
  14803. ASSERT_EQ("text1", text1);
  14804. const auto &text2 = req.form.get_field("text2");
  14805. ASSERT_EQ("text2", text2);
  14806. handled = true;
  14807. });
  14808. thread t = thread([&] { svr.listen(HOST, PORT); });
  14809. auto se = detail::scope_exit([&] {
  14810. svr.stop();
  14811. t.join();
  14812. ASSERT_FALSE(svr.is_running());
  14813. ASSERT_TRUE(handled);
  14814. });
  14815. svr.wait_until_ready();
  14816. auto req = "POST /test HTTP/1.1\r\n"
  14817. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14818. "Content-Length: 146\r\n"
  14819. "\r\n----------\r\n"
  14820. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14821. "\r\n"
  14822. "text1"
  14823. "\r\n----------\r\n"
  14824. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14825. "\r\n"
  14826. "text2"
  14827. "\r\n------------";
  14828. std::string response;
  14829. ASSERT_TRUE(send_request(1, req, &response));
  14830. ASSERT_EQ("200", response.substr(9, 3));
  14831. }
  14832. TEST(MultipartFormDataTest, ContentLength) {
  14833. auto handled = false;
  14834. Server svr;
  14835. svr.Post("/test", [&](const Request &req, Response &) {
  14836. ASSERT_EQ(2u, req.form.fields.size());
  14837. const auto &text1 = req.form.get_field("text1");
  14838. ASSERT_EQ("text1", text1);
  14839. const auto &text2 = req.form.get_field("text2");
  14840. ASSERT_EQ("text2", text2);
  14841. handled = true;
  14842. });
  14843. thread t = thread([&] { svr.listen(HOST, PORT); });
  14844. auto se = detail::scope_exit([&] {
  14845. svr.stop();
  14846. t.join();
  14847. ASSERT_FALSE(svr.is_running());
  14848. ASSERT_TRUE(handled);
  14849. });
  14850. svr.wait_until_ready();
  14851. auto req = "POST /test HTTP/1.1\r\n"
  14852. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14853. "Content-Length: 167\r\n"
  14854. "\r\n----------\r\n"
  14855. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14856. "Content-Length: 5\r\n"
  14857. "\r\n"
  14858. "text1"
  14859. "\r\n----------\r\n"
  14860. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14861. "\r\n"
  14862. "text2"
  14863. "\r\n------------\r\n";
  14864. std::string response;
  14865. ASSERT_TRUE(send_request(1, req, &response));
  14866. ASSERT_EQ("200", response.substr(9, 3));
  14867. }
  14868. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14869. auto handled = false;
  14870. Server svr;
  14871. svr.Post("/test", [&](const Request &req, Response &) {
  14872. ASSERT_EQ(2u, req.form.fields.size());
  14873. const auto &text1 = req.form.get_field("text1");
  14874. ASSERT_EQ("text1", text1);
  14875. // TODO: Add header access for text fields if needed
  14876. const auto &text2 = req.form.get_field("text2");
  14877. ASSERT_EQ("text2", text2);
  14878. // TODO: Header access for text fields needs to be implemented
  14879. // auto &headers = it->second.headers;
  14880. // ASSERT_EQ(3U, headers.size());
  14881. // auto custom_header = headers.find("x-whatever");
  14882. // ASSERT_TRUE(custom_header != headers.end());
  14883. // ASSERT_NE("customvalue", custom_header->second);
  14884. // ASSERT_EQ("CustomValue", custom_header->second);
  14885. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14886. handled = true;
  14887. });
  14888. thread t = thread([&] { svr.listen(HOST, PORT); });
  14889. auto se = detail::scope_exit([&] {
  14890. svr.stop();
  14891. t.join();
  14892. ASSERT_FALSE(svr.is_running());
  14893. ASSERT_TRUE(handled);
  14894. });
  14895. svr.wait_until_ready();
  14896. auto req = "POST /test HTTP/1.1\r\n"
  14897. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14898. "Content-Length: 232\r\n"
  14899. "\r\n----------\r\n"
  14900. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14901. "Content-Length: 5\r\n"
  14902. "X-Test: 1\r\n"
  14903. "\r\n"
  14904. "text1"
  14905. "\r\n----------\r\n"
  14906. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14907. "Content-Type: text/plain\r\n"
  14908. "X-Whatever: CustomValue\r\n"
  14909. "\r\n"
  14910. "text2"
  14911. "\r\n------------\r\n"
  14912. "That should be disregarded. Not even read";
  14913. std::string response;
  14914. ASSERT_TRUE(send_request(1, req, &response));
  14915. ASSERT_EQ("200", response.substr(9, 3));
  14916. }
  14917. TEST(MultipartFormDataTest, LargeHeader) {
  14918. auto handled = false;
  14919. Server svr;
  14920. svr.Post("/test", [&](const Request &req, Response &) {
  14921. ASSERT_EQ(1u, req.form.fields.size());
  14922. const auto &text = req.form.get_field("name1");
  14923. ASSERT_EQ("text1", text);
  14924. handled = true;
  14925. });
  14926. thread t = thread([&] { svr.listen(HOST, PORT); });
  14927. auto se = detail::scope_exit([&] {
  14928. svr.stop();
  14929. t.join();
  14930. ASSERT_FALSE(svr.is_running());
  14931. ASSERT_TRUE(handled);
  14932. });
  14933. svr.wait_until_ready();
  14934. auto boundary = std::string("cpp-httplib-multipart-data");
  14935. std::string content = "--" + boundary +
  14936. "\r\n"
  14937. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14938. "\r\n"
  14939. "text1\r\n"
  14940. "--" +
  14941. boundary + "--\r\n";
  14942. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14943. "Content-Type: multipart/form-data;boundary=" +
  14944. boundary +
  14945. "\r\n"
  14946. "Content-Length: " +
  14947. std::to_string(content.size()) +
  14948. "\r\n"
  14949. "Dummy-Header: ";
  14950. std::string header_suffix = "\r\n"
  14951. "\r\n";
  14952. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14953. size_t header_dummy_size =
  14954. read_buff_size -
  14955. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14956. auto header_dummy = std::string(header_dummy_size, '@');
  14957. auto req = header_prefix + header_dummy + header_suffix + content;
  14958. std::string response;
  14959. ASSERT_TRUE(send_request(1, req, &response));
  14960. ASSERT_EQ("200", response.substr(9, 3));
  14961. }
  14962. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14963. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14964. // (not chunked Transfer-Encoding) after the streaming refactor.
  14965. auto handled = false;
  14966. Server svr;
  14967. svr.Post("/upload", [&](const Request &req, Response &res) {
  14968. auto cl_it = req.headers.find("Content-Length");
  14969. EXPECT_TRUE(cl_it != req.headers.end());
  14970. auto te_it = req.headers.find("Transfer-Encoding");
  14971. EXPECT_TRUE(te_it == req.headers.end());
  14972. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14973. res.set_content("ok", "text/plain");
  14974. handled = true;
  14975. });
  14976. auto port = svr.bind_to_any_port(HOST);
  14977. auto t = thread([&] { svr.listen_after_bind(); });
  14978. auto se = detail::scope_exit([&] {
  14979. svr.stop();
  14980. t.join();
  14981. ASSERT_FALSE(svr.is_running());
  14982. ASSERT_TRUE(handled);
  14983. });
  14984. svr.wait_until_ready();
  14985. UploadFormDataItems items = {
  14986. {"field1", "hello", "", "text/plain"},
  14987. {"file1", "world", "test.txt", "application/octet-stream"},
  14988. };
  14989. Client cli(HOST, port);
  14990. auto res = cli.Post("/upload", {}, items);
  14991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14992. EXPECT_EQ(StatusCode::OK_200, res->status);
  14993. }
  14994. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14995. // Verify that make_multipart_content_provider coalesces many small segments
  14996. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14997. constexpr size_t kItemCount = 1000;
  14998. UploadFormDataItems items;
  14999. items.reserve(kItemCount);
  15000. for (size_t i = 0; i < kItemCount; i++) {
  15001. items.push_back(
  15002. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15003. }
  15004. const std::string boundary = "----test-boundary";
  15005. auto content_length = detail::get_multipart_content_length(items, boundary);
  15006. auto provider = detail::make_multipart_content_provider(items, boundary);
  15007. // Drive the provider the same way write_content_with_progress does
  15008. size_t write_count = 0;
  15009. size_t total_bytes = 0;
  15010. DataSink sink;
  15011. size_t offset = 0;
  15012. sink.write = [&](const char *d, size_t l) -> bool {
  15013. (void)d;
  15014. write_count++;
  15015. total_bytes += l;
  15016. offset += l;
  15017. return true;
  15018. };
  15019. sink.is_writable = []() -> bool { return true; };
  15020. while (offset < content_length) {
  15021. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15022. }
  15023. EXPECT_EQ(content_length, total_bytes);
  15024. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15025. // With buffering into 64KB blocks, write_count should be much smaller.
  15026. auto segment_count = 3 * kItemCount + 1;
  15027. EXPECT_LT(write_count, segment_count / 10);
  15028. }
  15029. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15030. // Integration test: send many UploadFormDataItems and verify the server
  15031. // receives all of them correctly (#2410).
  15032. constexpr size_t kItemCount = 500;
  15033. auto handled = false;
  15034. Server svr;
  15035. svr.Post("/upload", [&](const Request &req, Response &res) {
  15036. EXPECT_EQ(kItemCount, req.form.fields.size());
  15037. for (size_t i = 0; i < kItemCount; i++) {
  15038. auto key = "field" + std::to_string(i);
  15039. auto val = "value" + std::to_string(i);
  15040. auto it = req.form.fields.find(key);
  15041. if (it != req.form.fields.end()) {
  15042. EXPECT_EQ(val, it->second.content);
  15043. } else {
  15044. ADD_FAILURE() << "Missing field: " << key;
  15045. }
  15046. }
  15047. res.set_content("ok", "text/plain");
  15048. handled = true;
  15049. });
  15050. auto port = svr.bind_to_any_port(HOST);
  15051. auto t = thread([&] { svr.listen_after_bind(); });
  15052. auto se = detail::scope_exit([&] {
  15053. svr.stop();
  15054. t.join();
  15055. ASSERT_FALSE(svr.is_running());
  15056. ASSERT_TRUE(handled);
  15057. });
  15058. svr.wait_until_ready();
  15059. UploadFormDataItems items;
  15060. items.reserve(kItemCount);
  15061. for (size_t i = 0; i < kItemCount; i++) {
  15062. items.push_back(
  15063. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15064. }
  15065. Client cli(HOST, port);
  15066. auto res = cli.Post("/upload", items);
  15067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15068. EXPECT_EQ(StatusCode::OK_200, res->status);
  15069. }
  15070. TEST(MultipartFormDataTest, MakeFileProvider) {
  15071. // Verify make_file_provider sends a file's contents correctly.
  15072. const std::string file_content(4096, 'Z');
  15073. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15074. {
  15075. std::ofstream ofs(tmp_path, std::ios::binary);
  15076. ofs.write(file_content.data(),
  15077. static_cast<std::streamsize>(file_content.size()));
  15078. }
  15079. auto handled = false;
  15080. Server svr;
  15081. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15082. const ContentReader &content_reader) {
  15083. ASSERT_TRUE(req.is_multipart_form_data());
  15084. std::vector<FormData> items;
  15085. content_reader(
  15086. [&](const FormData &file) {
  15087. items.push_back(file);
  15088. return true;
  15089. },
  15090. [&](const char *data, size_t data_length) {
  15091. items.back().content.append(data, data_length);
  15092. return true;
  15093. });
  15094. ASSERT_EQ(1u, items.size());
  15095. EXPECT_EQ("myfile", items[0].name);
  15096. EXPECT_EQ("data.bin", items[0].filename);
  15097. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15098. EXPECT_EQ(file_content, items[0].content);
  15099. handled = true;
  15100. });
  15101. auto port = svr.bind_to_any_port(HOST);
  15102. auto t = thread([&] { svr.listen_after_bind(); });
  15103. auto se = detail::scope_exit([&] {
  15104. svr.stop();
  15105. t.join();
  15106. ASSERT_FALSE(svr.is_running());
  15107. ASSERT_TRUE(handled);
  15108. std::remove(tmp_path.c_str());
  15109. });
  15110. svr.wait_until_ready();
  15111. FormDataProviderItems providers;
  15112. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15113. "application/octet-stream"));
  15114. Client cli(HOST, port);
  15115. auto res = cli.Post("/upload", {}, {}, providers);
  15116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15117. EXPECT_EQ(StatusCode::OK_200, res->status);
  15118. }
  15119. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15120. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15121. // (100) headers is rejected with a 400 Bad Request response.
  15122. Server svr;
  15123. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15124. res.set_content("ok", "text/plain");
  15125. });
  15126. thread t = thread([&] { svr.listen(HOST, PORT); });
  15127. auto se = detail::scope_exit([&] {
  15128. svr.stop();
  15129. t.join();
  15130. ASSERT_FALSE(svr.is_running());
  15131. });
  15132. svr.wait_until_ready();
  15133. // Build a multipart part with 101 custom headers (exceeding
  15134. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15135. std::stringstream body;
  15136. body << "--simpleboundary\r\n"
  15137. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15138. for (int i = 0; i < 101; i++) {
  15139. body << "X-Custom-Header-" << i << ": value\r\n";
  15140. }
  15141. body << "\r\n"
  15142. << "value1\r\n"
  15143. << "--simpleboundary--\r\n";
  15144. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15145. Client cli(HOST, PORT);
  15146. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15148. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15149. }
  15150. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15151. // A body that never contains the declared boundary must not be accumulated
  15152. // while the parser waits for it. Buffering it would also make every read
  15153. // rescan everything seen so far, which is quadratic in the body size.
  15154. Server svr;
  15155. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15156. res.set_content("ok", "text/plain");
  15157. });
  15158. auto port = svr.bind_to_any_port(HOST);
  15159. thread t = thread([&] { svr.listen_after_bind(); });
  15160. auto se = detail::scope_exit([&] {
  15161. svr.stop();
  15162. t.join();
  15163. ASSERT_FALSE(svr.is_running());
  15164. });
  15165. svr.wait_until_ready();
  15166. Client cli(HOST, port);
  15167. cli.set_read_timeout(60, 0);
  15168. cli.set_write_timeout(60, 0);
  15169. // '-' is the worst case: it matches the first character of the boundary, so
  15170. // every position has to be checked against it.
  15171. auto post_dashes = [&](size_t size) {
  15172. const std::string body(size, '-');
  15173. auto start = std::chrono::steady_clock::now();
  15174. auto res =
  15175. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15176. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15177. std::chrono::steady_clock::now() - start)
  15178. .count();
  15179. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15180. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15181. return ms;
  15182. };
  15183. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15184. // Windows.
  15185. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15186. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15187. // Comparing the two sizes rather than checking an absolute duration keeps
  15188. // this meaningful across build types and CI load, both of which move the
  15189. // absolute numbers by more than an order of magnitude. Four times the bytes
  15190. // costs about four times the time when parsing is linear, and about sixteen
  15191. // times when the body is buffered and rescanned.
  15192. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15193. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15194. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15195. << "ms, which suggests the body is being buffered and rescanned";
  15196. }
  15197. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15198. // A boundary can only be followed by CRLF or by "--", so anything else is
  15199. // malformed no matter what comes next. The parser must say so right away
  15200. // instead of buffering the rest of the declared body.
  15201. Server svr;
  15202. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15203. res.set_content("ok", "text/plain");
  15204. });
  15205. auto port = svr.bind_to_any_port(HOST);
  15206. thread t = thread([&] { svr.listen_after_bind(); });
  15207. auto se = detail::scope_exit([&] {
  15208. svr.stop();
  15209. t.join();
  15210. ASSERT_FALSE(svr.is_running());
  15211. });
  15212. svr.wait_until_ready();
  15213. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15214. // buffers instead of failing would still be waiting for the remaining bytes.
  15215. const std::string body = "--zzzz\r\n"
  15216. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15217. "\r\n"
  15218. "text1"
  15219. "\r\n--zzzzXX";
  15220. const std::string req = "POST /post HTTP/1.1\r\n"
  15221. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15222. "Content-Length: 1048576\r\n"
  15223. "\r\n" +
  15224. body;
  15225. std::string response;
  15226. ASSERT_TRUE(send_request(3, req, &response, port));
  15227. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15228. EXPECT_EQ("400", response.substr(9, 3));
  15229. }
  15230. // Posts a multipart body split into two writes, so that the server sees the
  15231. // split at whatever offset the caller chose, and expects the single "text1"
  15232. // field to come through.
  15233. static void expect_split_multipart_ok(const std::string &body1,
  15234. const std::string &body2) {
  15235. auto handled = false;
  15236. Server svr;
  15237. svr.Post("/post", [&](const Request &req, Response &) {
  15238. EXPECT_EQ(1u, req.form.fields.size());
  15239. EXPECT_EQ("text1", req.form.get_field("text1"));
  15240. handled = true;
  15241. });
  15242. auto port = svr.bind_to_any_port(HOST);
  15243. thread t = thread([&] { svr.listen_after_bind(); });
  15244. auto se = detail::scope_exit([&] {
  15245. svr.stop();
  15246. t.join();
  15247. ASSERT_FALSE(svr.is_running());
  15248. ASSERT_TRUE(handled);
  15249. });
  15250. svr.wait_until_ready();
  15251. // "Connection: close" makes the server close once it has answered, so the
  15252. // response drain ends immediately instead of idling until the read timeout.
  15253. const std::string head =
  15254. "POST /post HTTP/1.1\r\n"
  15255. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15256. "Connection: close\r\n"
  15257. "Content-Length: " +
  15258. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15259. std::string response;
  15260. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15261. ASSERT_GE(response.size(), 12u) << "no response";
  15262. EXPECT_EQ("200", response.substr(9, 3));
  15263. }
  15264. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15265. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15266. // ignored, including when it does not arrive in the same read as the
  15267. // close-delimiter itself.
  15268. expect_split_multipart_ok("--zzzz\r\n"
  15269. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15270. "\r\n"
  15271. "text1"
  15272. "\r\n--zzzz--",
  15273. "\r\nthis epilogue must be ignored\r\n");
  15274. }
  15275. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15276. // The initial boundary may be preceded by a preamble of any length and may
  15277. // straddle a read boundary. Discarding data while waiting for it must not
  15278. // throw away a partial boundary sitting at the end of the buffer.
  15279. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15280. "zz\r\n"
  15281. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15282. "\r\n"
  15283. "text1"
  15284. "\r\n--zzzz--\r\n");
  15285. }
  15286. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15287. // The received boundary was only checked for being non-empty, so it could be
  15288. // as long as a header is allowed to be. The parser scans the body for
  15289. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15290. // costs a nearly full comparison at nearly every position, making the
  15291. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15292. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15293. Server svr;
  15294. svr.Post("/post", [](const Request &req, Response &res) {
  15295. EXPECT_EQ(1u, req.form.fields.size());
  15296. EXPECT_EQ("text1", req.form.get_field("text1"));
  15297. res.set_content("ok", "text/plain");
  15298. });
  15299. auto port = svr.bind_to_any_port(HOST);
  15300. thread t = thread([&] { svr.listen_after_bind(); });
  15301. auto se = detail::scope_exit([&] {
  15302. svr.stop();
  15303. t.join();
  15304. ASSERT_FALSE(svr.is_running());
  15305. });
  15306. svr.wait_until_ready();
  15307. Client cli(HOST, port);
  15308. auto post_with_boundary_of_length = [&](size_t len) {
  15309. const std::string boundary(len, 'a');
  15310. const std::string body =
  15311. "--" + boundary +
  15312. "\r\n"
  15313. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15314. "\r\n"
  15315. "text1"
  15316. "\r\n--" +
  15317. boundary + "--\r\n";
  15318. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15319. };
  15320. auto res = post_with_boundary_of_length(70);
  15321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15322. EXPECT_EQ(StatusCode::OK_200, res->status);
  15323. res = post_with_boundary_of_length(71);
  15324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15325. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15326. }
  15327. TEST(MakeFileBodyTest, Basic) {
  15328. const std::string file_content(4096, 'Z');
  15329. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15330. {
  15331. std::ofstream ofs(tmp_path, std::ios::binary);
  15332. ofs.write(file_content.data(),
  15333. static_cast<std::streamsize>(file_content.size()));
  15334. }
  15335. auto handled = false;
  15336. Server svr;
  15337. svr.Post("/upload", [&](const Request &req, Response &res) {
  15338. EXPECT_EQ(file_content, req.body);
  15339. handled = true;
  15340. res.status = StatusCode::OK_200;
  15341. });
  15342. auto port = svr.bind_to_any_port(HOST);
  15343. auto t = thread([&] { svr.listen_after_bind(); });
  15344. auto se = detail::scope_exit([&] {
  15345. svr.stop();
  15346. t.join();
  15347. ASSERT_FALSE(svr.is_running());
  15348. ASSERT_TRUE(handled);
  15349. std::remove(tmp_path.c_str());
  15350. });
  15351. svr.wait_until_ready();
  15352. auto fb = make_file_body(tmp_path);
  15353. ASSERT_GT(fb.first, 0u);
  15354. Client cli(HOST, port);
  15355. auto res =
  15356. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15358. EXPECT_EQ(StatusCode::OK_200, res->status);
  15359. }
  15360. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15361. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15362. {
  15363. std::ofstream ofs(path, std::ios::binary);
  15364. const std::string content(100, 'A');
  15365. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15366. }
  15367. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15368. auto body = make_file_body(path);
  15369. ASSERT_EQ(100u, body.first);
  15370. ASSERT_TRUE(static_cast<bool>(body.second));
  15371. // Rewritten shorter after its length was measured - and, on a server, after
  15372. // that length has already gone out as Content-Length.
  15373. {
  15374. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15375. const std::string content(10, 'A');
  15376. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15377. }
  15378. std::string written;
  15379. DataSink sink;
  15380. sink.write = [&](const char *d, size_t l) {
  15381. written.append(d, l);
  15382. return true;
  15383. };
  15384. // The provider has to report failure. write_content_with_progress() advances
  15385. // its offset only by what was written, so a provider that returns true
  15386. // without completing the length it promised is called again straight away,
  15387. // and again.
  15388. EXPECT_FALSE(body.second(0, body.first, sink));
  15389. EXPECT_EQ(std::string(10, 'A'), written);
  15390. }
  15391. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15392. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15393. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15394. {
  15395. std::ofstream ofs(path, std::ios::binary);
  15396. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15397. }
  15398. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15399. auto body = make_file_body(path);
  15400. ASSERT_EQ(content.size(), body.first);
  15401. ASSERT_TRUE(static_cast<bool>(body.second));
  15402. std::string written;
  15403. DataSink sink;
  15404. sink.write = [&](const char *d, size_t l) {
  15405. written.append(d, l);
  15406. return true;
  15407. };
  15408. EXPECT_TRUE(body.second(0, body.first, sink));
  15409. EXPECT_EQ(content, written);
  15410. }
  15411. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15412. static constexpr unsigned int number_of_tasks{1000000};
  15413. std::atomic_uint count{0};
  15414. std::unique_ptr<TaskQueue> task_queue{
  15415. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15416. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15417. auto queued = task_queue->enqueue(
  15418. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15419. EXPECT_TRUE(queued);
  15420. }
  15421. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15422. task_queue->shutdown();
  15423. #else
  15424. EXPECT_NO_THROW(task_queue->shutdown());
  15425. #endif
  15426. EXPECT_EQ(number_of_tasks, count.load());
  15427. }
  15428. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15429. static constexpr unsigned int number_of_tasks{1000000};
  15430. static constexpr unsigned int qlimit{2};
  15431. unsigned int queued_count{0};
  15432. std::atomic_uint count{0};
  15433. std::unique_ptr<TaskQueue> task_queue{
  15434. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15435. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15436. if (task_queue->enqueue(
  15437. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15438. queued_count++;
  15439. }
  15440. }
  15441. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15442. task_queue->shutdown();
  15443. #else
  15444. EXPECT_NO_THROW(task_queue->shutdown());
  15445. #endif
  15446. EXPECT_EQ(queued_count, count.load());
  15447. EXPECT_TRUE(queued_count <= number_of_tasks);
  15448. EXPECT_TRUE(queued_count >= qlimit);
  15449. }
  15450. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15451. // Use a short idle timeout so a dynamic thread spawns, times out and
  15452. // exits during the test, and the pool keeps working afterwards.
  15453. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15454. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15455. /*idle_timeout_sec=*/1}};
  15456. std::atomic_uint count{0};
  15457. std::condition_variable cv;
  15458. std::mutex mtx;
  15459. bool release = false;
  15460. // Block the base thread so the second task spawns a dynamic thread.
  15461. EXPECT_TRUE(task_queue->enqueue([&] {
  15462. std::unique_lock<std::mutex> lock(mtx);
  15463. while (!release) {
  15464. cv.wait(lock);
  15465. }
  15466. count++;
  15467. }));
  15468. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15469. // Let the dynamic thread finish its task and exceed the idle timeout.
  15470. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15471. {
  15472. std::unique_lock<std::mutex> lock(mtx);
  15473. release = true;
  15474. }
  15475. cv.notify_all();
  15476. // The pool must still accept and run tasks after the dynamic thread exited.
  15477. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15478. task_queue->shutdown();
  15479. EXPECT_EQ(3u, count.load());
  15480. }
  15481. TEST(TaskQueueTest, MaxQueuedRequests) {
  15482. static constexpr unsigned int qlimit{3};
  15483. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15484. std::condition_variable sem_cv;
  15485. std::mutex sem_mtx;
  15486. int credits = 0;
  15487. bool queued;
  15488. /* Fill up the queue with tasks that will block until we give them credits to
  15489. * complete. */
  15490. for (unsigned int n = 0; n <= qlimit;) {
  15491. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15492. std::unique_lock<std::mutex> lock(sem_mtx);
  15493. while (credits <= 0) {
  15494. sem_cv.wait(lock);
  15495. }
  15496. /* Consume the credit and signal the test code if they are all gone. */
  15497. if (--credits == 0) { sem_cv.notify_one(); }
  15498. });
  15499. if (n < qlimit) {
  15500. /* The first qlimit enqueues must succeed. */
  15501. EXPECT_TRUE(queued);
  15502. } else {
  15503. /* The last one will succeed only when the worker thread
  15504. * starts and dequeues the first blocking task. Although
  15505. * not necessary for the correctness of this test, we sleep for
  15506. * a short while to avoid busy waiting. */
  15507. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15508. }
  15509. if (queued) { n++; }
  15510. }
  15511. /* Further enqueues must fail since the queue is full. */
  15512. for (auto i = 0; i < 4; i++) {
  15513. queued = task_queue->enqueue([] {});
  15514. EXPECT_FALSE(queued);
  15515. }
  15516. /* Give the credits to allow the previous tasks to complete. */
  15517. {
  15518. std::unique_lock<std::mutex> lock(sem_mtx);
  15519. credits += qlimit + 1;
  15520. }
  15521. sem_cv.notify_all();
  15522. /* Wait for all the credits to be consumed. */
  15523. {
  15524. std::unique_lock<std::mutex> lock(sem_mtx);
  15525. while (credits > 0) {
  15526. sem_cv.wait(lock);
  15527. }
  15528. }
  15529. /* Check that we are able again to enqueue at least qlimit tasks. */
  15530. for (unsigned int i = 0; i < qlimit; i++) {
  15531. queued = task_queue->enqueue([] {});
  15532. EXPECT_TRUE(queued);
  15533. }
  15534. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15535. task_queue->shutdown();
  15536. #else
  15537. EXPECT_NO_THROW(task_queue->shutdown());
  15538. #endif
  15539. }
  15540. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15541. Server svr;
  15542. std::string method;
  15543. std::string body;
  15544. auto has_content_length = false;
  15545. auto has_transfer_encoding = false;
  15546. std::atomic<int> bad_requests{0};
  15547. // Leftover body bytes get parsed as a malformed request and answered with
  15548. // 400
  15549. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15550. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15551. });
  15552. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15553. res.set_redirect("/down", StatusCode::SeeOther_303);
  15554. });
  15555. svr.Get("/down", [&](const Request &req, Response &res) {
  15556. method = req.method;
  15557. body = req.body;
  15558. has_content_length = req.has_header("Content-Length");
  15559. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15560. res.set_content("ok", "text/plain");
  15561. });
  15562. auto port = svr.bind_to_any_port(HOST);
  15563. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15564. auto se = detail::scope_exit([&] {
  15565. svr.stop();
  15566. thread.join();
  15567. ASSERT_FALSE(svr.is_running());
  15568. });
  15569. svr.wait_until_ready();
  15570. const std::string payload = "SECRET-BODY";
  15571. auto check = [&](Client &cli, const Result &res) {
  15572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15573. EXPECT_EQ(StatusCode::OK_200, res->status);
  15574. EXPECT_EQ("ok", res->body);
  15575. EXPECT_EQ("GET", method);
  15576. EXPECT_TRUE(body.empty());
  15577. EXPECT_FALSE(has_content_length);
  15578. EXPECT_FALSE(has_transfer_encoding);
  15579. // Nothing of the original body may be left on the connection
  15580. auto res2 = cli.Get("/down");
  15581. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15582. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15583. EXPECT_EQ("ok", res2->body);
  15584. EXPECT_EQ(0, bad_requests);
  15585. };
  15586. // With content length
  15587. {
  15588. Client cli(HOST, port);
  15589. cli.set_keep_alive(true);
  15590. cli.set_follow_location(true);
  15591. auto res = cli.Post(
  15592. "/up", payload.size(),
  15593. [&](size_t offset, size_t length, DataSink &sink) {
  15594. return sink.write(payload.data() + offset, length);
  15595. },
  15596. "text/plain");
  15597. check(cli, res);
  15598. }
  15599. // Without content length (chunked)
  15600. {
  15601. Client cli(HOST, port);
  15602. cli.set_keep_alive(true);
  15603. cli.set_follow_location(true);
  15604. auto res = cli.Post(
  15605. "/up",
  15606. [&](size_t /*offset*/, DataSink &sink) {
  15607. sink.write(payload.data(), payload.size());
  15608. sink.done();
  15609. return true;
  15610. },
  15611. "text/plain");
  15612. check(cli, res);
  15613. }
  15614. }
  15615. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15616. Server svr;
  15617. std::string target;
  15618. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15619. // Echo the still-encoded name back in the Location
  15620. const std::string prefix = "/start/";
  15621. res.status = StatusCode::Found_302;
  15622. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15623. });
  15624. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15625. target = req.target;
  15626. res.set_content("ok", "text/plain");
  15627. });
  15628. auto port = svr.bind_to_any_port(HOST);
  15629. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15630. auto se = detail::scope_exit([&] {
  15631. svr.stop();
  15632. thread.join();
  15633. ASSERT_FALSE(svr.is_running());
  15634. });
  15635. svr.wait_until_ready();
  15636. // Decoding the Location path would turn the first four into a path
  15637. // separator, a query delimiter, a fragment delimiter and a different
  15638. // percent-encoded octet. The rest must keep reaching the server as they are.
  15639. const std::vector<std::string> names = {
  15640. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15641. };
  15642. for (auto path_encode : {true, false}) {
  15643. Client cli(HOST, port);
  15644. cli.set_follow_location(true);
  15645. cli.set_path_encode(path_encode);
  15646. for (const auto &name : names) {
  15647. target.clear();
  15648. auto res = cli.Get("/start/" + name);
  15649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15650. EXPECT_EQ(StatusCode::OK_200, res->status);
  15651. EXPECT_EQ("/dest/" + name, target);
  15652. }
  15653. }
  15654. }
  15655. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15656. Server svr;
  15657. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15658. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15659. });
  15660. svr.Get("/hello", [](const Request &req, Response &res) {
  15661. res.set_content(req.get_param_value("key"), "text/plain");
  15662. });
  15663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15664. auto se = detail::scope_exit([&] {
  15665. svr.stop();
  15666. thread.join();
  15667. ASSERT_FALSE(svr.is_running());
  15668. });
  15669. svr.wait_until_ready();
  15670. {
  15671. Client cli(HOST, PORT);
  15672. cli.set_follow_location(true);
  15673. auto res = cli.Get("/");
  15674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15675. EXPECT_EQ(StatusCode::OK_200, res->status);
  15676. EXPECT_EQ("val&key2=val2", res->body);
  15677. }
  15678. }
  15679. #endif
  15680. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15681. Server svr;
  15682. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15683. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15684. });
  15685. svr.Get("/hello", [](const Request &req, Response &res) {
  15686. res.set_content(req.get_param_value("key"), "text/plain");
  15687. });
  15688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15689. auto se = detail::scope_exit([&] {
  15690. svr.stop();
  15691. thread.join();
  15692. ASSERT_FALSE(svr.is_running());
  15693. });
  15694. svr.wait_until_ready();
  15695. {
  15696. Client cli(HOST, PORT);
  15697. cli.set_follow_location(true);
  15698. auto res = cli.Get("/");
  15699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15700. EXPECT_EQ(StatusCode::OK_200, res->status);
  15701. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15702. }
  15703. }
  15704. TEST(RedirectTest, RedirectWithPlusInPath) {
  15705. Server svr;
  15706. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15707. res.set_redirect("/a+b");
  15708. });
  15709. // Route pattern uses regex; escape + as \\+
  15710. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15711. res.set_content(req.path, "text/plain");
  15712. });
  15713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15714. auto se = detail::scope_exit([&] {
  15715. svr.stop();
  15716. thread.join();
  15717. ASSERT_FALSE(svr.is_running());
  15718. });
  15719. svr.wait_until_ready();
  15720. {
  15721. Client cli(HOST, PORT);
  15722. cli.set_follow_location(true);
  15723. auto res = cli.Get("/");
  15724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15725. EXPECT_EQ(StatusCode::OK_200, res->status);
  15726. EXPECT_EQ("/a+b", res->body);
  15727. }
  15728. }
  15729. TEST(RedirectTest, ResolveRelativeLocation) {
  15730. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15731. const std::vector<std::pair<std::string, std::string>> cases = {
  15732. {"g", "/b/c/g"},
  15733. {"./g", "/b/c/g"},
  15734. {"g/", "/b/c/g/"},
  15735. {"?y", "/b/c/d;p?y"},
  15736. {"g?y", "/b/c/g?y"},
  15737. {"#s", "/b/c/d;p?q#s"},
  15738. {"g#s", "/b/c/g#s"},
  15739. {"g?y#s", "/b/c/g?y#s"},
  15740. {";x", "/b/c/;x"},
  15741. {"g;x", "/b/c/g;x"},
  15742. {".", "/b/c/"},
  15743. {"./", "/b/c/"},
  15744. {"..", "/b/"},
  15745. {"../", "/b/"},
  15746. {"../g", "/b/g"},
  15747. {"../..", "/"},
  15748. {"../../", "/"},
  15749. {"../../g", "/g"},
  15750. {"../../../g", "/g"},
  15751. {"g.", "/b/c/g."},
  15752. {".g", "/b/c/.g"},
  15753. {"g..", "/b/c/g.."},
  15754. {"..g", "/b/c/..g"},
  15755. {"./../g", "/b/g"},
  15756. {"./g/.", "/b/c/g/"},
  15757. {"g/./h", "/b/c/g/h"},
  15758. {"g/../h", "/b/c/h"},
  15759. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15760. {"g;x=1/../y", "/b/c/y"},
  15761. {"g?y/./x", "/b/c/g?y/./x"},
  15762. {"g#s/../x", "/b/c/g#s/../x"},
  15763. // Not relative-path references, so left for parse_url.
  15764. {"/g", "/g"},
  15765. {"//g", "//g"},
  15766. {"http://g/x", "http://g/x"},
  15767. {"g:h", "g:h"},
  15768. };
  15769. for (const auto &c : cases) {
  15770. EXPECT_EQ(c.second,
  15771. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15772. << c.first;
  15773. }
  15774. }
  15775. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15776. Server svr;
  15777. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15778. res.set_redirect(req.get_param_value("to"));
  15779. });
  15780. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15781. res.set_content(req.target, "text/plain");
  15782. });
  15783. svr.Get("/other", [](const Request &req, Response &res) {
  15784. res.set_content(req.target, "text/plain");
  15785. });
  15786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15787. auto se = detail::scope_exit([&] {
  15788. svr.stop();
  15789. thread.join();
  15790. ASSERT_FALSE(svr.is_running());
  15791. });
  15792. svr.wait_until_ready();
  15793. const std::vector<std::pair<std::string, std::string>> cases = {
  15794. {"next", "/dir/next"},
  15795. {"./next?x=1", "/dir/next?x=1"},
  15796. {"../other", "/other"},
  15797. };
  15798. for (const auto &c : cases) {
  15799. Client cli(HOST, PORT);
  15800. cli.set_follow_location(true);
  15801. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15802. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15803. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15804. EXPECT_EQ(c.second, res->body) << c.first;
  15805. }
  15806. }
  15807. #ifdef CPPHTTPLIB_SSL_ENABLED
  15808. TEST(RedirectTest, Issue2185_Online) {
  15809. SSLClient client("github.com");
  15810. client.set_follow_location(true);
  15811. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15812. "Coollab-Windows.zip");
  15813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15814. EXPECT_EQ(StatusCode::OK_200, res->status);
  15815. EXPECT_EQ(9920427U, res->body.size());
  15816. }
  15817. #endif
  15818. TEST(VulnerabilityTest, CRLFInjection) {
  15819. Server svr;
  15820. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15821. res.set_content("Hello 1", "text/plain");
  15822. });
  15823. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15824. res.set_content("Hello 2", "text/plain");
  15825. });
  15826. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15827. res.set_content("Hello 3", "text/plain");
  15828. });
  15829. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15830. res.set_content("Hello 4", "text/plain");
  15831. });
  15832. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15833. for (const auto &x : req.headers) {
  15834. auto key = x.first;
  15835. EXPECT_STRNE("evil", key.c_str());
  15836. }
  15837. });
  15838. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15839. auto se = detail::scope_exit([&] {
  15840. svr.stop();
  15841. thread.join();
  15842. ASSERT_FALSE(svr.is_running());
  15843. });
  15844. svr.wait_until_ready();
  15845. {
  15846. Client cli(HOST, PORT);
  15847. cli.Post("/test1", "A=B",
  15848. "application/x-www-form-urlencoded\r\nevil: hello1");
  15849. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15850. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15851. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15852. }
  15853. }
  15854. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15855. auto server_thread = std::thread([] {
  15856. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15857. default_socket_options(srv);
  15858. sockaddr_in addr{};
  15859. addr.sin_family = AF_INET;
  15860. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15861. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15862. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15863. ::listen(srv, 1);
  15864. sockaddr_in cli_addr{};
  15865. socklen_t cli_len = sizeof(cli_addr);
  15866. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15867. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15868. std::string buf_all;
  15869. char buf[2048];
  15870. ssize_t n;
  15871. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15872. buf_all.append(buf, static_cast<size_t>(n));
  15873. size_t pos;
  15874. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15875. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15876. auto e = request_block.find("\r\n");
  15877. if (e != std::string::npos) {
  15878. auto request_line = request_block.substr(0, e);
  15879. std::string msg =
  15880. "CRLF injection detected in request line: '" + request_line + "'";
  15881. EXPECT_FALSE(true) << msg;
  15882. }
  15883. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15884. ::send(cli,
  15885. #ifdef _WIN32
  15886. static_cast<const char *>(resp.c_str()),
  15887. static_cast<int>(resp.size()),
  15888. #else
  15889. resp.c_str(), resp.size(),
  15890. #endif
  15891. 0);
  15892. buf_all.erase(0, pos + 4);
  15893. }
  15894. }
  15895. detail::close_socket(cli);
  15896. detail::close_socket(srv);
  15897. });
  15898. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15899. auto cli = Client("127.0.0.1", PORT + 1);
  15900. auto headers = Headers{
  15901. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15902. {"Connection", "keep-alive"}};
  15903. auto res = cli.Get("/hi", headers);
  15904. EXPECT_FALSE(res);
  15905. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15906. server_thread.join();
  15907. }
  15908. // A request rejected before any byte reaches the socket must fail right away
  15909. // instead of waiting for a response the server will never send.
  15910. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15911. // The kernel completes the TCP handshake from the listen backlog, so the
  15912. // client connects, but nothing ever reads, responds or closes.
  15913. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15914. default_socket_options(srv);
  15915. sockaddr_in addr{};
  15916. addr.sin_family = AF_INET;
  15917. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15918. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15919. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15920. ASSERT_EQ(0, ::listen(srv, 8));
  15921. auto cli = Client("127.0.0.1", PORT + 1);
  15922. cli.set_read_timeout(10, 0);
  15923. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15924. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15925. std::chrono::steady_clock::now() - start)
  15926. .count();
  15927. };
  15928. {
  15929. Request req;
  15930. req.method = "GE T";
  15931. req.path = "/";
  15932. auto start = std::chrono::steady_clock::now();
  15933. auto res = cli.send(req);
  15934. EXPECT_FALSE(res);
  15935. EXPECT_EQ(Error::Write, res.error());
  15936. EXPECT_LT(elapsed_ms(start), 1000);
  15937. }
  15938. {
  15939. auto start = std::chrono::steady_clock::now();
  15940. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15941. EXPECT_FALSE(res);
  15942. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15943. EXPECT_LT(elapsed_ms(start), 1000);
  15944. }
  15945. EXPECT_FALSE(cli.is_socket_open());
  15946. detail::close_socket(srv);
  15947. }
  15948. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15949. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15950. default_socket_options(srv);
  15951. sockaddr_in addr{};
  15952. addr.sin_family = AF_INET;
  15953. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15954. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15955. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15956. ASSERT_EQ(0, ::listen(srv, 1));
  15957. std::string received;
  15958. auto server_thread = std::thread([&] {
  15959. auto sock = ::accept(srv, nullptr, nullptr);
  15960. if (sock == INVALID_SOCKET) { return; }
  15961. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15962. char buf[2048];
  15963. ssize_t n;
  15964. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15965. received.append(buf, static_cast<size_t>(n));
  15966. }
  15967. detail::close_socket(sock);
  15968. });
  15969. {
  15970. auto cli = Client("127.0.0.1", PORT + 1);
  15971. // "Z" sorts after the default headers, so writing straight to the socket
  15972. // would have sent the request line and those headers before the rejection.
  15973. auto handle =
  15974. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15975. EXPECT_FALSE(handle.is_valid());
  15976. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15977. }
  15978. server_thread.join();
  15979. detail::close_socket(srv);
  15980. EXPECT_TRUE(received.empty()) << received;
  15981. }
  15982. TEST(PathParamsTest, StaticMatch) {
  15983. const auto pattern = "/users/all";
  15984. detail::PathParamsMatcher matcher(pattern);
  15985. Request request;
  15986. request.path = "/users/all";
  15987. ASSERT_TRUE(matcher.match(request));
  15988. std::unordered_map<std::string, std::string> expected_params = {};
  15989. EXPECT_EQ(request.path_params, expected_params);
  15990. }
  15991. TEST(PathParamsTest, StaticMismatch) {
  15992. const auto pattern = "/users/all";
  15993. detail::PathParamsMatcher matcher(pattern);
  15994. Request request;
  15995. request.path = "/users/1";
  15996. ASSERT_FALSE(matcher.match(request));
  15997. }
  15998. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15999. const auto pattern = "/users/:id/subscriptions";
  16000. detail::PathParamsMatcher matcher(pattern);
  16001. Request request;
  16002. request.path = "/users/42/subscriptions";
  16003. ASSERT_TRUE(matcher.match(request));
  16004. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16005. EXPECT_EQ(request.path_params, expected_params);
  16006. }
  16007. TEST(PathParamsTest, SingleParamInTheEnd) {
  16008. const auto pattern = "/users/:id";
  16009. detail::PathParamsMatcher matcher(pattern);
  16010. Request request;
  16011. request.path = "/users/24";
  16012. ASSERT_TRUE(matcher.match(request));
  16013. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16014. EXPECT_EQ(request.path_params, expected_params);
  16015. }
  16016. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16017. const auto pattern = "/users/:id/";
  16018. detail::PathParamsMatcher matcher(pattern);
  16019. Request request;
  16020. request.path = "/users/42/";
  16021. ASSERT_TRUE(matcher.match(request));
  16022. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16023. EXPECT_EQ(request.path_params, expected_params);
  16024. }
  16025. TEST(PathParamsTest, EmptyParam) {
  16026. const auto pattern = "/users/:id/";
  16027. detail::PathParamsMatcher matcher(pattern);
  16028. Request request;
  16029. request.path = "/users//";
  16030. ASSERT_TRUE(matcher.match(request));
  16031. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16032. EXPECT_EQ(request.path_params, expected_params);
  16033. }
  16034. TEST(PathParamsTest, FragmentMismatch) {
  16035. const auto pattern = "/users/:id/";
  16036. detail::PathParamsMatcher matcher(pattern);
  16037. Request request;
  16038. request.path = "/admins/24/";
  16039. ASSERT_FALSE(matcher.match(request));
  16040. }
  16041. TEST(PathParamsTest, ExtraFragments) {
  16042. const auto pattern = "/users/:id";
  16043. detail::PathParamsMatcher matcher(pattern);
  16044. Request request;
  16045. request.path = "/users/42/subscriptions";
  16046. ASSERT_FALSE(matcher.match(request));
  16047. }
  16048. TEST(PathParamsTest, MissingTrailingParam) {
  16049. const auto pattern = "/users/:id";
  16050. detail::PathParamsMatcher matcher(pattern);
  16051. Request request;
  16052. request.path = "/users";
  16053. ASSERT_FALSE(matcher.match(request));
  16054. }
  16055. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16056. const auto pattern = "/users/:id/subscriptions";
  16057. detail::PathParamsMatcher matcher(pattern);
  16058. Request request;
  16059. request.path = "/users/subscriptions";
  16060. ASSERT_FALSE(matcher.match(request));
  16061. }
  16062. TEST(PathParamsTest, MultipleParams) {
  16063. const auto pattern = "/users/:userid/subscriptions/:subid";
  16064. detail::PathParamsMatcher matcher(pattern);
  16065. Request request;
  16066. request.path = "/users/42/subscriptions/2";
  16067. ASSERT_TRUE(matcher.match(request));
  16068. std::unordered_map<std::string, std::string> expected_params = {
  16069. {"userid", "42"}, {"subid", "2"}};
  16070. EXPECT_EQ(request.path_params, expected_params);
  16071. }
  16072. TEST(PathParamsTest, SequenceOfParams) {
  16073. const auto pattern = "/values/:x/:y/:z";
  16074. detail::PathParamsMatcher matcher(pattern);
  16075. Request request;
  16076. request.path = "/values/1/2/3";
  16077. ASSERT_TRUE(matcher.match(request));
  16078. std::unordered_map<std::string, std::string> expected_params = {
  16079. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16080. EXPECT_EQ(request.path_params, expected_params);
  16081. }
  16082. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16083. const auto pattern = "/prefix:suffix";
  16084. detail::PathParamsMatcher matcher(pattern);
  16085. Request request;
  16086. request.path = "/prefix:suffix";
  16087. ASSERT_TRUE(matcher.match(request));
  16088. const std::unordered_map<std::string, std::string> expected_params = {};
  16089. EXPECT_EQ(request.path_params, expected_params);
  16090. }
  16091. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16092. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16093. // calling thread's stack on a long enough path for a quantified pattern;
  16094. // RegexMatcher must refuse to run regex matching on paths beyond
  16095. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16096. detail::RegexMatcher matcher("/files/(.*)");
  16097. Request within_limit;
  16098. within_limit.path = "/files/" + std::string(10, 'A');
  16099. EXPECT_TRUE(matcher.match(within_limit));
  16100. Request over_limit;
  16101. over_limit.path =
  16102. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16103. EXPECT_FALSE(matcher.match(over_limit));
  16104. }
  16105. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16106. Server svr;
  16107. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16108. res.set_content("ok", "text/plain");
  16109. });
  16110. auto port = svr.bind_to_any_port(HOST);
  16111. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16112. auto se = detail::scope_exit([&] {
  16113. svr.stop();
  16114. thread.join();
  16115. ASSERT_FALSE(svr.is_running());
  16116. });
  16117. svr.wait_until_ready();
  16118. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16119. // request URI limit; this used to be able to crash the process.
  16120. std::string path =
  16121. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16122. std::string req = "GET " + path +
  16123. " HTTP/1.1\r\n"
  16124. "Host: " +
  16125. std::string(HOST) + ":" + std::to_string(port) +
  16126. "\r\n"
  16127. "Connection: close\r\n"
  16128. "\r\n";
  16129. std::string response;
  16130. ASSERT_TRUE(send_request(5, req, &response, port));
  16131. EXPECT_NE(std::string::npos, response.find("404"));
  16132. }
  16133. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16134. Server svr;
  16135. auto handler = [](const Request & /*req*/, Response &res) {
  16136. res.set_content("hit", "text/plain");
  16137. };
  16138. // No regex metacharacter, so this one is compared literally
  16139. svr.Get("/literal/route", handler);
  16140. // '.' is a regex metacharacter, so this one must keep regex semantics
  16141. svr.Get("/a.c", handler);
  16142. auto port = svr.bind_to_any_port(HOST);
  16143. std::thread t([&]() { svr.listen_after_bind(); });
  16144. auto se = detail::scope_exit([&] {
  16145. svr.stop();
  16146. t.join();
  16147. ASSERT_FALSE(svr.is_running());
  16148. });
  16149. svr.wait_until_ready();
  16150. Client cli(HOST, port);
  16151. struct {
  16152. const char *path;
  16153. int status;
  16154. } cases[] = {
  16155. {"/literal/route", StatusCode::OK_200},
  16156. {"/literal/routes", StatusCode::NotFound_404},
  16157. {"/literal/rout", StatusCode::NotFound_404},
  16158. {"/abc", StatusCode::OK_200},
  16159. {"/a.c", StatusCode::OK_200},
  16160. };
  16161. for (const auto &x : cases) {
  16162. auto res = cli.Get(x.path);
  16163. ASSERT_TRUE(res) << x.path;
  16164. EXPECT_EQ(x.status, res->status) << x.path;
  16165. }
  16166. }
  16167. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16168. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16169. // from exhausting the stack, so it must only constrain routes that actually
  16170. // run a regular expression. A literal route is matched by comparison and
  16171. // stays usable at any length.
  16172. Server svr;
  16173. const std::string pattern =
  16174. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16175. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16176. res.set_content("hit", "text/plain");
  16177. });
  16178. auto port = svr.bind_to_any_port(HOST);
  16179. std::thread t([&]() { svr.listen_after_bind(); });
  16180. auto se = detail::scope_exit([&] {
  16181. svr.stop();
  16182. t.join();
  16183. ASSERT_FALSE(svr.is_running());
  16184. });
  16185. svr.wait_until_ready();
  16186. Client cli(HOST, port);
  16187. auto res = cli.Get(pattern);
  16188. ASSERT_TRUE(res);
  16189. EXPECT_EQ(StatusCode::OK_200, res->status);
  16190. }
  16191. TEST(ParseUrlTest, VariousPatterns) {
  16192. {
  16193. detail::UrlComponents uc;
  16194. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16195. EXPECT_EQ("http", uc.scheme);
  16196. EXPECT_EQ("example.com", uc.host);
  16197. EXPECT_EQ("8080", uc.port);
  16198. EXPECT_EQ("/path", uc.path);
  16199. EXPECT_EQ("?q=1", uc.query);
  16200. }
  16201. {
  16202. detail::UrlComponents uc;
  16203. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16204. EXPECT_EQ("https", uc.scheme);
  16205. EXPECT_EQ("example.com", uc.host);
  16206. EXPECT_TRUE(uc.port.empty());
  16207. EXPECT_EQ("/path", uc.path);
  16208. }
  16209. {
  16210. detail::UrlComponents uc;
  16211. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16212. EXPECT_EQ("::1", uc.host);
  16213. EXPECT_EQ("8080", uc.port);
  16214. EXPECT_EQ("/path", uc.path);
  16215. }
  16216. {
  16217. detail::UrlComponents uc;
  16218. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16219. }
  16220. {
  16221. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16222. // the path while the connection still targets the bracketed host.
  16223. detail::UrlComponents uc;
  16224. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16225. }
  16226. {
  16227. detail::UrlComponents uc;
  16228. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16229. }
  16230. {
  16231. detail::UrlComponents uc;
  16232. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16233. EXPECT_EQ("::1", uc.host);
  16234. EXPECT_TRUE(uc.port.empty());
  16235. EXPECT_EQ("/path", uc.path);
  16236. }
  16237. {
  16238. detail::UrlComponents uc;
  16239. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16240. EXPECT_TRUE(uc.scheme.empty());
  16241. EXPECT_EQ("example.com", uc.host);
  16242. EXPECT_EQ("/path", uc.path);
  16243. EXPECT_EQ("?q=1", uc.query);
  16244. }
  16245. {
  16246. detail::UrlComponents uc;
  16247. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16248. EXPECT_TRUE(uc.host.empty());
  16249. EXPECT_EQ("/path", uc.path);
  16250. EXPECT_EQ("?q=1", uc.query);
  16251. }
  16252. {
  16253. detail::UrlComponents uc;
  16254. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16255. EXPECT_EQ("example.com", uc.host);
  16256. EXPECT_EQ("8080", uc.port);
  16257. }
  16258. {
  16259. // Unix socket path — must not be parsed as host
  16260. detail::UrlComponents uc;
  16261. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16262. EXPECT_TRUE(uc.host.empty());
  16263. }
  16264. {
  16265. detail::UrlComponents uc;
  16266. ASSERT_TRUE(detail::parse_url("", uc));
  16267. EXPECT_TRUE(uc.host.empty());
  16268. EXPECT_TRUE(uc.path.empty());
  16269. }
  16270. {
  16271. detail::UrlComponents uc;
  16272. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16273. }
  16274. {
  16275. detail::UrlComponents uc;
  16276. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16277. }
  16278. {
  16279. // Accepted by parse_url; callers restrict to http/https
  16280. detail::UrlComponents uc;
  16281. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16282. EXPECT_EQ("ftp", uc.scheme);
  16283. }
  16284. {
  16285. detail::UrlComponents uc;
  16286. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16287. }
  16288. {
  16289. detail::UrlComponents uc;
  16290. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16291. }
  16292. }
  16293. TEST(ParseUrlTest, FragmentHandling) {
  16294. {
  16295. detail::UrlComponents uc;
  16296. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16297. EXPECT_EQ("/path", uc.path);
  16298. EXPECT_TRUE(uc.query.empty());
  16299. }
  16300. {
  16301. detail::UrlComponents uc;
  16302. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16303. EXPECT_TRUE(uc.path.empty());
  16304. EXPECT_TRUE(uc.query.empty());
  16305. }
  16306. }
  16307. TEST(ParseUrlTest, UserinfoHandling) {
  16308. // Userinfo with @ but no colon — host includes @
  16309. detail::UrlComponents uc;
  16310. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16311. EXPECT_EQ("user@host.com", uc.host);
  16312. EXPECT_EQ("/path", uc.path);
  16313. }
  16314. TEST(ParseUrlTest, IPv6EdgeCases) {
  16315. {
  16316. detail::UrlComponents uc;
  16317. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16318. EXPECT_TRUE(uc.scheme.empty());
  16319. EXPECT_EQ("::1", uc.host);
  16320. EXPECT_EQ("8080", uc.port);
  16321. }
  16322. {
  16323. // Zone ID '%25' is not in [a-fA-F0-9:]
  16324. detail::UrlComponents uc;
  16325. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16326. }
  16327. }
  16328. TEST(ParseUrlTest, SchemeEdgeCases) {
  16329. {
  16330. detail::UrlComponents uc;
  16331. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16332. }
  16333. {
  16334. detail::UrlComponents uc;
  16335. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16336. }
  16337. {
  16338. detail::UrlComponents uc;
  16339. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16340. }
  16341. }
  16342. TEST(ParseUrlTest, PortEdgeCases) {
  16343. {
  16344. detail::UrlComponents uc;
  16345. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16346. EXPECT_TRUE(uc.port.empty());
  16347. EXPECT_EQ("/path", uc.path);
  16348. }
  16349. {
  16350. // parse_url accepts any port string; validation is done by parse_port
  16351. detail::UrlComponents uc;
  16352. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16353. EXPECT_EQ("abc", uc.port);
  16354. }
  16355. }
  16356. TEST(ParseUrlTest, WebSocketPatterns) {
  16357. {
  16358. detail::UrlComponents uc;
  16359. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16360. EXPECT_EQ("ws", uc.scheme);
  16361. EXPECT_EQ("echo.example.com", uc.host);
  16362. EXPECT_EQ("8080", uc.port);
  16363. EXPECT_EQ("/ws", uc.path);
  16364. }
  16365. {
  16366. detail::UrlComponents uc;
  16367. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16368. EXPECT_EQ("wss", uc.scheme);
  16369. EXPECT_EQ("echo.example.com", uc.host);
  16370. EXPECT_TRUE(uc.port.empty());
  16371. EXPECT_EQ("/ws", uc.path);
  16372. }
  16373. }
  16374. TEST(ParseUrlTest, QueryOnly) {
  16375. detail::UrlComponents uc;
  16376. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16377. EXPECT_TRUE(uc.host.empty());
  16378. EXPECT_TRUE(uc.path.empty());
  16379. EXPECT_EQ("?q=1&r=2", uc.query);
  16380. }
  16381. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16382. detail::UrlComponents uc;
  16383. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16384. EXPECT_TRUE(uc.scheme.empty());
  16385. EXPECT_EQ("example.com", uc.host);
  16386. EXPECT_EQ("443", uc.port);
  16387. EXPECT_EQ("/path", uc.path);
  16388. }
  16389. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16390. // If ipv6 regex working, regex match codepath is taken.
  16391. // else port will default to 80 in Client impl
  16392. int clientImplMagicPort = 80;
  16393. int port = 4321;
  16394. // above ports must be different to avoid false negative
  16395. EXPECT_NE(clientImplMagicPort, port);
  16396. std::string ipV6TestURL = "http://[ff06::c3]";
  16397. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16398. CLIENT_PRIVATE_KEY_FILE);
  16399. EXPECT_EQ(cli.port(), port);
  16400. }
  16401. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16402. auto file_path = "./www/dir/index.html";
  16403. auto dir_path = "./www/dir";
  16404. detail::FileStat stat_file(file_path);
  16405. EXPECT_TRUE(stat_file.is_file());
  16406. EXPECT_FALSE(stat_file.is_dir());
  16407. detail::FileStat stat_dir(dir_path);
  16408. EXPECT_FALSE(stat_dir.is_file());
  16409. EXPECT_TRUE(stat_dir.is_dir());
  16410. }
  16411. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16412. // IPv4 with default HTTP port (80)
  16413. EXPECT_EQ("example.com",
  16414. detail::make_host_and_port_string("example.com", 80, false));
  16415. // IPv4 with default HTTPS port (443)
  16416. EXPECT_EQ("example.com",
  16417. detail::make_host_and_port_string("example.com", 443, true));
  16418. // IPv4 with non-default HTTP port
  16419. EXPECT_EQ("example.com:8080",
  16420. detail::make_host_and_port_string("example.com", 8080, false));
  16421. // IPv4 with non-default HTTPS port
  16422. EXPECT_EQ("example.com:8443",
  16423. detail::make_host_and_port_string("example.com", 8443, true));
  16424. // IPv6 with default HTTP port (80)
  16425. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16426. // IPv6 with default HTTPS port (443)
  16427. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16428. // IPv6 with non-default HTTP port
  16429. EXPECT_EQ("[::1]:8080",
  16430. detail::make_host_and_port_string("::1", 8080, false));
  16431. // IPv6 with non-default HTTPS port
  16432. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16433. // IPv6 full address with default port
  16434. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16435. detail::make_host_and_port_string(
  16436. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16437. // IPv6 full address with non-default port
  16438. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16439. detail::make_host_and_port_string(
  16440. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16441. // IPv6 localhost with non-default port
  16442. EXPECT_EQ("[::1]:3000",
  16443. detail::make_host_and_port_string("::1", 3000, false));
  16444. // IPv6 with zone ID (link-local address) with default port
  16445. EXPECT_EQ("[fe80::1%eth0]",
  16446. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16447. // IPv6 with zone ID (link-local address) with non-default port
  16448. EXPECT_EQ("[fe80::1%eth0]:8080",
  16449. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16450. // Edge case: Port 443 with is_ssl=false (should add port)
  16451. EXPECT_EQ("example.com:443",
  16452. detail::make_host_and_port_string("example.com", 443, false));
  16453. // Edge case: Port 80 with is_ssl=true (should add port)
  16454. EXPECT_EQ("example.com:80",
  16455. detail::make_host_and_port_string("example.com", 80, true));
  16456. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16457. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16458. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16459. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16460. // Security fix: Already bracketed IPv6 should not get double brackets
  16461. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16462. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16463. EXPECT_EQ("[::1]:8080",
  16464. detail::make_host_and_port_string("[::1]", 8080, false));
  16465. EXPECT_EQ("[2001:db8::1]:8080",
  16466. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16467. EXPECT_EQ("[fe80::1%eth0]",
  16468. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16469. EXPECT_EQ("[fe80::1%eth0]:8080",
  16470. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16471. // Edge case: Empty host (should return as-is)
  16472. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16473. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16474. // This is a known limitation but shouldn't crash
  16475. EXPECT_EQ("[host:name]",
  16476. detail::make_host_and_port_string("host:name", 80, false));
  16477. // Port number edge cases (no validation, but should not crash)
  16478. EXPECT_EQ("example.com:0",
  16479. detail::make_host_and_port_string("example.com", 0, false));
  16480. EXPECT_EQ("example.com:-1",
  16481. detail::make_host_and_port_string("example.com", -1, false));
  16482. EXPECT_EQ("example.com:65535",
  16483. detail::make_host_and_port_string("example.com", 65535, false));
  16484. EXPECT_EQ("example.com:65536",
  16485. detail::make_host_and_port_string("example.com", 65536, false));
  16486. }
  16487. #ifdef CPPHTTPLIB_SSL_ENABLED
  16488. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16489. httplib::SSLClient cli("roblox.com", 443);
  16490. cli.set_follow_location(true);
  16491. auto res = cli.Get("/");
  16492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16493. EXPECT_EQ(StatusCode::OK_200, res->status);
  16494. }
  16495. #endif
  16496. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16497. Server svr;
  16498. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16499. EXPECT_EQ(res.status, 400);
  16500. });
  16501. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16502. auto se = detail::scope_exit([&] {
  16503. svr.stop();
  16504. thread.join();
  16505. ASSERT_FALSE(svr.is_running());
  16506. });
  16507. svr.wait_until_ready();
  16508. Client cli(HOST, PORT);
  16509. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16510. }
  16511. TEST(InvalidHeaderCharsTest, is_field_name) {
  16512. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16513. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16514. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16515. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16516. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16517. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16518. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16519. EXPECT_FALSE(detail::fields::is_field_name(""));
  16520. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16521. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16522. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16523. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16524. }
  16525. TEST(InvalidHeaderCharsTest, is_field_value) {
  16526. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16527. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16528. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16529. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16530. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16531. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16532. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16533. EXPECT_TRUE(detail::fields::is_field_value(""));
  16534. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16535. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16536. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16537. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16538. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16539. }
  16540. TEST(InvalidHeaderCharsTest, OnServer) {
  16541. Server svr;
  16542. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16543. std::string header = "Not Set";
  16544. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16545. res.set_header(header, "value");
  16546. res.set_content("Page Content Page Content", "text/plain");
  16547. });
  16548. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16549. std::string header = "Not Set";
  16550. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16551. res.set_header("X-Test", header);
  16552. res.set_content("Page Content Page Content", "text/plain");
  16553. });
  16554. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16555. auto se = detail::scope_exit([&] {
  16556. svr.stop();
  16557. thread.join();
  16558. ASSERT_FALSE(svr.is_running());
  16559. });
  16560. svr.wait_until_ready();
  16561. Client cli(HOST, PORT);
  16562. {
  16563. auto res = cli.Get(
  16564. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16566. EXPECT_EQ("Page Content Page Content", res->body);
  16567. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16568. }
  16569. {
  16570. auto res = cli.Get(
  16571. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16573. EXPECT_EQ("Page Content Page Content", res->body);
  16574. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16575. }
  16576. }
  16577. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16578. auto handled = false;
  16579. Server svr;
  16580. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16581. thread t = thread([&] { svr.listen(HOST, PORT); });
  16582. auto se = detail::scope_exit([&] {
  16583. svr.stop();
  16584. t.join();
  16585. ASSERT_FALSE(svr.is_running());
  16586. ASSERT_FALSE(handled);
  16587. });
  16588. svr.wait_until_ready();
  16589. auto req = "POST /test HTTP/1.1\r\n"
  16590. "Content-Length: x\r\n"
  16591. "\r\n";
  16592. std::string response;
  16593. ASSERT_TRUE(send_request(1, req, &response));
  16594. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16595. response.substr(0, response.find("\r\n")));
  16596. }
  16597. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16598. // case-insensitive, and a server that receives a 100-continue expectation in
  16599. // an HTTP/1.0 request MUST ignore it.
  16600. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16601. std::string response;
  16602. ASSERT_TRUE(send_request(1, req, &response, port));
  16603. *got_100 = response.find("100 Continue") != std::string::npos;
  16604. }
  16605. class ExpectTokenTest : public ::testing::Test {
  16606. protected:
  16607. void SetUp() override {
  16608. svr_.Post("/p", [](const Request &, Response &res) {
  16609. res.set_content("ok", "text/plain");
  16610. });
  16611. port_ = svr_.bind_to_any_port(HOST);
  16612. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16613. svr_.wait_until_ready();
  16614. }
  16615. void TearDown() override {
  16616. svr_.stop();
  16617. if (thread_.joinable()) { thread_.join(); }
  16618. }
  16619. std::string request(const char *version, const char *expect_value) const {
  16620. return std::string("POST /p ") + version +
  16621. "\r\n"
  16622. "Host: localhost\r\n"
  16623. "Content-Length: 2\r\n"
  16624. "Connection: close\r\n"
  16625. "Expect: " +
  16626. expect_value +
  16627. "\r\n"
  16628. "\r\n"
  16629. "hi";
  16630. }
  16631. Server svr_;
  16632. int port_ = 0;
  16633. thread thread_;
  16634. };
  16635. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16636. bool got_100 = false;
  16637. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16638. EXPECT_TRUE(got_100);
  16639. }
  16640. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16641. bool got_100 = true;
  16642. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16643. EXPECT_FALSE(got_100);
  16644. }
  16645. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16646. bool got_100 = false;
  16647. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16648. EXPECT_TRUE(got_100);
  16649. }
  16650. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16651. bool got_100 = false;
  16652. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16653. EXPECT_TRUE(got_100);
  16654. }
  16655. // `100 Continue` is sent only when the server starts reading the body, so a
  16656. // request rejected before that never invites the client to send it. The
  16657. // requests below carry the expectation but withhold the body, as a client
  16658. // waiting for `100 Continue` would.
  16659. // A POST that expects `100 Continue` and withholds its two-byte body.
  16660. static std::string expect_headers_only(const std::string &path) {
  16661. return "POST " + path +
  16662. " HTTP/1.1\r\n"
  16663. "Host: localhost\r\n"
  16664. "Content-Length: 2\r\n"
  16665. "Expect: 100-continue\r\n"
  16666. "\r\n";
  16667. }
  16668. class ExpectLazyContinueTest : public ::testing::Test {
  16669. protected:
  16670. void SetUp() override {
  16671. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16672. if (req.path == "/pre-routing") {
  16673. res.status = StatusCode::Unauthorized_401;
  16674. return Server::HandlerResponse::Handled;
  16675. }
  16676. return Server::HandlerResponse::Unhandled;
  16677. });
  16678. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16679. if (req.matched_route == "/pre-request") {
  16680. res.status = StatusCode::Forbidden_403;
  16681. return Server::HandlerResponse::Handled;
  16682. }
  16683. return Server::HandlerResponse::Unhandled;
  16684. });
  16685. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16686. res.set_content("ok", "text/plain");
  16687. });
  16688. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16689. res.set_content("ok", "text/plain");
  16690. });
  16691. svr_.Post("/reader-used", [](const Request &, Response &res,
  16692. const ContentReader &content_reader) {
  16693. std::string body;
  16694. content_reader([&](const char *data, size_t len) {
  16695. body.append(data, len);
  16696. return true;
  16697. });
  16698. res.set_content(body, "text/plain");
  16699. });
  16700. svr_.Post("/reader-unused",
  16701. [](const Request &, Response &res, const ContentReader &) {
  16702. res.set_content("ignored", "text/plain");
  16703. });
  16704. port_ = svr_.bind_to_any_port(HOST);
  16705. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16706. svr_.wait_until_ready();
  16707. }
  16708. void TearDown() override {
  16709. svr_.stop();
  16710. if (thread_.joinable()) { thread_.join(); }
  16711. }
  16712. // Sends `req` and reads until the server closes the connection. Returns
  16713. // false if the read had to wait for the client-side timeout instead.
  16714. bool send_until_closed(const std::string &req, std::string *resp) const {
  16715. auto start = std::chrono::steady_clock::now();
  16716. if (!send_request(3, req, resp, port_)) { return false; }
  16717. auto elapsed = std::chrono::steady_clock::now() - start;
  16718. return elapsed < std::chrono::seconds(2);
  16719. }
  16720. // The final response comes without `100 Continue`, and the server closes
  16721. // the connection since the body may or may not follow.
  16722. void expect_final_without_interim(const std::string &path,
  16723. const char *status_line) const {
  16724. std::string resp;
  16725. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16726. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16727. EXPECT_EQ(0u, resp.find(status_line));
  16728. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16729. }
  16730. Server svr_;
  16731. int port_ = 0;
  16732. thread thread_;
  16733. };
  16734. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16735. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16736. }
  16737. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16738. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16739. }
  16740. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16741. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16742. }
  16743. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16744. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16745. }
  16746. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16747. // The body follows once `100 Continue` has had time to arrive.
  16748. auto req = expect_headers_only("/reader-used");
  16749. req.insert(req.size() - 2, "Connection: close\r\n");
  16750. std::string resp;
  16751. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16752. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16753. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16754. EXPECT_NE(std::string::npos, resp.find("hi"));
  16755. }
  16756. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16757. // Large enough for the client to add `Expect: 100-continue` itself.
  16758. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16759. std::atomic<bool> body_sent{false};
  16760. Client cli(HOST, port_);
  16761. auto res = cli.Post(
  16762. "/pre-request", length,
  16763. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16764. body_sent = true;
  16765. std::string chunk(len, 'x');
  16766. sink.write(chunk.data(), chunk.size());
  16767. return true;
  16768. },
  16769. "application/octet-stream");
  16770. ASSERT_TRUE(res);
  16771. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16772. EXPECT_FALSE(body_sent);
  16773. }
  16774. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16775. Server svr;
  16776. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16777. return StatusCode::ExpectationFailed_417;
  16778. });
  16779. svr.Post("/p", [](const Request &, Response &res) {
  16780. res.set_content("ok", "text/plain");
  16781. });
  16782. auto port = svr.bind_to_any_port(HOST);
  16783. thread t = thread([&] { svr.listen_after_bind(); });
  16784. auto se = detail::scope_exit([&] {
  16785. svr.stop();
  16786. t.join();
  16787. });
  16788. svr.wait_until_ready();
  16789. std::string resp;
  16790. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16791. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16792. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16793. // Exactly one response: the route handler must not run after the 417.
  16794. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16795. }
  16796. #ifndef _WIN32
  16797. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16798. static constexpr char reject[] = "Unauthorized";
  16799. static constexpr char accept[] = "Upload accepted";
  16800. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16801. Server svr;
  16802. svr.set_expect_100_continue_handler(
  16803. [](const Request & /*req*/, Response &res) {
  16804. res.status = StatusCode::Unauthorized_401;
  16805. res.set_content(reject, "text/plain");
  16806. return res.status;
  16807. });
  16808. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16809. res.set_content(accept, "text/plain");
  16810. });
  16811. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16812. auto se = detail::scope_exit([&] {
  16813. svr.stop();
  16814. thread.join();
  16815. ASSERT_FALSE(svr.is_running());
  16816. });
  16817. svr.wait_until_ready();
  16818. {
  16819. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16820. curl_easy_init(), &curl_easy_cleanup};
  16821. ASSERT_NE(curl, nullptr);
  16822. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16823. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16824. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16825. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16826. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16827. &curl_slist_free_all};
  16828. ASSERT_NE(list, nullptr);
  16829. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16830. struct read_data {
  16831. size_t read_size;
  16832. size_t total_size;
  16833. } data = {0, total_size};
  16834. using read_callback_t =
  16835. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16836. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16837. void *userdata) -> size_t {
  16838. read_data *d = (read_data *)userdata;
  16839. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16840. std::fill_n(ptr, size * nmemb, 'A');
  16841. d->read_size += size * nmemb;
  16842. return size * nmemb;
  16843. };
  16844. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16845. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16846. std::vector<char> buffer;
  16847. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16848. using write_callback_t =
  16849. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16850. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16851. void *userdata) -> size_t {
  16852. std::vector<char> *buf = (std::vector<char> *)userdata;
  16853. buf->reserve(buf->size() + size * nmemb + 1);
  16854. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16855. return size * nmemb;
  16856. };
  16857. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16858. {
  16859. const auto res = curl_easy_perform(curl.get());
  16860. ASSERT_EQ(res, CURLE_OK);
  16861. }
  16862. {
  16863. auto response_code = long{};
  16864. const auto res =
  16865. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16866. ASSERT_EQ(res, CURLE_OK);
  16867. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16868. }
  16869. {
  16870. auto dl = curl_off_t{};
  16871. const auto res =
  16872. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16873. ASSERT_EQ(res, CURLE_OK);
  16874. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16875. }
  16876. {
  16877. buffer.push_back('\0');
  16878. ASSERT_STRCASEEQ(buffer.data(), reject);
  16879. }
  16880. }
  16881. }
  16882. #endif
  16883. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16884. // Regression test for #2458.
  16885. //
  16886. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16887. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16888. // ticket can make the client socket spuriously readable during the
  16889. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16890. // the client withholds the body and then blocks reading a response that never
  16891. // comes, failing with `Failed to read connection`.
  16892. //
  16893. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16894. // within the timeout. This raw OpenSSL server deliberately never sends
  16895. // `100 Continue`; the client must still deliver the body and receive 200.
  16896. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16897. signal(SIGPIPE, SIG_IGN);
  16898. const auto port = PORT + 4;
  16899. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16900. ASSERT_NE(srv, INVALID_SOCKET);
  16901. int opt = 1;
  16902. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16903. sockaddr_in addr{};
  16904. addr.sin_family = AF_INET;
  16905. addr.sin_port = htons(static_cast<uint16_t>(port));
  16906. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16907. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16908. ASSERT_EQ(0, ::listen(srv, 1));
  16909. std::atomic<size_t> server_body_bytes{0};
  16910. auto server_thread = std::thread([&] {
  16911. sockaddr_in cli_addr{};
  16912. socklen_t cli_len = sizeof(cli_addr);
  16913. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16914. if (cli == INVALID_SOCKET) { return; }
  16915. // Bound the lifetime of the server side so a buggy client (which never
  16916. // sends the body) cannot make this thread block forever on join.
  16917. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16918. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16919. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16920. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16921. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16922. SSL *ssl = SSL_new(ctx);
  16923. SSL_set_fd(ssl, static_cast<int>(cli));
  16924. if (SSL_accept(ssl) > 0) {
  16925. // Read the request headers. Reading here also flushes the TLS 1.3
  16926. // session tickets to the client. Deliberately do NOT send
  16927. // `100 Continue`.
  16928. std::string buf;
  16929. char tmp[1024];
  16930. while (buf.find("\r\n\r\n") == std::string::npos) {
  16931. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16932. if (n <= 0) { break; }
  16933. buf.append(tmp, static_cast<size_t>(n));
  16934. }
  16935. // A correct client sends the body now; count what arrives.
  16936. auto pos = buf.find("\r\n\r\n");
  16937. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16938. while (body < 4096) {
  16939. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16940. if (n <= 0) { break; }
  16941. body += static_cast<size_t>(n);
  16942. }
  16943. server_body_bytes = body;
  16944. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16945. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16946. SSL_shutdown(ssl);
  16947. }
  16948. SSL_free(ssl);
  16949. detail::close_socket(cli);
  16950. SSL_CTX_free(ctx);
  16951. });
  16952. auto se = detail::scope_exit([&] {
  16953. server_thread.join();
  16954. detail::close_socket(srv);
  16955. });
  16956. SSLClient cli("127.0.0.1", port);
  16957. cli.enable_server_certificate_verification(false);
  16958. cli.set_connection_timeout(5, 0);
  16959. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16960. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16961. std::string body(4096, 'A');
  16962. auto res = cli.Put("/api/test", body, "application/json");
  16963. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16964. EXPECT_EQ(StatusCode::OK_200, res->status);
  16965. EXPECT_EQ(body.size(), server_body_bytes.load());
  16966. }
  16967. #endif
  16968. template <typename S, typename C>
  16969. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16970. svr.Get("/stream", [&](const Request &, Response &res) {
  16971. auto data = new std::string("01234567890123456789");
  16972. res.set_content_provider(
  16973. data->size(), "text/plain",
  16974. [&, data](size_t offset, size_t length, DataSink &sink) {
  16975. const size_t DATA_CHUNK_SIZE = 4;
  16976. const auto &d = *data;
  16977. std::this_thread::sleep_for(std::chrono::seconds(1));
  16978. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16979. return true;
  16980. },
  16981. [data](bool success) {
  16982. EXPECT_FALSE(success);
  16983. delete data;
  16984. });
  16985. });
  16986. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16987. auto i = new size_t(0);
  16988. res.set_content_provider(
  16989. "text/plain",
  16990. [i](size_t, DataSink &sink) {
  16991. if (*i < 5) {
  16992. std::this_thread::sleep_for(std::chrono::seconds(1));
  16993. sink.write("abcd", 4);
  16994. (*i)++;
  16995. } else {
  16996. sink.done();
  16997. }
  16998. return true;
  16999. },
  17000. [i](bool success) {
  17001. EXPECT_FALSE(success);
  17002. delete i;
  17003. });
  17004. });
  17005. svr.Get("/chunked", [&](const Request &, Response &res) {
  17006. auto i = new size_t(0);
  17007. res.set_chunked_content_provider(
  17008. "text/plain",
  17009. [i](size_t, DataSink &sink) {
  17010. if (*i < 5) {
  17011. std::this_thread::sleep_for(std::chrono::seconds(1));
  17012. sink.os << "abcd";
  17013. (*i)++;
  17014. } else {
  17015. sink.done();
  17016. }
  17017. return true;
  17018. },
  17019. [i](bool success) {
  17020. EXPECT_FALSE(success);
  17021. delete i;
  17022. });
  17023. });
  17024. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17025. auto se = detail::scope_exit([&] {
  17026. svr.stop();
  17027. listen_thread.join();
  17028. ASSERT_FALSE(svr.is_running());
  17029. });
  17030. svr.wait_until_ready();
  17031. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17032. {
  17033. auto start = std::chrono::steady_clock::now();
  17034. auto res = cli.Get("/stream");
  17035. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17036. std::chrono::steady_clock::now() - start)
  17037. .count();
  17038. ASSERT_FALSE(res);
  17039. EXPECT_EQ(Error::Read, res.error());
  17040. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17041. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17042. }
  17043. {
  17044. auto start = std::chrono::steady_clock::now();
  17045. auto res = cli.Get("/stream_without_length");
  17046. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17047. std::chrono::steady_clock::now() - start)
  17048. .count();
  17049. ASSERT_FALSE(res);
  17050. EXPECT_EQ(Error::Read, res.error());
  17051. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17052. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17053. }
  17054. {
  17055. auto start = std::chrono::steady_clock::now();
  17056. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17057. EXPECT_EQ("abcd", string(data, data_length));
  17058. return true;
  17059. });
  17060. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17061. std::chrono::steady_clock::now() - start)
  17062. .count();
  17063. ASSERT_FALSE(res);
  17064. EXPECT_EQ(Error::Read, res.error());
  17065. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17066. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17067. }
  17068. }
  17069. TEST(MaxTimeoutTest, ContentStream) {
  17070. time_t timeout = 2000;
  17071. time_t threshold = 200;
  17072. Server svr;
  17073. Client cli("localhost", PORT);
  17074. max_timeout_test(svr, cli, timeout, threshold);
  17075. }
  17076. #ifdef CPPHTTPLIB_SSL_ENABLED
  17077. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17078. time_t timeout = 2000;
  17079. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17080. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17081. SSLClient cli("localhost", PORT);
  17082. cli.enable_server_certificate_verification(false);
  17083. max_timeout_test(svr, cli, timeout, threshold);
  17084. }
  17085. #endif
  17086. class EventDispatcher {
  17087. public:
  17088. EventDispatcher() {}
  17089. bool wait_event(DataSink *sink) {
  17090. unique_lock<mutex> lk(m_);
  17091. int id = id_;
  17092. // Wait with timeout to prevent hanging if client disconnects
  17093. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17094. [&] { return cid_ == id; })) {
  17095. return false; // Timeout occurred
  17096. }
  17097. sink->write(message_.data(), message_.size());
  17098. return true;
  17099. }
  17100. void send_event(const string &message) {
  17101. lock_guard<mutex> lk(m_);
  17102. cid_ = id_++;
  17103. message_ = message;
  17104. cv_.notify_all();
  17105. }
  17106. private:
  17107. mutex m_;
  17108. condition_variable cv_;
  17109. atomic_int id_{0};
  17110. atomic_int cid_{-1};
  17111. string message_;
  17112. };
  17113. TEST(ClientInThreadTest, Issue2068) {
  17114. EventDispatcher ed;
  17115. Server svr;
  17116. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17117. res.set_chunked_content_provider("text/event-stream",
  17118. [&](size_t /*offset*/, DataSink &sink) {
  17119. return ed.wait_event(&sink);
  17120. });
  17121. });
  17122. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17123. svr.wait_until_ready();
  17124. thread event_thread([&] {
  17125. int id = 0;
  17126. while (svr.is_running()) {
  17127. this_thread::sleep_for(chrono::milliseconds(500));
  17128. std::stringstream ss;
  17129. ss << "data: " << id << "\n\n";
  17130. ed.send_event(ss.str());
  17131. id++;
  17132. }
  17133. });
  17134. auto se = detail::scope_exit([&] {
  17135. svr.stop();
  17136. listen_thread.join();
  17137. event_thread.join();
  17138. ASSERT_FALSE(svr.is_running());
  17139. });
  17140. {
  17141. auto client = detail::make_unique<Client>(HOST, PORT);
  17142. client->set_read_timeout(std::chrono::minutes(10));
  17143. std::atomic<bool> stop{false};
  17144. std::thread t([&] {
  17145. client->Get("/event1",
  17146. [&](const char *, size_t) -> bool { return !stop; });
  17147. });
  17148. std::this_thread::sleep_for(std::chrono::seconds(2));
  17149. stop = true;
  17150. client->stop();
  17151. t.join();
  17152. // Reset client after thread has finished
  17153. client.reset();
  17154. }
  17155. }
  17156. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17157. auto handled = false;
  17158. Server svr;
  17159. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17160. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17161. auto se = detail::scope_exit([&] {
  17162. svr.stop();
  17163. t.join();
  17164. ASSERT_FALSE(svr.is_running());
  17165. ASSERT_FALSE(handled);
  17166. });
  17167. svr.wait_until_ready();
  17168. // Two Content-Length headers with different values — must be rejected
  17169. auto req = "POST /test HTTP/1.1\r\n"
  17170. "Content-Length: 5\r\n"
  17171. "Content-Length: 10\r\n"
  17172. "\r\n"
  17173. "hello";
  17174. std::string response;
  17175. ASSERT_TRUE(send_request(1, req, &response));
  17176. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17177. response.substr(0, response.find("\r\n")));
  17178. }
  17179. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17180. auto handled = false;
  17181. Server svr;
  17182. svr.Post("/test", [&](const Request &, Response &res) {
  17183. handled = true;
  17184. res.set_content("ok", "text/plain");
  17185. });
  17186. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17187. auto se = detail::scope_exit([&] {
  17188. svr.stop();
  17189. t.join();
  17190. ASSERT_FALSE(svr.is_running());
  17191. ASSERT_TRUE(handled);
  17192. });
  17193. svr.wait_until_ready();
  17194. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17195. auto req = "POST /test HTTP/1.1\r\n"
  17196. "Content-Length: 5\r\n"
  17197. "Content-Length: 5\r\n"
  17198. "\r\n"
  17199. "hello";
  17200. std::string response;
  17201. ASSERT_TRUE(send_request(1, req, &response));
  17202. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17203. }
  17204. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17205. Server svr;
  17206. svr.Get("/test", [](const Request &, Response &res) {
  17207. res.set_content("ok", "text/plain");
  17208. });
  17209. auto port = svr.bind_to_any_port(HOST);
  17210. thread t = thread([&] { svr.listen_after_bind(); });
  17211. auto se = detail::scope_exit([&] {
  17212. svr.stop();
  17213. t.join();
  17214. ASSERT_FALSE(svr.is_running());
  17215. });
  17216. svr.wait_until_ready();
  17217. auto status_line = [&](const std::string &host_lines) {
  17218. std::string res;
  17219. send_request(
  17220. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17221. &res, port);
  17222. return res.substr(0, res.find("\r\n"));
  17223. };
  17224. const char *accepted[] = {
  17225. "Host: localhost\r\n",
  17226. "Host: a.example:8080\r\n",
  17227. "Host: my_service\r\n",
  17228. "Host: [::1]:8080\r\n",
  17229. "Host: [fe80::1%25eth0]\r\n",
  17230. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17231. };
  17232. for (auto host_lines : accepted) {
  17233. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17234. }
  17235. const char *rejected[] = {
  17236. "Host: a.example\r\nHost: b.example\r\n",
  17237. "Host: a.example\r\nHost: a.example\r\n",
  17238. "Host: a@b.example\r\n",
  17239. "Host: a.example/b\r\n",
  17240. "Host: a.example\\b\r\n",
  17241. "Host: a.example?b\r\n",
  17242. "Host: a.example#b\r\n",
  17243. "Host: a.example b.example\r\n",
  17244. };
  17245. for (auto host_lines : rejected) {
  17246. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17247. << host_lines;
  17248. }
  17249. }
  17250. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17251. Server svr;
  17252. svr.Get("/", [](const Request &req, Response &res) {
  17253. EXPECT_EQ(2U, req.trailers.size());
  17254. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17255. // Denied
  17256. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17257. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17258. // Accepted
  17259. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17260. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17261. EXPECT_TRUE(req.has_trailer("X-World"));
  17262. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17263. res.set_content("ok", "text/plain");
  17264. });
  17265. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17266. auto se = detail::scope_exit([&] {
  17267. svr.stop();
  17268. t.join();
  17269. ASSERT_FALSE(svr.is_running());
  17270. });
  17271. svr.wait_until_ready();
  17272. const std::string req = "GET / HTTP/1.1\r\n"
  17273. "Transfer-Encoding: chunked\r\n"
  17274. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17275. "\r\n"
  17276. "0\r\n"
  17277. "Content-Length: 10\r\n"
  17278. "Host: internal.local\r\n"
  17279. "Content-Type: malicious/content\r\n"
  17280. "Cookie: any\r\n"
  17281. "Set-Cookie: any\r\n"
  17282. "X-Forwarded-For: attacker.com\r\n"
  17283. "X-Real-Ip: 1.1.1.1\r\n"
  17284. "X-Hello: hello\r\n"
  17285. "X-World: world\r\n"
  17286. "\r\n";
  17287. std::string res;
  17288. ASSERT_TRUE(send_request(1, req, &res));
  17289. }
  17290. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17291. // several field lines, and the combined value is what has to be parsed. A
  17292. // Trailer field split across lines therefore declares every name it lists;
  17293. // reading only the first line silently drops the trailers the later lines
  17294. // declare. The prohibited-trailer filter still applies to every line.
  17295. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17296. Server svr;
  17297. size_t observed_trailer_count = 0;
  17298. std::string observed_hello;
  17299. std::string observed_world;
  17300. bool observed_content_length = true;
  17301. svr.Get("/", [&](const Request &req, Response &res) {
  17302. observed_trailer_count = req.trailers.size();
  17303. observed_hello = req.get_trailer_value("X-Hello");
  17304. observed_world = req.get_trailer_value("X-World");
  17305. observed_content_length = req.has_trailer("Content-Length");
  17306. res.set_content("ok", "text/plain");
  17307. });
  17308. auto port = svr.bind_to_any_port(HOST);
  17309. thread t = thread([&]() { svr.listen_after_bind(); });
  17310. auto se = detail::scope_exit([&] {
  17311. svr.stop();
  17312. t.join();
  17313. ASSERT_FALSE(svr.is_running());
  17314. });
  17315. svr.wait_until_ready();
  17316. const std::string req = "GET / HTTP/1.1\r\n"
  17317. "Transfer-Encoding: chunked\r\n"
  17318. "Trailer: X-Hello\r\n"
  17319. "Trailer: X-World, Content-Length\r\n"
  17320. "\r\n"
  17321. "0\r\n"
  17322. "X-Hello: hello\r\n"
  17323. "X-World: world\r\n"
  17324. "Content-Length: 10\r\n"
  17325. "\r\n";
  17326. std::string res;
  17327. ASSERT_TRUE(send_request(1, req, &res, port));
  17328. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17329. // Accepted: both field lines contribute to the declared set
  17330. EXPECT_EQ(2U, observed_trailer_count);
  17331. EXPECT_EQ(observed_hello, "hello");
  17332. EXPECT_EQ(observed_world, "world");
  17333. // Denied: a prohibited name stays prohibited on a later field line
  17334. EXPECT_FALSE(observed_content_length);
  17335. }
  17336. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17337. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17338. // unbounded run of fields that are never declared, because the counter would
  17339. // only advance for declared fields.
  17340. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17341. Server svr;
  17342. bool handler_called = false;
  17343. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17344. handler_called = true;
  17345. res.set_content("ok", "text/plain");
  17346. });
  17347. auto port = svr.bind_to_any_port(HOST);
  17348. thread t = thread([&]() { svr.listen_after_bind(); });
  17349. auto se = detail::scope_exit([&] {
  17350. svr.stop();
  17351. t.join();
  17352. ASSERT_FALSE(svr.is_running());
  17353. });
  17354. svr.wait_until_ready();
  17355. // Declare nothing, then send far more undeclared trailer fields than the
  17356. // header-count limit. Parsing must stop and reject the request rather than
  17357. // read every line.
  17358. std::string req = "GET / HTTP/1.1\r\n"
  17359. "Transfer-Encoding: chunked\r\n"
  17360. "\r\n"
  17361. "0\r\n";
  17362. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17363. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17364. }
  17365. req += "\r\n";
  17366. std::string res;
  17367. ASSERT_TRUE(send_request(1, req, &res, port));
  17368. // The request is rejected before the handler runs.
  17369. EXPECT_FALSE(handler_called);
  17370. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17371. }
  17372. // The set of declared trailer names is capped so a peer cannot grow it without
  17373. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17374. // declared past the cap is not honored, even if the field is actually sent.
  17375. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17376. Server svr;
  17377. // One name inside the cap and one past it, so the test tracks the cap rather
  17378. // than a fixed count.
  17379. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17380. const std::string within_cap_name = "X-T-0";
  17381. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17382. bool observed_within_cap = false;
  17383. bool observed_past_cap = false;
  17384. svr.Get("/", [&](const Request &req, Response &res) {
  17385. observed_within_cap = req.has_trailer(within_cap_name);
  17386. observed_past_cap = req.has_trailer(past_cap_name);
  17387. res.set_content("ok", "text/plain");
  17388. });
  17389. auto port = svr.bind_to_any_port(HOST);
  17390. thread t = thread([&]() { svr.listen_after_bind(); });
  17391. auto se = detail::scope_exit([&] {
  17392. svr.stop();
  17393. t.join();
  17394. ASSERT_FALSE(svr.is_running());
  17395. });
  17396. svr.wait_until_ready();
  17397. // Declare more trailer names than the cap in a single Trailer field, then
  17398. // actually send the first (within the cap) and the last (past it).
  17399. std::string trailer_decl = "Trailer: ";
  17400. for (int i = 0; i < declared_count; i++) {
  17401. if (i != 0) { trailer_decl += ", "; }
  17402. trailer_decl += "X-T-" + std::to_string(i);
  17403. }
  17404. trailer_decl += "\r\n";
  17405. const std::string req = "GET / HTTP/1.1\r\n"
  17406. "Transfer-Encoding: chunked\r\n" +
  17407. trailer_decl +
  17408. "\r\n"
  17409. "0\r\n" +
  17410. within_cap_name + ": a\r\n" + past_cap_name +
  17411. ": b\r\n"
  17412. "\r\n";
  17413. std::string res;
  17414. ASSERT_TRUE(send_request(1, req, &res, port));
  17415. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17416. // A name within the cap is honored; one declared past the cap is dropped.
  17417. EXPECT_TRUE(observed_within_cap);
  17418. EXPECT_FALSE(observed_past_cap);
  17419. }
  17420. // A direct client that is not listed in trusted_proxies must not be able to
  17421. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17422. // the peer address on the actual TCP connection determines whether the
  17423. // header is honored.
  17424. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17425. Server svr;
  17426. // Deliberately does NOT include the loopback address the test client
  17427. // actually connects from, so the direct connection is not a trusted proxy.
  17428. svr.set_trusted_proxies({"203.0.113.66"});
  17429. std::string observed_remote_addr;
  17430. svr.Get("/ip", [&](const Request &req, Response &res) {
  17431. observed_remote_addr = req.remote_addr;
  17432. res.set_content("ok", "text/plain");
  17433. });
  17434. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17435. auto se = detail::scope_exit([&] {
  17436. svr.stop();
  17437. t.join();
  17438. ASSERT_FALSE(svr.is_running());
  17439. });
  17440. svr.wait_until_ready();
  17441. Client cli(HOST, PORT);
  17442. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17444. EXPECT_EQ(StatusCode::OK_200, res->status);
  17445. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17446. // ignored entirely and the real connection-level address retained.
  17447. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17448. observed_remote_addr == "127.0.0.1");
  17449. }
  17450. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17451. Server svr;
  17452. std::string observed_remote_addr;
  17453. std::string observed_xff;
  17454. svr.Get("/ip", [&](const Request &req, Response &res) {
  17455. observed_remote_addr = req.remote_addr;
  17456. observed_xff = req.get_header_value("X-Forwarded-For");
  17457. res.set_content("ok", "text/plain");
  17458. });
  17459. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17460. auto se = detail::scope_exit([&] {
  17461. svr.stop();
  17462. t.join();
  17463. ASSERT_FALSE(svr.is_running());
  17464. });
  17465. svr.wait_until_ready();
  17466. Client cli(HOST, PORT);
  17467. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17469. EXPECT_EQ(StatusCode::OK_200, res->status);
  17470. EXPECT_EQ(observed_xff, "203.0.113.66");
  17471. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17472. observed_remote_addr == "127.0.0.1");
  17473. }
  17474. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17475. Server svr;
  17476. svr.set_trusted_proxies({"203.0.113.66"});
  17477. std::string observed_remote_addr;
  17478. std::string observed_xff;
  17479. svr.Get("/ip", [&](const Request &req, Response &res) {
  17480. observed_remote_addr = req.remote_addr;
  17481. observed_xff = req.get_header_value("X-Forwarded-For");
  17482. res.set_content("ok", "text/plain");
  17483. });
  17484. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17485. auto se = detail::scope_exit([&] {
  17486. svr.stop();
  17487. t.join();
  17488. ASSERT_FALSE(svr.is_running());
  17489. });
  17490. svr.wait_until_ready();
  17491. Client cli(HOST, PORT);
  17492. auto res = cli.Get("/ip");
  17493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17494. EXPECT_EQ(StatusCode::OK_200, res->status);
  17495. EXPECT_EQ(observed_xff, "");
  17496. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17497. observed_remote_addr == "127.0.0.1");
  17498. }
  17499. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17500. Server svr;
  17501. // Include the loopback address the test client actually connects from, so
  17502. // the direct connection itself is recognized as the trusted proxy hop.
  17503. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17504. std::string observed_remote_addr;
  17505. std::string observed_xff;
  17506. svr.Get("/ip", [&](const Request &req, Response &res) {
  17507. observed_remote_addr = req.remote_addr;
  17508. observed_xff = req.get_header_value("X-Forwarded-For");
  17509. res.set_content("ok", "text/plain");
  17510. });
  17511. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17512. auto se = detail::scope_exit([&] {
  17513. svr.stop();
  17514. t.join();
  17515. ASSERT_FALSE(svr.is_running());
  17516. });
  17517. svr.wait_until_ready();
  17518. Client cli(HOST, PORT);
  17519. auto res = cli.Get(
  17520. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17522. EXPECT_EQ(StatusCode::OK_200, res->status);
  17523. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17524. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17525. }
  17526. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17527. Server svr;
  17528. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17529. std::string observed_remote_addr;
  17530. std::string observed_xff;
  17531. svr.Get("/ip", [&](const Request &req, Response &res) {
  17532. observed_remote_addr = req.remote_addr;
  17533. observed_xff = req.get_header_value("X-Forwarded-For");
  17534. res.set_content("ok", "text/plain");
  17535. });
  17536. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17537. auto se = detail::scope_exit([&] {
  17538. svr.stop();
  17539. t.join();
  17540. ASSERT_FALSE(svr.is_running());
  17541. });
  17542. svr.wait_until_ready();
  17543. Client cli(HOST, PORT);
  17544. auto res = cli.Get(
  17545. "/ip",
  17546. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17548. EXPECT_EQ(StatusCode::OK_200, res->status);
  17549. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17550. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17551. }
  17552. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17553. Server svr;
  17554. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17555. std::string observed_remote_addr;
  17556. std::string observed_xff;
  17557. svr.Get("/ip", [&](const Request &req, Response &res) {
  17558. observed_remote_addr = req.remote_addr;
  17559. observed_xff = req.get_header_value("X-Forwarded-For");
  17560. res.set_content("ok", "text/plain");
  17561. });
  17562. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17563. auto se = detail::scope_exit([&] {
  17564. svr.stop();
  17565. t.join();
  17566. ASSERT_FALSE(svr.is_running());
  17567. });
  17568. svr.wait_until_ready();
  17569. Client cli(HOST, PORT);
  17570. auto res = cli.Get(
  17571. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17573. EXPECT_EQ(StatusCode::OK_200, res->status);
  17574. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17575. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17576. // and must not be selected.
  17577. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17578. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17579. }
  17580. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17581. Server svr;
  17582. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17583. std::string observed_remote_addr;
  17584. svr.Get("/ip", [&](const Request &req, Response &res) {
  17585. observed_remote_addr = req.remote_addr;
  17586. res.set_content("ok", "text/plain");
  17587. });
  17588. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17589. auto se = detail::scope_exit([&] {
  17590. svr.stop();
  17591. t.join();
  17592. ASSERT_FALSE(svr.is_running());
  17593. });
  17594. svr.wait_until_ready();
  17595. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17596. // a forged address and the trusted proxy's own address; the forged value must
  17597. // not win over the address the trusted proxy actually recorded.
  17598. Client cli(HOST, PORT);
  17599. auto res = cli.Get(
  17600. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17602. EXPECT_EQ(StatusCode::OK_200, res->status);
  17603. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17604. }
  17605. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17606. Server svr;
  17607. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17608. std::string observed_remote_addr;
  17609. std::string observed_xff;
  17610. svr.Get("/ip", [&](const Request &req, Response &res) {
  17611. observed_remote_addr = req.remote_addr;
  17612. observed_xff = req.get_header_value("X-Forwarded-For");
  17613. res.set_content("ok", "text/plain");
  17614. });
  17615. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17616. auto se = detail::scope_exit([&] {
  17617. svr.stop();
  17618. t.join();
  17619. ASSERT_FALSE(svr.is_running());
  17620. });
  17621. svr.wait_until_ready();
  17622. Client cli(HOST, PORT);
  17623. auto res = cli.Get(
  17624. "/ip",
  17625. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17627. EXPECT_EQ(StatusCode::OK_200, res->status);
  17628. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17629. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17630. }
  17631. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17632. Server svr;
  17633. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17634. std::string observed_remote_addr;
  17635. std::string observed_xff;
  17636. svr.Get("/ip", [&](const Request &req, Response &res) {
  17637. observed_remote_addr = req.remote_addr;
  17638. observed_xff = req.get_header_value("X-Forwarded-For");
  17639. res.set_content("ok", "text/plain");
  17640. });
  17641. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17642. auto se = detail::scope_exit([&] {
  17643. svr.stop();
  17644. t.join();
  17645. ASSERT_FALSE(svr.is_running());
  17646. });
  17647. svr.wait_until_ready();
  17648. std::string raw_req =
  17649. "GET /ip HTTP/1.1\r\n"
  17650. "Host: localhost\r\n"
  17651. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17652. "Connection: close\r\n"
  17653. "\r\n";
  17654. std::string out;
  17655. ASSERT_TRUE(send_request(5, raw_req, &out));
  17656. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17657. // Header parser trims surrounding whitespace of the header value
  17658. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17659. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17660. }
  17661. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17662. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17663. // their own X-Forwarded-For as a separate field line rather than extending the
  17664. // one the client sent, so every occurrence has to be taken into account.
  17665. // Reading only the first one hands back the address the client chose.
  17666. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17667. Server svr;
  17668. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17669. std::string observed_remote_addr;
  17670. size_t observed_xff_count = 0;
  17671. svr.Get("/ip", [&](const Request &req, Response &res) {
  17672. observed_remote_addr = req.remote_addr;
  17673. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17674. res.set_content("ok", "text/plain");
  17675. });
  17676. auto port = svr.bind_to_any_port(HOST);
  17677. thread t = thread([&]() { svr.listen_after_bind(); });
  17678. auto se = detail::scope_exit([&] {
  17679. svr.stop();
  17680. t.join();
  17681. ASSERT_FALSE(svr.is_running());
  17682. });
  17683. svr.wait_until_ready();
  17684. // The client supplies the first field line; the trusted proxy appends the
  17685. // address it observed as a second one.
  17686. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17687. "Host: localhost\r\n"
  17688. "X-Forwarded-For: 1.2.3.4\r\n"
  17689. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17690. "Connection: close\r\n"
  17691. "\r\n";
  17692. std::string out;
  17693. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17694. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17695. EXPECT_EQ(observed_xff_count, 2U);
  17696. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17697. // The same chain spread over one field line per hop derives the same client
  17698. // address, i.e. the split and the comma-joined representations agree.
  17699. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17700. "Host: localhost\r\n"
  17701. "X-Forwarded-For: 1.2.3.4\r\n"
  17702. "X-Forwarded-For: 198.51.100.23\r\n"
  17703. "X-Forwarded-For: 192.0.2.45\r\n"
  17704. "Connection: close\r\n"
  17705. "\r\n";
  17706. out.clear();
  17707. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17708. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17709. EXPECT_EQ(observed_xff_count, 3U);
  17710. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17711. }
  17712. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17713. // crash the server (it used to call front() on an empty vector inside
  17714. // get_client_ip). The connection-level remote address must be retained instead.
  17715. static void run_malformed_xff_test(const std::string &xff_value) {
  17716. Server svr;
  17717. svr.set_trusted_proxies({"192.0.2.45"});
  17718. std::string observed_remote_addr;
  17719. svr.Get("/ip", [&](const Request &req, Response &res) {
  17720. observed_remote_addr = req.remote_addr;
  17721. res.set_content("ok", "text/plain");
  17722. });
  17723. int port = 0;
  17724. thread t = thread([&]() {
  17725. port = svr.bind_to_any_port(HOST);
  17726. svr.listen_after_bind();
  17727. });
  17728. auto se = detail::scope_exit([&] {
  17729. svr.stop();
  17730. t.join();
  17731. ASSERT_FALSE(svr.is_running());
  17732. });
  17733. svr.wait_until_ready();
  17734. Client cli(HOST, port);
  17735. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17737. EXPECT_EQ(StatusCode::OK_200, res->status);
  17738. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17739. observed_remote_addr == "127.0.0.1");
  17740. }
  17741. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17742. run_malformed_xff_test("");
  17743. }
  17744. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17745. run_malformed_xff_test(",");
  17746. }
  17747. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17748. run_malformed_xff_test(", , ,");
  17749. }
  17750. // The same rule applies to Accept: a request whose acceptable types are spread
  17751. // over several field lines must be negotiated against all of them.
  17752. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17753. // case-insensitive connection options. Comparing the whole field value against
  17754. // one option misses a client that sends several of them, and misses every
  17755. // casing but the one written in the comparison.
  17756. //
  17757. // Sends req, reads the response, then reuses the same socket for a second
  17758. // request to find out whether the server kept the connection.
  17759. static void probe_connection_reuse(int port, const std::string &req,
  17760. bool *announced_close, bool *reusable) {
  17761. auto error = Error::Success;
  17762. auto sock = detail::create_client_socket(
  17763. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17764. /*connection_timeout_sec=*/5, 0,
  17765. /*read_timeout_sec=*/1, 0,
  17766. /*write_timeout_sec=*/5, 0, std::string(), error);
  17767. ASSERT_NE(sock, INVALID_SOCKET);
  17768. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17769. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17770. "Host: localhost\r\n"
  17771. "Connection: close\r\n"
  17772. "\r\n";
  17773. std::string first_response;
  17774. std::string second_response;
  17775. detail::process_client_socket(
  17776. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17777. [&](Stream &strm) {
  17778. if (strm.write(req.data(), req.size()) !=
  17779. static_cast<ssize_t>(req.size())) {
  17780. return false;
  17781. }
  17782. char buf[512];
  17783. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17784. // Headers plus the two-byte body of the handler below
  17785. while (reader.getline()) {
  17786. first_response += reader.ptr();
  17787. if (first_response.find("ok") != std::string::npos) { break; }
  17788. }
  17789. if (strm.write(second.data(), second.size()) !=
  17790. static_cast<ssize_t>(second.size())) {
  17791. return true;
  17792. }
  17793. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17794. while (reader2.getline()) {
  17795. second_response += reader2.ptr();
  17796. if (second_response.find("ok") != std::string::npos) { break; }
  17797. }
  17798. return true;
  17799. });
  17800. *announced_close =
  17801. first_response.find("Connection: close") != std::string::npos;
  17802. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17803. }
  17804. class ConnectionTokenTest : public ::testing::Test {
  17805. protected:
  17806. void SetUp() override {
  17807. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17808. res.set_content("ok", "text/plain");
  17809. });
  17810. port_ = svr_.bind_to_any_port(HOST);
  17811. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17812. svr_.wait_until_ready();
  17813. }
  17814. void TearDown() override {
  17815. svr_.stop();
  17816. if (thread_.joinable()) { thread_.join(); }
  17817. }
  17818. Server svr_;
  17819. int port_ = 0;
  17820. thread thread_;
  17821. };
  17822. // "close" alongside another option still closes the connection, and the
  17823. // response says so rather than leaving the peer to discover it.
  17824. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17825. bool announced_close = false;
  17826. bool reusable = true;
  17827. probe_connection_reuse(port_,
  17828. "GET /keepalive HTTP/1.1\r\n"
  17829. "Host: localhost\r\n"
  17830. "Connection: keep-alive, close\r\n"
  17831. "\r\n",
  17832. &announced_close, &reusable);
  17833. EXPECT_TRUE(announced_close);
  17834. EXPECT_FALSE(reusable);
  17835. }
  17836. // "close" split over two field lines is the same list, so it is honored too.
  17837. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17838. bool announced_close = false;
  17839. bool reusable = true;
  17840. probe_connection_reuse(port_,
  17841. "GET /keepalive HTTP/1.1\r\n"
  17842. "Host: localhost\r\n"
  17843. "Connection: keep-alive\r\n"
  17844. "Connection: close\r\n"
  17845. "\r\n",
  17846. &announced_close, &reusable);
  17847. EXPECT_TRUE(announced_close);
  17848. EXPECT_FALSE(reusable);
  17849. }
  17850. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17851. // keep-alive in the spelling everyone actually sends keeps its connection.
  17852. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17853. bool announced_close = false;
  17854. bool reusable = false;
  17855. probe_connection_reuse(port_,
  17856. "GET /keepalive HTTP/1.0\r\n"
  17857. "Host: localhost\r\n"
  17858. "Connection: keep-alive\r\n"
  17859. "\r\n",
  17860. &announced_close, &reusable);
  17861. EXPECT_FALSE(announced_close);
  17862. EXPECT_TRUE(reusable);
  17863. }
  17864. // A token the value merely contains is not the token itself.
  17865. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17866. bool announced_close = false;
  17867. bool reusable = false;
  17868. probe_connection_reuse(port_,
  17869. "GET /keepalive HTTP/1.1\r\n"
  17870. "Host: localhost\r\n"
  17871. "Connection: notclose\r\n"
  17872. "\r\n",
  17873. &announced_close, &reusable);
  17874. EXPECT_FALSE(announced_close);
  17875. EXPECT_TRUE(reusable);
  17876. }
  17877. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17878. Server svr;
  17879. std::vector<std::string> observed_types;
  17880. svr.Get("/", [&](const Request &req, Response &res) {
  17881. observed_types = req.accept_content_types;
  17882. res.set_content("ok", "text/plain");
  17883. });
  17884. auto port = svr.bind_to_any_port(HOST);
  17885. thread t = thread([&]() { svr.listen_after_bind(); });
  17886. auto se = detail::scope_exit([&] {
  17887. svr.stop();
  17888. t.join();
  17889. ASSERT_FALSE(svr.is_running());
  17890. });
  17891. svr.wait_until_ready();
  17892. Client cli(HOST, port);
  17893. Headers headers;
  17894. headers.emplace("Accept", "text/plain;q=0.5");
  17895. headers.emplace("Accept", "application/json");
  17896. auto res = cli.Get("/", headers);
  17897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17898. EXPECT_EQ(StatusCode::OK_200, res->status);
  17899. // Sorted by q-value, so the second field line's type comes first
  17900. ASSERT_EQ(2U, observed_types.size());
  17901. EXPECT_EQ("application/json", observed_types[0]);
  17902. EXPECT_EQ("text/plain", observed_types[1]);
  17903. }
  17904. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17905. // empty field line must not contribute a bare comma to the combined value.
  17906. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17907. Server svr;
  17908. std::vector<std::string> observed_types;
  17909. svr.Get("/", [&](const Request &req, Response &res) {
  17910. observed_types = req.accept_content_types;
  17911. res.set_content("ok", "text/plain");
  17912. });
  17913. auto port = svr.bind_to_any_port(HOST);
  17914. thread t = thread([&]() { svr.listen_after_bind(); });
  17915. auto se = detail::scope_exit([&] {
  17916. svr.stop();
  17917. t.join();
  17918. ASSERT_FALSE(svr.is_running());
  17919. });
  17920. svr.wait_until_ready();
  17921. // Empty first field line, then a real one
  17922. std::string raw_req = "GET / HTTP/1.1\r\n"
  17923. "Host: localhost\r\n"
  17924. "Accept:\r\n"
  17925. "Accept: application/json\r\n"
  17926. "Connection: close\r\n"
  17927. "\r\n";
  17928. std::string out;
  17929. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17930. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17931. ASSERT_EQ(1U, observed_types.size());
  17932. EXPECT_EQ("application/json", observed_types[0]);
  17933. }
  17934. // The skip in get_combined_header_value() is what keeps an empty field line
  17935. // from contributing a bare comma. Only a trailing empty field line exercises
  17936. // it: a leading one is already covered by the "combined is still empty" check,
  17937. // and parse_accept_header() now ignores the empty element either way, so the
  17938. // request-level test above can no longer tell the two apart.
  17939. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17940. Headers headers;
  17941. headers.emplace("Accept", "text/html");
  17942. headers.emplace("Accept", "");
  17943. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17944. headers.clear();
  17945. headers.emplace("Accept", "");
  17946. headers.emplace("Accept", "application/json");
  17947. EXPECT_EQ("application/json",
  17948. detail::get_combined_header_value(headers, "Accept"));
  17949. }
  17950. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17951. // An encoding offered on a later Accept-Encoding field line is still offered.
  17952. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17953. Server svr;
  17954. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17955. res.set_content(std::string(1024, 'x'), "text/plain");
  17956. });
  17957. auto port = svr.bind_to_any_port(HOST);
  17958. thread t = thread([&]() { svr.listen_after_bind(); });
  17959. auto se = detail::scope_exit([&] {
  17960. svr.stop();
  17961. t.join();
  17962. ASSERT_FALSE(svr.is_running());
  17963. });
  17964. svr.wait_until_ready();
  17965. Client cli(HOST, port);
  17966. cli.set_decompress(false);
  17967. Headers headers;
  17968. headers.emplace("Accept-Encoding", "identity");
  17969. headers.emplace("Accept-Encoding", "gzip");
  17970. auto res = cli.Get("/", headers);
  17971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17972. EXPECT_EQ(StatusCode::OK_200, res->status);
  17973. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17974. }
  17975. #endif
  17976. #ifndef _WIN32
  17977. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17978. Server svr;
  17979. svr.Post("/post", [&](const Request &req, Response &res) {
  17980. res.set_content(req.body, "text/plain");
  17981. });
  17982. svr.Put("/put", [&](const Request &req, Response &res) {
  17983. res.set_content(req.body, "text/plain");
  17984. });
  17985. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17986. res.set_content(req.body, "text/plain");
  17987. });
  17988. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17989. res.set_content(req.body, "text/plain");
  17990. });
  17991. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17992. auto se = detail::scope_exit([&] {
  17993. svr.stop();
  17994. t.join();
  17995. ASSERT_FALSE(svr.is_running());
  17996. });
  17997. svr.wait_until_ready();
  17998. std::string resp;
  17999. // POST without Content-Length
  18000. ASSERT_TRUE(send_request(5,
  18001. "POST /post HTTP/1.1\r\n"
  18002. "Host: localhost\r\n"
  18003. "Connection: close\r\n"
  18004. "\r\n",
  18005. &resp));
  18006. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18007. // PUT without Content-Length
  18008. resp.clear();
  18009. ASSERT_TRUE(send_request(5,
  18010. "PUT /put HTTP/1.1\r\n"
  18011. "Host: localhost\r\n"
  18012. "Connection: close\r\n"
  18013. "\r\n",
  18014. &resp));
  18015. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18016. // PATCH without Content-Length
  18017. resp.clear();
  18018. ASSERT_TRUE(send_request(5,
  18019. "PATCH /patch HTTP/1.1\r\n"
  18020. "Host: localhost\r\n"
  18021. "Connection: close\r\n"
  18022. "\r\n",
  18023. &resp));
  18024. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18025. // DELETE without Content-Length
  18026. resp.clear();
  18027. ASSERT_TRUE(send_request(5,
  18028. "DELETE /delete HTTP/1.1\r\n"
  18029. "Host: localhost\r\n"
  18030. "Connection: close\r\n"
  18031. "\r\n",
  18032. &resp));
  18033. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18034. }
  18035. #endif
  18036. //==============================================================================
  18037. // open_stream() Tests
  18038. //==============================================================================
  18039. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18040. std::string result;
  18041. char buf[8192];
  18042. ssize_t n;
  18043. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18044. result.append(buf, static_cast<size_t>(n));
  18045. }
  18046. return result;
  18047. }
  18048. // Mock stream for unit tests
  18049. class MockStream : public Stream {
  18050. public:
  18051. std::string data;
  18052. size_t pos = 0;
  18053. ssize_t error_after = -1; // -1 = no error
  18054. explicit MockStream(const std::string &d, ssize_t err = -1)
  18055. : data(d), error_after(err) {}
  18056. bool is_readable() const override { return true; }
  18057. bool wait_readable() const override { return true; }
  18058. bool wait_writable() const override { return true; }
  18059. ssize_t read(char *ptr, size_t size) override {
  18060. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18061. if (pos >= data.size()) return 0;
  18062. size_t limit =
  18063. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18064. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18065. std::memcpy(ptr, data.data() + pos, to_read);
  18066. pos += to_read;
  18067. return static_cast<ssize_t>(to_read);
  18068. }
  18069. ssize_t write(const char *, size_t) override { return -1; }
  18070. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18071. ip = "127.0.0.1";
  18072. port = 0;
  18073. }
  18074. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18075. ip = "127.0.0.1";
  18076. port = 0;
  18077. }
  18078. socket_t socket() const override { return INVALID_SOCKET; }
  18079. time_t duration() const override { return 0; }
  18080. };
  18081. TEST(StreamHandleTest, Basic) {
  18082. ClientImpl::StreamHandle handle;
  18083. EXPECT_FALSE(handle.is_valid());
  18084. handle.response = detail::make_unique<Response>();
  18085. handle.error = Error::Connection;
  18086. EXPECT_FALSE(handle.is_valid());
  18087. handle.error = Error::Success;
  18088. EXPECT_TRUE(handle.is_valid());
  18089. }
  18090. TEST(BodyReaderTest, Basic) {
  18091. MockStream stream("Hello, World!");
  18092. detail::BodyReader reader;
  18093. reader.stream = &stream;
  18094. reader.content_length = 13;
  18095. char buf[32];
  18096. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18097. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18098. EXPECT_TRUE(reader.eof);
  18099. }
  18100. TEST(BodyReaderTest, NoStream) {
  18101. detail::BodyReader reader;
  18102. char buf[32];
  18103. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18104. EXPECT_EQ(Error::Connection, reader.last_error);
  18105. }
  18106. TEST(BodyReaderTest, Error) {
  18107. MockStream stream("Hello, World!", 5);
  18108. detail::BodyReader reader;
  18109. reader.stream = &stream;
  18110. reader.content_length = 13;
  18111. char buf[32];
  18112. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18113. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18114. EXPECT_EQ(Error::Read, reader.last_error);
  18115. }
  18116. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18117. // Mock-based StreamHandle tests relying on private internals are removed.
  18118. class OpenStreamTest : public ::testing::Test {
  18119. protected:
  18120. void SetUp() override {
  18121. svr_.Get("/hello", [](const Request &, Response &res) {
  18122. res.set_content("Hello World!", "text/plain");
  18123. });
  18124. svr_.Get("/large", [](const Request &, Response &res) {
  18125. res.set_content(std::string(10000, 'X'), "text/plain");
  18126. });
  18127. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18128. res.set_content("Hello World!", "image/jpeg");
  18129. res.set_header("Content-Encoding", "UTF-8");
  18130. });
  18131. svr_.Get("/chunked", [](const Request &, Response &res) {
  18132. res.set_chunked_content_provider("text/plain",
  18133. [](size_t offset, DataSink &sink) {
  18134. if (offset < 15) {
  18135. sink.write("chunk", 5);
  18136. return true;
  18137. }
  18138. sink.done();
  18139. return true;
  18140. });
  18141. });
  18142. svr_.Get("/compressible", [](const Request &, Response &res) {
  18143. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18144. DataSink &sink) {
  18145. if (offset < 100 * 1024) {
  18146. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18147. sink.write(chunk.data(), chunk.size());
  18148. return true;
  18149. }
  18150. sink.done();
  18151. return true;
  18152. });
  18153. });
  18154. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18155. [](const Request & /*req*/, Response &res) {
  18156. auto i = new int(0);
  18157. res.set_header("Trailer", "Content-Length, X-Allowed");
  18158. res.set_chunked_content_provider(
  18159. "text/plain",
  18160. [i](size_t /*offset*/, DataSink &sink) {
  18161. switch (*i) {
  18162. case 0: sink.os << "123"; break;
  18163. case 1: sink.os << "456"; break;
  18164. case 2: sink.os << "789"; break;
  18165. case 3: {
  18166. sink.done_with_trailer(
  18167. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18168. } break;
  18169. }
  18170. (*i)++;
  18171. return true;
  18172. },
  18173. [i](bool success) {
  18174. EXPECT_TRUE(success);
  18175. delete i;
  18176. });
  18177. });
  18178. // Echo headers endpoint for header-related tests
  18179. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18180. std::string body;
  18181. for (const auto &h : req.headers) {
  18182. body.append(h.first);
  18183. body.push_back(':');
  18184. body.append(h.second);
  18185. body.push_back('\n');
  18186. }
  18187. res.set_content(body, "text/plain");
  18188. });
  18189. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18190. std::string body;
  18191. for (const auto &h : req.headers) {
  18192. body.append(h.first);
  18193. body.push_back(':');
  18194. body.append(h.second);
  18195. body.push_back('\n');
  18196. }
  18197. res.set_content(body, "text/plain");
  18198. });
  18199. port_ = svr_.bind_to_any_port("127.0.0.1");
  18200. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18201. svr_.wait_until_ready();
  18202. }
  18203. void TearDown() override {
  18204. svr_.stop();
  18205. if (thread_.joinable()) thread_.join();
  18206. }
  18207. Server svr_;
  18208. std::thread thread_;
  18209. int port_ = 0;
  18210. };
  18211. TEST_F(OpenStreamTest, Basic) {
  18212. Client cli("127.0.0.1", port_);
  18213. auto handle = cli.open_stream("GET", "/hello");
  18214. EXPECT_TRUE(handle.is_valid());
  18215. EXPECT_EQ("Hello World!", read_all(handle));
  18216. }
  18217. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18218. Client cli("127.0.0.1", port_);
  18219. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18220. ASSERT_TRUE(handle.is_valid());
  18221. EXPECT_EQ("Hello World!", read_all(handle));
  18222. }
  18223. TEST_F(OpenStreamTest, SmallBuffer) {
  18224. Client cli("127.0.0.1", port_);
  18225. auto handle = cli.open_stream("GET", "/hello");
  18226. std::string result;
  18227. char buf[4];
  18228. ssize_t n;
  18229. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18230. result.append(buf, static_cast<size_t>(n));
  18231. EXPECT_EQ("Hello World!", result);
  18232. }
  18233. TEST_F(OpenStreamTest, DefaultHeaders) {
  18234. Client cli("127.0.0.1", port_);
  18235. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18236. {
  18237. auto handle = cli.open_stream("GET", "/echo-headers");
  18238. ASSERT_TRUE(handle.is_valid());
  18239. auto body = read_all(handle);
  18240. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18241. std::string::npos);
  18242. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18243. std::string::npos);
  18244. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18245. }
  18246. // open_stream POST with body and no explicit content_type should NOT add
  18247. // text/plain Content-Type (behavior differs from non-streaming path), but
  18248. // should include Content-Length
  18249. {
  18250. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18251. ASSERT_TRUE(handle.is_valid());
  18252. auto body = read_all(handle);
  18253. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18254. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18255. }
  18256. // open_stream POST with explicit Content-Type should preserve it
  18257. {
  18258. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18259. {{"Content-Type", "application/custom"}},
  18260. "{}", "application/custom");
  18261. ASSERT_TRUE(handle.is_valid());
  18262. auto body = read_all(handle);
  18263. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18264. }
  18265. // User-specified User-Agent must not be overwritten for stream API
  18266. {
  18267. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18268. {{"User-Agent", "MyAgent/1.2"}});
  18269. ASSERT_TRUE(handle.is_valid());
  18270. auto body = read_all(handle);
  18271. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18272. }
  18273. }
  18274. TEST_F(OpenStreamTest, Large) {
  18275. Client cli("127.0.0.1", port_);
  18276. auto handle = cli.open_stream("GET", "/large");
  18277. EXPECT_EQ(10000u, read_all(handle).size());
  18278. }
  18279. TEST_F(OpenStreamTest, ConnectionError) {
  18280. Client cli("127.0.0.1", 9999);
  18281. auto handle = cli.open_stream("GET", "/hello");
  18282. EXPECT_FALSE(handle.is_valid());
  18283. }
  18284. TEST_F(OpenStreamTest, Chunked) {
  18285. Client cli("127.0.0.1", port_);
  18286. auto handle = cli.open_stream("GET", "/chunked");
  18287. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18288. "Transfer-Encoding") == "chunked");
  18289. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18290. }
  18291. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18292. Client cli("127.0.0.1", port_);
  18293. auto handle =
  18294. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18295. ASSERT_TRUE(handle.is_valid());
  18296. // Consume body to allow trailers to be received/parsed
  18297. auto body = read_all(handle);
  18298. // Explicitly parse trailers (ensure trailers are available for assertion)
  18299. handle.parse_trailers_if_needed();
  18300. EXPECT_EQ(std::string("123456789"), body);
  18301. // The response should include a Trailer header declaring both names
  18302. ASSERT_TRUE(handle.response);
  18303. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18304. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18305. handle.response->get_header_value("Trailer"));
  18306. // Prohibited trailer must not be present
  18307. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18308. // Allowed trailer should be present
  18309. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18310. EXPECT_EQ(std::string("yes"),
  18311. handle.response->get_trailer_value("X-Allowed"));
  18312. // Verify trailers are NOT present as regular headers
  18313. EXPECT_EQ(std::string(""),
  18314. handle.response->get_header_value("Content-Length"));
  18315. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18316. }
  18317. static std::thread serve_single_response(std::promise<int> &port_promise,
  18318. const std::string &response) {
  18319. return std::thread([&port_promise, response] {
  18320. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18321. default_socket_options(srv);
  18322. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18323. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18324. sockaddr_in addr{};
  18325. addr.sin_family = AF_INET;
  18326. addr.sin_port = htons(0); // Let OS assign a free port
  18327. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18328. int opt = 1;
  18329. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18330. #ifdef _WIN32
  18331. reinterpret_cast<const char *>(&opt),
  18332. #else
  18333. &opt,
  18334. #endif
  18335. sizeof(opt));
  18336. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18337. ::listen(srv, 1) != 0) {
  18338. port_promise.set_value(-1);
  18339. detail::close_socket(srv);
  18340. return;
  18341. }
  18342. socklen_t addr_len = sizeof(addr);
  18343. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18344. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18345. sockaddr_in cli_addr{};
  18346. socklen_t cli_len = sizeof(cli_addr);
  18347. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18348. if (cli != INVALID_SOCKET) {
  18349. // Read the complete HTTP request (until the blank line that terminates
  18350. // headers) before sending the response. If the server closes the socket
  18351. // while the client's request data is still unread in the kernel receive
  18352. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18353. // connection on both sides: it discards the client's receive buffer
  18354. // (which already holds our response) and causes any in-progress write on
  18355. // the client to fail with ECONNRESET. Reading all request data first
  18356. // ensures close() emits a graceful FIN.
  18357. {
  18358. char rbuf[256];
  18359. std::string req;
  18360. while (req.find("\r\n\r\n") == std::string::npos) {
  18361. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18362. if (n <= 0) { break; }
  18363. req.append(rbuf, static_cast<size_t>(n));
  18364. }
  18365. }
  18366. ::send(cli,
  18367. #ifdef _WIN32
  18368. static_cast<const char *>(response.c_str()),
  18369. static_cast<int>(response.size()),
  18370. #else
  18371. response.c_str(), response.size(),
  18372. #endif
  18373. 0);
  18374. detail::close_socket(cli);
  18375. }
  18376. detail::close_socket(srv);
  18377. });
  18378. }
  18379. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18380. #ifndef _WIN32
  18381. signal(SIGPIPE, SIG_IGN);
  18382. #endif
  18383. std::promise<int> port_promise;
  18384. auto port_future = port_promise.get_future();
  18385. auto server_thread =
  18386. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18387. "Content-Type: text/plain\r\n"
  18388. "Content-Length: not-a-number\r\n"
  18389. "Connection: close\r\n"
  18390. "\r\n"
  18391. "hello");
  18392. auto port = port_future.get();
  18393. ASSERT_GT(port, 0);
  18394. Client cli("127.0.0.1", port);
  18395. auto handle = cli.open_stream("GET", "/");
  18396. EXPECT_FALSE(handle.is_valid());
  18397. server_thread.join();
  18398. }
  18399. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18400. #ifndef _WIN32
  18401. signal(SIGPIPE, SIG_IGN);
  18402. #endif
  18403. std::promise<int> port_promise;
  18404. auto port_future = port_promise.get_future();
  18405. auto server_thread = serve_single_response(
  18406. port_promise, "HTTP/1.1 200 OK\r\n"
  18407. "Content-Type: text/plain\r\n"
  18408. "Content-Length: 99999999999999999999999999\r\n"
  18409. "Connection: close\r\n"
  18410. "\r\n"
  18411. "hello");
  18412. auto port = port_future.get();
  18413. ASSERT_GT(port, 0);
  18414. // Historically std::stoull would throw std::out_of_range here and crash
  18415. // the process, then parsing silently clamped to a bogus framing length and
  18416. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18417. // so the stream fails to open, matching the not-a-number case above. The
  18418. // process still must NOT terminate.
  18419. Client cli("127.0.0.1", port);
  18420. auto handle = cli.open_stream("GET", "/");
  18421. EXPECT_FALSE(handle.is_valid());
  18422. server_thread.join();
  18423. }
  18424. // Serves `response` to the single request `fn` makes with a fresh client.
  18425. template <typename Fn>
  18426. static void with_single_response(const std::string &response, Fn fn) {
  18427. #ifndef _WIN32
  18428. signal(SIGPIPE, SIG_IGN);
  18429. #endif
  18430. std::promise<int> port_promise;
  18431. auto port_future = port_promise.get_future();
  18432. auto server_thread = serve_single_response(port_promise, response);
  18433. auto se = detail::scope_exit([&] { server_thread.join(); });
  18434. auto port = port_future.get();
  18435. ASSERT_GT(port, 0);
  18436. Client cli("127.0.0.1", port);
  18437. fn(cli);
  18438. }
  18439. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18440. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18441. // the chunked coding and drop Content-Length, so a front-end that trusts
  18442. // Content-Length would disagree about where the body ends (response
  18443. // smuggling). The client must reject such a response.
  18444. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18445. for (const char *te : {"chunked", "gzip, chunked"}) {
  18446. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18447. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18448. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18449. "5\r\nhello\r\n0\r\n\r\n";
  18450. with_single_response(response, [&](Client &cli) {
  18451. auto res = cli.Get("/");
  18452. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18453. EXPECT_EQ(Error::Read, res.error()) << te;
  18454. });
  18455. with_single_response(response, [&](Client &cli) {
  18456. auto handle = cli.open_stream("GET", "/");
  18457. EXPECT_FALSE(handle.is_valid()) << te;
  18458. EXPECT_EQ(Error::Read, handle.error) << te;
  18459. });
  18460. }
  18461. }
  18462. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18463. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18464. // closing the connection (unlike a request, which must be rejected).
  18465. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18466. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18467. "Transfer-Encoding: chunked\r\n"
  18468. "Connection: close\r\n"
  18469. "\r\n"
  18470. "5\r\nhello\r\n0\r\n\r\n",
  18471. "HTTP/1.1 200 OK\r\n"
  18472. "Transfer-Encoding: gzip\r\n"
  18473. "Connection: close\r\n"
  18474. "\r\n"
  18475. "hello"}) {
  18476. with_single_response(response, [&](Client &cli) {
  18477. auto res = cli.Get("/");
  18478. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18479. EXPECT_EQ("hello", res->body);
  18480. });
  18481. with_single_response(response, [&](Client &cli) {
  18482. auto handle = cli.open_stream("GET", "/");
  18483. ASSERT_TRUE(handle.is_valid()) << response;
  18484. EXPECT_EQ("hello", read_all(handle));
  18485. });
  18486. }
  18487. }
  18488. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18489. // framing headers describe nothing to read and must not be rejected.
  18490. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18491. const std::string framing = "Content-Length: 5\r\n"
  18492. "Transfer-Encoding: chunked\r\n"
  18493. "Connection: close\r\n"
  18494. "\r\n";
  18495. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18496. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18497. });
  18498. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18499. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18500. });
  18501. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18502. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18503. with_single_response(response, [&](Client &cli) {
  18504. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18505. });
  18506. with_single_response(response, [&](Client &cli) {
  18507. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18508. });
  18509. }
  18510. }
  18511. // A payload max length of 0 means no limit, however the body is framed.
  18512. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18513. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18514. "Transfer-Encoding: chunked\r\n"
  18515. "\r\n"
  18516. "5\r\nhello\r\n0\r\n\r\n",
  18517. "HTTP/1.1 200 OK\r\n"
  18518. "Connection: close\r\n"
  18519. "\r\n"
  18520. "hello"}) {
  18521. with_single_response(response, [&](Client &cli) {
  18522. cli.set_payload_max_length(0);
  18523. auto res = cli.Get("/");
  18524. ASSERT_TRUE(res) << response;
  18525. EXPECT_EQ("hello", res->body) << response;
  18526. });
  18527. }
  18528. }
  18529. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18530. Server svr;
  18531. svr.set_payload_max_length(0);
  18532. svr.Post("/echo", [](const Request &req, Response &res) {
  18533. res.set_content(req.body, "text/plain");
  18534. });
  18535. auto port = svr.bind_to_any_port(HOST);
  18536. thread t = thread([&] { svr.listen_after_bind(); });
  18537. auto se = detail::scope_exit([&] {
  18538. svr.stop();
  18539. t.join();
  18540. ASSERT_FALSE(svr.is_running());
  18541. });
  18542. svr.wait_until_ready();
  18543. Client cli(HOST, port);
  18544. auto res = cli.Post(
  18545. "/echo",
  18546. [](size_t /*offset*/, DataSink &sink) {
  18547. sink.write("hello", 5);
  18548. sink.done();
  18549. return true;
  18550. },
  18551. "text/plain");
  18552. ASSERT_TRUE(res);
  18553. EXPECT_EQ(StatusCode::OK_200, res->status);
  18554. EXPECT_EQ("hello", res->body);
  18555. }
  18556. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18557. TEST_F(OpenStreamTest, Gzip) {
  18558. Client cli("127.0.0.1", port_);
  18559. auto handle = cli.open_stream("GET", "/compressible", {},
  18560. {{"Accept-Encoding", "gzip"}});
  18561. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18562. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18563. }
  18564. #endif
  18565. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18566. TEST_F(OpenStreamTest, Brotli) {
  18567. Client cli("127.0.0.1", port_);
  18568. auto handle =
  18569. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18570. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18571. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18572. }
  18573. #endif
  18574. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18575. TEST_F(OpenStreamTest, Zstd) {
  18576. Client cli("127.0.0.1", port_);
  18577. auto handle = cli.open_stream("GET", "/compressible", {},
  18578. {{"Accept-Encoding", "zstd"}});
  18579. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18580. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18581. }
  18582. #endif
  18583. #ifdef CPPHTTPLIB_SSL_ENABLED
  18584. class SSLOpenStreamTest : public ::testing::Test {
  18585. protected:
  18586. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18587. void SetUp() override {
  18588. svr_.Get("/hello", [](const Request &, Response &res) {
  18589. res.set_content("Hello SSL World!", "text/plain");
  18590. });
  18591. svr_.Get("/chunked", [](const Request &, Response &res) {
  18592. res.set_chunked_content_provider("text/plain",
  18593. [](size_t offset, DataSink &sink) {
  18594. if (offset < 15) {
  18595. sink.write("chunk", 5);
  18596. return true;
  18597. }
  18598. sink.done();
  18599. return true;
  18600. });
  18601. });
  18602. svr_.Post("/echo", [](const Request &req, Response &res) {
  18603. res.set_content(req.body, req.get_header_value("Content-Type"));
  18604. });
  18605. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18606. std::string body = req.body;
  18607. res.set_chunked_content_provider(
  18608. "text/plain", [body](size_t offset, DataSink &sink) {
  18609. if (offset < body.size()) {
  18610. sink.write(body.data() + offset, body.size() - offset);
  18611. }
  18612. sink.done();
  18613. return true;
  18614. });
  18615. });
  18616. port_ = svr_.bind_to_any_port("127.0.0.1");
  18617. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18618. svr_.wait_until_ready();
  18619. }
  18620. void TearDown() override {
  18621. svr_.stop();
  18622. if (thread_.joinable()) thread_.join();
  18623. }
  18624. SSLServer svr_;
  18625. std::thread thread_;
  18626. int port_ = 0;
  18627. };
  18628. TEST_F(SSLOpenStreamTest, Basic) {
  18629. SSLClient cli("127.0.0.1", port_);
  18630. cli.enable_server_certificate_verification(false);
  18631. auto handle = cli.open_stream("GET", "/hello");
  18632. ASSERT_TRUE(handle.is_valid());
  18633. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18634. }
  18635. TEST_F(SSLOpenStreamTest, Chunked) {
  18636. SSLClient cli("127.0.0.1", port_);
  18637. cli.enable_server_certificate_verification(false);
  18638. auto handle = cli.open_stream("GET", "/chunked");
  18639. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18640. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18641. "Transfer-Encoding") == "chunked");
  18642. auto body = read_all(handle);
  18643. EXPECT_EQ("chunkchunkchunk", body);
  18644. }
  18645. TEST_F(SSLOpenStreamTest, Post) {
  18646. SSLClient cli("127.0.0.1", port_);
  18647. cli.enable_server_certificate_verification(false);
  18648. auto handle =
  18649. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18650. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18651. EXPECT_EQ(200, handle.response->status);
  18652. auto body = read_all(handle);
  18653. EXPECT_EQ("Hello SSL POST", body);
  18654. }
  18655. TEST_F(SSLOpenStreamTest, PostChunked) {
  18656. SSLClient cli("127.0.0.1", port_);
  18657. cli.enable_server_certificate_verification(false);
  18658. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18659. "Chunked SSL Data", "text/plain");
  18660. ASSERT_TRUE(handle.is_valid());
  18661. EXPECT_EQ(200, handle.response->status);
  18662. auto body = read_all(handle);
  18663. EXPECT_EQ("Chunked SSL Data", body);
  18664. }
  18665. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18666. // Content-Length is terminated by the server closing the connection. When the
  18667. // SSL peer sends a close_notify after the body, the client must treat it as a
  18668. // clean EOF and return a successful response rather than an error.
  18669. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18671. ASSERT_TRUE(svr.is_valid());
  18672. svr.set_keep_alive_max_count(1);
  18673. const std::string expected_body = "Hello from connection-close response!";
  18674. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18675. res.set_content_provider("text/plain",
  18676. [&](size_t offset, DataSink &sink) -> bool {
  18677. if (offset < expected_body.size()) {
  18678. sink.write(expected_body.data() + offset,
  18679. expected_body.size() - offset);
  18680. }
  18681. sink.done();
  18682. return true;
  18683. });
  18684. });
  18685. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18686. auto se = detail::scope_exit([&] {
  18687. svr.stop();
  18688. listen_thread.join();
  18689. ASSERT_FALSE(svr.is_running());
  18690. });
  18691. svr.wait_until_ready();
  18692. SSLClient cli(HOST, PORT);
  18693. cli.enable_server_certificate_verification(false);
  18694. auto res = cli.Get("/no-content-length");
  18695. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18696. EXPECT_EQ(StatusCode::OK_200, res->status);
  18697. EXPECT_EQ(expected_body, res->body);
  18698. }
  18699. #endif // CPPHTTPLIB_SSL_ENABLED
  18700. //==============================================================================
  18701. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18702. // results for various scenarios.
  18703. //==============================================================================
  18704. TEST(ParityTest, GetVsOpenStream) {
  18705. Server svr;
  18706. const std::string path = "/parity";
  18707. const std::string content = "Parity test content: hello world";
  18708. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18709. res.set_content(content, "text/plain");
  18710. });
  18711. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18712. auto se = detail::scope_exit([&] {
  18713. svr.stop();
  18714. t.join();
  18715. ASSERT_FALSE(svr.is_running());
  18716. });
  18717. svr.wait_until_ready();
  18718. Client cli(HOST, PORT);
  18719. // Non-stream path
  18720. auto r1 = cli.Get(path);
  18721. ASSERT_TRUE(r1);
  18722. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18723. // Stream path
  18724. auto h = cli.open_stream("GET", path);
  18725. ASSERT_TRUE(h.is_valid());
  18726. EXPECT_EQ(r1->body, read_all(h));
  18727. }
  18728. // Helper to compress data with provided compressor type T
  18729. template <typename Compressor>
  18730. static std::string compress_payload_for_parity(const std::string &in) {
  18731. std::string out;
  18732. Compressor compressor;
  18733. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18734. [&](const char *data, size_t n) {
  18735. out.append(data, n);
  18736. return true;
  18737. });
  18738. EXPECT_TRUE(ok);
  18739. return out;
  18740. }
  18741. // Helper function for compression parity tests
  18742. template <typename Compressor>
  18743. static void test_compression_parity(const std::string &original,
  18744. const std::string &path,
  18745. const std::string &encoding) {
  18746. const std::string compressed =
  18747. compress_payload_for_parity<Compressor>(original);
  18748. Server svr;
  18749. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18750. res.set_content(compressed, "application/octet-stream");
  18751. res.set_header("Content-Encoding", encoding);
  18752. });
  18753. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18754. auto se = detail::scope_exit([&] {
  18755. svr.stop();
  18756. t.join();
  18757. ASSERT_FALSE(svr.is_running());
  18758. });
  18759. svr.wait_until_ready();
  18760. Client cli(HOST, PORT);
  18761. // Non-streaming
  18762. {
  18763. auto res = cli.Get(path);
  18764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18765. EXPECT_EQ(StatusCode::OK_200, res->status);
  18766. EXPECT_EQ(original, res->body);
  18767. }
  18768. // Streaming
  18769. {
  18770. auto h = cli.open_stream("GET", path);
  18771. ASSERT_TRUE(h.is_valid());
  18772. EXPECT_EQ(original, read_all(h));
  18773. }
  18774. }
  18775. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18776. TEST(ParityTest, Gzip) {
  18777. test_compression_parity<detail::gzip_compressor>(
  18778. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18779. }
  18780. #endif
  18781. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18782. TEST(ParityTest, Brotli) {
  18783. test_compression_parity<detail::brotli_compressor>(
  18784. "Hello, brotli parity test payload", "/parity-br", "br");
  18785. }
  18786. #endif
  18787. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18788. TEST(ParityTest, Zstd) {
  18789. test_compression_parity<detail::zstd_compressor>(
  18790. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18791. }
  18792. #endif
  18793. //==============================================================================
  18794. // New Stream API Tests
  18795. //==============================================================================
  18796. inline std::string read_body(httplib::stream::Result &result) {
  18797. std::string body;
  18798. while (result.next()) {
  18799. body.append(result.data(), result.size());
  18800. }
  18801. return body;
  18802. }
  18803. TEST(ClientConnectionTest, Basic) {
  18804. httplib::ClientConnection conn;
  18805. EXPECT_FALSE(conn.is_open());
  18806. conn.sock = 1;
  18807. EXPECT_TRUE(conn.is_open());
  18808. httplib::ClientConnection conn2(std::move(conn));
  18809. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18810. conn2.sock = INVALID_SOCKET;
  18811. }
  18812. // Unified test server for all stream::* tests
  18813. class StreamApiTest : public ::testing::Test {
  18814. protected:
  18815. void SetUp() override {
  18816. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18817. res.set_content("Hello World!", "text/plain");
  18818. });
  18819. svr_.Get("/echo-params",
  18820. [](const httplib::Request &req, httplib::Response &res) {
  18821. std::string r;
  18822. for (const auto &p : req.params) {
  18823. if (!r.empty()) r += "&";
  18824. r += p.first + "=" + p.second;
  18825. }
  18826. res.set_content(r, "text/plain");
  18827. });
  18828. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18829. res.set_content(req.body, req.get_header_value("Content-Type"));
  18830. });
  18831. svr_.Post("/echo-headers",
  18832. [](const httplib::Request &req, httplib::Response &res) {
  18833. std::string r;
  18834. for (const auto &h : req.headers)
  18835. r += h.first + ": " + h.second + "\n";
  18836. res.set_content(r, "text/plain");
  18837. });
  18838. svr_.Post("/echo-params",
  18839. [](const httplib::Request &req, httplib::Response &res) {
  18840. std::string r = "params:";
  18841. for (const auto &p : req.params)
  18842. r += p.first + "=" + p.second + ";";
  18843. res.set_content(r + " body:" + req.body, "text/plain");
  18844. });
  18845. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18846. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18847. });
  18848. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18849. res.set_content("PUT:" + req.body, "text/plain");
  18850. });
  18851. svr_.Patch("/echo",
  18852. [](const httplib::Request &req, httplib::Response &res) {
  18853. res.set_content("PATCH:" + req.body, "text/plain");
  18854. });
  18855. svr_.Delete(
  18856. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18857. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18858. "text/plain");
  18859. });
  18860. svr_.Get("/head-test",
  18861. [](const httplib::Request &, httplib::Response &res) {
  18862. res.set_content("body for HEAD", "text/plain");
  18863. });
  18864. svr_.Options("/options",
  18865. [](const httplib::Request &, httplib::Response &res) {
  18866. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18867. });
  18868. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18869. svr_.wait_until_ready();
  18870. }
  18871. void TearDown() override {
  18872. svr_.stop();
  18873. if (thread_.joinable()) thread_.join();
  18874. }
  18875. httplib::Server svr_;
  18876. std::thread thread_;
  18877. };
  18878. // stream::Get tests
  18879. TEST_F(StreamApiTest, GetBasic) {
  18880. httplib::Client cli(HOST, PORT);
  18881. auto result = httplib::stream::Get(cli, "/hello");
  18882. ASSERT_TRUE(result.is_valid());
  18883. EXPECT_EQ(200, result.status());
  18884. EXPECT_EQ("Hello World!", read_body(result));
  18885. }
  18886. TEST_F(StreamApiTest, GetWithParams) {
  18887. httplib::Client cli(HOST, PORT);
  18888. httplib::Params params{{"foo", "bar"}};
  18889. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18890. ASSERT_TRUE(result.is_valid());
  18891. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18892. }
  18893. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18894. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  18895. httplib::Client cli(HOST, PORT);
  18896. cli.set_payload_max_length(0);
  18897. auto result = httplib::stream::Get(cli, "/hello");
  18898. ASSERT_TRUE(result.is_valid());
  18899. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  18900. EXPECT_EQ("Hello World!", read_body(result));
  18901. }
  18902. #endif
  18903. TEST_F(StreamApiTest, GetConnectionError) {
  18904. httplib::Client cli(HOST, 9999);
  18905. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18906. }
  18907. TEST_F(StreamApiTest, Get404) {
  18908. httplib::Client cli(HOST, PORT);
  18909. auto result = httplib::stream::Get(cli, "/nonexistent");
  18910. EXPECT_TRUE(result.is_valid());
  18911. EXPECT_EQ(404, result.status());
  18912. }
  18913. // stream::Post tests
  18914. TEST_F(StreamApiTest, PostBasic) {
  18915. httplib::Client cli(HOST, PORT);
  18916. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18917. "application/json");
  18918. ASSERT_TRUE(result.is_valid());
  18919. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18920. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18921. }
  18922. TEST_F(StreamApiTest, PostWithHeaders) {
  18923. httplib::Client cli(HOST, PORT);
  18924. httplib::Headers headers{{"X-Custom", "value"}};
  18925. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18926. "text/plain");
  18927. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18928. }
  18929. TEST_F(StreamApiTest, PostWithParams) {
  18930. httplib::Client cli(HOST, PORT);
  18931. httplib::Params params{{"k", "v"}};
  18932. auto result =
  18933. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18934. auto body = read_body(result);
  18935. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18936. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18937. }
  18938. TEST_F(StreamApiTest, PostLarge) {
  18939. httplib::Client cli(HOST, PORT);
  18940. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18941. size_t total = 0;
  18942. while (result.next()) {
  18943. total += result.size();
  18944. }
  18945. EXPECT_EQ(100u * 1024u, total);
  18946. }
  18947. // stream::Put/Patch tests
  18948. TEST_F(StreamApiTest, PutAndPatch) {
  18949. httplib::Client cli(HOST, PORT);
  18950. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18951. EXPECT_EQ("PUT:test", read_body(put));
  18952. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18953. EXPECT_EQ("PATCH:test", read_body(patch));
  18954. }
  18955. // stream::Delete tests
  18956. TEST_F(StreamApiTest, Delete) {
  18957. httplib::Client cli(HOST, PORT);
  18958. auto del1 = httplib::stream::Delete(cli, "/resource");
  18959. EXPECT_EQ("Deleted", read_body(del1));
  18960. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18961. EXPECT_EQ("Deleted:data", read_body(del2));
  18962. }
  18963. // stream::Head/Options tests
  18964. TEST_F(StreamApiTest, HeadAndOptions) {
  18965. httplib::Client cli(HOST, PORT);
  18966. auto head = httplib::stream::Head(cli, "/head-test");
  18967. EXPECT_TRUE(head.is_valid());
  18968. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18969. auto opts = httplib::stream::Options(cli, "/options");
  18970. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18971. }
  18972. // SSL stream::* tests
  18973. #ifdef CPPHTTPLIB_SSL_ENABLED
  18974. class SSLStreamApiTest : public ::testing::Test {
  18975. protected:
  18976. void SetUp() override {
  18977. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18978. res.set_content("Hello SSL!", "text/plain");
  18979. });
  18980. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18981. res.set_content(req.body, "text/plain");
  18982. });
  18983. port_ = svr_.bind_to_any_port("127.0.0.1");
  18984. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18985. svr_.wait_until_ready();
  18986. }
  18987. void TearDown() override {
  18988. svr_.stop();
  18989. if (thread_.joinable()) thread_.join();
  18990. }
  18991. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18992. std::thread thread_;
  18993. int port_ = 0;
  18994. };
  18995. TEST_F(SSLStreamApiTest, GetAndPost) {
  18996. httplib::SSLClient cli("127.0.0.1", port_);
  18997. cli.enable_server_certificate_verification(false);
  18998. auto get = httplib::stream::Get(cli, "/hello");
  18999. EXPECT_EQ("Hello SSL!", read_body(get));
  19000. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19001. EXPECT_EQ("test", read_body(post));
  19002. }
  19003. #endif
  19004. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19005. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19006. // BodyReader
  19007. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19008. // Test that read timeout during streaming is detected
  19009. // Use a large content-length response where server delays mid-stream
  19010. Server svr;
  19011. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19012. // Send a large response with delay in the middle
  19013. res.set_content_provider(
  19014. 1000, // content_length
  19015. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19016. if (offset < 100) {
  19017. // Send first 100 bytes immediately
  19018. std::string data(100, 'A');
  19019. sink.write(data.c_str(), data.size());
  19020. return true;
  19021. }
  19022. // Then delay longer than client timeout
  19023. std::this_thread::sleep_for(std::chrono::seconds(3));
  19024. std::string data(900, 'B');
  19025. sink.write(data.c_str(), data.size());
  19026. return true;
  19027. });
  19028. });
  19029. auto port = 8091;
  19030. std::thread t([&]() { svr.listen("localhost", port); });
  19031. svr.wait_until_ready();
  19032. Client cli("localhost", port);
  19033. cli.set_read_timeout(1, 0); // 1 second timeout
  19034. auto handle = cli.open_stream("GET", "/slow-stream");
  19035. ASSERT_TRUE(handle.is_valid());
  19036. char buf[256];
  19037. ssize_t total = 0;
  19038. ssize_t n;
  19039. bool got_error = false;
  19040. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19041. total += n;
  19042. }
  19043. if (n < 0) {
  19044. got_error = true;
  19045. // Should be timeout or read error
  19046. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19047. handle.get_read_error() == Error::Read)
  19048. << "Actual error: " << to_string(handle.get_read_error());
  19049. }
  19050. // Either we got an error, or we got less data than expected
  19051. EXPECT_TRUE(got_error || total < 1000)
  19052. << "Expected timeout but got all " << total << " bytes";
  19053. svr.stop();
  19054. t.join();
  19055. }
  19056. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19057. // Test connection closed detection via BodyReader
  19058. Server svr;
  19059. std::atomic<bool> close_now{false};
  19060. svr.Get("/will-close", [&](const Request &, Response &res) {
  19061. res.set_content_provider(
  19062. 10000, // Large content_length that we won't fully send
  19063. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19064. if (offset < 100) {
  19065. std::string data(100, 'X');
  19066. sink.write(data.c_str(), data.size());
  19067. return true;
  19068. }
  19069. // Wait for signal then abort
  19070. while (!close_now) {
  19071. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19072. }
  19073. return false; // Abort - server will close connection
  19074. });
  19075. });
  19076. auto port = 8092;
  19077. std::thread t([&]() { svr.listen("localhost", port); });
  19078. svr.wait_until_ready();
  19079. Client cli("localhost", port);
  19080. auto handle = cli.open_stream("GET", "/will-close");
  19081. ASSERT_TRUE(handle.is_valid());
  19082. char buf[256];
  19083. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19084. EXPECT_GT(n, 0) << "First read should succeed";
  19085. // Signal server to close
  19086. close_now = true;
  19087. // Keep reading until error or EOF
  19088. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19089. // Keep reading
  19090. }
  19091. // Should get an error since content_length wasn't satisfied
  19092. if (n < 0) {
  19093. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19094. handle.get_read_error() == Error::Read)
  19095. << "Actual error: " << to_string(handle.get_read_error());
  19096. }
  19097. svr.stop();
  19098. t.join();
  19099. }
  19100. #ifdef CPPHTTPLIB_SSL_ENABLED
  19101. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19102. // Test that read timeout during SSL streaming is detected
  19103. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19104. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19105. res.set_content_provider(
  19106. 1000, "text/plain",
  19107. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19108. if (offset < 100) {
  19109. std::string data(100, 'A');
  19110. sink.write(data.c_str(), data.size());
  19111. return true;
  19112. }
  19113. std::this_thread::sleep_for(std::chrono::seconds(3));
  19114. std::string data(900, 'B');
  19115. sink.write(data.c_str(), data.size());
  19116. return true;
  19117. });
  19118. });
  19119. auto port = 8093;
  19120. std::thread t([&]() { svr.listen("localhost", port); });
  19121. svr.wait_until_ready();
  19122. SSLClient cli("localhost", port);
  19123. cli.enable_server_certificate_verification(false);
  19124. cli.set_read_timeout(1, 0); // 1 second timeout
  19125. auto handle = cli.open_stream("GET", "/slow-stream");
  19126. ASSERT_TRUE(handle.is_valid());
  19127. char buf[256];
  19128. ssize_t total = 0;
  19129. ssize_t n;
  19130. bool got_error = false;
  19131. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19132. total += n;
  19133. }
  19134. if (n < 0) {
  19135. got_error = true;
  19136. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19137. handle.get_read_error() == Error::Read)
  19138. << "Actual error: " << to_string(handle.get_read_error());
  19139. }
  19140. EXPECT_TRUE(got_error || total < 1000)
  19141. << "Expected timeout but got all " << total << " bytes";
  19142. svr.stop();
  19143. t.join();
  19144. }
  19145. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19146. // Test SSL connection closed detection
  19147. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19148. std::atomic<bool> close_now{false};
  19149. svr.Get("/will-close", [&](const Request &, Response &res) {
  19150. res.set_content_provider(
  19151. 10000, "text/plain",
  19152. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19153. if (offset < 100) {
  19154. std::string data(100, 'X');
  19155. sink.write(data.c_str(), data.size());
  19156. return true;
  19157. }
  19158. while (!close_now) {
  19159. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19160. }
  19161. return false;
  19162. });
  19163. });
  19164. auto port = 8094;
  19165. std::thread t([&]() { svr.listen("localhost", port); });
  19166. svr.wait_until_ready();
  19167. SSLClient cli("localhost", port);
  19168. cli.enable_server_certificate_verification(false);
  19169. auto handle = cli.open_stream("GET", "/will-close");
  19170. ASSERT_TRUE(handle.is_valid());
  19171. char buf[256];
  19172. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19173. EXPECT_GT(n, 0);
  19174. // Signal server to close
  19175. close_now = true;
  19176. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19177. // Keep reading
  19178. }
  19179. if (n < 0) {
  19180. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19181. handle.get_read_error() == Error::Read)
  19182. << "Actual error: " << to_string(handle.get_read_error());
  19183. }
  19184. svr.stop();
  19185. t.join();
  19186. }
  19187. #endif
  19188. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19189. using namespace httplib;
  19190. // Create a test file
  19191. const char *fname = "etag_testfile.txt";
  19192. const char *content = "etag-content";
  19193. {
  19194. std::ofstream ofs(fname);
  19195. ofs << content;
  19196. ASSERT_TRUE(ofs.good());
  19197. }
  19198. Server svr;
  19199. svr.set_mount_point("/static", ".");
  19200. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19201. svr.wait_until_ready();
  19202. Client cli(HOST, PORT);
  19203. // First request: should get 200 with ETag header
  19204. auto res1 = cli.Get("/static/etag_testfile.txt");
  19205. ASSERT_TRUE(res1);
  19206. ASSERT_EQ(200, res1->status);
  19207. ASSERT_TRUE(res1->has_header("ETag"));
  19208. std::string etag = res1->get_header_value("ETag");
  19209. EXPECT_FALSE(etag.empty());
  19210. // Verify ETag format: W/"hex-hex"
  19211. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19212. EXPECT_EQ('W', etag[0]);
  19213. EXPECT_EQ('/', etag[1]);
  19214. EXPECT_EQ('"', etag[2]);
  19215. EXPECT_EQ('"', etag.back());
  19216. // Exact match: expect 304 Not Modified
  19217. Headers h2 = {{"If-None-Match", etag}};
  19218. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19219. ASSERT_TRUE(res2);
  19220. EXPECT_EQ(304, res2->status);
  19221. // Wildcard match: expect 304 Not Modified
  19222. Headers h3 = {{"If-None-Match", "*"}};
  19223. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19224. ASSERT_TRUE(res3);
  19225. EXPECT_EQ(304, res3->status);
  19226. // Non-matching ETag: expect 200
  19227. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19228. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19229. ASSERT_TRUE(res4);
  19230. EXPECT_EQ(200, res4->status);
  19231. // Multiple ETags with one matching: expect 304
  19232. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19233. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19234. ASSERT_TRUE(res5);
  19235. EXPECT_EQ(304, res5->status);
  19236. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19237. // that equivalent to the single comma-separated list above, so the match on
  19238. // the second line must still be found.
  19239. Headers h6;
  19240. h6.emplace("If-None-Match", "W/\"other\"");
  19241. h6.emplace("If-None-Match", etag);
  19242. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19243. ASSERT_TRUE(res6);
  19244. EXPECT_EQ(304, res6->status);
  19245. svr.stop();
  19246. t.join();
  19247. std::remove(fname);
  19248. }
  19249. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19250. using namespace httplib;
  19251. Server svr;
  19252. svr.set_mount_point("/static", ".");
  19253. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19254. svr.wait_until_ready();
  19255. Client cli(HOST, PORT);
  19256. // Send If-None-Match: * to a non-existent file
  19257. Headers h = {{"If-None-Match", "*"}};
  19258. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19260. EXPECT_EQ(404, res->status);
  19261. svr.stop();
  19262. t.join();
  19263. }
  19264. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19265. using namespace httplib;
  19266. // Create a test file
  19267. const char *fname = "etag_boundary_testfile.txt";
  19268. const char *content = "boundary-test";
  19269. {
  19270. std::ofstream ofs(fname);
  19271. ofs << content;
  19272. ASSERT_TRUE(ofs.good());
  19273. }
  19274. Server svr;
  19275. svr.set_mount_point("/static", ".");
  19276. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19277. svr.wait_until_ready();
  19278. Client cli(HOST, PORT);
  19279. // Get the actual ETag
  19280. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19281. ASSERT_TRUE(res1);
  19282. ASSERT_EQ(200, res1->status);
  19283. ASSERT_TRUE(res1->has_header("ETag"));
  19284. std::string etag = res1->get_header_value("ETag");
  19285. // Test 1: Very long ETag value (longer than actual ETag)
  19286. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19287. Headers h1 = {{"If-None-Match", "W/"
  19288. "\"very-long-etag-value-that-is-much-longer-"
  19289. "than-the-actual-etag-value\""}};
  19290. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19291. ASSERT_TRUE(res2);
  19292. EXPECT_EQ(200, res2->status); // Should not match
  19293. // Test 2: Long string followed by wildcard
  19294. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19295. // string)
  19296. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19297. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19298. ASSERT_TRUE(res3);
  19299. EXPECT_EQ(304, res3->status); // Should match on "*"
  19300. // Test 3: Wildcard followed by long string
  19301. // Should match on "*" immediately and return 304
  19302. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19303. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19304. ASSERT_TRUE(res4);
  19305. EXPECT_EQ(304, res4->status); // Should match on "*"
  19306. // Test 4: Multiple long non-matching values
  19307. // Should NOT match and return 200 (test that all comparisons are safe)
  19308. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19309. "W/\"second-long-non-matching-value\", "
  19310. "W/\"third-long-non-matching-value\""}};
  19311. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19312. ASSERT_TRUE(res5);
  19313. EXPECT_EQ(200, res5->status); // Should not match
  19314. // Test 5: Single character that is not "*" (edge case)
  19315. Headers h5 = {{"If-None-Match", "X"}};
  19316. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19317. ASSERT_TRUE(res6);
  19318. EXPECT_EQ(200, res6->status); // Should not match
  19319. svr.stop();
  19320. t.join();
  19321. std::remove(fname);
  19322. }
  19323. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19324. using namespace httplib;
  19325. // Create a test file
  19326. const char *fname = "ims_testfile.txt";
  19327. const char *content = "if-modified-since-test";
  19328. {
  19329. std::ofstream ofs(fname);
  19330. ofs << content;
  19331. ASSERT_TRUE(ofs.good());
  19332. }
  19333. Server svr;
  19334. svr.set_mount_point("/static", ".");
  19335. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19336. svr.wait_until_ready();
  19337. Client cli(HOST, PORT);
  19338. // First request: should get 200 with Last-Modified header
  19339. auto res1 = cli.Get("/static/ims_testfile.txt");
  19340. ASSERT_TRUE(res1);
  19341. ASSERT_EQ(200, res1->status);
  19342. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19343. std::string last_modified = res1->get_header_value("Last-Modified");
  19344. EXPECT_FALSE(last_modified.empty());
  19345. // If-Modified-Since with same time: expect 304
  19346. Headers h2 = {{"If-Modified-Since", last_modified}};
  19347. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19348. ASSERT_TRUE(res2);
  19349. EXPECT_EQ(304, res2->status);
  19350. // If-Modified-Since with future time: expect 304
  19351. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19352. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19353. ASSERT_TRUE(res3);
  19354. EXPECT_EQ(304, res3->status);
  19355. // If-Modified-Since with past time: expect 200
  19356. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19357. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19358. ASSERT_TRUE(res4);
  19359. EXPECT_EQ(200, res4->status);
  19360. // If-None-Match takes precedence over If-Modified-Since
  19361. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19362. ASSERT_TRUE(res1->has_header("ETag"));
  19363. std::string etag = res1->get_header_value("ETag");
  19364. Headers h5 = {{"If-None-Match", etag},
  19365. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19366. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19367. ASSERT_TRUE(res5);
  19368. EXPECT_EQ(304, res5->status);
  19369. svr.stop();
  19370. t.join();
  19371. std::remove(fname);
  19372. }
  19373. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19374. using namespace httplib;
  19375. Server svr;
  19376. // Endpoint that returns compressible content
  19377. svr.Get("/compressible", [](const Request &, Response &res) {
  19378. // Return a large enough body to trigger compression
  19379. std::string body(1000, 'a');
  19380. res.set_content(body, "text/plain");
  19381. });
  19382. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19383. svr.wait_until_ready();
  19384. Client cli(HOST, PORT);
  19385. // Request with gzip support: should get Vary header when compressed
  19386. cli.set_compress(true);
  19387. auto res1 = cli.Get("/compressible");
  19388. ASSERT_TRUE(res1);
  19389. EXPECT_EQ(200, res1->status);
  19390. // If Content-Encoding is set, Vary should also be set
  19391. if (res1->has_header("Content-Encoding")) {
  19392. EXPECT_TRUE(res1->has_header("Vary"));
  19393. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19394. }
  19395. // Request without Accept-Encoding header: should not have compression
  19396. Headers h_no_compress;
  19397. auto res2 = cli.Get("/compressible", h_no_compress);
  19398. ASSERT_TRUE(res2);
  19399. EXPECT_EQ(200, res2->status);
  19400. // Verify Vary header is present when compression is applied
  19401. // (the exact behavior depends on server configuration)
  19402. svr.stop();
  19403. t.join();
  19404. }
  19405. TEST(ETagTest, IfRangeWithETag) {
  19406. using namespace httplib;
  19407. // Create a test file with known content
  19408. const char *fname = "if_range_testfile.txt";
  19409. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19410. {
  19411. std::ofstream ofs(fname);
  19412. ofs << content;
  19413. ASSERT_TRUE(ofs.good());
  19414. }
  19415. Server svr;
  19416. svr.set_mount_point("/static", ".");
  19417. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19418. svr.wait_until_ready();
  19419. Client cli(HOST, PORT);
  19420. // First request: get ETag
  19421. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19422. ASSERT_TRUE(res1);
  19423. ASSERT_EQ(200, res1->status);
  19424. ASSERT_TRUE(res1->has_header("ETag"));
  19425. std::string etag = res1->get_header_value("ETag");
  19426. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19427. // Since our server generates weak ETags (W/"..."), If-Range with our
  19428. // ETag should NOT result in partial content - it should return full content.
  19429. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19430. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19431. ASSERT_TRUE(res2);
  19432. // Weak ETag in If-Range -> full content (200), not partial (206)
  19433. EXPECT_EQ(200, res2->status);
  19434. EXPECT_EQ(content, res2->body);
  19435. EXPECT_FALSE(res2->has_header("Content-Range"));
  19436. // Range request with non-matching If-Range (ETag): should get 200 (full
  19437. // content)
  19438. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19439. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19440. ASSERT_TRUE(res3);
  19441. EXPECT_EQ(200, res3->status);
  19442. EXPECT_EQ(content, res3->body);
  19443. EXPECT_FALSE(res3->has_header("Content-Range"));
  19444. // Range request with strong ETag (hypothetical - our server doesn't generate
  19445. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19446. // should return full content)
  19447. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19448. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19449. ASSERT_TRUE(res4);
  19450. EXPECT_EQ(200, res4->status);
  19451. EXPECT_EQ(content, res4->body);
  19452. EXPECT_FALSE(res4->has_header("Content-Range"));
  19453. svr.stop();
  19454. t.join();
  19455. std::remove(fname);
  19456. }
  19457. TEST(ETagTest, IfRangeWithDate) {
  19458. using namespace httplib;
  19459. // Create a test file
  19460. const char *fname = "if_range_date_testfile.txt";
  19461. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19462. {
  19463. std::ofstream ofs(fname);
  19464. ofs << content;
  19465. ASSERT_TRUE(ofs.good());
  19466. }
  19467. Server svr;
  19468. svr.set_mount_point("/static", ".");
  19469. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19470. svr.wait_until_ready();
  19471. Client cli(HOST, PORT);
  19472. // First request: get Last-Modified
  19473. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19474. ASSERT_TRUE(res1);
  19475. ASSERT_EQ(200, res1->status);
  19476. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19477. std::string last_modified = res1->get_header_value("Last-Modified");
  19478. // Range request with matching If-Range (date): should get 206
  19479. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19480. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19481. ASSERT_TRUE(res2);
  19482. EXPECT_EQ(206, res2->status);
  19483. EXPECT_EQ("FGHIJ", res2->body);
  19484. // Range request with old If-Range date: should get 200 (full content)
  19485. Headers h3 = {{"Range", "bytes=5-9"},
  19486. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19487. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19488. ASSERT_TRUE(res3);
  19489. EXPECT_EQ(200, res3->status);
  19490. EXPECT_EQ(content, res3->body);
  19491. // Range request with future If-Range date: should get 206
  19492. Headers h4 = {{"Range", "bytes=0-4"},
  19493. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19494. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19495. ASSERT_TRUE(res4);
  19496. EXPECT_EQ(206, res4->status);
  19497. EXPECT_EQ("ABCDE", res4->body);
  19498. svr.stop();
  19499. t.join();
  19500. std::remove(fname);
  19501. }
  19502. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19503. using namespace httplib;
  19504. const char *fname = "etag_malformed.txt";
  19505. const char *content = "malformed-etag";
  19506. {
  19507. std::ofstream ofs(fname);
  19508. ofs << content;
  19509. ASSERT_TRUE(ofs.good());
  19510. }
  19511. Server svr;
  19512. svr.set_mount_point("/static", ".");
  19513. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19514. svr.wait_until_ready();
  19515. Client cli(HOST, PORT);
  19516. // baseline: should get 200 and an ETag
  19517. auto res1 = cli.Get("/static/etag_malformed.txt");
  19518. ASSERT_TRUE(res1);
  19519. ASSERT_EQ(200, res1->status);
  19520. ASSERT_TRUE(res1->has_header("ETag"));
  19521. // Malformed ETag value (missing quotes) should be treated as non-matching
  19522. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19523. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19524. ASSERT_TRUE(res_bad);
  19525. EXPECT_EQ(200, res_bad->status);
  19526. // Whitespace-only header value should be considered invalid / non-matching
  19527. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19528. "Host: localhost\r\n"
  19529. "If-None-Match: \r\n"
  19530. "Connection: close\r\n"
  19531. "\r\n";
  19532. std::string out;
  19533. ASSERT_TRUE(send_request(5, raw_req, &out));
  19534. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19535. svr.stop();
  19536. t.join();
  19537. std::remove(fname);
  19538. }
  19539. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19540. using namespace httplib;
  19541. const char *fname = "ims_invalid_format.txt";
  19542. const char *content = "ims-bad-format";
  19543. {
  19544. std::ofstream ofs(fname);
  19545. ofs << content;
  19546. ASSERT_TRUE(ofs.good());
  19547. }
  19548. Server svr;
  19549. svr.set_mount_point("/static", ".");
  19550. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19551. svr.wait_until_ready();
  19552. Client cli(HOST, PORT);
  19553. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19554. ASSERT_TRUE(res1);
  19555. ASSERT_EQ(200, res1->status);
  19556. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19557. // If-Modified-Since with invalid format should not result in 304
  19558. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19559. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19560. ASSERT_TRUE(res_bad);
  19561. EXPECT_EQ(200, res_bad->status);
  19562. // If-Range with invalid date format should be treated as mismatch -> full
  19563. // content (200)
  19564. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19565. {"If-Range", "invalid-date"}};
  19566. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19567. ASSERT_TRUE(res_ifrange);
  19568. EXPECT_EQ(200, res_ifrange->status);
  19569. svr.stop();
  19570. t.join();
  19571. std::remove(fname);
  19572. }
  19573. TEST(ETagTest, IfRangeWithMalformedETag) {
  19574. using namespace httplib;
  19575. const char *fname = "ifrange_malformed.txt";
  19576. const std::string content = "0123456789";
  19577. {
  19578. std::ofstream ofs(fname);
  19579. ofs << content;
  19580. ASSERT_TRUE(ofs.good());
  19581. }
  19582. Server svr;
  19583. svr.set_mount_point("/static", ".");
  19584. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19585. svr.wait_until_ready();
  19586. Client cli(HOST, PORT);
  19587. // First request: get ETag
  19588. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19589. ASSERT_TRUE(res1);
  19590. ASSERT_EQ(200, res1->status);
  19591. ASSERT_TRUE(res1->has_header("ETag"));
  19592. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19593. // full content (200)
  19594. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19595. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19596. ASSERT_TRUE(res2);
  19597. EXPECT_EQ(200, res2->status);
  19598. EXPECT_EQ(content, res2->body);
  19599. svr.stop();
  19600. t.join();
  19601. std::remove(fname);
  19602. }
  19603. TEST(ETagTest, ExtremeLargeDateValues) {
  19604. using namespace httplib;
  19605. const char *fname = "ims_extreme_date.txt";
  19606. const char *content = "ims-extreme-date";
  19607. {
  19608. std::ofstream ofs(fname);
  19609. ofs << content;
  19610. ASSERT_TRUE(ofs.good());
  19611. }
  19612. Server svr;
  19613. svr.set_mount_point("/static", ".");
  19614. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19615. svr.wait_until_ready();
  19616. Client cli(HOST, PORT);
  19617. auto res1 = cli.Get(std::string("/static/") + fname);
  19618. ASSERT_TRUE(res1);
  19619. ASSERT_EQ(200, res1->status);
  19620. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19621. // Extremely large year that may overflow date parsing routines.
  19622. Headers h_large_date = {
  19623. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19624. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19625. ASSERT_TRUE(res_bad);
  19626. // Expect server to treat this as invalid/mismatch and return full content
  19627. EXPECT_EQ(200, res_bad->status);
  19628. // If-Range with extremely large date should be treated as mismatch -> full
  19629. // content (200)
  19630. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19631. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19632. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19633. ASSERT_TRUE(res_ifrange);
  19634. EXPECT_EQ(200, res_ifrange->status);
  19635. svr.stop();
  19636. t.join();
  19637. std::remove(fname);
  19638. }
  19639. TEST(ETagTest, NegativeFileModificationTime) {
  19640. using namespace httplib;
  19641. const char *fname = "ims_negative_mtime.txt";
  19642. const std::string content = "negative-mtime";
  19643. {
  19644. std::ofstream ofs(fname);
  19645. ofs << content;
  19646. ASSERT_TRUE(ofs.good());
  19647. }
  19648. // Try to set file mtime to a negative value. This may fail on some
  19649. // platforms/filesystems; if it fails, the test will still verify server
  19650. // behaves safely by performing a regular conditional request.
  19651. #if defined(__APPLE__) || defined(__linux__)
  19652. bool set_negative = false;
  19653. do {
  19654. struct timeval times[2];
  19655. // access time: now
  19656. times[0].tv_sec = time(nullptr);
  19657. times[0].tv_usec = 0;
  19658. // modification time: negative (e.g., -1)
  19659. times[1].tv_sec = -1;
  19660. times[1].tv_usec = 0;
  19661. if (utimes(fname, times) == 0) { set_negative = true; }
  19662. } while (0);
  19663. #else
  19664. bool set_negative = false;
  19665. #endif
  19666. Server svr;
  19667. svr.set_mount_point("/static", ".");
  19668. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19669. svr.wait_until_ready();
  19670. Client cli(HOST, PORT);
  19671. auto res1 = cli.Get(std::string("/static/") + fname);
  19672. ASSERT_TRUE(res1);
  19673. ASSERT_EQ(200, res1->status);
  19674. bool has_last_modified = res1->has_header("Last-Modified");
  19675. std::string last_modified;
  19676. if (has_last_modified) {
  19677. last_modified = res1->get_header_value("Last-Modified");
  19678. }
  19679. if (set_negative) {
  19680. // If we successfully set a negative mtime, ensure server returns a
  19681. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19682. // with an old date and ensure server handles it without crash.
  19683. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19684. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19685. ASSERT_TRUE(res2);
  19686. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19687. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19688. } else {
  19689. // Could not set negative mtime on this platform; fall back to verifying
  19690. // that normal invalid/malformed dates are treated safely (non-304).
  19691. Headers h_bad_date = {
  19692. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19693. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19694. ASSERT_TRUE(res_bad);
  19695. EXPECT_EQ(200, res_bad->status);
  19696. }
  19697. svr.stop();
  19698. t.join();
  19699. std::remove(fname);
  19700. }
  19701. //==============================================================================
  19702. // Integration Tests with Server
  19703. //==============================================================================
  19704. class SSEIntegrationTest : public ::testing::Test {
  19705. protected:
  19706. void SetUp() override {
  19707. stop_server_.store(false);
  19708. events_.clear();
  19709. server_ = httplib::detail::make_unique<Server>();
  19710. setup_server();
  19711. start_server();
  19712. }
  19713. void TearDown() override {
  19714. stop_server_.store(true);
  19715. event_cv_.notify_all();
  19716. server_->stop();
  19717. if (server_thread_.joinable()) { server_thread_.join(); }
  19718. }
  19719. void setup_server() {
  19720. // Simple SSE endpoint
  19721. server_->Get("/events", [this](const Request &req, Response &res) {
  19722. auto last_id = req.get_header_value("Last-Event-ID");
  19723. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19724. res.set_chunked_content_provider(
  19725. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19726. std::unique_lock<std::mutex> lock(event_mutex_);
  19727. if (event_cv_.wait_for(
  19728. lock, std::chrono::milliseconds(200), [this] {
  19729. return !events_.empty() || stop_server_.load();
  19730. })) {
  19731. if (stop_server_.load()) { return false; }
  19732. if (!events_.empty()) {
  19733. std::string event = events_.front();
  19734. events_.erase(events_.begin());
  19735. sink.write(event.data(), event.size());
  19736. return true;
  19737. }
  19738. }
  19739. return !stop_server_.load();
  19740. });
  19741. });
  19742. // Endpoint that returns error
  19743. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19744. res.status = 500;
  19745. res.set_content("Internal Server Error", "text/plain");
  19746. });
  19747. // Endpoint for custom event types
  19748. server_->Get("/custom-events", [](const Request &, Response &res) {
  19749. res.set_chunked_content_provider(
  19750. "text/event-stream", [](size_t offset, DataSink &sink) {
  19751. if (offset == 0) {
  19752. std::string event = "event: update\ndata: updated\n\n"
  19753. "event: delete\ndata: deleted\n\n";
  19754. sink.write(event.data(), event.size());
  19755. }
  19756. return false; // End stream after sending
  19757. });
  19758. });
  19759. }
  19760. void start_server() {
  19761. port_ = server_->bind_to_any_port(HOST);
  19762. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19763. // Wait for server to start
  19764. while (!server_->is_running()) {
  19765. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19766. }
  19767. }
  19768. int get_port() const { return port_; }
  19769. void send_event(const std::string &event) {
  19770. std::lock_guard<std::mutex> lock(event_mutex_);
  19771. events_.push_back(event);
  19772. event_cv_.notify_all();
  19773. }
  19774. std::unique_ptr<Server> server_;
  19775. std::thread server_thread_;
  19776. std::mutex event_mutex_;
  19777. std::condition_variable event_cv_;
  19778. std::vector<std::string> events_;
  19779. std::atomic<bool> stop_server_{false};
  19780. std::string last_received_event_id_;
  19781. int port_ = 0;
  19782. };
  19783. //==============================================================================
  19784. // SSE Parsing Tests
  19785. //==============================================================================
  19786. class SSEParsingTest : public SSEIntegrationTest {
  19787. protected:
  19788. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19789. // A trailing sentinel event tells when the whole stream has been parsed.
  19790. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19791. auto body = stream + "event: end\ndata: end\n\n";
  19792. server_->Get("/parse", [body](const Request &, Response &res) {
  19793. res.set_content(body, "text/event-stream");
  19794. });
  19795. return collect("/parse");
  19796. }
  19797. // Runs SSEClient against path until an "end" event arrives and returns the
  19798. // messages dispatched before it
  19799. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19800. Client client(HOST, get_port());
  19801. sse::SSEClient sse(client, path);
  19802. std::mutex mutex;
  19803. std::condition_variable cv;
  19804. std::vector<sse::SSEMessage> messages;
  19805. auto done = false;
  19806. sse.on_message([&](const sse::SSEMessage &msg) {
  19807. std::lock_guard<std::mutex> lock(mutex);
  19808. // Ignore a replay from a reconnect that races with stop()
  19809. if (!done) { messages.push_back(msg); }
  19810. });
  19811. sse.on_event("end", [&](const sse::SSEMessage &) {
  19812. std::lock_guard<std::mutex> lock(mutex);
  19813. done = true;
  19814. cv.notify_all();
  19815. });
  19816. sse.set_reconnect_interval(100);
  19817. sse.start_async();
  19818. {
  19819. std::unique_lock<std::mutex> lock(mutex);
  19820. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19821. }
  19822. sse.stop();
  19823. EXPECT_TRUE(done);
  19824. return messages;
  19825. }
  19826. };
  19827. TEST_F(SSEParsingTest, SingleLineData) {
  19828. auto msgs = parse("data: hello\n\n");
  19829. ASSERT_EQ(msgs.size(), 1u);
  19830. EXPECT_EQ(msgs[0].data, "hello");
  19831. EXPECT_EQ(msgs[0].event, "message");
  19832. }
  19833. TEST_F(SSEParsingTest, MultiLineData) {
  19834. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19835. ASSERT_EQ(msgs.size(), 1u);
  19836. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19837. }
  19838. TEST_F(SSEParsingTest, CustomEventType) {
  19839. auto msgs = parse("event: update\ndata: payload\n\n");
  19840. ASSERT_EQ(msgs.size(), 1u);
  19841. EXPECT_EQ(msgs[0].event, "update");
  19842. EXPECT_EQ(msgs[0].data, "payload");
  19843. }
  19844. TEST_F(SSEParsingTest, EventIdHandling) {
  19845. auto msgs = parse("id: 12345\ndata: test\n\n");
  19846. ASSERT_EQ(msgs.size(), 1u);
  19847. EXPECT_EQ(msgs[0].id, "12345");
  19848. }
  19849. TEST_F(SSEParsingTest, EmptyEventId) {
  19850. auto msgs = parse("id:\ndata: test\n\n");
  19851. ASSERT_EQ(msgs.size(), 1u);
  19852. EXPECT_EQ(msgs[0].id, "");
  19853. }
  19854. TEST_F(SSEParsingTest, CommentsIgnored) {
  19855. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19856. ASSERT_EQ(msgs.size(), 1u);
  19857. EXPECT_EQ(msgs[0].data, "hello");
  19858. EXPECT_EQ(msgs[0].event, "message");
  19859. }
  19860. TEST_F(SSEParsingTest, ColonInValue) {
  19861. auto msgs = parse("data: hello:world:test\n\n");
  19862. ASSERT_EQ(msgs.size(), 1u);
  19863. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19864. }
  19865. TEST_F(SSEParsingTest, FieldNameOnly) {
  19866. // A line without a colon is a field name with an empty value
  19867. auto msgs = parse("data\n\n");
  19868. ASSERT_EQ(msgs.size(), 1u);
  19869. EXPECT_EQ(msgs[0].data, "");
  19870. }
  19871. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19872. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19873. ASSERT_EQ(msgs.size(), 1u);
  19874. EXPECT_EQ(msgs[0].event, "update");
  19875. EXPECT_EQ(msgs[0].data, "hello");
  19876. }
  19877. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19878. auto msgs = parse("data\r\n\r\n");
  19879. ASSERT_EQ(msgs.size(), 1u);
  19880. EXPECT_EQ(msgs[0].data, "");
  19881. }
  19882. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19883. auto msgs = parse("event: update\rdata: hello\r\r");
  19884. ASSERT_EQ(msgs.size(), 1u);
  19885. EXPECT_EQ(msgs[0].event, "update");
  19886. EXPECT_EQ(msgs[0].data, "hello");
  19887. }
  19888. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19889. // Chunk boundaries fall inside every \r\n and right before the first one
  19890. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19891. "\n\r", "\nevent: end\ndata: end\n\n"};
  19892. server_->Get("/split", [chunks](const Request &, Response &res) {
  19893. auto i = std::make_shared<size_t>(0);
  19894. res.set_chunked_content_provider(
  19895. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19896. if (*i == chunks.size()) {
  19897. sink.done();
  19898. } else {
  19899. sink.write(chunks[*i].data(), chunks[*i].size());
  19900. (*i)++;
  19901. }
  19902. return true;
  19903. });
  19904. });
  19905. auto msgs = collect("/split");
  19906. ASSERT_EQ(msgs.size(), 1u);
  19907. EXPECT_EQ(msgs[0].event, "update");
  19908. EXPECT_EQ(msgs[0].data, "hello");
  19909. }
  19910. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19911. // Only a BOM at the start of the stream is ignored
  19912. auto msgs = parse("\xEF\xBB\xBF"
  19913. "data: first\n\n"
  19914. "\xEF\xBB\xBF"
  19915. "data: second\n\n");
  19916. ASSERT_EQ(msgs.size(), 1u);
  19917. EXPECT_EQ(msgs[0].data, "first");
  19918. }
  19919. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19920. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19921. ASSERT_EQ(msgs.size(), 1u);
  19922. EXPECT_EQ(msgs[0].data, "hello");
  19923. EXPECT_EQ(msgs[0].event, "message");
  19924. }
  19925. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19926. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19927. ASSERT_EQ(msgs.size(), 2u);
  19928. EXPECT_EQ(msgs[0].data, "hello");
  19929. EXPECT_EQ(msgs[1].data, "hello");
  19930. }
  19931. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19932. // An event without data is not dispatched, and its type must not leak
  19933. // into the next event
  19934. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19935. ASSERT_EQ(msgs.size(), 1u);
  19936. EXPECT_EQ(msgs[0].event, "message");
  19937. EXPECT_EQ(msgs[0].data, "hello");
  19938. }
  19939. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19940. // The first connection sends only an id; the second echoes back the
  19941. // Last-Event-ID it was reconnected with
  19942. std::atomic<int> connection_count{0};
  19943. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19944. if (connection_count++ == 0) {
  19945. res.set_content("id: 42\n\n", "text/event-stream");
  19946. } else {
  19947. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19948. "\n\nevent: end\ndata: end\n\n",
  19949. "text/event-stream");
  19950. }
  19951. });
  19952. auto msgs = collect("/id-only");
  19953. ASSERT_EQ(msgs.size(), 1u);
  19954. EXPECT_EQ(msgs[0].data, "42");
  19955. }
  19956. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19957. // The first connection sets an id and then clears it with an empty one; the
  19958. // second reports whether it was reconnected with a Last-Event-ID
  19959. std::atomic<int> connection_count{0};
  19960. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19961. if (connection_count++ == 0) {
  19962. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19963. "text/event-stream");
  19964. } else {
  19965. res.set_content(
  19966. std::string("data: ") +
  19967. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19968. "\n\nevent: end\ndata: end\n\n",
  19969. "text/event-stream");
  19970. }
  19971. });
  19972. auto msgs = collect("/id-clear");
  19973. ASSERT_EQ(msgs.size(), 3u);
  19974. EXPECT_EQ(msgs[0].id, "1");
  19975. EXPECT_EQ(msgs[1].id, "");
  19976. EXPECT_EQ(msgs[2].data, "not sent");
  19977. }
  19978. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19979. // The first connection sets an id and then sends ids that cannot be carried
  19980. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19981. // with
  19982. std::atomic<int> connection_count{0};
  19983. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19984. if (connection_count++ == 0) {
  19985. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19986. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19987. "text/event-stream");
  19988. } else {
  19989. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19990. "\n\nevent: end\ndata: end\n\n",
  19991. "text/event-stream");
  19992. }
  19993. });
  19994. auto msgs = collect("/id-unsendable");
  19995. ASSERT_EQ(msgs.size(), 1u);
  19996. EXPECT_EQ(msgs[0].data, "42");
  19997. }
  19998. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19999. auto msgs = parse("event: notification\nid: evt-42\n"
  20000. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20001. ASSERT_EQ(msgs.size(), 1u);
  20002. EXPECT_EQ(msgs[0].event, "notification");
  20003. EXPECT_EQ(msgs[0].id, "evt-42");
  20004. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20005. }
  20006. TEST(SSEMessageTest, Clear) {
  20007. sse::SSEMessage msg;
  20008. msg.event = "custom";
  20009. msg.data = "some data";
  20010. msg.id = "123";
  20011. msg.clear();
  20012. EXPECT_EQ(msg.event, "message");
  20013. EXPECT_EQ(msg.data, "");
  20014. EXPECT_EQ(msg.id, "");
  20015. }
  20016. //==============================================================================
  20017. // SSE Integration Tests
  20018. //==============================================================================
  20019. // Test: Successful connection and on_open callback
  20020. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20021. // Add a simple endpoint that sends one event and closes
  20022. server_->Get("/simple-event", [](const Request &, Response &res) {
  20023. res.set_chunked_content_provider(
  20024. "text/event-stream", [](size_t offset, DataSink &sink) {
  20025. if (offset == 0) {
  20026. std::string event = "data: hello\n\n";
  20027. sink.write(event.data(), event.size());
  20028. }
  20029. return false; // Close stream after sending
  20030. });
  20031. });
  20032. Client client("localhost", get_port());
  20033. sse::SSEClient sse(client, "/simple-event");
  20034. std::atomic<bool> open_called{false};
  20035. std::atomic<bool> message_received{false};
  20036. sse.on_open([&open_called]() { open_called.store(true); });
  20037. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20038. if (msg.data == "hello") { message_received.store(true); }
  20039. });
  20040. sse.set_reconnect_interval(100);
  20041. sse.set_max_reconnect_attempts(1);
  20042. // Start async
  20043. sse.start_async();
  20044. // Wait for message to be processed
  20045. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20046. sse.stop();
  20047. EXPECT_TRUE(open_called.load());
  20048. EXPECT_TRUE(message_received.load());
  20049. }
  20050. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20051. // A data line that never ends.
  20052. server_->Get("/endless-line", [](const Request &, Response &res) {
  20053. res.set_chunked_content_provider(
  20054. "text/event-stream", [](size_t offset, DataSink &sink) {
  20055. if (offset == 0) { sink.write("data: ", 6); }
  20056. std::string chunk(64 * 1024, 'A');
  20057. return sink.write(chunk.data(), chunk.size());
  20058. });
  20059. });
  20060. Client client("localhost", get_port());
  20061. // A stream that may run forever, so that only the event is bounded.
  20062. client.set_payload_max_length(0);
  20063. sse::SSEClient sse(client, "/endless-line");
  20064. std::atomic<bool> too_long{false};
  20065. sse.on_error([&](Error err) {
  20066. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20067. });
  20068. sse.set_max_reconnect_attempts(1);
  20069. sse.start_async();
  20070. for (int i = 0; i < 500 && !too_long; i++) {
  20071. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20072. }
  20073. sse.stop();
  20074. EXPECT_TRUE(too_long);
  20075. }
  20076. // Test: on_message callback
  20077. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20078. // Endpoint that sends multiple events then closes
  20079. server_->Get("/multi-event", [](const Request &, Response &res) {
  20080. res.set_chunked_content_provider(
  20081. "text/event-stream", [](size_t offset, DataSink &sink) {
  20082. if (offset == 0) {
  20083. std::string events = "data: message1\n\ndata: message2\n\n";
  20084. sink.write(events.data(), events.size());
  20085. }
  20086. return false;
  20087. });
  20088. });
  20089. Client client("localhost", get_port());
  20090. sse::SSEClient sse(client, "/multi-event");
  20091. std::vector<std::string> received_messages;
  20092. std::mutex messages_mutex;
  20093. sse.on_message([&](const sse::SSEMessage &msg) {
  20094. std::lock_guard<std::mutex> lock(messages_mutex);
  20095. received_messages.push_back(msg.data);
  20096. });
  20097. sse.set_reconnect_interval(100);
  20098. sse.set_max_reconnect_attempts(1);
  20099. sse.start_async();
  20100. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20101. sse.stop();
  20102. std::lock_guard<std::mutex> lock(messages_mutex);
  20103. EXPECT_GE(received_messages.size(), 2u);
  20104. if (received_messages.size() >= 2) {
  20105. EXPECT_EQ(received_messages[0], "message1");
  20106. EXPECT_EQ(received_messages[1], "message2");
  20107. }
  20108. }
  20109. // Test: on_event for specific types
  20110. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20111. Client client("localhost", get_port());
  20112. sse::SSEClient sse(client, "/custom-events");
  20113. std::atomic<bool> update_received{false};
  20114. std::atomic<bool> delete_received{false};
  20115. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20116. if (msg.data == "updated") { update_received.store(true); }
  20117. });
  20118. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20119. if (msg.data == "deleted") { delete_received.store(true); }
  20120. });
  20121. sse.set_max_reconnect_attempts(1);
  20122. sse.start_async();
  20123. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20124. sse.stop();
  20125. EXPECT_TRUE(update_received.load());
  20126. EXPECT_TRUE(delete_received.load());
  20127. }
  20128. // Test: on_error callback on connection failure
  20129. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20130. // Connect to a non-existent port
  20131. Client client("localhost", 59999);
  20132. sse::SSEClient sse(client, "/events");
  20133. std::atomic<bool> error_called{false};
  20134. Error received_error = Error::Success;
  20135. sse.on_error([&](Error err) {
  20136. error_called.store(true);
  20137. received_error = err;
  20138. });
  20139. sse.set_reconnect_interval(50);
  20140. sse.set_max_reconnect_attempts(1);
  20141. sse.start_async();
  20142. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20143. sse.stop();
  20144. EXPECT_TRUE(error_called.load());
  20145. EXPECT_NE(received_error, Error::Success);
  20146. }
  20147. // Test: Last-Event-ID header sent on reconnect
  20148. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20149. // Endpoint that sends event with ID
  20150. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20151. res.set_chunked_content_provider(
  20152. "text/event-stream", [](size_t offset, DataSink &sink) {
  20153. if (offset == 0) {
  20154. std::string event = "id: evt-123\ndata: test\n\n";
  20155. sink.write(event.data(), event.size());
  20156. }
  20157. return false;
  20158. });
  20159. });
  20160. Client client("localhost", get_port());
  20161. sse::SSEClient sse(client, "/event-with-id");
  20162. std::atomic<bool> id_received{false};
  20163. sse.on_message([&](const sse::SSEMessage &msg) {
  20164. if (!msg.id.empty()) { id_received.store(true); }
  20165. });
  20166. sse.set_reconnect_interval(100);
  20167. sse.set_max_reconnect_attempts(1);
  20168. sse.start_async();
  20169. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20170. sse.stop();
  20171. EXPECT_TRUE(id_received.load());
  20172. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20173. }
  20174. // Test: Manual stop
  20175. TEST_F(SSEIntegrationTest, ManualStop) {
  20176. // Endpoint that sends one event and stays open briefly
  20177. std::atomic<bool> handler_running{true};
  20178. server_->Get("/stay-open", [&handler_running](const Request &,
  20179. Response &res) {
  20180. res.set_chunked_content_provider(
  20181. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20182. if (offset == 0) {
  20183. std::string event = "data: connected\n\n";
  20184. sink.write(event.data(), event.size());
  20185. }
  20186. // Keep connection open while handler_running is true
  20187. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20188. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20189. }
  20190. return false;
  20191. });
  20192. });
  20193. Client client("localhost", get_port());
  20194. sse::SSEClient sse(client, "/stay-open");
  20195. std::atomic<bool> connected{false};
  20196. sse.on_open([&connected]() { connected.store(true); });
  20197. sse.set_reconnect_interval(100);
  20198. sse.set_max_reconnect_attempts(1);
  20199. sse.start_async();
  20200. // Wait for connection to establish
  20201. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20202. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20203. }
  20204. EXPECT_TRUE(connected.load());
  20205. EXPECT_TRUE(sse.is_connected());
  20206. // Signal handler to stop
  20207. handler_running.store(false);
  20208. // Stop SSE client
  20209. sse.stop();
  20210. EXPECT_FALSE(sse.is_connected());
  20211. }
  20212. // Test: SSEClient with custom headers
  20213. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20214. // Setup a server endpoint that checks for custom header
  20215. std::atomic<bool> header_received{false};
  20216. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20217. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20218. header_received.store(true);
  20219. }
  20220. res.set_chunked_content_provider("text/event-stream",
  20221. [](size_t, DataSink &) { return false; });
  20222. });
  20223. Client client("localhost", get_port());
  20224. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20225. sse::SSEClient sse(client, "/header-check", headers);
  20226. sse.set_max_reconnect_attempts(1);
  20227. sse.start_async();
  20228. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20229. sse.stop();
  20230. EXPECT_TRUE(header_received.load());
  20231. }
  20232. // Test: Reconnect interval configuration
  20233. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20234. Client client("localhost", get_port());
  20235. sse::SSEClient sse(client, "/events");
  20236. auto &result = sse.set_reconnect_interval(500);
  20237. // Builder pattern should return reference to self
  20238. EXPECT_EQ(&result, &sse);
  20239. }
  20240. // Test: Max reconnect attempts
  20241. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20242. // Connect to non-existent port to force reconnects
  20243. Client client("localhost", 59998);
  20244. sse::SSEClient sse(client, "/events");
  20245. std::atomic<int> error_count{0};
  20246. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20247. sse.set_reconnect_interval(50);
  20248. sse.set_max_reconnect_attempts(2);
  20249. auto start = std::chrono::steady_clock::now();
  20250. sse.start(); // Blocking call
  20251. auto end = std::chrono::steady_clock::now();
  20252. // Should have stopped after 2 failed attempts
  20253. EXPECT_GE(error_count.load(), 2);
  20254. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20255. auto duration =
  20256. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20257. #ifdef _WIN32
  20258. // Windows is much slower for socket connection failures
  20259. EXPECT_LT(duration.count(), 7000);
  20260. #else
  20261. EXPECT_LT(duration.count(), 1000);
  20262. #endif
  20263. }
  20264. // Test: Multi-line data in integration
  20265. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20266. // Endpoint with multi-line data
  20267. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20268. res.set_chunked_content_provider(
  20269. "text/event-stream", [](size_t offset, DataSink &sink) {
  20270. if (offset == 0) {
  20271. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20272. sink.write(event.data(), event.size());
  20273. }
  20274. return false;
  20275. });
  20276. });
  20277. Client client("localhost", get_port());
  20278. sse::SSEClient sse(client, "/multiline-data");
  20279. std::string received_data;
  20280. std::mutex data_mutex;
  20281. sse.on_message([&](const sse::SSEMessage &msg) {
  20282. std::lock_guard<std::mutex> lock(data_mutex);
  20283. received_data = msg.data;
  20284. });
  20285. sse.set_reconnect_interval(100);
  20286. sse.set_max_reconnect_attempts(1);
  20287. sse.start_async();
  20288. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20289. sse.stop();
  20290. std::lock_guard<std::mutex> lock(data_mutex);
  20291. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20292. }
  20293. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20294. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20295. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20296. DataSink &sink) {
  20297. if (offset == 0) {
  20298. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20299. sink.write(events.data(), events.size());
  20300. }
  20301. return false;
  20302. });
  20303. });
  20304. Client client("localhost", get_port());
  20305. sse::SSEClient sse(client, "/empty-data-lines");
  20306. std::mutex mutex;
  20307. std::condition_variable cv;
  20308. std::vector<std::string> received;
  20309. sse.on_message([&](const sse::SSEMessage &msg) {
  20310. std::lock_guard<std::mutex> lock(mutex);
  20311. received.push_back(msg.data);
  20312. cv.notify_all();
  20313. });
  20314. sse.set_max_reconnect_attempts(1);
  20315. sse.start_async();
  20316. {
  20317. std::unique_lock<std::mutex> lock(mutex);
  20318. cv.wait_for(lock, std::chrono::seconds(2),
  20319. [&] { return received.size() >= 3; });
  20320. }
  20321. sse.stop();
  20322. ASSERT_GE(received.size(), 3u);
  20323. EXPECT_EQ(received[0], "");
  20324. EXPECT_EQ(received[1], "\nhello");
  20325. EXPECT_EQ(received[2], "");
  20326. }
  20327. // Test: Auto-reconnect after server disconnection
  20328. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20329. std::atomic<int> connection_count{0};
  20330. std::atomic<int> message_count{0};
  20331. // Endpoint that sends one event and closes, forcing reconnect
  20332. server_->Get("/reconnect-test",
  20333. [&connection_count](const Request &, Response &res) {
  20334. connection_count.fetch_add(1);
  20335. res.set_chunked_content_provider(
  20336. "text/event-stream", [](size_t offset, DataSink &sink) {
  20337. if (offset == 0) {
  20338. std::string event = "data: hello\n\n";
  20339. sink.write(event.data(), event.size());
  20340. }
  20341. return false; // Close connection after sending
  20342. });
  20343. });
  20344. Client client("localhost", get_port());
  20345. sse::SSEClient sse(client, "/reconnect-test");
  20346. sse.on_message([&message_count](const sse::SSEMessage &) {
  20347. message_count.fetch_add(1);
  20348. });
  20349. sse.set_reconnect_interval(100);
  20350. sse.set_max_reconnect_attempts(3);
  20351. sse.start_async();
  20352. // Wait long enough for multiple reconnects
  20353. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20354. sse.stop();
  20355. // Should have connected multiple times (initial + reconnects)
  20356. EXPECT_GE(connection_count.load(), 2);
  20357. // Should have received messages from multiple connections
  20358. EXPECT_GE(message_count.load(), 2);
  20359. }
  20360. // Test: A retry field that is not all ASCII digits is ignored
  20361. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20362. std::atomic<int> connection_count{0};
  20363. server_->Get("/bad-retry",
  20364. [&connection_count](const Request &, Response &res) {
  20365. connection_count.fetch_add(1);
  20366. res.set_chunked_content_provider(
  20367. "text/event-stream", [](size_t offset, DataSink &sink) {
  20368. if (offset == 0) {
  20369. std::string event = "retry: -1\ndata: hello\n\n";
  20370. sink.write(event.data(), event.size());
  20371. }
  20372. return false;
  20373. });
  20374. });
  20375. Client client("localhost", get_port());
  20376. sse::SSEClient sse(client, "/bad-retry");
  20377. sse.set_reconnect_interval(10000);
  20378. sse.start_async();
  20379. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20380. sse.stop();
  20381. EXPECT_EQ(connection_count.load(), 1);
  20382. }
  20383. // Test: A retry field of all ASCII digits sets the reconnection time
  20384. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20385. std::mutex mutex;
  20386. std::condition_variable cv;
  20387. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20388. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20389. {
  20390. std::lock_guard<std::mutex> lock(mutex);
  20391. connected_at.push_back(std::chrono::steady_clock::now());
  20392. cv.notify_all();
  20393. }
  20394. res.set_chunked_content_provider(
  20395. "text/event-stream", [](size_t offset, DataSink &sink) {
  20396. if (offset == 0) {
  20397. std::string event = "retry: 0\ndata: hello\n\n";
  20398. sink.write(event.data(), event.size());
  20399. }
  20400. return false;
  20401. });
  20402. });
  20403. Client client("localhost", get_port());
  20404. sse::SSEClient sse(client, "/zero-retry");
  20405. sse.set_reconnect_interval(10000);
  20406. sse.start_async();
  20407. {
  20408. std::unique_lock<std::mutex> lock(mutex);
  20409. cv.wait_for(lock, std::chrono::seconds(5),
  20410. [&] { return connected_at.size() >= 2; });
  20411. }
  20412. sse.stop();
  20413. // The server-supplied interval is applied, but never below 100ms, so
  20414. // "retry: 0" does not cause a busy reconnect loop
  20415. std::lock_guard<std::mutex> lock(mutex);
  20416. ASSERT_GE(connected_at.size(), 2u);
  20417. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20418. connected_at[1] - connected_at[0])
  20419. .count();
  20420. EXPECT_GE(interval_ms, 100);
  20421. }
  20422. // Test: Last-Event-ID sent on reconnect
  20423. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20424. std::atomic<int> connection_count{0};
  20425. std::vector<std::string> received_last_event_ids;
  20426. std::mutex id_mutex;
  20427. // Endpoint that checks Last-Event-ID header and sends event with ID
  20428. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20429. int conn = connection_count.fetch_add(1);
  20430. // Capture the Last-Event-ID header from each connection
  20431. {
  20432. std::lock_guard<std::mutex> lock(id_mutex);
  20433. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20434. }
  20435. res.set_chunked_content_provider(
  20436. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20437. if (offset == 0) {
  20438. std::string event =
  20439. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20440. sink.write(event.data(), event.size());
  20441. }
  20442. return false;
  20443. });
  20444. });
  20445. Client client("localhost", get_port());
  20446. sse::SSEClient sse(client, "/reconnect-with-id");
  20447. sse.set_reconnect_interval(100);
  20448. sse.set_max_reconnect_attempts(3);
  20449. sse.start_async();
  20450. // Wait for at least 2 connections
  20451. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20452. sse.stop();
  20453. // Verify behavior
  20454. std::lock_guard<std::mutex> lock(id_mutex);
  20455. EXPECT_GE(received_last_event_ids.size(), 2u);
  20456. // First connection should have no Last-Event-ID
  20457. if (!received_last_event_ids.empty()) {
  20458. EXPECT_EQ(received_last_event_ids[0], "");
  20459. }
  20460. // Second connection should have Last-Event-ID from first connection
  20461. if (received_last_event_ids.size() >= 2) {
  20462. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20463. }
  20464. }
  20465. // Test: set_headers updates headers used on reconnect
  20466. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20467. std::vector<std::string> received_tokens;
  20468. std::mutex token_mutex;
  20469. // Endpoint that captures Authorization header
  20470. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20471. {
  20472. std::lock_guard<std::mutex> lock(token_mutex);
  20473. received_tokens.push_back(req.get_header_value("Authorization"));
  20474. }
  20475. res.set_chunked_content_provider(
  20476. "text/event-stream", [](size_t offset, DataSink &sink) {
  20477. if (offset == 0) {
  20478. std::string event = "data: hello\n\n";
  20479. sink.write(event.data(), event.size());
  20480. }
  20481. return false; // Close connection to trigger reconnect
  20482. });
  20483. });
  20484. Client client("localhost", get_port());
  20485. Headers headers = {{"Authorization", "Bearer old-token"}};
  20486. sse::SSEClient sse(client, "/auth-check", headers);
  20487. // Update headers on each successful connection
  20488. sse.on_open(
  20489. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20490. sse.set_reconnect_interval(100);
  20491. sse.set_max_reconnect_attempts(3);
  20492. sse.start_async();
  20493. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20494. sse.stop();
  20495. std::lock_guard<std::mutex> lock(token_mutex);
  20496. ASSERT_GE(received_tokens.size(), 2u);
  20497. // First connection uses original header
  20498. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20499. // Second connection uses updated header from set_headers
  20500. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20501. }
  20502. // Test: 401 allows reconnection (so on_error can refresh headers)
  20503. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20504. std::atomic<int> connection_count{0};
  20505. // Endpoint: returns 401 on first attempt, 200 on second
  20506. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20507. int conn = connection_count.fetch_add(1);
  20508. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20509. res.status = StatusCode::Unauthorized_401;
  20510. res.set_content("Unauthorized", "text/plain");
  20511. return;
  20512. }
  20513. res.set_chunked_content_provider(
  20514. "text/event-stream", [](size_t offset, DataSink &sink) {
  20515. if (offset == 0) {
  20516. std::string event = "data: authenticated\n\n";
  20517. sink.write(event.data(), event.size());
  20518. }
  20519. return false;
  20520. });
  20521. });
  20522. Client client("localhost", get_port());
  20523. Headers headers = {{"Authorization", "Bearer expired"}};
  20524. sse::SSEClient sse(client, "/auth-retry", headers);
  20525. std::atomic<bool> message_received{false};
  20526. // Refresh token on error
  20527. sse.on_error(
  20528. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20529. sse.on_message([&](const sse::SSEMessage &msg) {
  20530. if (msg.data == "authenticated") { message_received.store(true); }
  20531. });
  20532. sse.set_reconnect_interval(100);
  20533. sse.set_max_reconnect_attempts(3);
  20534. sse.start_async();
  20535. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20536. sse.stop();
  20537. // Should have reconnected after 401 and succeeded with new token
  20538. EXPECT_GE(connection_count.load(), 2);
  20539. EXPECT_TRUE(message_received.load());
  20540. }
  20541. TEST(Issue2318Test, EmptyHostString) {
  20542. {
  20543. httplib::Client cli_empty("", PORT);
  20544. auto res = cli_empty.Get("/");
  20545. ASSERT_FALSE(res);
  20546. EXPECT_EQ(httplib::Error::Connection, res.error());
  20547. }
  20548. {
  20549. httplib::Client cli(" ", PORT);
  20550. auto res = cli.Get("/");
  20551. ASSERT_FALSE(res);
  20552. EXPECT_EQ(httplib::Error::Connection, res.error());
  20553. }
  20554. }
  20555. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20556. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20557. Server svr;
  20558. // Set a small payload limit (1KB)
  20559. svr.set_payload_max_length(1024);
  20560. svr.Post("/test", [&](const Request &req, Response &res) {
  20561. res.set_content("Body size: " + std::to_string(req.body.size()),
  20562. "text/plain");
  20563. });
  20564. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20565. auto se = detail::scope_exit([&] {
  20566. svr.stop();
  20567. listen_thread.join();
  20568. });
  20569. svr.wait_until_ready();
  20570. // Create data that compresses well but exceeds limit when decompressed
  20571. // 8KB of repeated null bytes compresses to a very small size
  20572. std::string original_data(8 * 1024, '\0');
  20573. // Compress the data using gzip
  20574. std::string compressed_data;
  20575. detail::gzip_compressor compressor;
  20576. compressor.compress(original_data.data(), original_data.size(), true,
  20577. [&](const char *data, size_t size) {
  20578. compressed_data.append(data, size);
  20579. return true;
  20580. });
  20581. // Verify compression worked (compressed should be much smaller)
  20582. ASSERT_LT(compressed_data.size(), original_data.size());
  20583. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20584. // Send compressed data with Content-Encoding: gzip
  20585. Client cli(HOST, PORT);
  20586. Headers headers = {{"Content-Encoding", "gzip"}};
  20587. auto res =
  20588. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20589. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20591. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20592. }
  20593. #endif
  20594. // ============================================================================
  20595. // OpenSSL-Specific Tests
  20596. // ============================================================================
  20597. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20598. X509 *readCertificate(const std::string &strFileName) {
  20599. std::ifstream inStream(strFileName);
  20600. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20601. std::istreambuf_iterator<char>());
  20602. if (strCertPEM.empty()) return (nullptr);
  20603. BIO *pbCert = BIO_new(BIO_s_mem());
  20604. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20605. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20606. BIO_free(pbCert);
  20607. return (pCert);
  20608. }
  20609. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20610. std::ifstream inStream(strFileName);
  20611. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20612. std::istreambuf_iterator<char>());
  20613. if (strPrivateKeyPEM.empty()) return (nullptr);
  20614. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20615. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20616. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20617. BIO_free(pbPrivKey);
  20618. return (pPrivateKey);
  20619. }
  20620. TEST(BindServerTest, UpdateCerts) {
  20621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20622. int port = svr.bind_to_any_port("0.0.0.0");
  20623. ASSERT_TRUE(svr.is_valid());
  20624. ASSERT_TRUE(port > 0);
  20625. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20626. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20627. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20628. ASSERT_TRUE(cert != nullptr);
  20629. ASSERT_TRUE(ca_cert != nullptr);
  20630. ASSERT_TRUE(key != nullptr);
  20631. X509_STORE *cert_store = X509_STORE_new();
  20632. X509_STORE_add_cert(cert_store, ca_cert);
  20633. // svr.update_certs(cert, key, cert_store); // deprecated
  20634. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20635. CLIENT_CA_CERT_FILE);
  20636. ASSERT_TRUE(svr.is_valid());
  20637. svr.stop();
  20638. X509_STORE_free(cert_store);
  20639. X509_free(cert);
  20640. X509_free(ca_cert);
  20641. EVP_PKEY_free(key);
  20642. }
  20643. // Test that update_certs() updates client CA list correctly
  20644. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20645. // Start with file-based constructor
  20646. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20647. ASSERT_TRUE(svr.is_valid());
  20648. // Initially no client CA list should be set
  20649. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20650. ASSERT_TRUE(ssl_ctx != nullptr);
  20651. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20652. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20653. EXPECT_EQ(0, count_before);
  20654. // Now update with client CA (PEM string)
  20655. std::string cert_pem, key_pem, ca_pem;
  20656. read_file(SERVER_CERT_FILE, cert_pem);
  20657. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20658. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20659. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20660. ASSERT_TRUE(svr.is_valid());
  20661. // Now client CA list should be set
  20662. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20663. ASSERT_TRUE(ca_list_after != nullptr);
  20664. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20665. }
  20666. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20667. // Test that the file-path SSLServer constructor properly sets the client CA
  20668. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20669. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20670. ASSERT_TRUE(svr.is_valid());
  20671. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20672. ASSERT_TRUE(ssl_ctx != nullptr);
  20673. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20674. ASSERT_TRUE(ca_list != nullptr);
  20675. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20676. }
  20677. #endif
  20678. // ============================================================================
  20679. // MbedTLS-Specific Tests
  20680. // ============================================================================
  20681. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20682. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20683. using namespace httplib::tls;
  20684. // Track if callback was invoked
  20685. bool callback_invoked = false;
  20686. // The callback receives void* ctx which is actually MbedTlsContext*
  20687. // We can access the mbedtls_ssl_config via the context
  20688. auto setup_callback = [&callback_invoked](void *ctx) {
  20689. callback_invoked = true;
  20690. // Cast to MbedTlsContext* to access the ssl config
  20691. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20692. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20693. // Use static variables to hold certificate data (simplified for test)
  20694. static mbedtls_x509_crt own_cert;
  20695. static mbedtls_pk_context own_key;
  20696. static mbedtls_x509_crt ca_chain;
  20697. static bool initialized = false;
  20698. if (!initialized) {
  20699. mbedtls_x509_crt_init(&own_cert);
  20700. mbedtls_pk_init(&own_key);
  20701. mbedtls_x509_crt_init(&ca_chain);
  20702. // Load server certificate
  20703. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20704. return false;
  20705. }
  20706. // Load server private key.
  20707. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20708. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20709. #if MBEDTLS_VERSION_MAJOR == 3
  20710. ,
  20711. mbedtls_ctr_drbg_random, nullptr
  20712. #endif
  20713. ) != 0) {
  20714. return false;
  20715. }
  20716. // Load CA chain for client verification
  20717. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20718. return false;
  20719. }
  20720. initialized = true;
  20721. }
  20722. // Configure the SSL config
  20723. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20724. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20725. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20726. // Set minimum TLS version using mbedTLS native API
  20727. #if MBEDTLS_VERSION_MAJOR >= 3
  20728. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20729. #else
  20730. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20731. MBEDTLS_SSL_MINOR_VERSION_3);
  20732. #endif
  20733. return true;
  20734. };
  20735. SSLServer svr(setup_callback);
  20736. ASSERT_TRUE(svr.is_valid());
  20737. ASSERT_TRUE(callback_invoked);
  20738. svr.Get("/test", [&](const Request &req, Response &res) {
  20739. res.set_content("test", "text/plain");
  20740. auto cert = req.peer_cert();
  20741. ASSERT_TRUE(static_cast<bool>(cert));
  20742. auto common_name = cert.subject_cn();
  20743. EXPECT_EQ("Common Name", common_name);
  20744. });
  20745. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20746. auto se = detail::scope_exit([&] {
  20747. svr.stop();
  20748. t.join();
  20749. ASSERT_FALSE(svr.is_running());
  20750. });
  20751. svr.wait_until_ready();
  20752. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20753. cli.enable_server_certificate_verification(false);
  20754. cli.set_connection_timeout(30);
  20755. auto res = cli.Get("/test");
  20756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20757. ASSERT_EQ(StatusCode::OK_200, res->status);
  20758. }
  20759. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20760. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20761. // keep-alive SSL session, which reads through that config in
  20762. // mbedtls_ssl_close_notify.
  20763. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20764. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20765. ASSERT_TRUE(svr.is_valid());
  20766. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20767. res.set_content("test", "text/plain");
  20768. });
  20769. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20770. auto se = detail::scope_exit([&] {
  20771. svr.stop();
  20772. t.join();
  20773. ASSERT_FALSE(svr.is_running());
  20774. });
  20775. svr.wait_until_ready();
  20776. {
  20777. SSLClient cli(HOST, PORT);
  20778. cli.enable_server_certificate_verification(false);
  20779. cli.set_keep_alive(true);
  20780. auto res = cli.Get("/test");
  20781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20782. ASSERT_EQ(StatusCode::OK_200, res->status);
  20783. // cli is destructed here with the keep-alive SSL session still open.
  20784. }
  20785. }
  20786. #endif
  20787. // WebSocket Tests
  20788. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20789. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20790. // defining the meaning of these bits has been negotiated.
  20791. auto make_frame = [](uint8_t first_byte) {
  20792. std::string frame;
  20793. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20794. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20795. frame += "Hello";
  20796. return frame;
  20797. };
  20798. // RSV1 set (0x40)
  20799. {
  20800. detail::BufferStream strm;
  20801. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20802. ws::Opcode opcode;
  20803. std::string payload;
  20804. bool fin;
  20805. EXPECT_EQ(
  20806. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20807. ws::impl::FrameRead::Fail);
  20808. }
  20809. // RSV2 set (0x20)
  20810. {
  20811. detail::BufferStream strm;
  20812. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20813. ws::Opcode opcode;
  20814. std::string payload;
  20815. bool fin;
  20816. EXPECT_EQ(
  20817. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20818. ws::impl::FrameRead::Fail);
  20819. }
  20820. // RSV3 set (0x10)
  20821. {
  20822. detail::BufferStream strm;
  20823. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20824. ws::Opcode opcode;
  20825. std::string payload;
  20826. bool fin;
  20827. EXPECT_EQ(
  20828. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20829. ws::impl::FrameRead::Fail);
  20830. }
  20831. // No RSV bits set - should succeed
  20832. {
  20833. detail::BufferStream strm;
  20834. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20835. ws::Opcode opcode;
  20836. std::string payload;
  20837. bool fin;
  20838. EXPECT_EQ(
  20839. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20840. ws::impl::FrameRead::Ok);
  20841. EXPECT_EQ(ws::Opcode::Text, opcode);
  20842. EXPECT_EQ("Hello", payload);
  20843. EXPECT_TRUE(fin);
  20844. }
  20845. }
  20846. TEST(WebSocketTest, ControlFrameValidation) {
  20847. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20848. // payload length <= 125.
  20849. // Ping with FIN=0 - must be rejected
  20850. {
  20851. detail::BufferStream strm;
  20852. std::string frame;
  20853. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20854. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20855. strm.write(frame.data(), frame.size());
  20856. ws::Opcode opcode;
  20857. std::string payload;
  20858. bool fin;
  20859. EXPECT_EQ(
  20860. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20861. ws::impl::FrameRead::Fail);
  20862. }
  20863. // Close with FIN=0 - must be rejected
  20864. {
  20865. detail::BufferStream strm;
  20866. std::string frame;
  20867. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20868. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20869. strm.write(frame.data(), frame.size());
  20870. ws::Opcode opcode;
  20871. std::string payload;
  20872. bool fin;
  20873. EXPECT_EQ(
  20874. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20875. ws::impl::FrameRead::Fail);
  20876. }
  20877. // Ping with payload_len=126 (extended length) - must be rejected
  20878. {
  20879. detail::BufferStream strm;
  20880. std::string frame;
  20881. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20882. frame += static_cast<char>(126); // payload_len=126 (>125)
  20883. frame += static_cast<char>(0x00); // extended length high byte
  20884. frame += static_cast<char>(126); // extended length low byte
  20885. frame += std::string(126, 'x');
  20886. strm.write(frame.data(), frame.size());
  20887. ws::Opcode opcode;
  20888. std::string payload;
  20889. bool fin;
  20890. EXPECT_EQ(
  20891. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20892. ws::impl::FrameRead::Fail);
  20893. }
  20894. // Ping with FIN=1 and payload_len=125 - should succeed
  20895. {
  20896. detail::BufferStream strm;
  20897. std::string frame;
  20898. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20899. frame += static_cast<char>(125); // payload_len=125
  20900. frame += std::string(125, 'x');
  20901. strm.write(frame.data(), frame.size());
  20902. ws::Opcode opcode;
  20903. std::string payload;
  20904. bool fin;
  20905. EXPECT_EQ(
  20906. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20907. ws::impl::FrameRead::Ok);
  20908. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20909. EXPECT_EQ(125u, payload.size());
  20910. EXPECT_TRUE(fin);
  20911. }
  20912. }
  20913. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20914. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20915. // length MUST be 0.
  20916. // MSB set - must be rejected
  20917. {
  20918. detail::BufferStream strm;
  20919. std::string frame;
  20920. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20921. frame += static_cast<char>(127); // 64-bit extended length
  20922. frame += static_cast<char>(0x80); // MSB set (invalid)
  20923. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20924. strm.write(frame.data(), frame.size());
  20925. ws::Opcode opcode;
  20926. std::string payload;
  20927. bool fin;
  20928. EXPECT_EQ(
  20929. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20930. ws::impl::FrameRead::Fail);
  20931. }
  20932. // MSB clear - should pass length parsing (will be rejected by max_len,
  20933. // but that's a different check; use a small length to verify)
  20934. {
  20935. detail::BufferStream strm;
  20936. std::string frame;
  20937. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20938. frame += static_cast<char>(127); // 64-bit extended length
  20939. frame += std::string(7, '\0'); // high bytes = 0
  20940. frame += static_cast<char>(0x03); // length = 3
  20941. frame += "abc";
  20942. strm.write(frame.data(), frame.size());
  20943. ws::Opcode opcode;
  20944. std::string payload;
  20945. bool fin;
  20946. EXPECT_EQ(
  20947. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20948. ws::impl::FrameRead::Ok);
  20949. EXPECT_EQ(ws::Opcode::Text, opcode);
  20950. EXPECT_EQ("abc", payload);
  20951. }
  20952. }
  20953. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20954. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20955. // Valid UTF-8
  20956. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20957. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20958. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20959. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20960. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20961. // Invalid UTF-8
  20962. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20963. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20964. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20965. EXPECT_FALSE(
  20966. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20967. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20968. }
  20969. TEST(WebSocketTest, ConnectAndDisconnect) {
  20970. Server svr;
  20971. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20972. std::string msg;
  20973. while (ws.read(msg)) {}
  20974. });
  20975. auto port = svr.bind_to_any_port(HOST);
  20976. std::thread t([&]() { svr.listen_after_bind(); });
  20977. svr.wait_until_ready();
  20978. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20979. auto res = client.connect();
  20980. ASSERT_TRUE(res);
  20981. EXPECT_EQ(Error::Success, res.error());
  20982. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20983. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20984. EXPECT_TRUE(client.is_open());
  20985. client.close();
  20986. EXPECT_FALSE(client.is_open());
  20987. svr.stop();
  20988. t.join();
  20989. }
  20990. TEST(WebSocketTest, ValidURL) {
  20991. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20992. EXPECT_TRUE(ws1.is_valid());
  20993. ws::WebSocketClient ws2("ws://example.com/path");
  20994. EXPECT_TRUE(ws2.is_valid());
  20995. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20996. EXPECT_TRUE(ws3.is_valid());
  20997. #ifdef CPPHTTPLIB_SSL_ENABLED
  20998. ws::WebSocketClient wss1("wss://example.com/path");
  20999. EXPECT_TRUE(wss1.is_valid());
  21000. ws::WebSocketClient wss2("wss://example.com:443/path");
  21001. EXPECT_TRUE(wss2.is_valid());
  21002. #endif
  21003. }
  21004. TEST(WebSocketTest, InvalidURL) {
  21005. // No scheme
  21006. ws::WebSocketClient ws1("localhost:8080/path");
  21007. EXPECT_FALSE(ws1.is_valid());
  21008. // No path
  21009. ws::WebSocketClient ws2("ws://localhost:8080");
  21010. EXPECT_FALSE(ws2.is_valid());
  21011. // Empty string
  21012. ws::WebSocketClient ws3("");
  21013. EXPECT_FALSE(ws3.is_valid());
  21014. // Missing host
  21015. ws::WebSocketClient ws4("ws://:8080/path");
  21016. EXPECT_FALSE(ws4.is_valid());
  21017. // Port number overflow — should not crash
  21018. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21019. EXPECT_FALSE(ws5.is_valid());
  21020. // Port out of range
  21021. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21022. EXPECT_FALSE(ws6.is_valid());
  21023. }
  21024. TEST(WebSocketTest, UnsupportedScheme) {
  21025. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21026. ws::WebSocketClient ws1("http://localhost:8080/path");
  21027. EXPECT_FALSE(ws1.is_valid());
  21028. ws::WebSocketClient ws2("https://localhost:8080/path");
  21029. EXPECT_FALSE(ws2.is_valid());
  21030. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21031. EXPECT_FALSE(ws3.is_valid());
  21032. #else
  21033. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21034. std::invalid_argument);
  21035. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21036. std::invalid_argument);
  21037. #endif
  21038. }
  21039. TEST(WebSocketTest, ConnectWhenInvalid) {
  21040. ws::WebSocketClient ws("not a valid url");
  21041. EXPECT_FALSE(ws.is_valid());
  21042. auto res = ws.connect();
  21043. EXPECT_FALSE(res);
  21044. EXPECT_EQ(Error::Connection, res.error());
  21045. EXPECT_EQ(-1, res.status());
  21046. }
  21047. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21048. // Grab a port that is free, then close it again so nothing listens there
  21049. Server svr;
  21050. auto port = svr.bind_to_any_port(HOST);
  21051. svr.stop();
  21052. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21053. auto res = client.connect();
  21054. ASSERT_FALSE(res);
  21055. EXPECT_EQ(Error::Connection, res.error());
  21056. EXPECT_EQ(-1, res.status());
  21057. }
  21058. TEST(WebSocketTest, DefaultPort) {
  21059. ws::WebSocketClient ws1("ws://example.com/path");
  21060. EXPECT_TRUE(ws1.is_valid());
  21061. // ws:// defaults to port 80 (verified by successful parse)
  21062. #ifdef CPPHTTPLIB_SSL_ENABLED
  21063. ws::WebSocketClient ws2("wss://example.com/path");
  21064. EXPECT_TRUE(ws2.is_valid());
  21065. // wss:// defaults to port 443 (verified by successful parse)
  21066. #endif
  21067. }
  21068. TEST(WebSocketTest, IPv6LiteralAddress) {
  21069. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21070. EXPECT_TRUE(ws1.is_valid());
  21071. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21072. EXPECT_TRUE(ws2.is_valid());
  21073. }
  21074. TEST(WebSocketTest, ComplexPath) {
  21075. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21076. EXPECT_TRUE(ws1.is_valid());
  21077. ws::WebSocketClient ws2("ws://localhost:8080/");
  21078. EXPECT_TRUE(ws2.is_valid());
  21079. }
  21080. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21081. Server svr;
  21082. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21083. std::string msg;
  21084. while (ws.read(msg)) {}
  21085. });
  21086. auto port = svr.bind_to_any_port(HOST);
  21087. std::thread t([&]() { svr.listen_after_bind(); });
  21088. svr.wait_until_ready();
  21089. auto another_host = "example.com";
  21090. auto wrong_ip = "192.0.2.1";
  21091. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21092. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21093. ASSERT_TRUE(client.connect());
  21094. EXPECT_TRUE(client.is_open());
  21095. client.close();
  21096. svr.stop();
  21097. t.join();
  21098. }
  21099. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21100. Server svr;
  21101. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21102. std::string msg;
  21103. while (ws.read(msg)) {}
  21104. });
  21105. auto port = svr.bind_to_any_port(HOST);
  21106. std::thread t([&]() { svr.listen_after_bind(); });
  21107. svr.wait_until_ready();
  21108. auto wrong_ip = "192.0.2.1";
  21109. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21110. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21111. client.set_connection_timeout(1);
  21112. client.set_read_timeout(1);
  21113. client.set_write_timeout(1);
  21114. EXPECT_FALSE(client.connect());
  21115. EXPECT_FALSE(client.is_open());
  21116. svr.stop();
  21117. t.join();
  21118. }
  21119. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21120. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21121. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21122. // (RFC 6761) is only a map key and the Host header value.
  21123. auto host = "target.invalid";
  21124. Server svr;
  21125. std::string received_host;
  21126. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21127. received_host = req.get_header_value("Host");
  21128. std::string msg;
  21129. while (ws.read(msg)) {}
  21130. });
  21131. auto port = svr.bind_to_any_port(HOST);
  21132. std::thread t([&]() { svr.listen_after_bind(); });
  21133. // ASSERT_* below returns from the test body, which would leave t joinable
  21134. // and make ~thread call std::terminate.
  21135. auto se = detail::scope_exit([&] {
  21136. svr.stop();
  21137. if (t.joinable()) { t.join(); }
  21138. });
  21139. svr.wait_until_ready();
  21140. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21141. std::to_string(port) + "/ws");
  21142. client.set_hostname_addr_map({{host, HOST}});
  21143. ASSERT_TRUE(client.connect());
  21144. EXPECT_TRUE(client.is_open());
  21145. client.close();
  21146. svr.stop();
  21147. t.join();
  21148. // The mapping only redirects the connection; the identity stays host_.
  21149. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21150. }
  21151. class WebSocketIntegrationTest : public ::testing::Test {
  21152. protected:
  21153. void SetUp() override {
  21154. server_ = httplib::detail::make_unique<Server>();
  21155. setup_server();
  21156. start_server();
  21157. }
  21158. void TearDown() override {
  21159. server_->stop();
  21160. if (server_thread_.joinable()) { server_thread_.join(); }
  21161. }
  21162. void setup_server() {
  21163. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21164. std::string msg;
  21165. ws::ReadResult ret;
  21166. while ((ret = ws.read(msg))) {
  21167. if (ret == ws::Binary) {
  21168. ws.send(msg.data(), msg.size());
  21169. } else {
  21170. ws.send(msg);
  21171. }
  21172. }
  21173. });
  21174. server_->WebSocket("/ws-echo-string",
  21175. [](const Request &, ws::WebSocket &ws) {
  21176. std::string msg;
  21177. while (ws.read(msg)) {
  21178. ws.send("echo: " + msg);
  21179. }
  21180. });
  21181. server_->WebSocket(
  21182. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21183. // Echo back request metadata
  21184. ws.send("path:" + req.path);
  21185. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21186. std::string msg;
  21187. while (ws.read(msg)) {}
  21188. });
  21189. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21190. std::string msg;
  21191. ws.read(msg); // wait for a message
  21192. ws.close();
  21193. });
  21194. server_->WebSocket("/ws-close-status",
  21195. [](const Request &, ws::WebSocket &ws) {
  21196. std::string msg;
  21197. ws.read(msg); // wait for a message
  21198. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21199. });
  21200. server_->WebSocket(
  21201. "/ws-subprotocol",
  21202. [](const Request &, ws::WebSocket &ws) {
  21203. std::string msg;
  21204. while (ws.read(msg)) {
  21205. ws.send(msg);
  21206. }
  21207. },
  21208. [](const std::vector<std::string> &protocols) -> std::string {
  21209. for (const auto &p : protocols) {
  21210. if (p == "graphql-ws") { return p; }
  21211. }
  21212. return "";
  21213. });
  21214. server_->WebSocket(
  21215. "/ws-subprotocol-unoffered",
  21216. [](const Request &, ws::WebSocket &ws) {
  21217. std::string msg;
  21218. while (ws.read(msg)) {
  21219. ws.send(msg);
  21220. }
  21221. },
  21222. [](const std::vector<std::string> &) -> std::string {
  21223. return "admin";
  21224. });
  21225. }
  21226. void start_server() {
  21227. port_ = server_->bind_to_any_port(HOST);
  21228. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21229. server_->wait_until_ready();
  21230. }
  21231. std::unique_ptr<Server> server_;
  21232. std::thread server_thread_;
  21233. int port_ = 0;
  21234. };
  21235. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21236. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21237. "/ws-echo");
  21238. ASSERT_TRUE(client.connect());
  21239. ASSERT_TRUE(client.is_open());
  21240. ASSERT_TRUE(client.send("Hello WebSocket"));
  21241. std::string msg;
  21242. EXPECT_EQ(ws::Text, client.read(msg));
  21243. EXPECT_EQ("Hello WebSocket", msg);
  21244. client.close();
  21245. }
  21246. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21247. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21248. "/ws-echo");
  21249. ASSERT_TRUE(client.connect());
  21250. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21251. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21252. std::string msg;
  21253. EXPECT_EQ(ws::Binary, client.read(msg));
  21254. EXPECT_EQ(binary_data, msg);
  21255. client.close();
  21256. }
  21257. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21259. "/ws-echo");
  21260. ASSERT_TRUE(client.connect());
  21261. for (int i = 0; i < 10; i++) {
  21262. auto text = "message " + std::to_string(i);
  21263. ASSERT_TRUE(client.send(text));
  21264. std::string msg;
  21265. ASSERT_TRUE(client.read(msg));
  21266. EXPECT_EQ(text, msg);
  21267. }
  21268. client.close();
  21269. }
  21270. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21271. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21272. "/ws-close");
  21273. ASSERT_TRUE(client.connect());
  21274. // Send a message to trigger the server to close
  21275. ASSERT_TRUE(client.send("trigger close"));
  21276. // The server will close, so read should return false
  21277. std::string msg;
  21278. EXPECT_FALSE(client.read(msg));
  21279. EXPECT_FALSE(client.is_open());
  21280. }
  21281. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21282. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21283. "/ws-echo");
  21284. ASSERT_TRUE(client.connect());
  21285. // 128KB message
  21286. std::string large_data(128 * 1024, 'X');
  21287. ASSERT_TRUE(client.send(large_data));
  21288. std::string msg;
  21289. ASSERT_TRUE(client.read(msg));
  21290. EXPECT_EQ(large_data, msg);
  21291. client.close();
  21292. }
  21293. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21294. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21295. "/ws-echo");
  21296. ASSERT_TRUE(client.connect());
  21297. const int num_threads = 4;
  21298. std::vector<std::thread> threads;
  21299. std::atomic<int> send_count{0};
  21300. for (int t = 0; t < num_threads; t++) {
  21301. threads.emplace_back([&client, &send_count, t]() {
  21302. for (int i = 0; i < 5; i++) {
  21303. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21304. if (client.send(text)) { send_count++; }
  21305. }
  21306. });
  21307. }
  21308. for (auto &th : threads) {
  21309. th.join();
  21310. }
  21311. int received = 0;
  21312. std::string msg;
  21313. while (received < send_count.load()) {
  21314. if (!client.read(msg)) { break; }
  21315. received++;
  21316. }
  21317. EXPECT_EQ(send_count.load(), received);
  21318. client.close();
  21319. }
  21320. TEST_F(WebSocketIntegrationTest, ReadString) {
  21321. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21322. "/ws-echo-string");
  21323. ASSERT_TRUE(client.connect());
  21324. ASSERT_TRUE(client.send("hello"));
  21325. std::string msg;
  21326. ASSERT_TRUE(client.read(msg));
  21327. EXPECT_EQ("echo: hello", msg);
  21328. ASSERT_TRUE(client.send("world"));
  21329. ASSERT_TRUE(client.read(msg));
  21330. EXPECT_EQ("echo: world", msg);
  21331. client.close();
  21332. }
  21333. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21334. Headers headers = {{"X-Test-Header", "test-value"}};
  21335. ws::WebSocketClient client(
  21336. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21337. ASSERT_TRUE(client.connect());
  21338. std::string msg;
  21339. ASSERT_TRUE(client.read(msg));
  21340. EXPECT_EQ("path:/ws-request-info", msg);
  21341. ASSERT_TRUE(client.read(msg));
  21342. EXPECT_EQ("header:test-value", msg);
  21343. client.close();
  21344. }
  21345. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21346. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21347. "/ws-echo");
  21348. client.set_read_timeout(1, 0); // 1 second
  21349. ASSERT_TRUE(client.connect());
  21350. // Don't send anything — server echo handler waits for a message, so read()
  21351. // should time out. The connection survives it: nothing was consumed.
  21352. std::string msg;
  21353. EXPECT_EQ(client.read(msg), ws::Timeout);
  21354. EXPECT_TRUE(client.is_open());
  21355. // And it is still usable afterwards.
  21356. EXPECT_TRUE(client.send("after timeout"));
  21357. EXPECT_EQ(client.read(msg), ws::Text);
  21358. EXPECT_EQ(msg, "after timeout");
  21359. }
  21360. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21361. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21362. "/ws-echo");
  21363. client.set_read_timeout(1, 0);
  21364. ASSERT_TRUE(client.connect());
  21365. ASSERT_TRUE(client.send("first"));
  21366. std::string msg;
  21367. ASSERT_EQ(client.read(msg), ws::Text);
  21368. ASSERT_EQ(msg, "first");
  21369. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21370. // not be used with a read timeout: it would reprocess the previous message.
  21371. EXPECT_EQ(client.read(msg), ws::Timeout);
  21372. EXPECT_EQ(msg, "first");
  21373. }
  21374. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21375. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21376. "/ws-echo");
  21377. ASSERT_TRUE(client.connect());
  21378. // Setting it once the connection is open reaches the live stream, not just
  21379. // the seed for the next connect().
  21380. client.set_read_timeout(1, 0);
  21381. std::string msg;
  21382. EXPECT_EQ(client.read(msg), ws::Timeout);
  21383. EXPECT_TRUE(client.is_open());
  21384. }
  21385. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21386. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21387. "/ws-echo");
  21388. client.set_read_timeout(5, 0);
  21389. ASSERT_TRUE(client.connect());
  21390. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21391. // The server should reject it and close the connection.
  21392. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21393. client.send(oversized);
  21394. // The server's read() should have failed due to payload limit,
  21395. // so our read() should return false (connection closed).
  21396. std::string msg;
  21397. EXPECT_FALSE(client.read(msg));
  21398. }
  21399. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21400. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21401. "/ws-echo");
  21402. client.set_read_timeout(10, 0);
  21403. ASSERT_TRUE(client.connect());
  21404. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21405. // This should succeed.
  21406. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21407. ASSERT_TRUE(client.send(at_limit));
  21408. std::string msg;
  21409. ASSERT_TRUE(client.read(msg));
  21410. EXPECT_EQ(at_limit.size(), msg.size());
  21411. client.close();
  21412. }
  21413. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21414. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21415. "/nonexistent");
  21416. auto res = client.connect();
  21417. EXPECT_FALSE(res);
  21418. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21419. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21420. EXPECT_FALSE(client.is_open());
  21421. }
  21422. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21423. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21424. "/ws-echo");
  21425. ASSERT_TRUE(client.connect());
  21426. ASSERT_TRUE(client.send(""));
  21427. std::string msg;
  21428. EXPECT_EQ(ws::Text, client.read(msg));
  21429. EXPECT_EQ("", msg);
  21430. client.close();
  21431. }
  21432. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21434. "/ws-echo");
  21435. // First connection
  21436. ASSERT_TRUE(client.connect());
  21437. ASSERT_TRUE(client.send("first"));
  21438. std::string msg;
  21439. ASSERT_TRUE(client.read(msg));
  21440. EXPECT_EQ("first", msg);
  21441. client.close();
  21442. EXPECT_FALSE(client.is_open());
  21443. // Reconnect using the same client object
  21444. ASSERT_TRUE(client.connect());
  21445. ASSERT_TRUE(client.is_open());
  21446. ASSERT_TRUE(client.send("second"));
  21447. ASSERT_TRUE(client.read(msg));
  21448. EXPECT_EQ("second", msg);
  21449. client.close();
  21450. }
  21451. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21452. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21453. "/ws-close-status");
  21454. ASSERT_TRUE(client.connect());
  21455. // Trigger the server to close with GoingAway status
  21456. ASSERT_TRUE(client.send("trigger"));
  21457. // read() should return false after receiving the close frame
  21458. std::string msg;
  21459. EXPECT_FALSE(client.read(msg));
  21460. EXPECT_FALSE(client.is_open());
  21461. }
  21462. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21463. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21464. "/ws-echo");
  21465. ASSERT_TRUE(client.connect());
  21466. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21467. EXPECT_FALSE(client.is_open());
  21468. }
  21469. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21470. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21471. ws::WebSocketClient client(
  21472. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21473. ASSERT_TRUE(client.connect());
  21474. // Server should have selected graphql-ws
  21475. EXPECT_EQ("graphql-ws", client.subprotocol());
  21476. client.close();
  21477. }
  21478. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21479. Headers headers;
  21480. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21481. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21482. ws::WebSocketClient client(
  21483. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21484. ASSERT_TRUE(client.connect());
  21485. // The offer on the second field line counts too, so graphql-ws is selected
  21486. EXPECT_EQ("graphql-ws", client.subprotocol());
  21487. client.close();
  21488. }
  21489. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21490. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21491. ws::WebSocketClient client(
  21492. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21493. ASSERT_TRUE(client.connect());
  21494. // Server should not have selected any subprotocol
  21495. EXPECT_TRUE(client.subprotocol().empty());
  21496. client.close();
  21497. }
  21498. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21499. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21500. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21501. "/ws-subprotocol-unoffered",
  21502. headers);
  21503. ASSERT_TRUE(client.connect());
  21504. EXPECT_TRUE(client.subprotocol().empty());
  21505. client.close();
  21506. }
  21507. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21508. // Connect without requesting any subprotocol
  21509. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21510. "/ws-subprotocol");
  21511. ASSERT_TRUE(client.connect());
  21512. EXPECT_TRUE(client.subprotocol().empty());
  21513. client.close();
  21514. }
  21515. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21516. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21517. "/ws-echo");
  21518. client.set_tcp_nodelay(true);
  21519. client.set_connection_timeout(3, 0);
  21520. bool socket_options_called = false;
  21521. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21522. ASSERT_TRUE(client.connect());
  21523. ASSERT_TRUE(client.is_open());
  21524. EXPECT_TRUE(socket_options_called);
  21525. ASSERT_TRUE(client.send("hello"));
  21526. std::string msg;
  21527. auto result = client.read(msg);
  21528. EXPECT_EQ(result, ws::ReadResult::Text);
  21529. EXPECT_EQ(msg, "hello");
  21530. client.close();
  21531. }
  21532. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21533. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21534. "/ws-echo");
  21535. client.set_connection_timeout(std::chrono::seconds(3));
  21536. client.set_write_timeout(std::chrono::seconds(3));
  21537. // A sub-second remainder exercises the seconds/microseconds split.
  21538. client.set_read_timeout(std::chrono::milliseconds(1500));
  21539. ASSERT_TRUE(client.connect());
  21540. auto start = std::chrono::steady_clock::now();
  21541. std::string msg;
  21542. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21543. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21544. std::chrono::steady_clock::now() - start)
  21545. .count();
  21546. // Above 1s so that dropping the microseconds half of the split fails here.
  21547. // Ignoring the setter altogether would not reach this line at all: a client
  21548. // waits forever by default.
  21549. EXPECT_GE(elapsed, 1400);
  21550. EXPECT_LT(elapsed, 30000);
  21551. }
  21552. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21553. Server svr;
  21554. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21555. if (!req.has_header("Authorization")) {
  21556. res.status = StatusCode::Unauthorized_401;
  21557. res.set_content("Unauthorized", "text/plain");
  21558. return Server::HandlerResponse::Handled;
  21559. }
  21560. return Server::HandlerResponse::Unhandled;
  21561. });
  21562. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21563. std::string msg;
  21564. while (ws.read(msg)) {
  21565. ws.send(msg);
  21566. }
  21567. });
  21568. auto port = svr.bind_to_any_port("localhost");
  21569. std::thread t([&]() { svr.listen_after_bind(); });
  21570. svr.wait_until_ready();
  21571. // Without Authorization header - should be rejected before upgrade
  21572. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21573. EXPECT_FALSE(client1.connect());
  21574. // The rejection is framed like any other HTTP response
  21575. {
  21576. Client cli("localhost", port);
  21577. Headers headers = {{"Upgrade", "websocket"},
  21578. {"Connection", "Upgrade"},
  21579. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21580. {"Sec-WebSocket-Version", "13"}};
  21581. auto res = cli.Get("/ws", headers);
  21582. ASSERT_TRUE(res);
  21583. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21584. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21585. EXPECT_EQ("Unauthorized", res->body);
  21586. }
  21587. // With Authorization header - should succeed
  21588. Headers headers = {{"Authorization", "Bearer token123"}};
  21589. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21590. headers);
  21591. ASSERT_TRUE(client2.connect());
  21592. ASSERT_TRUE(client2.send("hello"));
  21593. std::string msg;
  21594. ASSERT_TRUE(client2.read(msg));
  21595. EXPECT_EQ("hello", msg);
  21596. client2.close();
  21597. svr.stop();
  21598. t.join();
  21599. }
  21600. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21601. Server svr;
  21602. std::atomic<int> pre_request_calls{0};
  21603. std::atomic<bool> route_matched{false};
  21604. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21605. pre_request_calls++;
  21606. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21607. if (req.get_header_value("Authorization") != "Bearer token123") {
  21608. res.status = StatusCode::Unauthorized_401;
  21609. res.set_content("Unauthorized", "text/plain");
  21610. return Server::HandlerResponse::Handled;
  21611. }
  21612. return Server::HandlerResponse::Unhandled;
  21613. });
  21614. std::atomic<bool> handler_called{false};
  21615. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21616. handler_called = true;
  21617. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21618. });
  21619. auto port = svr.bind_to_any_port("localhost");
  21620. std::thread t([&]() { svr.listen_after_bind(); });
  21621. svr.wait_until_ready();
  21622. // Without Authorization header - should be rejected before upgrade
  21623. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21624. "/ws/1");
  21625. EXPECT_FALSE(client1.connect());
  21626. EXPECT_FALSE(handler_called);
  21627. EXPECT_EQ(1, pre_request_calls);
  21628. EXPECT_TRUE(route_matched);
  21629. // The rejection is an ordinary HTTP response, not a protocol switch
  21630. {
  21631. Client cli("localhost", port);
  21632. Headers headers = {{"Upgrade", "websocket"},
  21633. {"Connection", "Upgrade"},
  21634. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21635. {"Sec-WebSocket-Version", "13"}};
  21636. auto res = cli.Get("/ws/1", headers);
  21637. ASSERT_TRUE(res);
  21638. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21639. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21640. EXPECT_EQ("Unauthorized", res->body);
  21641. }
  21642. EXPECT_FALSE(handler_called);
  21643. // With Authorization header - should succeed
  21644. Headers headers = {{"Authorization", "Bearer token123"}};
  21645. ws::WebSocketClient client2(
  21646. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21647. ASSERT_TRUE(client2.connect());
  21648. std::string msg;
  21649. ASSERT_TRUE(client2.read(msg));
  21650. EXPECT_EQ("/ws/:id 2", msg);
  21651. EXPECT_TRUE(handler_called);
  21652. client2.close();
  21653. svr.stop();
  21654. t.join();
  21655. }
  21656. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21657. Server svr;
  21658. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21659. // A read timeout is how a handler gets control back. Without it, a handler
  21660. // parked in read() can never write on the connection it is reading.
  21661. ws.set_read_timeout(std::chrono::milliseconds(100));
  21662. std::string msg;
  21663. while (ws.is_open()) {
  21664. auto r = ws.read(msg);
  21665. if (r == httplib::ws::Timeout) {
  21666. ws.send("tick");
  21667. continue;
  21668. }
  21669. if (r == httplib::ws::Fail) { break; }
  21670. ws.send(msg);
  21671. }
  21672. });
  21673. auto port = svr.bind_to_any_port("localhost");
  21674. std::thread t([&]() { svr.listen_after_bind(); });
  21675. svr.wait_until_ready();
  21676. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21677. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21678. ASSERT_TRUE(client.connect());
  21679. // The client sends nothing, so anything it receives came out of the
  21680. // handler's timeout path.
  21681. std::string msg;
  21682. ASSERT_EQ(client.read(msg), ws::Text);
  21683. EXPECT_EQ("tick", msg);
  21684. client.close();
  21685. svr.stop();
  21686. t.join();
  21687. }
  21688. // Stream::read may return fewer bytes than asked for. This is that contract at
  21689. // its worst -- one byte per call -- which is what a frame header straddling a
  21690. // read buffer's boundary looks like to the frame parser.
  21691. class WsByteAtATimeStream : public Stream {
  21692. public:
  21693. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21694. bool is_readable() const override { return true; }
  21695. bool wait_readable() const override { return true; }
  21696. bool wait_writable() const override { return true; }
  21697. ssize_t read(char *ptr, size_t size) override {
  21698. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21699. *ptr = data_[pos_++];
  21700. return 1;
  21701. }
  21702. ssize_t write(const char *, size_t size) override {
  21703. return static_cast<ssize_t>(size);
  21704. }
  21705. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21706. ip = "127.0.0.1";
  21707. port = 0;
  21708. }
  21709. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21710. ip = "127.0.0.1";
  21711. port = 0;
  21712. }
  21713. socket_t socket() const override { return INVALID_SOCKET; }
  21714. time_t duration() const override { return 0; }
  21715. private:
  21716. std::string data_;
  21717. size_t pos_ = 0;
  21718. };
  21719. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21720. // The payload uses the 16-bit extended length, so the header, the length
  21721. // and the mask key are all multi-byte fields here. Each used to be read
  21722. // with a single read() call, which fails as soon as one is split. The
  21723. // payload is also a little over one read chunk, so it is read in two.
  21724. std::string body;
  21725. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21726. body += static_cast<char>(i % 251);
  21727. }
  21728. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21729. std::string frame;
  21730. frame += static_cast<char>(0x81); // FIN + Text
  21731. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21732. frame += static_cast<char>(body.size() >> 8);
  21733. frame += static_cast<char>(body.size() & 0xff);
  21734. for (size_t i = 0; i < 4; i++) {
  21735. frame += static_cast<char>(mask[i]);
  21736. }
  21737. for (size_t i = 0; i < body.size(); i++) {
  21738. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21739. }
  21740. WsByteAtATimeStream strm(frame);
  21741. ws::Opcode opcode;
  21742. std::string payload;
  21743. bool fin = false;
  21744. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21745. /*expect_masked=*/true, body.size()),
  21746. ws::impl::FrameRead::Ok);
  21747. EXPECT_TRUE(fin);
  21748. EXPECT_EQ(opcode, ws::Opcode::Text);
  21749. EXPECT_EQ(payload, body);
  21750. }
  21751. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  21752. std::string body(2000, 'x');
  21753. std::string frame;
  21754. frame += static_cast<char>(0x82); // FIN + Binary
  21755. frame += static_cast<char>(126); // 16-bit length follows
  21756. frame += static_cast<char>(body.size() >> 8);
  21757. frame += static_cast<char>(body.size() & 0xff);
  21758. frame += body;
  21759. detail::BufferStream strm;
  21760. strm.write(frame.data(), frame.size());
  21761. ws::Opcode opcode;
  21762. std::string payload;
  21763. bool fin;
  21764. EXPECT_EQ(
  21765. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  21766. ws::impl::FrameRead::Ok);
  21767. EXPECT_EQ(body, payload);
  21768. }
  21769. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21770. // The header announces the largest payload allowed, and only 3 bytes of it
  21771. // ever arrive.
  21772. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21773. std::string frame;
  21774. frame += static_cast<char>(0x82); // FIN + Binary
  21775. frame += static_cast<char>(127); // 64-bit length follows
  21776. for (int shift = 56; shift >= 0; shift -= 8) {
  21777. frame += static_cast<char>((len >> shift) & 0xff);
  21778. }
  21779. frame += "abc";
  21780. detail::BufferStream strm;
  21781. strm.write(frame.data(), frame.size());
  21782. ws::Opcode opcode;
  21783. std::string payload;
  21784. bool fin;
  21785. EXPECT_EQ(
  21786. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21787. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21788. ws::impl::FrameRead::Fail);
  21789. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21790. }
  21791. TEST(WebSocketTest, QueryStringInHandshake) {
  21792. Server svr;
  21793. std::mutex mtx;
  21794. std::string received_target;
  21795. std::string received_token;
  21796. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21797. {
  21798. std::lock_guard<std::mutex> lock(mtx);
  21799. received_target = req.target;
  21800. if (req.has_param("token")) {
  21801. received_token = req.get_param_value("token");
  21802. }
  21803. }
  21804. std::string msg;
  21805. while (ws.read(msg)) {
  21806. ws.send(msg);
  21807. }
  21808. });
  21809. auto port = svr.bind_to_any_port("localhost");
  21810. std::thread t([&]() { svr.listen_after_bind(); });
  21811. svr.wait_until_ready();
  21812. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21813. "/ws?token=ABC&session=123");
  21814. ASSERT_TRUE(client.connect());
  21815. // Round-trip ensures the handler has run and captured the request.
  21816. ASSERT_TRUE(client.send("hello"));
  21817. std::string msg;
  21818. ASSERT_TRUE(client.read(msg));
  21819. EXPECT_EQ("hello", msg);
  21820. client.close();
  21821. {
  21822. std::lock_guard<std::mutex> lock(mtx);
  21823. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21824. EXPECT_EQ("ABC", received_token);
  21825. }
  21826. svr.stop();
  21827. t.join();
  21828. }
  21829. // Run a handshake against a throwaway server and hand the request the server
  21830. // received back to the caller, so tests can assert on the headers the client
  21831. // actually put on the wire.
  21832. static void capture_websocket_handshake_request(
  21833. const Headers &client_headers,
  21834. std::function<void(const Request &, int port)> verify) {
  21835. Server svr;
  21836. std::mutex mtx;
  21837. Request received;
  21838. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21839. {
  21840. std::lock_guard<std::mutex> lock(mtx);
  21841. received = req;
  21842. }
  21843. std::string msg;
  21844. while (ws.read(msg)) {
  21845. ws.send(msg);
  21846. }
  21847. });
  21848. auto port = svr.bind_to_any_port("localhost");
  21849. std::thread t([&]() { svr.listen_after_bind(); });
  21850. auto se = detail::scope_exit([&] {
  21851. svr.stop();
  21852. t.join();
  21853. });
  21854. svr.wait_until_ready();
  21855. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21856. client_headers);
  21857. ASSERT_TRUE(client.connect());
  21858. ASSERT_TRUE(client.send("hello"));
  21859. std::string msg;
  21860. ASSERT_TRUE(client.read(msg));
  21861. client.close();
  21862. {
  21863. std::lock_guard<std::mutex> lock(mtx);
  21864. verify(received, port);
  21865. }
  21866. }
  21867. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21868. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21869. // Non-default port must be present in the Host header. Default ports
  21870. // (80/443) are omitted; that logic is covered by
  21871. // MakeHostAndPortStringTest.
  21872. EXPECT_EQ("localhost:" + std::to_string(port),
  21873. req.get_header_value("Host"));
  21874. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21875. req.get_header_value("User-Agent"));
  21876. EXPECT_FALSE(req.has_header("Accept"));
  21877. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21878. EXPECT_FALSE(req.has_header("Content-Length"));
  21879. });
  21880. }
  21881. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21882. capture_websocket_handshake_request(
  21883. {{"Host", "example.com"},
  21884. {"User-Agent", "custom-agent"},
  21885. {"X-Custom", "value"}},
  21886. [](const Request &req, int) {
  21887. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21888. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21889. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21890. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21891. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21892. });
  21893. }
  21894. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21895. capture_websocket_handshake_request(
  21896. {{"Upgrade", "bogus"},
  21897. {"Connection", "close"},
  21898. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21899. {"Sec-WebSocket-Version", "8"}},
  21900. [](const Request &req, int) {
  21901. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21902. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21903. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21904. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21905. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21906. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21907. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21908. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21909. req.get_header_value("Sec-WebSocket-Key"));
  21910. });
  21911. }
  21912. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21913. // A header the client refuses to send must abort the handshake before any
  21914. // part of it reaches the wire; a lone request line would otherwise sit in
  21915. // the peer's buffer as a truncated request.
  21916. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21917. ASSERT_NE(INVALID_SOCKET, srv);
  21918. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21919. sockaddr_in addr{};
  21920. addr.sin_family = AF_INET;
  21921. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21922. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21923. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21924. ASSERT_EQ(0, ::listen(srv, 1));
  21925. sockaddr_in bound{};
  21926. socklen_t bound_len = sizeof(bound);
  21927. ASSERT_EQ(
  21928. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21929. auto port = ntohs(bound.sin_port);
  21930. ssize_t received = -1;
  21931. std::thread t([&] {
  21932. // Bound every blocking call so a regression fails the test with a bad
  21933. // value instead of hanging the suite.
  21934. fd_set rfds;
  21935. FD_ZERO(&rfds);
  21936. FD_SET(srv, &rfds);
  21937. timeval tv{5, 0};
  21938. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21939. 0) {
  21940. return;
  21941. }
  21942. sockaddr_in cli_addr{};
  21943. socklen_t cli_len = sizeof(cli_addr);
  21944. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21945. if (cli == INVALID_SOCKET) { return; }
  21946. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21947. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21948. char buf[4096];
  21949. received = ::recv(cli, buf, sizeof(buf), 0);
  21950. });
  21951. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21952. // connect() has already shut the socket down by the time it returns false,
  21953. // so the peer sees EOF without waiting for the client to be destroyed.
  21954. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21955. {{"X-Bad", "a\r\nInjected: 1"}});
  21956. EXPECT_FALSE(client.connect());
  21957. t.join();
  21958. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21959. EXPECT_EQ(0, received);
  21960. }
  21961. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21962. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21963. // contains "upgrade" as a substring is a different token and must not
  21964. // start a WebSocket handshake.
  21965. auto make_request = [](const std::vector<std::string> &connection_values) {
  21966. Request req;
  21967. req.method = "GET";
  21968. req.headers.emplace("Upgrade", "websocket");
  21969. for (const auto &value : connection_values) {
  21970. req.headers.emplace("Connection", value);
  21971. }
  21972. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21973. req.headers.emplace("Sec-WebSocket-Version", "13");
  21974. return req;
  21975. };
  21976. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21977. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21978. EXPECT_TRUE(
  21979. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21980. EXPECT_TRUE(
  21981. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21982. EXPECT_TRUE(
  21983. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21984. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21985. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21986. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21987. EXPECT_FALSE(
  21988. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21989. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21990. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21991. }
  21992. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21993. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21994. // asks recipients to match each protocol-name case-insensitively, and RFC
  21995. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21996. // client naming websocket alongside another protocol, or on a second field
  21997. // line, is offering websocket; a value that merely contains "websocket" as a
  21998. // substring is a different protocol name and is not.
  21999. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22000. Request req;
  22001. req.method = "GET";
  22002. for (const auto &value : upgrade_values) {
  22003. req.headers.emplace("Upgrade", value);
  22004. }
  22005. req.headers.emplace("Connection", "Upgrade");
  22006. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22007. req.headers.emplace("Sec-WebSocket-Version", "13");
  22008. return req;
  22009. };
  22010. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22011. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22012. EXPECT_TRUE(
  22013. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22014. EXPECT_TRUE(
  22015. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22016. EXPECT_TRUE(
  22017. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22018. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22019. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22020. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22021. EXPECT_FALSE(
  22022. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22023. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22024. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22025. }
  22026. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22027. Server svr;
  22028. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22029. auto port = svr.bind_to_any_port("localhost");
  22030. std::thread t([&]() { svr.listen_after_bind(); });
  22031. auto se = detail::scope_exit([&] {
  22032. svr.stop();
  22033. t.join();
  22034. });
  22035. svr.wait_until_ready();
  22036. Headers headers = {{"Upgrade", "websocket"},
  22037. {"Connection", "notupgrade"},
  22038. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22039. {"Sec-WebSocket-Version", "13"}};
  22040. Client cli("localhost", port);
  22041. auto res = cli.Get("/ws", headers);
  22042. // The route exists only as a WebSocket route, so a request that fails the
  22043. // handshake check falls through to ordinary routing.
  22044. ASSERT_TRUE(res);
  22045. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22046. }
  22047. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22048. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22049. // Connection value is the only thing left for the client to reject.
  22050. Server svr;
  22051. svr.Get("/ws", [](const Request &req, Response &res) {
  22052. res.status = StatusCode::SwitchingProtocol_101;
  22053. res.set_header("Upgrade", "websocket");
  22054. res.set_header("Connection", "notupgrade");
  22055. res.set_header("Sec-WebSocket-Accept",
  22056. detail::websocket_accept_key(
  22057. req.get_header_value("Sec-WebSocket-Key")));
  22058. });
  22059. auto port = svr.bind_to_any_port("localhost");
  22060. std::thread t([&]() { svr.listen_after_bind(); });
  22061. auto se = detail::scope_exit([&] {
  22062. svr.stop();
  22063. t.join();
  22064. });
  22065. svr.wait_until_ready();
  22066. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22067. auto res = client.connect();
  22068. EXPECT_FALSE(res);
  22069. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22070. EXPECT_FALSE(client.is_open());
  22071. }
  22072. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22073. Server svr;
  22074. svr.Get("/ws", [](const Request &req, Response &res) {
  22075. res.status = StatusCode::SwitchingProtocol_101;
  22076. res.set_header("Upgrade", "websocket");
  22077. res.set_header("Connection", "Upgrade");
  22078. res.set_header("Sec-WebSocket-Accept",
  22079. detail::websocket_accept_key(
  22080. req.get_header_value("Sec-WebSocket-Key")));
  22081. res.set_header("Sec-WebSocket-Protocol", "admin");
  22082. });
  22083. auto port = svr.bind_to_any_port("localhost");
  22084. std::thread t([&]() { svr.listen_after_bind(); });
  22085. auto se = detail::scope_exit([&] {
  22086. svr.stop();
  22087. t.join();
  22088. });
  22089. svr.wait_until_ready();
  22090. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22091. // Server selects a subprotocol the client never offered
  22092. {
  22093. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22094. ws::WebSocketClient client(url, headers);
  22095. auto res = client.connect();
  22096. EXPECT_FALSE(res);
  22097. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22098. EXPECT_FALSE(client.is_open());
  22099. EXPECT_TRUE(client.subprotocol().empty());
  22100. }
  22101. // Client offered none but the server named one anyway
  22102. {
  22103. ws::WebSocketClient client(url);
  22104. auto res = client.connect();
  22105. EXPECT_FALSE(res);
  22106. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22107. EXPECT_FALSE(client.is_open());
  22108. EXPECT_TRUE(client.subprotocol().empty());
  22109. }
  22110. }
  22111. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22112. // The socket path doubles as the URL host, so it must not contain '/'.
  22113. const char *shard = getenv("GTEST_SHARD_INDEX");
  22114. const std::string sock_path =
  22115. shard ? std::string("httplib-ws-") + shard + ".sock"
  22116. : std::string("httplib-ws.sock");
  22117. std::remove(sock_path.c_str());
  22118. Server svr;
  22119. std::mutex mtx;
  22120. std::string received_host;
  22121. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22122. {
  22123. std::lock_guard<std::mutex> lock(mtx);
  22124. received_host = req.get_header_value("Host");
  22125. }
  22126. std::string msg;
  22127. while (ws.read(msg)) {
  22128. ws.send(msg);
  22129. }
  22130. });
  22131. svr.set_address_family(AF_UNIX);
  22132. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22133. auto se = detail::scope_exit([&] {
  22134. svr.stop();
  22135. t.join();
  22136. std::remove(sock_path.c_str());
  22137. });
  22138. svr.wait_until_ready();
  22139. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22140. client.set_address_family(AF_UNIX);
  22141. ASSERT_TRUE(client.connect());
  22142. ASSERT_TRUE(client.send("hello"));
  22143. std::string msg;
  22144. ASSERT_TRUE(client.read(msg));
  22145. client.close();
  22146. {
  22147. std::lock_guard<std::mutex> lock(mtx);
  22148. // There is no host:port for a Unix socket, so the same "localhost"
  22149. // placeholder the HTTP client uses is expected.
  22150. EXPECT_EQ("localhost", received_host);
  22151. }
  22152. }
  22153. // Two threads must never parse WebSocket frames from the same stream.
  22154. // close() used to read the peer's Close reply with its own frame read, so it
  22155. // raced a reader thread that was in the middle of a payload: the payload loop
  22156. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22157. // so bytes taken by close() were replaced with bytes from further along the
  22158. // stream. The message kept its length and silently changed content.
  22159. //
  22160. // The raw peer below sends a frame header plus part of the payload, waits for
  22161. // the handler to call close(), and only then sends the rest. Whichever thread
  22162. // would win the race for those bytes, the message must arrive intact, because
  22163. // close() must not touch the stream while read() owns it.
  22164. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22165. #ifndef _WIN32
  22166. signal(SIGPIPE, SIG_IGN);
  22167. #endif
  22168. const size_t payload_len = 120; // fits the 7-bit length field
  22169. const size_t prefix_len = 8;
  22170. const int attempts = 8;
  22171. std::string expected(payload_len, '\0');
  22172. for (size_t i = 0; i < payload_len; i++) {
  22173. expected[i] = static_cast<char>('a' + i % 26);
  22174. }
  22175. std::atomic<bool> peer_stalled{false};
  22176. std::atomic<bool> handler_done{false};
  22177. std::mutex received_mutex;
  22178. std::vector<std::string> received;
  22179. // Bound every wait, so a regression fails the test instead of hanging the
  22180. // suite.
  22181. auto wait_for = [](const std::atomic<bool> &flag) {
  22182. for (int i = 0; i < 500 && !flag; i++) {
  22183. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22184. }
  22185. };
  22186. Server svr;
  22187. svr.set_websocket_ping_interval(0);
  22188. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22189. std::thread reader([&]() {
  22190. std::string msg;
  22191. while (ws.read(msg)) {
  22192. std::lock_guard<std::mutex> guard(received_mutex);
  22193. received.push_back(msg);
  22194. }
  22195. });
  22196. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22197. // inside read_websocket_frame() when close() runs.
  22198. wait_for(peer_stalled);
  22199. ws.close();
  22200. reader.join();
  22201. handler_done = true;
  22202. });
  22203. auto port = svr.bind_to_any_port("127.0.0.1");
  22204. std::thread t([&]() { svr.listen_after_bind(); });
  22205. auto se = detail::scope_exit([&] {
  22206. svr.stop();
  22207. t.join();
  22208. });
  22209. svr.wait_until_ready();
  22210. auto send_bytes = [](socket_t s, const std::string &data) {
  22211. #ifdef _WIN32
  22212. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22213. #else
  22214. auto n = ::send(s, data.data(), data.size(), 0);
  22215. #endif
  22216. return n == static_cast<decltype(n)>(data.size());
  22217. };
  22218. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22219. // Every length used here fits the 7-bit length field.
  22220. auto masked_header = [](uint8_t first_byte, size_t len) {
  22221. std::string h;
  22222. h += static_cast<char>(first_byte);
  22223. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22224. h.append(4, '\0'); // mask key
  22225. return h;
  22226. };
  22227. for (int attempt = 0; attempt < attempts; attempt++) {
  22228. peer_stalled = false;
  22229. handler_done = false;
  22230. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22231. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22232. auto se_sock = detail::scope_exit([&] {
  22233. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22234. });
  22235. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22236. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22237. sockaddr_in addr{};
  22238. addr.sin_family = AF_INET;
  22239. addr.sin_port = htons(static_cast<uint16_t>(port));
  22240. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22241. ASSERT_EQ(
  22242. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22243. << "attempt " << attempt;
  22244. ASSERT_TRUE(send_bytes(sock,
  22245. "GET /ws HTTP/1.1\r\n"
  22246. "Host: 127.0.0.1\r\n"
  22247. "Upgrade: websocket\r\n"
  22248. "Connection: Upgrade\r\n"
  22249. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22250. "Sec-WebSocket-Version: 13\r\n"
  22251. "\r\n"))
  22252. << "attempt " << attempt;
  22253. std::string response;
  22254. while (response.find("\r\n\r\n") == std::string::npos) {
  22255. char buf[512];
  22256. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22257. if (n <= 0) { break; }
  22258. response.append(buf, static_cast<size_t>(n));
  22259. }
  22260. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22261. << "attempt " << attempt;
  22262. // Send the header of a Binary message but only the first prefix_len bytes
  22263. // of its payload, leaving the reader thread stalled inside the payload.
  22264. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22265. expected.substr(0, prefix_len)))
  22266. << "attempt " << attempt;
  22267. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22268. peer_stalled = true;
  22269. // Let close() send its Close frame and park in its own read before the
  22270. // rest of the payload arrives, so both threads are waiting for it.
  22271. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22272. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22273. close_frame += static_cast<char>(0x03); // status 1000
  22274. close_frame += static_cast<char>(0xE8);
  22275. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22276. << "attempt " << attempt;
  22277. // Closing the peer releases the reader thread even on the buggy path,
  22278. // where it waits for bytes another thread already consumed.
  22279. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22280. detail::close_socket(sock);
  22281. sock = INVALID_SOCKET;
  22282. wait_for(handler_done);
  22283. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22284. }
  22285. std::lock_guard<std::mutex> guard(received_mutex);
  22286. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22287. << "a message in flight when close() ran was dropped";
  22288. for (size_t i = 0; i < received.size(); i++) {
  22289. EXPECT_EQ(expected, received[i]) << "message " << i;
  22290. }
  22291. }
  22292. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22293. std::atomic<bool> done{false};
  22294. std::string received;
  22295. Server svr;
  22296. svr.set_websocket_ping_interval(0);
  22297. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22298. std::string msg;
  22299. if (ws.read(msg) == ws::Binary) { received = msg; }
  22300. done = true;
  22301. });
  22302. auto port = svr.bind_to_any_port("127.0.0.1");
  22303. std::thread t([&]() { svr.listen_after_bind(); });
  22304. auto se = detail::scope_exit([&] {
  22305. svr.stop();
  22306. t.join();
  22307. });
  22308. svr.wait_until_ready();
  22309. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22310. ASSERT_NE(INVALID_SOCKET, sock);
  22311. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22312. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22313. sockaddr_in addr{};
  22314. addr.sin_family = AF_INET;
  22315. addr.sin_port = htons(static_cast<uint16_t>(port));
  22316. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22317. ASSERT_EQ(0,
  22318. ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22319. // Frames with an all-zero mask key, so the payload goes out verbatim.
  22320. auto frame = [](uint8_t first_byte, const std::string &payload) {
  22321. std::string f;
  22322. f += static_cast<char>(first_byte);
  22323. f += static_cast<char>(0x80 | payload.size());
  22324. f.append(4, '\0');
  22325. return f + payload;
  22326. };
  22327. std::string data = "GET /ws HTTP/1.1\r\n"
  22328. "Host: 127.0.0.1\r\n"
  22329. "Upgrade: websocket\r\n"
  22330. "Connection: Upgrade\r\n"
  22331. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22332. "Sec-WebSocket-Version: 13\r\n"
  22333. "\r\n";
  22334. data += frame(0x02, "Hel"); // Binary, more to come
  22335. data += frame(0x89, "p"); // FIN + Ping
  22336. data += frame(0x80, "lo"); // FIN + Continuation
  22337. #ifdef _WIN32
  22338. ::send(sock, data.data(), static_cast<int>(data.size()), 0);
  22339. #else
  22340. ::send(sock, data.data(), data.size(), 0);
  22341. #endif
  22342. for (int i = 0; i < 500 && !done; i++) {
  22343. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22344. }
  22345. ASSERT_TRUE(done);
  22346. EXPECT_EQ("Hello", received);
  22347. }
  22348. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22349. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22350. protected:
  22351. void SetUp() override {
  22352. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22353. SERVER_PRIVATE_KEY_FILE);
  22354. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22355. std::string msg;
  22356. ws::ReadResult ret;
  22357. while ((ret = ws.read(msg))) {
  22358. if (ret == ws::Binary) {
  22359. ws.send(msg.data(), msg.size());
  22360. } else {
  22361. ws.send(msg);
  22362. }
  22363. }
  22364. });
  22365. port_ = server_->bind_to_any_port(HOST);
  22366. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22367. server_->wait_until_ready();
  22368. }
  22369. void TearDown() override {
  22370. server_->stop();
  22371. if (server_thread_.joinable()) { server_thread_.join(); }
  22372. }
  22373. std::unique_ptr<SSLServer> server_;
  22374. std::thread server_thread_;
  22375. int port_ = 0;
  22376. };
  22377. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22378. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22379. "/ws-echo");
  22380. client.enable_server_certificate_verification(false);
  22381. ASSERT_TRUE(client.connect());
  22382. ASSERT_TRUE(client.is_open());
  22383. ASSERT_TRUE(client.send("Hello WSS"));
  22384. std::string msg;
  22385. EXPECT_EQ(ws::Text, client.read(msg));
  22386. EXPECT_EQ("Hello WSS", msg);
  22387. client.close();
  22388. }
  22389. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22390. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22391. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22392. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22393. // client (without calling close() first) is the only path that runs
  22394. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22395. // bug exactly.
  22396. //
  22397. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22398. // when linked against an instrumented libssl; run under Valgrind to catch it
  22399. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22400. // suite (the freed session otherwise stalls on the close handshake) — this test
  22401. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22402. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22403. {
  22404. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22405. "/ws-echo");
  22406. client.enable_server_certificate_verification(false);
  22407. client.set_read_timeout(2, 0);
  22408. client.set_write_timeout(2, 0);
  22409. ASSERT_TRUE(client.connect());
  22410. ASSERT_TRUE(client.is_open());
  22411. ASSERT_TRUE(client.send("still open"));
  22412. // Intentionally do NOT call client.close(): leaving scope runs
  22413. // shutdown_and_close() with the WebSocket still open, which must send the
  22414. // close frame while the TLS session is still alive.
  22415. }
  22416. }
  22417. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22418. // shutdown_and_close() at the start of connect(), reproducing the same
  22419. // use-after-free within the test body rather than at scope exit. The second
  22420. // connect must succeed and echo, proving the close handshake ran over a live
  22421. // session. See the note above about memory-tool requirements.
  22422. TEST_F(WebSocketSSLIntegrationTest,
  22423. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22424. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22425. "/ws-echo");
  22426. client.enable_server_certificate_verification(false);
  22427. client.set_read_timeout(2, 0);
  22428. client.set_write_timeout(2, 0);
  22429. ASSERT_TRUE(client.connect());
  22430. ASSERT_TRUE(client.is_open());
  22431. ASSERT_TRUE(client.send("still open"));
  22432. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22433. // the still-open connection, which must not touch a freed TLS session.
  22434. ASSERT_TRUE(client.connect());
  22435. ASSERT_TRUE(client.is_open());
  22436. ASSERT_TRUE(client.send("after reconnect"));
  22437. std::string msg;
  22438. EXPECT_EQ(ws::Text, client.read(msg));
  22439. EXPECT_EQ("after reconnect", msg);
  22440. client.close();
  22441. }
  22442. #endif
  22443. #ifdef CPPHTTPLIB_SSL_ENABLED
  22444. class WebSocketSSLCATest : public ::testing::Test {
  22445. protected:
  22446. void SetUp() override {
  22447. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22448. SERVER_PRIVATE_KEY_FILE);
  22449. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22450. std::string msg;
  22451. while (ws.read(msg)) {
  22452. ws.send(msg);
  22453. }
  22454. });
  22455. port_ = server_->bind_to_any_port("127.0.0.1");
  22456. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22457. server_->wait_until_ready();
  22458. }
  22459. void TearDown() override {
  22460. server_->stop();
  22461. if (server_thread_.joinable()) { server_thread_.join(); }
  22462. }
  22463. std::string url() const {
  22464. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22465. }
  22466. std::unique_ptr<SSLServer> server_;
  22467. std::thread server_thread_;
  22468. int port_ = 0;
  22469. };
  22470. // A custom CA loaded as PEM verifies the server with full certificate
  22471. // verification enabled
  22472. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22473. ws::WebSocketClient client(url());
  22474. std::string cert;
  22475. read_file(SERVER_CERT2_FILE, cert);
  22476. client.load_ca_cert_store(cert.c_str(), cert.size());
  22477. ASSERT_TRUE(client.connect());
  22478. ASSERT_TRUE(client.send("hello"));
  22479. std::string msg;
  22480. EXPECT_EQ(ws::Text, client.read(msg));
  22481. EXPECT_EQ("hello", msg);
  22482. client.close();
  22483. }
  22484. // A custom CA that does not cover the server must fail verification (the
  22485. // custom CA is exclusive; system certs are not loaded alongside it)
  22486. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22487. ws::WebSocketClient client(url());
  22488. std::string cert;
  22489. read_file(CLIENT_CA_CERT_FILE, cert);
  22490. client.load_ca_cert_store(cert.c_str(), cert.size());
  22491. auto res = client.connect();
  22492. ASSERT_FALSE(res);
  22493. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22494. EXPECT_EQ(-1, res.status());
  22495. EXPECT_NE(0u, res.ssl_backend_error());
  22496. }
  22497. // The same CA as a file path rather than PEM in memory
  22498. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22499. ws::WebSocketClient client(url());
  22500. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22501. ASSERT_TRUE(client.connect());
  22502. ASSERT_TRUE(client.send("hello"));
  22503. std::string msg;
  22504. EXPECT_EQ(ws::Text, client.read(msg));
  22505. EXPECT_EQ("hello", msg);
  22506. client.close();
  22507. }
  22508. // ...and a CA file that does not cover the server still fails, so it is the
  22509. // path above that decides the outcome
  22510. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22511. ws::WebSocketClient client(url());
  22512. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22513. ASSERT_FALSE(client.connect());
  22514. }
  22515. // Regression test: reconnecting with a native custom CA store used to reuse
  22516. // a store handle the previous TLS context had already freed (use-after-free
  22517. // under the OpenSSL backend). The context now lives as long as the client.
  22518. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22519. ws::WebSocketClient client(url());
  22520. std::string cert;
  22521. read_file(SERVER_CERT2_FILE, cert);
  22522. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22523. ASSERT_TRUE(client.connect());
  22524. client.close();
  22525. ASSERT_TRUE(client.connect());
  22526. ASSERT_TRUE(client.send("again"));
  22527. std::string msg;
  22528. EXPECT_EQ(ws::Text, client.read(msg));
  22529. EXPECT_EQ("again", msg);
  22530. client.close();
  22531. }
  22532. // Regression test: a certificate with a trusted chain but no identity match
  22533. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22534. // verification entirely for IP hosts, so this connection succeeded there.
  22535. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22536. // chain verification while the identity check must still fail.
  22537. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22539. ASSERT_TRUE(svr.is_valid());
  22540. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22541. std::string msg;
  22542. while (ws.read(msg)) {
  22543. ws.send(msg);
  22544. }
  22545. });
  22546. auto port = svr.bind_to_any_port("127.0.0.1");
  22547. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22548. auto se = detail::scope_exit([&] {
  22549. svr.stop();
  22550. t.join();
  22551. });
  22552. svr.wait_until_ready();
  22553. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22554. "/echo");
  22555. std::string cert;
  22556. read_file(SERVER_CERT_FILE, cert);
  22557. client.load_ca_cert_store(cert.c_str(), cert.size());
  22558. ASSERT_FALSE(client.connect());
  22559. }
  22560. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22561. // SNI, so nothing binds the host name to the TLS session. These bind the
  22562. // server to "localhost" instead, the only shape that exercises the SNI and
  22563. // hostname-verification path with certificate verification left enabled.
  22564. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22565. protected:
  22566. void Start(const char *cert_file) {
  22567. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22568. SERVER_PRIVATE_KEY_FILE);
  22569. ASSERT_TRUE(server_->is_valid());
  22570. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22571. std::string msg;
  22572. while (ws.read(msg)) {
  22573. ws.send(msg);
  22574. }
  22575. });
  22576. port_ = server_->bind_to_any_port("localhost");
  22577. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22578. server_->wait_until_ready();
  22579. }
  22580. void TearDown() override {
  22581. if (server_) { server_->stop(); }
  22582. if (server_thread_.joinable()) { server_thread_.join(); }
  22583. }
  22584. std::string url() const {
  22585. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22586. }
  22587. std::unique_ptr<SSLServer> server_;
  22588. std::thread server_thread_;
  22589. int port_ = 0;
  22590. };
  22591. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22592. // out and the connection is usable
  22593. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22594. Start(SERVER_CERT2_FILE);
  22595. ws::WebSocketClient client(url());
  22596. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22597. ASSERT_TRUE(client.connect());
  22598. ASSERT_TRUE(client.send("hello"));
  22599. std::string msg;
  22600. EXPECT_EQ(ws::Text, client.read(msg));
  22601. EXPECT_EQ("hello", msg);
  22602. client.close();
  22603. }
  22604. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22605. // while the identity check must still reject "localhost"
  22606. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22607. Start(SERVER_CERT_FILE);
  22608. ws::WebSocketClient client(url());
  22609. client.set_ca_cert_path(SERVER_CERT_FILE);
  22610. auto res = client.connect();
  22611. ASSERT_FALSE(res);
  22612. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22613. EXPECT_EQ(-1, res.status());
  22614. }
  22615. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22616. // disabled: the chain is still checked, only the identity check is skipped
  22617. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22618. Start(SERVER_CERT_FILE);
  22619. ws::WebSocketClient client(url());
  22620. client.set_ca_cert_path(SERVER_CERT_FILE);
  22621. client.enable_server_hostname_verification(false);
  22622. ASSERT_TRUE(client.connect());
  22623. ASSERT_TRUE(client.send("hello"));
  22624. std::string msg;
  22625. EXPECT_EQ(ws::Text, client.read(msg));
  22626. EXPECT_EQ("hello", msg);
  22627. client.close();
  22628. }
  22629. // A CA that did not sign the server certificate fails the chain, even though
  22630. // the name would match
  22631. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22632. Start(SERVER_CERT2_FILE);
  22633. ws::WebSocketClient client(url());
  22634. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22635. ASSERT_FALSE(client.connect());
  22636. }
  22637. // With verification disabled, neither the chain nor the name is checked
  22638. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22639. Start(SERVER_CERT_FILE);
  22640. ws::WebSocketClient client(url());
  22641. client.enable_server_certificate_verification(false);
  22642. ASSERT_TRUE(client.connect());
  22643. ASSERT_TRUE(client.send("hello"));
  22644. std::string msg;
  22645. EXPECT_EQ(ws::Text, client.read(msg));
  22646. EXPECT_EQ("hello", msg);
  22647. client.close();
  22648. }
  22649. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22650. protected:
  22651. void SetUp() override {
  22652. server_ = httplib::detail::make_unique<SSLServer>(
  22653. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22654. ASSERT_TRUE(server_->is_valid());
  22655. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22656. std::string msg;
  22657. while (ws.read(msg)) {
  22658. ws.send(msg);
  22659. }
  22660. });
  22661. port_ = server_->bind_to_any_port("localhost");
  22662. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22663. server_->wait_until_ready();
  22664. }
  22665. void TearDown() override {
  22666. server_->stop();
  22667. if (server_thread_.joinable()) { server_thread_.join(); }
  22668. }
  22669. std::string url() const {
  22670. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22671. }
  22672. void ConnectWithClientCert(const std::string &client_cert_file,
  22673. const std::string &client_private_key_file,
  22674. const char *private_key_password) {
  22675. std::string cert_pem, key_pem;
  22676. read_file(client_cert_file, cert_pem);
  22677. read_file(client_private_key_file, key_pem);
  22678. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22679. key_pem.c_str(), key_pem.size(),
  22680. private_key_password};
  22681. ws::WebSocketClient client(url(), pem);
  22682. ASSERT_TRUE(client.is_valid());
  22683. client.enable_server_certificate_verification(false);
  22684. ASSERT_TRUE(client.connect());
  22685. ASSERT_TRUE(client.send("hello"));
  22686. std::string msg;
  22687. EXPECT_EQ(ws::Text, client.read(msg));
  22688. EXPECT_EQ("hello", msg);
  22689. client.close();
  22690. }
  22691. std::unique_ptr<SSLServer> server_;
  22692. std::thread server_thread_;
  22693. int port_ = 0;
  22694. };
  22695. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22696. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22697. }
  22698. // Control for the tests above: the fixture's server really does require a
  22699. // client certificate, so it is the PEM the constructor installed that decides
  22700. // the outcome.
  22701. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22702. ws::WebSocketClient client(url());
  22703. ASSERT_TRUE(client.is_valid());
  22704. client.enable_server_certificate_verification(false);
  22705. EXPECT_FALSE(client.connect());
  22706. }
  22707. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22708. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22709. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22710. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22711. }
  22712. #endif
  22713. #if !defined(_WIN32)
  22714. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22715. auto secret_dir = std::string("./symlink_test_secret");
  22716. auto served_dir = std::string("./symlink_test_served");
  22717. auto secret_file = secret_dir + "/secret.txt";
  22718. auto symlink_path = served_dir + "/escape";
  22719. // Setup: create directories and files
  22720. mkdir(secret_dir.c_str(), 0755);
  22721. mkdir(served_dir.c_str(), 0755);
  22722. {
  22723. std::ofstream ofs(secret_file);
  22724. ofs << "SECRET_DATA";
  22725. }
  22726. // Create symlink using absolute path so it resolves correctly
  22727. #ifdef PATH_MAX
  22728. char abs_secret[PATH_MAX];
  22729. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22730. #else
  22731. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22732. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22733. ASSERT_NE(nullptr, abs_secret);
  22734. #endif
  22735. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22736. auto se = detail::scope_exit([&] {
  22737. unlink(symlink_path.c_str());
  22738. unlink(secret_file.c_str());
  22739. rmdir(served_dir.c_str());
  22740. rmdir(secret_dir.c_str());
  22741. });
  22742. Server svr;
  22743. svr.set_mount_point("/", served_dir);
  22744. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22745. auto se2 = detail::scope_exit([&] {
  22746. svr.stop();
  22747. listen_thread.join();
  22748. });
  22749. svr.wait_until_ready();
  22750. Client cli("localhost", PORT);
  22751. // Symlink pointing outside base dir should be blocked
  22752. auto res = cli.Get("/escape/secret.txt");
  22753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22754. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22755. }
  22756. #endif
  22757. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22758. // "GET /smuggled" request), reads the first response, and only then sends the
  22759. // embedded request as the body. Returns how many times /smuggled ran.
  22760. //
  22761. // The body is sent AFTER receiving the first response (as in the original
  22762. // PoC) so that the stream_line_reader cannot buffer it together with the
  22763. // headers of the first request.
  22764. static int count_smuggled_requests(const std::string &outer_head,
  22765. std::string &first_response) {
  22766. Server svr;
  22767. svr.set_mount_point("/", "./www");
  22768. std::atomic<int> smuggled_count(0);
  22769. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22770. smuggled_count++;
  22771. res.set_content("oops", "text/plain");
  22772. });
  22773. svr.Post("/post", [&](const Request &req, Response &res) {
  22774. res.set_content(req.body, "text/plain");
  22775. });
  22776. auto port = svr.bind_to_any_port("localhost");
  22777. thread t = thread([&] { svr.listen_after_bind(); });
  22778. auto se = detail::scope_exit([&] {
  22779. svr.stop();
  22780. t.join();
  22781. });
  22782. svr.wait_until_ready();
  22783. auto error = Error::Success;
  22784. auto sock = detail::create_client_socket(
  22785. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22786. /*connection_timeout_sec=*/2, 0,
  22787. /*read_timeout_sec=*/2, 0,
  22788. /*write_timeout_sec=*/2, 0, std::string(), error);
  22789. EXPECT_NE(INVALID_SOCKET, sock);
  22790. if (sock == INVALID_SOCKET) { return -1; }
  22791. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22792. // The "smuggled" request will be sent as the body of the outer request
  22793. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22794. "Host: localhost\r\n"
  22795. "Connection: close\r\n"
  22796. "\r\n";
  22797. auto head = outer_head;
  22798. auto len = std::to_string(smuggled.size());
  22799. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22800. pos = head.find("{len}", pos + len.size())) {
  22801. head.replace(pos, 5, len);
  22802. }
  22803. // Step 1: Send only the outer request headers (no body yet)
  22804. auto sent = send(sock, head.data(), head.size(), 0);
  22805. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22806. // Step 2: Read the first response
  22807. char buf[4096];
  22808. for (;;) {
  22809. auto n = recv(sock, buf, sizeof(buf), 0);
  22810. if (n <= 0) break;
  22811. first_response.append(buf, static_cast<size_t>(n));
  22812. // Stop once we have a complete response (headers + body)
  22813. auto hdr_end = first_response.find("\r\n\r\n");
  22814. if (hdr_end != std::string::npos) {
  22815. // Check for Content-Length to know when the body is complete
  22816. auto cl_pos = first_response.find("Content-Length:");
  22817. if (cl_pos != std::string::npos) {
  22818. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22819. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22820. auto cl = std::stoul(
  22821. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22822. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22823. } else {
  22824. break; // No Content-Length, assume headers-only response
  22825. }
  22826. }
  22827. }
  22828. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22829. // vulnerable server the keep-alive loop reads this as a second request. The
  22830. // server may already have closed the connection, so the result is ignored.
  22831. send(sock, smuggled.data(), smuggled.size(), 0);
  22832. // Half-close so that a server which drained the body sees EOF and closes,
  22833. // instead of the read below waiting for the read timeout.
  22834. #ifdef _WIN32
  22835. ::shutdown(sock, SD_SEND);
  22836. #else
  22837. ::shutdown(sock, SHUT_WR);
  22838. #endif
  22839. // Step 4: Read until the server closes the connection
  22840. for (;;) {
  22841. auto n = recv(sock, buf, sizeof(buf), 0);
  22842. if (n <= 0) break;
  22843. }
  22844. return smuggled_count.load();
  22845. }
  22846. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22847. // A GET request with Content-Length to a static file handler must have its
  22848. // body drained before the keep-alive connection is reused. Otherwise the
  22849. // unread body bytes are interpreted as the next HTTP request.
  22850. std::string first_response;
  22851. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22852. "Host: localhost\r\n"
  22853. "Content-Length: {len}\r\n"
  22854. "\r\n",
  22855. first_response));
  22856. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22857. }
  22858. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22859. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22860. // be answered with 400 and the connection closed. Treating it as "no body"
  22861. // leaves the body to be parsed as the next request.
  22862. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22863. const char *targets[] = {
  22864. "GET /file", // handler that never reads the body
  22865. "GET /not-found", // no handler matches (404)
  22866. "POST /post", // handler that reads the body
  22867. };
  22868. for (auto target : targets) {
  22869. for (auto value : values) {
  22870. std::string first_response;
  22871. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22872. " HTTP/1.1\r\n"
  22873. "Host: localhost\r\n"
  22874. "Content-Length: " +
  22875. value + "\r\n\r\n",
  22876. first_response))
  22877. << target << " with Content-Length: " << value;
  22878. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22879. << target << " with Content-Length: " << value;
  22880. }
  22881. }
  22882. }
  22883. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22884. // A 400 for an unparseable request line leaves the rest of the message
  22885. // unread, so the connection must be closed rather than reused.
  22886. std::string first_response;
  22887. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22888. "Host: localhost\r\n"
  22889. "Content-Length: {len}\r\n"
  22890. "\r\n",
  22891. first_response));
  22892. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22893. }
  22894. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22895. // Same as above for a header block that fails to parse.
  22896. std::string first_response;
  22897. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22898. "Host: localhost\r\n"
  22899. "Bad Header\r\n"
  22900. "Content-Length: {len}\r\n"
  22901. "\r\n",
  22902. first_response));
  22903. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22904. }
  22905. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22906. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22907. // server must not read another request on that connection, even when the
  22908. // request had no body to drain.
  22909. std::string first_response;
  22910. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22911. "Host: localhost\r\n"
  22912. "\r\n",
  22913. first_response));
  22914. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22915. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22916. }
  22917. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22918. // A content reader that stops early leaves the stream inside the body.
  22919. // Draining the whole Content-Length from there, or reading the body again,
  22920. // reads into the next request, and whatever follows is parsed as a request
  22921. // of its own.
  22922. Server svr;
  22923. std::atomic<int> smuggled_count(0);
  22924. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22925. svr.Post("/upload", [](const Request &req, Response &res,
  22926. const ContentReader &content_reader) {
  22927. // Stop at the last chunk, so the whole body has been read however it
  22928. // arrives.
  22929. auto length = req.get_header_value_u64("Content-Length");
  22930. size_t total = 0;
  22931. auto consumed = content_reader([&](const char *, size_t n) {
  22932. total += n;
  22933. return total < length;
  22934. });
  22935. EXPECT_FALSE(consumed);
  22936. if (req.has_param("retry")) {
  22937. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22938. }
  22939. // Replace the 400 the aborted read set, which would close the connection.
  22940. res.set_redirect("/done");
  22941. });
  22942. auto port = svr.bind_to_any_port(HOST);
  22943. thread t = thread([&] { svr.listen_after_bind(); });
  22944. auto se = detail::scope_exit([&] {
  22945. svr.stop();
  22946. t.join();
  22947. });
  22948. svr.wait_until_ready();
  22949. // A front end sees the second request as a POST whose body is the GET. The
  22950. // first body is as long as the POST's headers, so draining it again reads
  22951. // exactly those and leaves the GET to be parsed next.
  22952. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22953. "Host: localhost\r\n"
  22954. "\r\n";
  22955. std::string second_head = "POST /post HTTP/1.1\r\n"
  22956. "Host: localhost\r\n"
  22957. "Content-Length: " +
  22958. std::to_string(inner.size()) +
  22959. "\r\n"
  22960. "\r\n";
  22961. for (auto target : {"/upload", "/upload?retry"}) {
  22962. smuggled_count = 0;
  22963. std::string request = "POST " + std::string(target) +
  22964. " HTTP/1.1\r\n"
  22965. "Host: localhost\r\n"
  22966. "Content-Length: " +
  22967. std::to_string(second_head.size()) +
  22968. "\r\n"
  22969. "\r\n" +
  22970. std::string(second_head.size(), 'A') + second_head +
  22971. inner;
  22972. std::string response;
  22973. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22974. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22975. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22976. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22977. EXPECT_EQ(0, smuggled_count.load()) << target;
  22978. }
  22979. }
  22980. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22981. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22982. // must be rejected with 400 Bad Request.
  22983. Server svr;
  22984. svr.Post("/test", [&](const Request &, Response &res) {
  22985. res.set_content("ok", "text/plain");
  22986. });
  22987. thread t = thread([&] { svr.listen(HOST, PORT); });
  22988. auto se = detail::scope_exit([&] {
  22989. svr.stop();
  22990. t.join();
  22991. ASSERT_FALSE(svr.is_running());
  22992. });
  22993. svr.wait_until_ready();
  22994. // Exact "chunked"
  22995. {
  22996. auto req = "POST /test HTTP/1.1\r\n"
  22997. "Host: localhost\r\n"
  22998. "Content-Length: 5\r\n"
  22999. "Transfer-Encoding: chunked\r\n"
  23000. "Connection: close\r\n"
  23001. "\r\n"
  23002. "hello";
  23003. std::string response;
  23004. ASSERT_TRUE(send_request(1, req, &response));
  23005. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23006. response.substr(0, response.find("\r\n")));
  23007. }
  23008. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23009. {
  23010. auto req = "POST /test HTTP/1.1\r\n"
  23011. "Host: localhost\r\n"
  23012. "Content-Length: 5\r\n"
  23013. "Transfer-Encoding: gzip, chunked\r\n"
  23014. "Connection: close\r\n"
  23015. "\r\n"
  23016. "hello";
  23017. std::string response;
  23018. ASSERT_TRUE(send_request(1, req, &response));
  23019. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23020. response.substr(0, response.find("\r\n")));
  23021. }
  23022. }
  23023. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23024. Server svr;
  23025. svr.Post("/test", [&](const Request &, Response &res) {
  23026. res.set_content("ok", "text/plain");
  23027. });
  23028. thread t = thread([&] { svr.listen(HOST, PORT); });
  23029. auto se = detail::scope_exit([&] {
  23030. svr.stop();
  23031. t.join();
  23032. ASSERT_FALSE(svr.is_running());
  23033. });
  23034. svr.wait_until_ready();
  23035. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23036. // length cannot be determined, so the server must answer 400 and close
  23037. // rather than treat the request as bodyless and leave the body in the
  23038. // socket for the next request to pick up.
  23039. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23040. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23041. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23042. std::string response;
  23043. ASSERT_TRUE(send_request(1, req, &response));
  23044. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23045. response.substr(0, response.find("\r\n")))
  23046. << transfer_encoding;
  23047. }
  23048. // RFC 9110 5.3: the codings may also be split across several
  23049. // Transfer-Encoding lines, which combine in the order they were received.
  23050. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23051. // just like the single-line "chunked, gzip" above.
  23052. {
  23053. auto req = "POST /test HTTP/1.1\r\n"
  23054. "Host: localhost\r\n"
  23055. "Transfer-Encoding: chunked\r\n"
  23056. "Transfer-Encoding: gzip\r\n"
  23057. "\r\n"
  23058. "0\r\n\r\n";
  23059. std::string response;
  23060. ASSERT_TRUE(send_request(1, req, &response));
  23061. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23062. response.substr(0, response.find("\r\n")));
  23063. }
  23064. // A sequence ending in chunked stays valid.
  23065. auto req = "POST /test HTTP/1.1\r\n"
  23066. "Host: localhost\r\n"
  23067. "Transfer-Encoding: gzip, chunked\r\n"
  23068. "Connection: close\r\n"
  23069. "\r\n"
  23070. "0\r\n\r\n";
  23071. std::string response;
  23072. ASSERT_TRUE(send_request(1, req, &response));
  23073. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23074. // ...including when it is spread over several lines.
  23075. auto split_req = "POST /test HTTP/1.1\r\n"
  23076. "Host: localhost\r\n"
  23077. "Transfer-Encoding: gzip\r\n"
  23078. "Transfer-Encoding: chunked\r\n"
  23079. "Connection: close\r\n"
  23080. "\r\n"
  23081. "0\r\n\r\n";
  23082. std::string split_response;
  23083. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23084. EXPECT_EQ("HTTP/1.1 200 OK",
  23085. split_response.substr(0, split_response.find("\r\n")));
  23086. }
  23087. // Regression for issue #2450: a DELETE without Content-Length on a
  23088. // keep-alive connection must not let the post-response drain consume the
  23089. // next request's bytes.
  23090. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23091. Server svr;
  23092. std::atomic<int> delete_count(0);
  23093. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23094. delete_count++;
  23095. res.status = StatusCode::NoContent_204;
  23096. });
  23097. auto port = svr.bind_to_any_port(HOST);
  23098. thread t = thread([&] { svr.listen_after_bind(); });
  23099. auto se = detail::scope_exit([&] {
  23100. svr.stop();
  23101. t.join();
  23102. });
  23103. svr.wait_until_ready();
  23104. auto error = Error::Success;
  23105. auto sock = detail::create_client_socket(
  23106. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23107. /*connection_timeout_sec=*/2, 0,
  23108. /*read_timeout_sec=*/2, 0,
  23109. /*write_timeout_sec=*/2, 0, std::string(), error);
  23110. ASSERT_NE(INVALID_SOCKET, sock);
  23111. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23112. auto send_request_and_read_response = [&](const std::string &req,
  23113. std::string &out) -> bool {
  23114. auto sent = send(sock, req.data(), req.size(), 0);
  23115. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23116. char buf[4096];
  23117. for (;;) {
  23118. auto n = recv(sock, buf, sizeof(buf), 0);
  23119. if (n <= 0) { return !out.empty(); }
  23120. out.append(buf, static_cast<size_t>(n));
  23121. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23122. }
  23123. };
  23124. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23125. "Host: localhost\r\n"
  23126. "\r\n";
  23127. std::string resp1;
  23128. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23129. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23130. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23131. "Host: localhost\r\n"
  23132. "Connection: close\r\n"
  23133. "\r\n";
  23134. std::string resp2;
  23135. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23136. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23137. EXPECT_EQ(2, delete_count.load());
  23138. }
  23139. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23140. Server svr;
  23141. svr.Post("/ingest", [&](const Request &, Response &res,
  23142. const ContentReader &content_reader) {
  23143. auto consumed = content_reader([](const char *, size_t) { return false; });
  23144. EXPECT_FALSE(consumed);
  23145. res.status = StatusCode::Conflict_409;
  23146. res.set_header("Connection", "close");
  23147. });
  23148. auto port = svr.bind_to_any_port(HOST);
  23149. thread t = thread([&] { svr.listen_after_bind(); });
  23150. auto se = detail::scope_exit([&] {
  23151. svr.stop();
  23152. t.join();
  23153. });
  23154. svr.wait_until_ready();
  23155. auto error = Error::Success;
  23156. auto sock = detail::create_client_socket(
  23157. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23158. /*connection_timeout_sec=*/2, 0,
  23159. /*read_timeout_sec=*/1, 0,
  23160. /*write_timeout_sec=*/2, 0, std::string(), error);
  23161. ASSERT_NE(INVALID_SOCKET, sock);
  23162. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23163. std::string request = "POST /ingest HTTP/1.1\r\n"
  23164. "Host: localhost\r\n"
  23165. "Transfer-Encoding: chunked\r\n"
  23166. "\r\n"
  23167. "4\r\n"
  23168. "data\r\n";
  23169. auto sent = send(sock, request.data(), request.size(), 0);
  23170. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23171. std::string response;
  23172. ssize_t received = 0;
  23173. do {
  23174. char buf[4096];
  23175. received = recv(sock, buf, sizeof(buf), 0);
  23176. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23177. } while (received > 0);
  23178. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23179. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23180. EXPECT_EQ(0, received);
  23181. }
  23182. namespace no_proxy_test {
  23183. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23184. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23185. // calling listen().
  23186. class ScopedServer {
  23187. public:
  23188. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23189. ~ScopedServer() {
  23190. svr_.stop();
  23191. if (th_.joinable()) { th_.join(); }
  23192. }
  23193. Server &svr() { return svr_; }
  23194. int port() const { return port_; }
  23195. void listen() {
  23196. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23197. svr_.wait_until_ready();
  23198. }
  23199. private:
  23200. Server svr_;
  23201. std::thread th_;
  23202. int port_ = 0;
  23203. };
  23204. class ProxyAndTargetServers {
  23205. public:
  23206. ProxyAndTargetServers() {
  23207. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23208. proxy_hits_++;
  23209. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23210. res.set_content("via-proxy", "text/plain");
  23211. });
  23212. target_.Get(".*", [this](const Request &req, Response &res) {
  23213. target_hits_++;
  23214. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23215. res.set_content("direct", "text/plain");
  23216. });
  23217. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23218. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23219. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23220. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23221. proxy_mock_.wait_until_ready();
  23222. target_.wait_until_ready();
  23223. }
  23224. ~ProxyAndTargetServers() {
  23225. proxy_mock_.stop();
  23226. target_.stop();
  23227. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23228. if (target_thread_.joinable()) { target_thread_.join(); }
  23229. }
  23230. Server &proxy_mock() { return proxy_mock_; }
  23231. Server &target() { return target_; }
  23232. int proxy_port() const { return proxy_port_; }
  23233. int target_port() const { return target_port_; }
  23234. int proxy_hits() const { return proxy_hits_.load(); }
  23235. int target_hits() const { return target_hits_.load(); }
  23236. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23237. void reset_counters() {
  23238. proxy_hits_ = 0;
  23239. target_hits_ = 0;
  23240. last_had_proxy_authz_ = false;
  23241. }
  23242. private:
  23243. Server proxy_mock_;
  23244. Server target_;
  23245. std::thread proxy_thread_;
  23246. std::thread target_thread_;
  23247. int proxy_port_ = 0;
  23248. int target_port_ = 0;
  23249. std::atomic<int> proxy_hits_{0};
  23250. std::atomic<int> target_hits_{0};
  23251. std::atomic<bool> last_had_proxy_authz_{false};
  23252. };
  23253. inline std::unique_ptr<Client> make_client(const std::string &host,
  23254. ProxyAndTargetServers &s) {
  23255. auto cli = detail::make_unique<Client>(host, s.target_port());
  23256. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23257. cli->set_proxy("127.0.0.1", s.proxy_port());
  23258. return cli;
  23259. }
  23260. } // namespace no_proxy_test
  23261. using no_proxy_test::make_client;
  23262. using no_proxy_test::ProxyAndTargetServers;
  23263. TEST(NoProxyTest, ExactHostnameBypasses) {
  23264. ProxyAndTargetServers s;
  23265. auto cli = make_client("example.com", s);
  23266. cli->set_no_proxy({"example.com"});
  23267. auto res = cli->Get("/");
  23268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23269. EXPECT_EQ(0, s.proxy_hits());
  23270. EXPECT_EQ(1, s.target_hits());
  23271. }
  23272. TEST(NoProxyTest, SubdomainBypasses) {
  23273. ProxyAndTargetServers s;
  23274. auto cli = make_client("foo.example.com", s);
  23275. cli->set_no_proxy({"example.com"});
  23276. auto res = cli->Get("/");
  23277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23278. EXPECT_EQ(0, s.proxy_hits());
  23279. EXPECT_EQ(1, s.target_hits());
  23280. }
  23281. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23282. // Regression guard: "evilexample.com" must not be considered a subdomain
  23283. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23284. // check would let traffic bypass the proxy and leak credentials direct
  23285. // to the attacker host.
  23286. ProxyAndTargetServers s;
  23287. auto cli = make_client("evilexample.com", s);
  23288. cli->set_no_proxy({"example.com"});
  23289. auto res = cli->Get("/");
  23290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23291. EXPECT_GE(s.proxy_hits(), 1);
  23292. EXPECT_EQ(0, s.target_hits());
  23293. }
  23294. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23295. ProxyAndTargetServers s;
  23296. auto cli = make_client("example.com.evil.com", s);
  23297. cli->set_no_proxy({"example.com"});
  23298. auto res = cli->Get("/");
  23299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23300. EXPECT_GE(s.proxy_hits(), 1);
  23301. EXPECT_EQ(0, s.target_hits());
  23302. }
  23303. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23304. ProxyAndTargetServers s;
  23305. auto cli = make_client("example.com", s);
  23306. cli->set_no_proxy({".example.com"});
  23307. auto res = cli->Get("/");
  23308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23309. EXPECT_EQ(0, s.proxy_hits());
  23310. EXPECT_EQ(1, s.target_hits());
  23311. }
  23312. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23313. ProxyAndTargetServers s;
  23314. auto cli = make_client("Example.COM", s);
  23315. cli->set_no_proxy({"EXAMPLE.com"});
  23316. auto res = cli->Get("/");
  23317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23318. EXPECT_EQ(0, s.proxy_hits());
  23319. EXPECT_EQ(1, s.target_hits());
  23320. }
  23321. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23322. ProxyAndTargetServers s;
  23323. auto cli = make_client("example.com.", s);
  23324. cli->set_no_proxy({"example.com"});
  23325. auto res = cli->Get("/");
  23326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23327. EXPECT_EQ(0, s.proxy_hits());
  23328. EXPECT_EQ(1, s.target_hits());
  23329. }
  23330. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23331. // Trailing dots must be normalized on BOTH sides — host and entry.
  23332. // An implementation that only strips the host-side trailing dot would
  23333. // fail to match host "example.com" against entry "example.com." because
  23334. // a literal substring search would compare 11 chars against 12.
  23335. ProxyAndTargetServers s;
  23336. auto cli = make_client("example.com", s);
  23337. cli->set_no_proxy({"example.com."});
  23338. auto res = cli->Get("/");
  23339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23340. EXPECT_EQ(0, s.proxy_hits());
  23341. EXPECT_EQ(1, s.target_hits());
  23342. }
  23343. TEST(NoProxyTest, WildcardBypassesEverything) {
  23344. ProxyAndTargetServers s;
  23345. auto cli = make_client("anything.invalid.test", s);
  23346. cli->set_no_proxy({"*"});
  23347. auto res = cli->Get("/");
  23348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23349. EXPECT_EQ(0, s.proxy_hits());
  23350. EXPECT_EQ(1, s.target_hits());
  23351. }
  23352. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23353. ProxyAndTargetServers s;
  23354. Client cli("127.0.0.1", s.target_port());
  23355. cli.set_proxy("127.0.0.1", s.proxy_port());
  23356. cli.set_no_proxy({"127.0.0.1"});
  23357. auto res = cli.Get("/");
  23358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23359. EXPECT_EQ(0, s.proxy_hits());
  23360. EXPECT_EQ(1, s.target_hits());
  23361. }
  23362. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23363. ProxyAndTargetServers s;
  23364. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23365. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23366. cli.set_proxy("127.0.0.1", s.proxy_port());
  23367. cli.set_no_proxy({"::1"});
  23368. auto res = cli.Get("/");
  23369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23370. EXPECT_EQ(0, s.proxy_hits());
  23371. EXPECT_EQ(1, s.target_hits());
  23372. }
  23373. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23374. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23375. // must still be recognized as IPv6 for CIDR matching. Implementations
  23376. // that detect IPv6 only when the host begins with '[' would parse the
  23377. // host as a hostname and miss the match.
  23378. ProxyAndTargetServers s;
  23379. Client cli("fe80::1", s.target_port());
  23380. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23381. cli.set_proxy("127.0.0.1", s.proxy_port());
  23382. cli.set_no_proxy({"fe80::/10"});
  23383. auto res = cli.Get("/");
  23384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23385. EXPECT_EQ(0, s.proxy_hits());
  23386. EXPECT_EQ(1, s.target_hits());
  23387. }
  23388. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23389. ProxyAndTargetServers s;
  23390. Client cli("::1", s.target_port());
  23391. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23392. cli.set_proxy("127.0.0.1", s.proxy_port());
  23393. cli.set_no_proxy({"[::1]"});
  23394. auto res = cli.Get("/");
  23395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23396. EXPECT_EQ(0, s.proxy_hits());
  23397. EXPECT_EQ(1, s.target_hits());
  23398. }
  23399. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23400. ProxyAndTargetServers s;
  23401. Client cli("fe80::1", s.target_port());
  23402. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23403. cli.set_proxy("127.0.0.1", s.proxy_port());
  23404. cli.set_no_proxy({"[fe80::]/10"});
  23405. auto res = cli.Get("/");
  23406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23407. EXPECT_EQ(0, s.proxy_hits());
  23408. EXPECT_EQ(1, s.target_hits());
  23409. }
  23410. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23411. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23412. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23413. // tricks via address-family conversion.
  23414. ProxyAndTargetServers s;
  23415. Client cli("::ffff:127.0.0.1", s.target_port());
  23416. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23417. cli.set_proxy("127.0.0.1", s.proxy_port());
  23418. cli.set_no_proxy({"127.0.0.1"});
  23419. auto res = cli.Get("/");
  23420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23421. EXPECT_GE(s.proxy_hits(), 1);
  23422. EXPECT_EQ(0, s.target_hits());
  23423. }
  23424. TEST(NoProxyTest, IPv4CidrMatch) {
  23425. ProxyAndTargetServers s;
  23426. Client cli("127.0.0.1", s.target_port());
  23427. cli.set_proxy("127.0.0.1", s.proxy_port());
  23428. cli.set_no_proxy({"127.0.0.0/8"});
  23429. auto res = cli.Get("/");
  23430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23431. EXPECT_EQ(0, s.proxy_hits());
  23432. EXPECT_EQ(1, s.target_hits());
  23433. }
  23434. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23435. ProxyAndTargetServers s;
  23436. Client cli("127.0.0.1", s.target_port());
  23437. cli.set_proxy("127.0.0.1", s.proxy_port());
  23438. cli.set_no_proxy({"10.0.0.0/8"});
  23439. auto res = cli.Get("/");
  23440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23441. EXPECT_GE(s.proxy_hits(), 1);
  23442. EXPECT_EQ(0, s.target_hits());
  23443. }
  23444. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23445. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23446. // IPv4 target matches.
  23447. ProxyAndTargetServers s;
  23448. Client cli("127.0.0.1", s.target_port());
  23449. cli.set_proxy("127.0.0.1", s.proxy_port());
  23450. cli.set_no_proxy({"0.0.0.0/0"});
  23451. auto res = cli.Get("/");
  23452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23453. EXPECT_EQ(0, s.proxy_hits());
  23454. EXPECT_EQ(1, s.target_hits());
  23455. }
  23456. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23457. ProxyAndTargetServers s;
  23458. Client cli("127.0.0.1", s.target_port());
  23459. cli.set_proxy("127.0.0.1", s.proxy_port());
  23460. cli.set_no_proxy({"127.0.0.1"});
  23461. auto res = cli.Get("/");
  23462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23463. EXPECT_EQ(0, s.proxy_hits());
  23464. EXPECT_EQ(1, s.target_hits());
  23465. }
  23466. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23467. ProxyAndTargetServers s;
  23468. Client cli("127.0.0.1", s.target_port());
  23469. cli.set_proxy("127.0.0.1", s.proxy_port());
  23470. cli.set_no_proxy({"127.0.0.0/33"});
  23471. auto res = cli.Get("/");
  23472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23473. EXPECT_GE(s.proxy_hits(), 1);
  23474. EXPECT_EQ(0, s.target_hits());
  23475. }
  23476. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23477. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23478. ProxyAndTargetServers s;
  23479. Client cli("127.0.0.1", s.target_port());
  23480. cli.set_proxy("127.0.0.1", s.proxy_port());
  23481. cli.set_no_proxy({"127.0.0.1/"});
  23482. auto res = cli.Get("/");
  23483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23484. EXPECT_GE(s.proxy_hits(), 1);
  23485. EXPECT_EQ(0, s.target_hits());
  23486. }
  23487. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23488. ProxyAndTargetServers s;
  23489. auto cli = make_client("internal.corp", s);
  23490. cli->set_proxy_basic_auth("u", "p");
  23491. cli->set_no_proxy({"internal.corp"});
  23492. auto res = cli->Get("/");
  23493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23494. EXPECT_EQ(1, s.target_hits());
  23495. EXPECT_EQ(0, s.proxy_hits());
  23496. EXPECT_FALSE(s.last_had_proxy_authz())
  23497. << "Proxy-Authorization must not be sent direct to the target";
  23498. }
  23499. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23500. ProxyAndTargetServers s;
  23501. auto cli = make_client("public.example", s);
  23502. cli->set_proxy_basic_auth("u", "p");
  23503. cli->set_no_proxy({"internal.corp"}); // does not match
  23504. auto res = cli->Get("/");
  23505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23506. EXPECT_GE(s.proxy_hits(), 1);
  23507. EXPECT_TRUE(s.last_had_proxy_authz());
  23508. }
  23509. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23510. std::atomic<int> hits{0};
  23511. std::atomic<int> hits_with_authz{0};
  23512. no_proxy_test::ScopedServer proxy_mock;
  23513. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23514. hits++;
  23515. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23516. if (req.target.find("/redir") != std::string::npos) {
  23517. res.set_redirect("http://other.example/landed");
  23518. } else {
  23519. res.set_content("via-proxy", "text/plain");
  23520. }
  23521. });
  23522. proxy_mock.listen();
  23523. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23524. hits = 0;
  23525. hits_with_authz = 0;
  23526. Client cli("public.example", 80);
  23527. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23528. cli.set_proxy_basic_auth(c.first, c.second);
  23529. cli.set_follow_location(true);
  23530. // The redirect to another host goes through the proxy as well
  23531. auto res = cli.Get("/redir");
  23532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23533. EXPECT_EQ(2, hits.load());
  23534. EXPECT_EQ(2, hits_with_authz.load());
  23535. }
  23536. }
  23537. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23538. ProxyAndTargetServers s;
  23539. auto cli = make_client("anything.test", s);
  23540. auto res = cli->Get("/");
  23541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23542. EXPECT_GE(s.proxy_hits(), 1);
  23543. EXPECT_EQ(0, s.target_hits());
  23544. }
  23545. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23546. ProxyAndTargetServers s;
  23547. auto cli = make_client("example.com", s);
  23548. cli->set_no_proxy({"example.com:8080"});
  23549. auto res = cli->Get("/");
  23550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23551. EXPECT_GE(s.proxy_hits(), 1);
  23552. EXPECT_EQ(0, s.target_hits());
  23553. }
  23554. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23555. ProxyAndTargetServers s;
  23556. auto cli = make_client("anything.test", s);
  23557. cli->set_no_proxy({"", " ", "\t"});
  23558. auto res = cli->Get("/");
  23559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23560. EXPECT_GE(s.proxy_hits(), 1);
  23561. EXPECT_EQ(0, s.target_hits());
  23562. }
  23563. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23564. // An entry with leading/trailing whitespace must still match — env-style
  23565. // values are commonly pasted with stray spaces and an implementation
  23566. // that feeds the raw token directly to inet_pton would fail to match
  23567. // valid CIDRs because of the spaces.
  23568. ProxyAndTargetServers s;
  23569. Client cli("127.0.0.1", s.target_port());
  23570. cli.set_proxy("127.0.0.1", s.proxy_port());
  23571. cli.set_no_proxy({" 127.0.0.0/8 "});
  23572. auto res = cli.Get("/");
  23573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23574. EXPECT_EQ(0, s.proxy_hits());
  23575. EXPECT_EQ(1, s.target_hits());
  23576. }
  23577. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23578. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23579. // go direct and must NOT carry Proxy-Authorization.
  23580. std::atomic<int> proxy_hits{0};
  23581. std::atomic<int> target_hits{0};
  23582. std::atomic<bool> target_saw_authz{false};
  23583. no_proxy_test::ScopedServer proxy_mock, target;
  23584. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23585. proxy_hits++;
  23586. res.status = 302;
  23587. res.set_header("Location", "http://127.0.0.1:" +
  23588. std::to_string(target.port()) + "/landed");
  23589. });
  23590. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23591. target_hits++;
  23592. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23593. res.set_content("direct", "text/plain");
  23594. });
  23595. proxy_mock.listen();
  23596. target.listen();
  23597. Client cli("public.example", target.port());
  23598. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23599. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23600. cli.set_proxy_basic_auth("u", "p");
  23601. cli.set_no_proxy({"127.0.0.1"});
  23602. cli.set_follow_location(true);
  23603. auto res = cli.Get("/redir");
  23604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23605. EXPECT_GE(proxy_hits.load(), 1);
  23606. EXPECT_GE(target_hits.load(), 1);
  23607. EXPECT_FALSE(target_saw_authz.load());
  23608. }
  23609. #ifdef CPPHTTPLIB_SSL_ENABLED
  23610. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23611. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23612. // proxy creds would be sent to the (possibly hostile) origin.
  23613. std::atomic<int> target_hits{0};
  23614. std::atomic<bool> target_saw_proxy_authz{false};
  23615. no_proxy_test::ScopedServer target;
  23616. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23617. target_hits++;
  23618. if (req.has_header("Proxy-Authorization")) {
  23619. target_saw_proxy_authz = true;
  23620. }
  23621. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23622. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23623. "nonce=\"abc\", algorithm=MD5");
  23624. });
  23625. target.listen();
  23626. // The proxy address is set to the target's port: the bypass MUST kick in;
  23627. // if it doesn't, the test still routes "via proxy" to the same server and
  23628. // the Proxy-Authorization assertion below catches the leak.
  23629. Client cli("evil.example", target.port());
  23630. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23631. cli.set_proxy("127.0.0.1", target.port());
  23632. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23633. cli.set_no_proxy({"evil.example"});
  23634. auto res = cli.Get("/x");
  23635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23636. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23637. EXPECT_EQ(1, target_hits.load());
  23638. EXPECT_FALSE(target_saw_proxy_authz.load());
  23639. }
  23640. #endif
  23641. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23642. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23643. std::atomic<int> proxy_hits{0};
  23644. std::atomic<int> bypass_hits{0};
  23645. std::atomic<bool> proxy_saw_c_url{false};
  23646. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23647. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23648. proxy_hits++;
  23649. if (req.path.find("/start") != std::string::npos) {
  23650. res.status = 302;
  23651. res.set_header("Location", "http://127.0.0.1:" +
  23652. std::to_string(bypass_server.port()) +
  23653. "/middle");
  23654. return;
  23655. }
  23656. if (req.path.find("/end") != std::string::npos) {
  23657. proxy_saw_c_url = true;
  23658. res.set_content("c-via-proxy", "text/plain");
  23659. return;
  23660. }
  23661. res.set_content("unexpected", "text/plain");
  23662. });
  23663. // public.example's "advertised" port is arbitrary (the request never lands
  23664. // there — it goes through the proxy), but use a dynamic value to stay
  23665. // friendly with sharded parallel runs.
  23666. int public_port = bypass_server.port();
  23667. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23668. bypass_hits++;
  23669. res.status = 302;
  23670. res.set_header("Location", "http://public.example:" +
  23671. std::to_string(public_port) + "/end");
  23672. });
  23673. proxy_mock.listen();
  23674. bypass_server.listen();
  23675. Client cli("public.example", public_port);
  23676. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23677. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23678. cli.set_no_proxy({"127.0.0.1"});
  23679. cli.set_follow_location(true);
  23680. auto res = cli.Get("/start");
  23681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23682. EXPECT_EQ(StatusCode::OK_200, res->status);
  23683. EXPECT_EQ("c-via-proxy", res->body);
  23684. EXPECT_GE(proxy_hits.load(), 2);
  23685. EXPECT_GE(bypass_hits.load(), 1);
  23686. EXPECT_TRUE(proxy_saw_c_url.load());
  23687. }
  23688. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23689. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23690. // request reconnects to the correct endpoint.
  23691. std::atomic<int> proxy_hits{0};
  23692. std::atomic<int> target_hits{0};
  23693. no_proxy_test::ScopedServer proxy_mock, target;
  23694. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23695. proxy_hits++;
  23696. res.set_content("via-proxy", "text/plain");
  23697. });
  23698. target.svr().Get(".*", [&](const Request &, Response &res) {
  23699. target_hits++;
  23700. res.set_content("direct", "text/plain");
  23701. });
  23702. proxy_mock.listen();
  23703. target.listen();
  23704. Client cli("public.example", target.port());
  23705. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23706. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23707. cli.set_keep_alive(true);
  23708. auto res1 = cli.Get("/a");
  23709. ASSERT_TRUE(res1);
  23710. EXPECT_EQ("via-proxy", res1->body);
  23711. EXPECT_EQ(1, proxy_hits.load());
  23712. EXPECT_EQ(0, target_hits.load());
  23713. cli.set_no_proxy({"public.example"});
  23714. auto res2 = cli.Get("/b");
  23715. ASSERT_TRUE(res2);
  23716. EXPECT_EQ("direct", res2->body);
  23717. EXPECT_EQ(1, proxy_hits.load());
  23718. EXPECT_EQ(1, target_hits.load());
  23719. }
  23720. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23721. namespace proxy_tunnel_test {
  23722. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23723. class ScopedSSLServer {
  23724. public:
  23725. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23726. port_ = svr_.bind_to_any_port("127.0.0.1");
  23727. }
  23728. ~ScopedSSLServer() {
  23729. svr_.stop();
  23730. if (th_.joinable()) { th_.join(); }
  23731. }
  23732. SSLServer &svr() { return svr_; }
  23733. int port() const { return port_; }
  23734. void listen() {
  23735. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23736. svr_.wait_until_ready();
  23737. }
  23738. private:
  23739. SSLServer svr_;
  23740. std::thread th_;
  23741. int port_ = 0;
  23742. };
  23743. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23744. class ScopedConnectProxy {
  23745. public:
  23746. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23747. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23748. if (listen_fd_ < 0) { return; }
  23749. int yes = 1;
  23750. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23751. sockaddr_in a{};
  23752. a.sin_family = AF_INET;
  23753. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23754. a.sin_port = 0;
  23755. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23756. return;
  23757. }
  23758. socklen_t alen = sizeof(a);
  23759. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23760. 0) {
  23761. return;
  23762. }
  23763. port_ = ntohs(a.sin_port);
  23764. if (::listen(listen_fd_, 1) != 0) { return; }
  23765. th_ = std::thread([this] { run(); });
  23766. }
  23767. ~ScopedConnectProxy() {
  23768. stop_ = true;
  23769. if (listen_fd_ >= 0) {
  23770. ::shutdown(listen_fd_, SHUT_RDWR);
  23771. ::close(listen_fd_);
  23772. }
  23773. if (th_.joinable()) { th_.join(); }
  23774. }
  23775. int port() const { return port_; }
  23776. int connect_hits() const { return connect_hits_.load(); }
  23777. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23778. std::string connect_request() const {
  23779. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23780. return connect_request_;
  23781. }
  23782. private:
  23783. void run() {
  23784. while (!stop_.load()) {
  23785. fd_set rfds;
  23786. FD_ZERO(&rfds);
  23787. FD_SET(listen_fd_, &rfds);
  23788. timeval tv{0, 100 * 1000};
  23789. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23790. if (sel <= 0) { continue; }
  23791. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23792. if (client_fd < 0) { continue; }
  23793. std::string req;
  23794. char buf[2048];
  23795. while (req.find("\r\n\r\n") == std::string::npos) {
  23796. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23797. if (n <= 0) { break; }
  23798. req.append(buf, static_cast<size_t>(n));
  23799. }
  23800. if (req.compare(0, 7, "CONNECT") != 0) {
  23801. ::close(client_fd);
  23802. continue;
  23803. }
  23804. connect_hits_++;
  23805. {
  23806. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23807. connect_request_ = req;
  23808. }
  23809. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23810. ::send(client_fd, ok, std::strlen(ok), 0);
  23811. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23812. sockaddr_in o{};
  23813. o.sin_family = AF_INET;
  23814. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23815. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23816. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23817. 0) {
  23818. ::close(client_fd);
  23819. ::close(origin_fd);
  23820. continue;
  23821. }
  23822. auto forward = [](int from, int to) {
  23823. char b[8192];
  23824. for (;;) {
  23825. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23826. if (n <= 0) { break; }
  23827. ssize_t off = 0;
  23828. while (off < n) {
  23829. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23830. if (s <= 0) {
  23831. off = n;
  23832. break;
  23833. }
  23834. off += s;
  23835. }
  23836. }
  23837. ::shutdown(to, SHUT_WR);
  23838. };
  23839. std::thread t1([&] { forward(client_fd, origin_fd); });
  23840. std::thread t2([&] { forward(origin_fd, client_fd); });
  23841. t1.join();
  23842. t2.join();
  23843. ::close(client_fd);
  23844. ::close(origin_fd);
  23845. }
  23846. }
  23847. int forward_port_ = -1;
  23848. int listen_fd_ = -1;
  23849. int port_ = 0;
  23850. std::thread th_;
  23851. std::atomic<bool> stop_{false};
  23852. std::atomic<int> connect_hits_{0};
  23853. mutable std::mutex connect_request_mutex_;
  23854. std::string connect_request_;
  23855. };
  23856. // Sends one request through the CONNECT proxy to the TLS origin with a
  23857. // credential configured for each hop, and checks that each credential reaches
  23858. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23859. // origin's (every header in origin_headers) on the tunnelled request.
  23860. void CredentialsStayWithTheirHop(
  23861. const std::function<void(SSLClient &)> &set_credentials,
  23862. const std::string &scheme,
  23863. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23864. std::atomic<int> origin_hits{0};
  23865. std::atomic<bool> origin_saw_proxy_authz{false};
  23866. std::atomic<bool> origin_saw_headers{false};
  23867. ScopedSSLServer origin;
  23868. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23869. origin_hits++;
  23870. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23871. origin_saw_headers =
  23872. std::all_of(origin_headers.begin(), origin_headers.end(),
  23873. [&](const std::string &h) { return req.has_header(h); });
  23874. res.set_content("ok", "text/plain");
  23875. });
  23876. origin.listen();
  23877. ScopedConnectProxy proxy(origin.port());
  23878. ASSERT_NE(0, proxy.port());
  23879. // Pinned to 127.0.0.1 for the same reason as the test below.
  23880. SSLClient cli("127.0.0.1", origin.port());
  23881. cli.enable_server_certificate_verification(false);
  23882. cli.set_proxy("127.0.0.1", proxy.port());
  23883. set_credentials(cli);
  23884. auto res = cli.Get("/x");
  23885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23886. EXPECT_EQ(StatusCode::OK_200, res->status);
  23887. EXPECT_EQ(1, origin_hits.load());
  23888. EXPECT_EQ(1, proxy.connect_hits());
  23889. EXPECT_TRUE(origin_saw_headers.load());
  23890. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23891. << "Proxy-Authorization must not be sent inside the tunnel";
  23892. auto connect_req = proxy.connect_request();
  23893. EXPECT_NE(std::string::npos,
  23894. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23895. for (const auto &h : origin_headers) {
  23896. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23897. << h << " must not be sent to the proxy on CONNECT";
  23898. }
  23899. }
  23900. } // namespace proxy_tunnel_test
  23901. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23902. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23903. [](SSLClient &cli) {
  23904. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23905. cli.set_basic_auth("origin-user", "origin-pass");
  23906. },
  23907. "Basic");
  23908. }
  23909. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23910. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23911. [](SSLClient &cli) {
  23912. cli.set_proxy_bearer_token_auth("proxy-token");
  23913. cli.set_bearer_token_auth("origin-token");
  23914. },
  23915. "Bearer");
  23916. }
  23917. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23918. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23919. [](SSLClient &cli) {
  23920. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23921. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23922. {"Cookie", "sid=origin-session"},
  23923. {"X-Api-Key", "origin-key"}});
  23924. },
  23925. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23926. }
  23927. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23928. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23929. // retry; otherwise proxy creds would be sent to the origin.
  23930. std::atomic<int> origin_hits{0};
  23931. std::atomic<bool> origin_saw_proxy_authz{false};
  23932. proxy_tunnel_test::ScopedSSLServer origin;
  23933. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23934. origin_hits++;
  23935. if (req.has_header("Proxy-Authorization")) {
  23936. origin_saw_proxy_authz = true;
  23937. }
  23938. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23939. res.set_header("Proxy-Authenticate",
  23940. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23941. "algorithm=MD5");
  23942. });
  23943. origin.listen();
  23944. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23945. ASSERT_NE(0, proxy.port());
  23946. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23947. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23948. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23949. // and answer with its own status, making this test flaky.
  23950. SSLClient cli("127.0.0.1", origin.port());
  23951. cli.enable_server_certificate_verification(false);
  23952. cli.set_proxy("127.0.0.1", proxy.port());
  23953. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23954. auto res = cli.Get("/x");
  23955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23956. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23957. EXPECT_EQ(1, origin_hits.load());
  23958. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23959. EXPECT_EQ(1, proxy.connect_hits());
  23960. }
  23961. #endif