test.cc 938 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898
  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, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. }
  613. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  614. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  615. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  616. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  617. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  618. // Same 26-bit hash as REMOTE_ADDR.
  619. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  620. }
  621. // Forward declaration: in split builds split.py strips `inline` and moves the
  622. // definition into httplib.cc, so detail::base64_encode is not visible from the
  623. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  624. // in both header-only and split builds.
  625. namespace httplib {
  626. namespace detail {
  627. std::string base64_encode(const std::string &in);
  628. } // namespace detail
  629. } // namespace httplib
  630. TEST(Base64EncodeTest, KnownAnswers) {
  631. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  632. // where the accumulator's top bit is already set before the next shift.
  633. EXPECT_EQ("", detail::base64_encode(""));
  634. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  635. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  636. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  637. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  638. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  639. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  640. // High bytes keep the top bit set across several rounds.
  641. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  642. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  643. }
  644. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  645. string unescapedCharacters = "-_.!~*'()";
  646. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  647. }
  648. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  649. string reservedCharacters = ";,/?:@&=+$";
  650. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  651. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  652. }
  653. TEST(ClientQueryOrder, PreserveOrder) {
  654. // This test reproduces Issue #2259: client may reorder query parameters
  655. // when sending a GET request. The expected behavior is that the client
  656. // preserves the original query string order when the caller supplied it
  657. // as part of the path.
  658. Server svr;
  659. svr.Get("/", [&](const Request &req, Response &res) {
  660. // Echo back the raw target so the test can assert ordering
  661. res.set_content(req.target, "text/plain");
  662. });
  663. std::thread t{[&] { svr.listen(HOST, PORT); }};
  664. auto se = detail::scope_exit([&] {
  665. svr.stop();
  666. t.join();
  667. ASSERT_FALSE(svr.is_running());
  668. });
  669. svr.wait_until_ready();
  670. Client cli(HOST, PORT);
  671. ASSERT_TRUE(cli.is_valid());
  672. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  673. auto res = cli.Get(original);
  674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  675. // Expect the echoed target to exactly match the original path (order
  676. // preserved)
  677. EXPECT_EQ(res->body, original);
  678. }
  679. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  680. string chineseCharacters = U8("中国語");
  681. string russianCharacters = U8("дом");
  682. string brazilianCharacters = U8("óculos");
  683. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  684. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  685. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  686. "%D0%B4%D0%BE%D0%BC");
  687. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  688. }
  689. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  690. string unescapedCharacters = "-_.!~*'()";
  691. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  692. }
  693. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  694. string reservedCharacters = ";,/?:@&=+$";
  695. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  696. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  697. }
  698. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  699. string chineseCharacters = U8("中国語");
  700. string russianCharacters = U8("дом");
  701. string brazilianCharacters = U8("óculos");
  702. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  703. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  704. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  705. "%D0%B4%D0%BE%D0%BC");
  706. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  707. }
  708. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  709. // Issue #2082 use case: encoding path component with ampersand
  710. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  711. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  712. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  713. }
  714. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  715. string unescapedCharacters = "-_.!~*'()";
  716. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  717. }
  718. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  719. string reservedCharacters = ";,/?:@&=+$#";
  720. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  721. }
  722. TEST(EncodeUriTest, TestUTF8Characters) {
  723. string chineseCharacters = U8("中国語");
  724. string russianCharacters = U8("дом");
  725. string brazilianCharacters = U8("óculos");
  726. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  727. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  728. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  729. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  730. }
  731. TEST(EncodeUriTest, TestCompleteUri) {
  732. string uri =
  733. "https://example.com/path/to/resource?query=value&param=test#fragment";
  734. EXPECT_EQ(
  735. httplib::encode_uri(uri),
  736. "https://example.com/path/to/resource?query=value&param=test#fragment");
  737. }
  738. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  739. string uri =
  740. "https://example.com/path with spaces/file name.html?q=hello world";
  741. EXPECT_EQ(httplib::encode_uri(uri),
  742. "https://example.com/path%20with%20spaces/"
  743. "file%20name.html?q=hello%20world");
  744. }
  745. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  746. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  747. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  748. }
  749. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  750. string unescapedCharacters = "-_.!~*'()";
  751. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  752. }
  753. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  754. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  755. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  756. string encodedBrazilian = "%C3%B3culos";
  757. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  758. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  759. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  760. }
  761. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  762. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  763. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  764. "Piri Tommy Villiers - on & on");
  765. }
  766. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  767. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  768. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  769. }
  770. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  772. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  773. }
  774. TEST(DecodeUriTest, TestUTF8Characters) {
  775. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  776. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  777. string encodedBrazilian = "%C3%B3culos";
  778. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  779. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  780. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  781. }
  782. TEST(DecodeUriTest, TestCompleteUri) {
  783. string encodedUri = "https://example.com/path%20with%20spaces/"
  784. "file%20name.html?q=hello%20world";
  785. EXPECT_EQ(
  786. httplib::decode_uri(encodedUri),
  787. "https://example.com/path with spaces/file name.html?q=hello world");
  788. }
  789. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  790. string original =
  791. "https://example.com/path with spaces/file name.html?q=hello world";
  792. string encoded = httplib::encode_uri(original);
  793. string decoded = httplib::decode_uri(encoded);
  794. EXPECT_EQ(decoded, original);
  795. }
  796. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  797. // decode_uri is the inverse of encode_uri: an escaped reserved character
  798. // stays encoded so it is not promoted into a real delimiter, while
  799. // non-reserved escapes still decode (like JS decodeURI).
  800. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  801. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  802. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  803. "%3F%3A%40%26%3D%2B%24%2C%3B");
  804. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  805. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  806. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  807. "http://example.com/a%2Fb");
  808. // decode_uri_component still decodes the reserved character.
  809. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  810. }
  811. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  812. string original = "Piri Tommy Villiers - on & on";
  813. string encoded = httplib::encode_uri_component(original);
  814. string decoded = httplib::decode_uri_component(encoded);
  815. EXPECT_EQ(decoded, original);
  816. }
  817. TEST(TrimTests, TrimStringTests) {
  818. EXPECT_EQ("abc", detail::trim_copy("abc"));
  819. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  820. EXPECT_TRUE(detail::trim_copy("").empty());
  821. }
  822. TEST(AsciiTest, LocaleIndependentClassification) {
  823. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  824. // which consult the global C locale: std::isalnum(0xC5) can return true
  825. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  826. // helpers must classify every byte by the ASCII grammar alone.
  827. for (int i = 0; i < 256; i++) {
  828. auto c = static_cast<char>(i);
  829. auto is_digit = i >= '0' && i <= '9';
  830. auto is_upper = i >= 'A' && i <= 'Z';
  831. auto is_lower = i >= 'a' && i <= 'z';
  832. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  833. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  834. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  835. << "byte " << i;
  836. }
  837. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  838. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  839. // Non-ASCII bytes must be percent-encoded, never passed through as
  840. // alphanumeric.
  841. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  842. }
  843. TEST(FromCharsTest, Double) {
  844. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  845. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  846. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  847. auto parse = [](const std::string &s, double &v) {
  848. return detail::from_chars(s.data(), s.data() + s.size(), v);
  849. };
  850. double v = -1.0;
  851. // Representative quality values.
  852. EXPECT_EQ(parse("0", v).ec, std::errc{});
  853. EXPECT_DOUBLE_EQ(v, 0.0);
  854. EXPECT_EQ(parse("1", v).ec, std::errc{});
  855. EXPECT_DOUBLE_EQ(v, 1.0);
  856. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.8);
  858. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 0.001);
  860. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 1.0);
  862. // A missing integer or fractional part is tolerated.
  863. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.5);
  865. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 5.0);
  867. // Values outside [0, 1] still parse; the caller range-checks them.
  868. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 123.456);
  870. // Stops at the first byte that is not part of the number and reports where.
  871. std::string trailing = "0.9, text/html";
  872. auto r = parse(trailing, v);
  873. EXPECT_EQ(r.ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 0.9);
  875. EXPECT_EQ(*r.ptr, ',');
  876. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  877. // outright, and an 'e'/'E' simply ends the number.
  878. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  879. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  880. std::string exp_input = "1.5e3";
  881. r = parse(exp_input, v);
  882. EXPECT_EQ(r.ec, std::errc{});
  883. EXPECT_DOUBLE_EQ(v, 1.5);
  884. EXPECT_EQ(*r.ptr, 'e');
  885. // Invalid inputs.
  886. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  888. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  889. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  890. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  891. // Pathological but well-formed inputs must stay bounded (no overflow, no
  892. // out-of-bounds table access) and stay within [0, 1] for the caller.
  893. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  894. std::errc{});
  895. EXPECT_DOUBLE_EQ(v, 0.0);
  896. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  897. std::errc{});
  898. EXPECT_GE(v, 0.0);
  899. EXPECT_LE(v, 1.0);
  900. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  901. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  902. }
  903. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  904. // Simple case without quality values
  905. std::vector<std::string> result1;
  906. EXPECT_TRUE(detail::parse_accept_header(
  907. "text/html,application/json,text/plain", result1));
  908. EXPECT_EQ(result1.size(), 3U);
  909. EXPECT_EQ(result1[0], "text/html");
  910. EXPECT_EQ(result1[1], "application/json");
  911. EXPECT_EQ(result1[2], "text/plain");
  912. // With quality values
  913. std::vector<std::string> result2;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  916. EXPECT_EQ(result2.size(), 3U);
  917. EXPECT_EQ(result2[0], "application/json"); // highest q value
  918. EXPECT_EQ(result2[1], "text/html");
  919. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  920. }
  921. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  922. // Mixed with and without quality values
  923. std::vector<std::string> result;
  924. EXPECT_TRUE(detail::parse_accept_header(
  925. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  926. EXPECT_EQ(result.size(), 3U);
  927. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  928. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  929. EXPECT_EQ(result[2], "application/json"); // q=0.5
  930. }
  931. TEST(ParseAcceptHeaderTest, EdgeCases) {
  932. // Empty header
  933. std::vector<std::string> empty_result;
  934. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  935. EXPECT_TRUE(empty_result.empty());
  936. // Single type
  937. std::vector<std::string> single_result;
  938. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  939. EXPECT_EQ(single_result.size(), 1U);
  940. EXPECT_EQ(single_result[0], "application/json");
  941. // Wildcard types
  942. std::vector<std::string> wildcard_result;
  943. EXPECT_TRUE(detail::parse_accept_header(
  944. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  945. EXPECT_EQ(wildcard_result.size(), 3U);
  946. EXPECT_EQ(wildcard_result[0], "application/json");
  947. EXPECT_EQ(wildcard_result[1], "text/*");
  948. EXPECT_EQ(wildcard_result[2], "*/*");
  949. }
  950. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  951. // Common browser Accept header
  952. std::vector<std::string> browser_result;
  953. EXPECT_TRUE(
  954. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  955. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  956. browser_result));
  957. EXPECT_EQ(browser_result.size(), 6U);
  958. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  959. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  960. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  961. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  962. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  963. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  964. // API client header
  965. std::vector<std::string> api_result;
  966. EXPECT_TRUE(detail::parse_accept_header(
  967. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  968. api_result));
  969. EXPECT_EQ(api_result.size(), 3U);
  970. EXPECT_EQ(api_result[0], "application/json");
  971. EXPECT_EQ(api_result[1], "application/xml");
  972. EXPECT_EQ(api_result[2], "text/plain");
  973. }
  974. TEST(ParseAcceptHeaderTest, SpecialCases) {
  975. // Quality value with 3 decimal places
  976. std::vector<std::string> decimal_result;
  977. EXPECT_TRUE(detail::parse_accept_header(
  978. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  979. EXPECT_EQ(decimal_result.size(), 2U);
  980. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  981. EXPECT_EQ(decimal_result[1], "text/html");
  982. // Zero quality (should still be included but with lowest priority)
  983. std::vector<std::string> zero_q_result;
  984. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  985. zero_q_result));
  986. EXPECT_EQ(zero_q_result.size(), 2U);
  987. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  988. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  989. // No spaces around commas
  990. std::vector<std::string> no_space_result;
  991. EXPECT_TRUE(detail::parse_accept_header(
  992. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  993. no_space_result));
  994. EXPECT_EQ(no_space_result.size(), 3U);
  995. EXPECT_EQ(no_space_result[0], "text/html");
  996. EXPECT_EQ(no_space_result[1], "application/json");
  997. EXPECT_EQ(no_space_result[2], "text/plain");
  998. }
  999. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1000. // Quality values always use '.' as the decimal separator, so parsing must
  1001. // not depend on the process locale. An embedding application may have
  1002. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1003. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1004. std::string saved = cur ? cur : "C";
  1005. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1006. "fr_FR.UTF-8"};
  1007. bool switched = false;
  1008. for (const auto loc : comma_locales) {
  1009. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1010. std::localeconv()->decimal_point[0] == ',') {
  1011. switched = true;
  1012. break;
  1013. }
  1014. }
  1015. if (!switched) {
  1016. std::setlocale(LC_NUMERIC, saved.c_str());
  1017. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1018. }
  1019. // The higher-weighted type appears later in the list, so a correct parse
  1020. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1021. // sensitive parse reads both weights as 0 and leaves the original order.
  1022. std::vector<std::string> result;
  1023. EXPECT_TRUE(detail::parse_accept_header(
  1024. "application/json;q=0.1,text/html;q=0.9", result));
  1025. ASSERT_EQ(result.size(), 2U);
  1026. EXPECT_EQ(result[0], "text/html");
  1027. EXPECT_EQ(result[1], "application/json");
  1028. std::setlocale(LC_NUMERIC, saved.c_str());
  1029. }
  1030. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1031. std::vector<std::string> result;
  1032. // Invalid quality value (> 1.0)
  1033. EXPECT_FALSE(
  1034. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1035. // Invalid quality value (< 0.0)
  1036. EXPECT_FALSE(
  1037. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1038. // Invalid quality value (not a number)
  1039. EXPECT_FALSE(detail::parse_accept_header(
  1040. "text/html;q=invalid,application/json", result));
  1041. // A valid numeric prefix does not make the entire quality value valid.
  1042. EXPECT_FALSE(detail::parse_accept_header(
  1043. "text/html;q=0.5junk,application/json", result));
  1044. // Empty quality value
  1045. EXPECT_FALSE(
  1046. detail::parse_accept_header("text/html;q=,application/json", result));
  1047. // Invalid media type format (no slash and not wildcard)
  1048. EXPECT_FALSE(
  1049. detail::parse_accept_header("invalidtype,application/json", result));
  1050. // Valid cases should still work
  1051. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1052. EXPECT_EQ(result.size(), 1U);
  1053. EXPECT_EQ(result[0], "*/*");
  1054. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1055. EXPECT_EQ(result.size(), 1U);
  1056. EXPECT_EQ(result[0], "*");
  1057. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1058. EXPECT_EQ(result.size(), 1U);
  1059. EXPECT_EQ(result[0], "text/*");
  1060. }
  1061. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1062. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1063. // and must not be answered with 400 Bad Request.
  1064. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1065. struct {
  1066. const char *value;
  1067. std::vector<std::string> expected;
  1068. } cases[] = {
  1069. {",application/json", {"application/json"}},
  1070. {"text/html,", {"text/html"}},
  1071. {"text/html,,*/*", {"text/html", "*/*"}},
  1072. // An empty element may be spelled with whitespace in it
  1073. {"text/html, , application/json", {"text/html", "application/json"}},
  1074. // Nothing but empty elements is an empty list, which means the same
  1075. // thing as no Accept header at all
  1076. {",,,", {}},
  1077. // Quality values still apply across ignored empty elements
  1078. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1079. };
  1080. for (const auto &c : cases) {
  1081. std::vector<std::string> result;
  1082. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1083. << "value: " << c.value;
  1084. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1085. }
  1086. // An invalid entry is still rejected when empty elements surround it
  1087. std::vector<std::string> result;
  1088. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1089. }
  1090. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1091. // or ';' inside one does not end the list element or the parameter. Section
  1092. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1093. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1094. struct {
  1095. const char *value;
  1096. std::vector<std::string> expected;
  1097. } cases[] = {
  1098. {"text/html;profile=\"a,b\",application/json",
  1099. {"text/html", "application/json"}},
  1100. // A "q=" inside a quoted value is not the weight
  1101. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1102. {"text/html", "application/json"}},
  1103. // The weight after a quoted value still applies
  1104. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1105. {"application/json", "text/html"}},
  1106. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1107. {"application/json", "text/html"}},
  1108. {"text/html;profile=\"a\\\"b\",application/json",
  1109. {"text/html", "application/json"}},
  1110. // An escaped backslash does not escape the '"' after it
  1111. {"text/html;profile=\"a\\\\\",application/json",
  1112. {"text/html", "application/json"}},
  1113. };
  1114. for (const auto &c : cases) {
  1115. std::vector<std::string> result;
  1116. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1117. << "value: " << c.value;
  1118. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1119. }
  1120. }
  1121. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1122. Server svr;
  1123. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1124. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1125. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1126. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1127. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1128. res.set_content("ok", "text/plain");
  1129. });
  1130. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1131. EXPECT_TRUE(false);
  1132. res.set_content("bad request", "text/plain");
  1133. });
  1134. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1135. auto se = detail::scope_exit([&] {
  1136. svr.stop();
  1137. listen_thread.join();
  1138. ASSERT_FALSE(svr.is_running());
  1139. });
  1140. svr.wait_until_ready();
  1141. Client cli("localhost", PORT);
  1142. {
  1143. auto res = cli.Get(
  1144. "/accept_ok",
  1145. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1147. EXPECT_EQ(StatusCode::OK_200, res->status);
  1148. }
  1149. {
  1150. auto res = cli.Get("/accept_bad_request",
  1151. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1153. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1154. }
  1155. }
  1156. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1157. Server svr;
  1158. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1159. res.set_content("ok", "text/plain");
  1160. });
  1161. std::atomic<int> start_count{0};
  1162. std::atomic<bool> running_when_called{false};
  1163. svr.set_start_handler([&]() {
  1164. running_when_called = svr.is_running();
  1165. start_count++;
  1166. });
  1167. auto port = svr.bind_to_any_port(HOST);
  1168. std::thread t([&]() { svr.listen_after_bind(); });
  1169. auto se = detail::scope_exit([&] {
  1170. svr.stop();
  1171. t.join();
  1172. ASSERT_FALSE(svr.is_running());
  1173. });
  1174. svr.wait_until_ready();
  1175. // A successful request proves the accept loop is running, which the start
  1176. // handler precedes; so by now the handler must have run exactly once.
  1177. Client cli(HOST, port);
  1178. cli.set_connection_timeout(std::chrono::seconds(5));
  1179. auto res = cli.Get("/");
  1180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1181. EXPECT_EQ(StatusCode::OK_200, res->status);
  1182. EXPECT_EQ(1, start_count.load());
  1183. EXPECT_TRUE(running_when_called.load());
  1184. }
  1185. TEST(DivideTest, DivideStringTests) {
  1186. auto divide = [](const std::string &str, char d) {
  1187. std::string lhs;
  1188. std::string rhs;
  1189. detail::divide(str, d,
  1190. [&](const char *lhs_data, std::size_t lhs_size,
  1191. const char *rhs_data, std::size_t rhs_size) {
  1192. lhs.assign(lhs_data, lhs_size);
  1193. rhs.assign(rhs_data, rhs_size);
  1194. });
  1195. return std::make_pair(std::move(lhs), std::move(rhs));
  1196. };
  1197. {
  1198. const auto res = divide("", '=');
  1199. EXPECT_EQ(res.first, "");
  1200. EXPECT_EQ(res.second, "");
  1201. }
  1202. {
  1203. const auto res = divide("=", '=');
  1204. EXPECT_EQ(res.first, "");
  1205. EXPECT_EQ(res.second, "");
  1206. }
  1207. {
  1208. const auto res = divide(" ", '=');
  1209. EXPECT_EQ(res.first, " ");
  1210. EXPECT_EQ(res.second, "");
  1211. }
  1212. {
  1213. const auto res = divide("a", '=');
  1214. EXPECT_EQ(res.first, "a");
  1215. EXPECT_EQ(res.second, "");
  1216. }
  1217. {
  1218. const auto res = divide("a=", '=');
  1219. EXPECT_EQ(res.first, "a");
  1220. EXPECT_EQ(res.second, "");
  1221. }
  1222. {
  1223. const auto res = divide("=b", '=');
  1224. EXPECT_EQ(res.first, "");
  1225. EXPECT_EQ(res.second, "b");
  1226. }
  1227. {
  1228. const auto res = divide("a=b", '=');
  1229. EXPECT_EQ(res.first, "a");
  1230. EXPECT_EQ(res.second, "b");
  1231. }
  1232. {
  1233. const auto res = divide("a=b=", '=');
  1234. EXPECT_EQ(res.first, "a");
  1235. EXPECT_EQ(res.second, "b=");
  1236. }
  1237. {
  1238. const auto res = divide("a=b=c", '=');
  1239. EXPECT_EQ(res.first, "a");
  1240. EXPECT_EQ(res.second, "b=c");
  1241. }
  1242. }
  1243. TEST(SplitTest, ParseQueryString) {
  1244. string s = "key1=val1&key2=val2&key3=val3";
  1245. Params dic;
  1246. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1247. [&](const char *b, const char *e) {
  1248. string key, val;
  1249. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1250. if (key.empty()) {
  1251. key.assign(b2, e2);
  1252. } else {
  1253. val.assign(b2, e2);
  1254. }
  1255. });
  1256. dic.emplace(key, val);
  1257. });
  1258. EXPECT_EQ("val1", dic.find("key1")->second);
  1259. EXPECT_EQ("val2", dic.find("key2")->second);
  1260. EXPECT_EQ("val3", dic.find("key3")->second);
  1261. }
  1262. TEST(SplitTest, ParseInvalidQueryTests) {
  1263. {
  1264. string s = " ";
  1265. Params dict;
  1266. detail::parse_query_text(s, dict);
  1267. EXPECT_TRUE(dict.empty());
  1268. }
  1269. {
  1270. string s = " = =";
  1271. Params dict;
  1272. detail::parse_query_text(s, dict);
  1273. EXPECT_TRUE(dict.empty());
  1274. }
  1275. }
  1276. TEST(ParseQueryTest, ParseQueryString) {
  1277. {
  1278. std::string s = "key1=val1&key2=val2&key3=val3";
  1279. Params dic;
  1280. detail::parse_query_text(s, dic);
  1281. EXPECT_EQ("val1", dic.find("key1")->second);
  1282. EXPECT_EQ("val2", dic.find("key2")->second);
  1283. EXPECT_EQ("val3", dic.find("key3")->second);
  1284. }
  1285. {
  1286. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("", dic.find("key1")->second);
  1290. EXPECT_EQ("val1", dic.find("key2")->second);
  1291. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1292. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1293. }
  1294. }
  1295. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1296. Params dic;
  1297. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1298. dic.emplace("key1", "val1");
  1299. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1300. dic.emplace("key2", "val2");
  1301. dic.emplace("key3", "val3");
  1302. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1303. }
  1304. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1305. Params params;
  1306. params.emplace("a", "1");
  1307. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1308. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1309. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1310. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1311. // Long enough to overflow the stack when matched with std::regex.
  1312. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1313. EXPECT_EQ("/p?" + long_query + "&a=1",
  1314. append_query_params("/p?" + long_query, params));
  1315. }
  1316. // Joins every entry of a Headers or Params into "key=value " so a whole
  1317. // traversal can be compared in one assertion. Both are instantiations of the
  1318. // same insertion-ordered container, so one helper serves both.
  1319. template <typename Map> static std::string entries_to_string(const Map &m) {
  1320. std::string s;
  1321. for (const auto &entry : m) {
  1322. s += entry.first + "=" + entry.second + " ";
  1323. }
  1324. return s;
  1325. }
  1326. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1327. // Params used to be a std::multimap, which sorted by name and handed the
  1328. // caller's query back alphabetised. A client signing its query string could
  1329. // not reproduce the order it asked for.
  1330. Params dic;
  1331. dic.emplace("zulu", "1");
  1332. dic.emplace("alpha", "2");
  1333. dic.emplace("mike", "3");
  1334. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1335. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1336. }
  1337. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1338. Params dic;
  1339. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1340. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1341. }
  1342. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1343. Request req;
  1344. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1345. req.params);
  1346. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1347. EXPECT_EQ("first", req.get_param_value("tag"));
  1348. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1349. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1350. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1351. EXPECT_EQ("", req.get_param_value("tag", 3));
  1352. }
  1353. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1354. // Params shares its container with Headers, which matches field names
  1355. // case-insensitively. Parameter names must not pick that up.
  1356. Params dic;
  1357. dic.emplace("Key", "upper");
  1358. dic.emplace("key", "lower");
  1359. EXPECT_EQ(2U, dic.size());
  1360. EXPECT_EQ(1U, dic.count("Key"));
  1361. EXPECT_EQ(1U, dic.count("key"));
  1362. EXPECT_EQ("upper", dic.find("Key")->second);
  1363. EXPECT_EQ("lower", dic.find("key")->second);
  1364. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1365. }
  1366. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1367. Server svr;
  1368. std::string order;
  1369. svr.Get("/order", [&](const Request &req, Response &res) {
  1370. order = entries_to_string(req.params);
  1371. res.set_content("ok", "text/plain");
  1372. });
  1373. auto port = svr.bind_to_any_port(HOST);
  1374. thread t = thread([&] { svr.listen_after_bind(); });
  1375. auto se = detail::scope_exit([&] {
  1376. svr.stop();
  1377. t.join();
  1378. ASSERT_FALSE(svr.is_running());
  1379. });
  1380. svr.wait_until_ready();
  1381. Client cli(HOST, port);
  1382. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1383. ASSERT_TRUE(res);
  1384. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1385. }
  1386. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1387. Server svr;
  1388. std::string field_order, file_order;
  1389. svr.Post("/order", [&](const Request &req, Response &res) {
  1390. for (const auto &field : req.form.fields) {
  1391. field_order += field.first + "=" + field.second.content + " ";
  1392. }
  1393. for (const auto &file : req.form.files) {
  1394. file_order += file.first + "=" + file.second.filename + " ";
  1395. }
  1396. res.set_content("ok", "text/plain");
  1397. });
  1398. auto port = svr.bind_to_any_port(HOST);
  1399. thread t = thread([&] { svr.listen_after_bind(); });
  1400. auto se = detail::scope_exit([&] {
  1401. svr.stop();
  1402. t.join();
  1403. ASSERT_FALSE(svr.is_running());
  1404. });
  1405. svr.wait_until_ready();
  1406. UploadFormDataItems items = {
  1407. {"zulu", "1", "", ""},
  1408. {"alpha", "2", "", ""},
  1409. {"mike", "3", "", ""},
  1410. {"zebra", "z", "z.txt", "text/plain"},
  1411. {"apple", "a", "a.txt", "text/plain"},
  1412. };
  1413. Client cli(HOST, port);
  1414. auto res = cli.Post("/order", items);
  1415. ASSERT_TRUE(res);
  1416. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1417. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1418. }
  1419. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1420. Server svr;
  1421. std::vector<std::string> values;
  1422. std::string first, second, out_of_range, order;
  1423. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1424. values = req.form.get_fields("tag");
  1425. first = req.form.get_field("tag", 0);
  1426. second = req.form.get_field("tag", 1);
  1427. out_of_range = req.form.get_field("tag", 2);
  1428. for (const auto &field : req.form.fields) {
  1429. order += field.first + "=" + field.second.content + " ";
  1430. }
  1431. res.set_content("ok", "text/plain");
  1432. });
  1433. auto port = svr.bind_to_any_port(HOST);
  1434. thread t = thread([&] { svr.listen_after_bind(); });
  1435. auto se = detail::scope_exit([&] {
  1436. svr.stop();
  1437. t.join();
  1438. ASSERT_FALSE(svr.is_running());
  1439. });
  1440. svr.wait_until_ready();
  1441. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1442. // not adjacent in the container.
  1443. UploadFormDataItems items = {
  1444. {"tag", "first", "", ""},
  1445. {"other", "x", "", ""},
  1446. {"tag", "second", "", ""},
  1447. };
  1448. Client cli(HOST, port);
  1449. auto res = cli.Post("/repeated", items);
  1450. ASSERT_TRUE(res);
  1451. ASSERT_EQ(2U, values.size());
  1452. EXPECT_EQ("first", values[0]);
  1453. EXPECT_EQ("second", values[1]);
  1454. EXPECT_EQ("first", first);
  1455. EXPECT_EQ("second", second);
  1456. // std::multimap already kept entries sharing a name in insertion order, so
  1457. // everything above passes without this change too. The whole traversal is
  1458. // what tells the two apart: sorting by name would hoist "other" to the front
  1459. // and the two "tag" parts would end up adjacent.
  1460. EXPECT_EQ("tag=first other=x tag=second ", order);
  1461. // Advancing past the last entry of a name used to run off the container;
  1462. // the container's saturating increment makes it return the default instead.
  1463. EXPECT_EQ("", out_of_range);
  1464. }
  1465. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1466. // Server::read_content() keeps a FormFields::iterator alive across the
  1467. // content callbacks that fill the part it points at. The container is
  1468. // vector-backed, so a later emplace can reallocate and invalidate an older
  1469. // iterator; 64 parts grow the vector through seven reallocations, which
  1470. // checks that every part's content still lands in its own entry.
  1471. const size_t part_count = 64;
  1472. // One formula for both the parts sent and the values expected back, so the
  1473. // two cannot drift apart.
  1474. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1475. auto content_of = [](size_t i) {
  1476. return std::string(64, static_cast<char>('a' + (i % 26)));
  1477. };
  1478. Server svr;
  1479. std::vector<std::pair<std::string, std::string>> received;
  1480. svr.Post("/many", [&](const Request &req, Response &res) {
  1481. for (const auto &field : req.form.fields) {
  1482. received.emplace_back(field.first, field.second.content);
  1483. }
  1484. res.set_content("ok", "text/plain");
  1485. });
  1486. auto port = svr.bind_to_any_port(HOST);
  1487. thread t = thread([&] { svr.listen_after_bind(); });
  1488. auto se = detail::scope_exit([&] {
  1489. svr.stop();
  1490. t.join();
  1491. ASSERT_FALSE(svr.is_running());
  1492. });
  1493. svr.wait_until_ready();
  1494. UploadFormDataItems items;
  1495. for (size_t i = 0; i < part_count; i++) {
  1496. items.push_back({name_of(i), content_of(i), "", ""});
  1497. }
  1498. Client cli(HOST, port);
  1499. auto res = cli.Post("/many", items);
  1500. ASSERT_TRUE(res);
  1501. ASSERT_EQ(part_count, received.size());
  1502. for (size_t i = 0; i < part_count; i++) {
  1503. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1504. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1505. }
  1506. }
  1507. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1508. string content_type = "multipart/form-data; boundary=something";
  1509. string boundary;
  1510. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1511. EXPECT_TRUE(ret);
  1512. EXPECT_EQ(boundary, "something");
  1513. }
  1514. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1515. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1516. string boundary;
  1517. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1518. EXPECT_TRUE(ret);
  1519. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1520. }
  1521. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1522. string content_type =
  1523. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1524. string boundary;
  1525. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1526. EXPECT_TRUE(ret);
  1527. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1528. }
  1529. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1530. string content_type =
  1531. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1532. string boundary;
  1533. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1534. EXPECT_TRUE(ret);
  1535. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1536. }
  1537. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1538. const string boundary(70, 'a');
  1539. string content_type = "multipart/form-data; boundary=" + boundary;
  1540. string parsed;
  1541. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1542. EXPECT_TRUE(ret);
  1543. EXPECT_EQ(parsed, boundary);
  1544. }
  1545. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1546. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1547. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1548. string parsed;
  1549. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1550. EXPECT_FALSE(ret);
  1551. }
  1552. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1553. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1554. // is 72 characters on the wire and still valid.
  1555. const string boundary(70, 'a');
  1556. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1557. string parsed;
  1558. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1559. EXPECT_EQ(parsed, boundary);
  1560. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1561. parsed.clear();
  1562. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1565. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1566. // The parameter parser must not treat that '=' as the key/value separator.
  1567. string content_type =
  1568. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1569. "charset=UTF-8";
  1570. string parsed;
  1571. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1572. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1573. }
  1574. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1575. // A ';' inside the quoted-string is part of the value, not a parameter
  1576. // separator, so it must not truncate the boundary.
  1577. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1578. string parsed;
  1579. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1580. EXPECT_EQ(parsed, "a;b");
  1581. }
  1582. TEST(ParseDispositionParamsTest, QuotedValues) {
  1583. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1584. // ';' and '=' are ordinary characters inside one.
  1585. struct {
  1586. const char *value;
  1587. std::vector<std::pair<const char *, const char *>> expected;
  1588. } cases[] = {
  1589. {"name=\"file1\"; filename=\"a.txt\"",
  1590. {{"name", "file1"}, {"filename", "a.txt"}}},
  1591. // Whitespace around '=' and ';' is still trimmed
  1592. {"name=\"file2\" ;filename = \"a.html\"",
  1593. {{"name", "file2"}, {"filename", "a.html"}}},
  1594. // '=' inside the value used to leave only the text after the last one
  1595. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1596. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1597. {"name=\"x=y\"", {{"name", "x=y"}}},
  1598. // ';' inside the value used to truncate the pair and leave a bogus one
  1599. {"name=\"file3\"; filename=\"a;b.txt\"",
  1600. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1601. // An unquoted value keeps working, and so does filename*
  1602. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1603. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1604. // A parameter with no key is dropped rather than turned into one whose
  1605. // key is the value
  1606. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1607. // An escaped quote does not end the value
  1608. {"name=\"a\\\"; filename=evil.php\"",
  1609. {{"name", "a\"; filename=evil.php"}}},
  1610. // Other backslashes, as in a Windows path, are kept
  1611. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1612. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1613. };
  1614. for (const auto &c : cases) {
  1615. Params params;
  1616. detail::parse_disposition_params(c.value, params);
  1617. for (const auto &kv : c.expected) {
  1618. auto it = params.find(kv.first);
  1619. ASSERT_NE(it, params.end())
  1620. << "value: " << c.value << ", key: " << kv.first;
  1621. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1622. }
  1623. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1624. }
  1625. }
  1626. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1627. Server svr;
  1628. std::string filename;
  1629. std::string content;
  1630. svr.Post("/upload", [&](const Request &req, Response &) {
  1631. const auto &file = req.form.get_file("file");
  1632. filename = file.filename;
  1633. content = file.content;
  1634. });
  1635. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1636. auto se = detail::scope_exit([&] {
  1637. svr.stop();
  1638. thread.join();
  1639. ASSERT_FALSE(svr.is_running());
  1640. });
  1641. svr.wait_until_ready();
  1642. std::string body = "--B\r\n"
  1643. "Content-Disposition: form-data; name=\"file\"; "
  1644. "filename=\"a.txt\"\r\n"
  1645. "Content-Type: text/plain\r\n"
  1646. "\r\n"
  1647. "hello\r\n"
  1648. "--B--\r\n";
  1649. Client cli(HOST, PORT);
  1650. auto res = cli.Post(
  1651. "/upload",
  1652. [&](size_t offset, DataSink &sink) {
  1653. if (offset < body.size()) {
  1654. sink.write(&body[offset], 1);
  1655. } else {
  1656. sink.done();
  1657. }
  1658. return true;
  1659. },
  1660. "multipart/form-data; boundary=B");
  1661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1662. EXPECT_EQ(StatusCode::OK_200, res->status);
  1663. EXPECT_EQ("a.txt", filename);
  1664. EXPECT_EQ("hello", content);
  1665. }
  1666. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1667. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1668. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1669. Server svr;
  1670. std::string field_value, file_name, file_filename;
  1671. bool has_field = false, has_file = false;
  1672. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1673. has_field = req.form.has_field("x=y");
  1674. field_value = req.form.get_field("x=y");
  1675. has_file = req.form.has_file("file1");
  1676. const auto &file = req.form.get_file("file1");
  1677. file_name = file.name;
  1678. file_filename = file.filename;
  1679. res.set_content("ok", "text/plain");
  1680. });
  1681. auto port = svr.bind_to_any_port(HOST);
  1682. thread t = thread([&] { svr.listen_after_bind(); });
  1683. auto se = detail::scope_exit([&] {
  1684. svr.stop();
  1685. t.join();
  1686. ASSERT_FALSE(svr.is_running());
  1687. });
  1688. svr.wait_until_ready();
  1689. UploadFormDataItems items = {
  1690. {"x=y", "field-value", "", ""},
  1691. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1692. };
  1693. Client cli(HOST, port);
  1694. auto res = cli.Post("/quoted", items);
  1695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1696. ASSERT_EQ(StatusCode::OK_200, res->status);
  1697. EXPECT_TRUE(has_field);
  1698. EXPECT_EQ("field-value", field_value);
  1699. EXPECT_TRUE(has_file);
  1700. EXPECT_EQ("file1", file_name);
  1701. EXPECT_EQ("a;b=report.pdf", file_filename);
  1702. }
  1703. TEST(GetHeaderValueTest, DefaultValue) {
  1704. Headers headers = {{"Dummy", "Dummy"}};
  1705. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1706. EXPECT_STREQ("text/plain", val);
  1707. }
  1708. TEST(GetHeaderValueTest, DefaultValueInt) {
  1709. Headers headers = {{"Dummy", "Dummy"}};
  1710. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1711. EXPECT_EQ(100ull, val);
  1712. }
  1713. TEST(GetHeaderValueTest, RegularValue) {
  1714. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1715. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1716. EXPECT_STREQ("text/html", val);
  1717. }
  1718. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1719. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1720. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1721. EXPECT_STREQ("text/html", val);
  1722. }
  1723. TEST(GetHeaderValueTest, SetContent) {
  1724. Response res;
  1725. res.set_content("html", "text/html");
  1726. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1727. res.set_content("text", "text/plain");
  1728. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1729. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1730. }
  1731. TEST(GetHeaderValueTest, RegularValueInt) {
  1732. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1733. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1734. EXPECT_EQ(100ull, val);
  1735. }
  1736. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1737. Headers headers = {{"Content-Length", "x"}};
  1738. auto is_invalid_value = false;
  1739. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1740. is_invalid_value);
  1741. EXPECT_EQ(0ull, val);
  1742. EXPECT_TRUE(is_invalid_value);
  1743. }
  1744. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1745. // An all-digit value that overflows size_t must be reported as invalid, not
  1746. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1747. // a large length to a small one on 32-bit builds, leaving the framing length
  1748. // wrong while is_invalid_value stayed false.
  1749. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1750. auto is_invalid_value = false;
  1751. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1752. is_invalid_value);
  1753. EXPECT_TRUE(is_invalid_value);
  1754. // A well-formed length is unaffected.
  1755. Headers ok = {{"Content-Length", "1234"}};
  1756. is_invalid_value = false;
  1757. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1758. is_invalid_value);
  1759. EXPECT_EQ(1234ull, val);
  1760. EXPECT_FALSE(is_invalid_value);
  1761. }
  1762. TEST(GetHeaderValueTest, Range) {
  1763. {
  1764. Headers headers = {make_range_header({{1, -1}})};
  1765. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1766. EXPECT_STREQ("bytes=1-", val);
  1767. }
  1768. {
  1769. Headers headers = {make_range_header({{-1, 1}})};
  1770. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1771. EXPECT_STREQ("bytes=-1", val);
  1772. }
  1773. {
  1774. Headers headers = {make_range_header({{1, 10}})};
  1775. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1776. EXPECT_STREQ("bytes=1-10", val);
  1777. }
  1778. {
  1779. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1780. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1781. EXPECT_STREQ("bytes=1-10, 100-", val);
  1782. }
  1783. {
  1784. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1785. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1786. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1787. }
  1788. {
  1789. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1790. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1791. EXPECT_STREQ("bytes=0-0, -1", val);
  1792. }
  1793. }
  1794. TEST(BearerTokenAuthTest, SchemeValidation) {
  1795. // A value shorter than "Bearer " must not throw from the fixed-length
  1796. // substr, and a non-Bearer scheme must not be reported as a token.
  1797. struct {
  1798. const char *value;
  1799. const char *expected;
  1800. } cases[] = {
  1801. {"x", ""},
  1802. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1803. {"Bearer abc123", "abc123"},
  1804. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1805. };
  1806. for (const auto &c : cases) {
  1807. Request req;
  1808. req.set_header("Authorization", c.value);
  1809. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1810. }
  1811. }
  1812. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1813. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1814. // to depend on the standard library (libstdc++ handed back duplicates in
  1815. // reverse insertion order, libc++ in insertion order).
  1816. Request req;
  1817. req.set_header("Accept-Encoding", "gzip");
  1818. req.set_header("Accept-Encoding", "deflate");
  1819. req.set_header("Accept-Encoding", "br");
  1820. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1821. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1822. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1823. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1824. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1825. }
  1826. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1827. Request req;
  1828. req.set_header("X-Test", "only");
  1829. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1830. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1831. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1832. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1833. }
  1834. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1835. Request req;
  1836. req.set_header("X-First", "1");
  1837. req.set_header("X-Test", "2");
  1838. req.params.emplace("first", "1");
  1839. req.params.emplace("test", "2");
  1840. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1841. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1842. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1843. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1844. // The second one is negative when read as a signed value
  1845. const auto max_id = (std::numeric_limits<size_t>::max)();
  1846. for (auto id : {max_id / 2, max_id}) {
  1847. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1848. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1849. EXPECT_EQ("", req.get_param_value("test", id));
  1850. EXPECT_EQ("", req.form.get_field("test", id));
  1851. EXPECT_EQ("", req.form.get_file("test", id).content);
  1852. }
  1853. }
  1854. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1855. Headers headers;
  1856. headers.emplace("Host", "example.com");
  1857. headers.emplace("Accept-Encoding", "gzip");
  1858. headers.emplace("User-Agent", "test");
  1859. headers.emplace("Accept-Encoding", "deflate");
  1860. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1861. "Accept-Encoding=deflate ",
  1862. entries_to_string(headers));
  1863. }
  1864. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1865. Headers headers = {{"Content-Type", "text/html"},
  1866. {"CONTENT-TYPE", "text/xml"}};
  1867. EXPECT_EQ(2U, headers.count("content-type"));
  1868. auto it = headers.find("content-type");
  1869. ASSERT_TRUE(it != headers.end());
  1870. EXPECT_EQ("text/html", it->second);
  1871. }
  1872. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1873. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1874. // drop only those fields and leave everything positioned between them.
  1875. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1876. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1877. auto rng = headers.equal_range("a");
  1878. headers.erase(rng.first, rng.second);
  1879. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1880. }
  1881. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1882. Headers headers = {
  1883. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1884. EXPECT_EQ(3U, headers.erase("A"));
  1885. EXPECT_EQ(0U, headers.count("A"));
  1886. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1887. }
  1888. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1889. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1890. headers.emplace_front("Host", "example.com");
  1891. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1892. entries_to_string(headers));
  1893. }
  1894. TEST(ParseHeaderValueTest, Range) {
  1895. {
  1896. Ranges ranges;
  1897. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1898. EXPECT_TRUE(ret);
  1899. EXPECT_EQ(1u, ranges.size());
  1900. EXPECT_EQ(1u, ranges[0].first);
  1901. EXPECT_EQ(-1, ranges[0].second);
  1902. }
  1903. {
  1904. Ranges ranges;
  1905. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1906. EXPECT_TRUE(ret);
  1907. EXPECT_EQ(1u, ranges.size());
  1908. EXPECT_EQ(-1, ranges[0].first);
  1909. EXPECT_EQ(1u, ranges[0].second);
  1910. }
  1911. {
  1912. Ranges ranges;
  1913. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1914. EXPECT_TRUE(ret);
  1915. EXPECT_EQ(1u, ranges.size());
  1916. EXPECT_EQ(1u, ranges[0].first);
  1917. EXPECT_EQ(10u, ranges[0].second);
  1918. }
  1919. {
  1920. Ranges ranges;
  1921. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1922. EXPECT_FALSE(ret);
  1923. }
  1924. {
  1925. Ranges ranges;
  1926. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1927. EXPECT_TRUE(ret);
  1928. EXPECT_EQ(2u, ranges.size());
  1929. EXPECT_EQ(1u, ranges[0].first);
  1930. EXPECT_EQ(10u, ranges[0].second);
  1931. EXPECT_EQ(100u, ranges[1].first);
  1932. EXPECT_EQ(-1, ranges[1].second);
  1933. }
  1934. {
  1935. Ranges ranges;
  1936. auto ret =
  1937. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1938. EXPECT_TRUE(ret);
  1939. EXPECT_EQ(3u, ranges.size());
  1940. EXPECT_EQ(1u, ranges[0].first);
  1941. EXPECT_EQ(10u, ranges[0].second);
  1942. EXPECT_EQ(100u, ranges[1].first);
  1943. EXPECT_EQ(200u, ranges[1].second);
  1944. EXPECT_EQ(300u, ranges[2].first);
  1945. EXPECT_EQ(400u, ranges[2].second);
  1946. }
  1947. {
  1948. Ranges ranges;
  1949. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1950. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1951. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1952. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1953. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1954. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1955. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1956. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1957. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1958. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1959. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1960. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1961. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1962. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1963. EXPECT_FALSE(
  1964. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1965. EXPECT_TRUE(ranges.empty());
  1966. }
  1967. {
  1968. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1969. // remainder of the representation, so it stays accepted.
  1970. Ranges ranges;
  1971. auto ret =
  1972. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1973. EXPECT_TRUE(ret);
  1974. ASSERT_EQ(1u, ranges.size());
  1975. EXPECT_EQ(0, ranges[0].first);
  1976. EXPECT_EQ(-1, ranges[0].second);
  1977. }
  1978. // RFC 9110 14.1: range unit names are case-insensitive.
  1979. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1980. Ranges ranges;
  1981. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1982. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1983. }
  1984. }
  1985. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1986. Request req;
  1987. req.set_header("Accept-Encoding", "gzip");
  1988. Response res;
  1989. res.set_header("Content-Type", "text/plain");
  1990. auto ret = detail::encoding_type(req, res);
  1991. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1992. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1993. #else
  1994. EXPECT_TRUE(ret == detail::EncodingType::None);
  1995. #endif
  1996. }
  1997. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1998. Request req;
  1999. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2000. Response res;
  2001. res.set_header("Content-Type", "text/plain");
  2002. auto ret = detail::encoding_type(req, res);
  2003. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2004. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2005. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2006. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2007. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2008. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2009. #else
  2010. EXPECT_TRUE(ret == detail::EncodingType::None);
  2011. #endif
  2012. }
  2013. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding",
  2016. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2017. Response res;
  2018. res.set_header("Content-Type", "text/plain");
  2019. auto ret = detail::encoding_type(req, res);
  2020. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2021. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2022. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2023. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2024. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2025. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2026. #else
  2027. EXPECT_TRUE(ret == detail::EncodingType::None);
  2028. #endif
  2029. }
  2030. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2031. // All supported encodings rejected with q=0 should return None
  2032. Request req;
  2033. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2034. Response res;
  2035. res.set_header("Content-Type", "text/plain");
  2036. auto ret = detail::encoding_type(req, res);
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. }
  2039. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2040. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2041. Request req;
  2042. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2043. Response res;
  2044. res.set_header("Content-Type", "text/plain");
  2045. auto ret = detail::encoding_type(req, res);
  2046. EXPECT_TRUE(ret == detail::EncodingType::None);
  2047. }
  2048. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2049. Request req;
  2050. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2051. Response res;
  2052. res.set_header("Content-Type", "text/plain");
  2053. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2054. }
  2055. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2056. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2057. Request req;
  2058. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2059. Response res;
  2060. res.set_header("Content-Type", "text/plain");
  2061. auto ret = detail::encoding_type(req, res);
  2062. EXPECT_TRUE(ret == detail::EncodingType::None);
  2063. }
  2064. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2065. // RFC 7231: Accept-Encoding values are case-insensitive
  2066. Request req;
  2067. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2068. Response res;
  2069. res.set_header("Content-Type", "text/plain");
  2070. auto ret = detail::encoding_type(req, res);
  2071. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2072. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2073. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2074. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2075. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2076. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2077. #else
  2078. EXPECT_TRUE(ret == detail::EncodingType::None);
  2079. #endif
  2080. }
  2081. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2082. // q value should determine priority, not hardcoded order
  2083. Request req;
  2084. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2085. Response res;
  2086. res.set_header("Content-Type", "text/plain");
  2087. auto ret = detail::encoding_type(req, res);
  2088. // gzip has highest q=1.0, so it should be selected even though
  2089. // br and zstd are also supported
  2090. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2091. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2092. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2093. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2094. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2095. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2096. #else
  2097. EXPECT_TRUE(ret == detail::EncodingType::None);
  2098. #endif
  2099. }
  2100. TEST(BufferStreamTest, read) {
  2101. detail::BufferStream strm1;
  2102. Stream &strm = strm1;
  2103. EXPECT_EQ(5, strm.write("hello"));
  2104. char buf[512];
  2105. EXPECT_EQ(2, strm.read(buf, 2));
  2106. EXPECT_EQ('h', buf[0]);
  2107. EXPECT_EQ('e', buf[1]);
  2108. EXPECT_EQ(2, strm.read(buf, 2));
  2109. EXPECT_EQ('l', buf[0]);
  2110. EXPECT_EQ('l', buf[1]);
  2111. EXPECT_EQ(1, strm.read(buf, 1));
  2112. EXPECT_EQ('o', buf[0]);
  2113. EXPECT_EQ(0, strm.read(buf, 1));
  2114. }
  2115. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2116. auto host = "www.httpwatch.com";
  2117. auto ip = hosted_at(host);
  2118. EXPECT_EQ("23.96.13.243", ip);
  2119. std::vector<std::string> addrs;
  2120. hosted_at(host, addrs);
  2121. EXPECT_EQ(1u, addrs.size());
  2122. }
  2123. #if 0 // It depends on each test environment...
  2124. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2125. auto host = "www.youtube.com";
  2126. std::vector<std::string> addrs;
  2127. hosted_at(host, addrs);
  2128. EXPECT_EQ(20u, addrs.size());
  2129. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2130. EXPECT_TRUE(it != addrs.end());
  2131. }
  2132. #endif
  2133. class ChunkedEncodingTest : public ::testing::Test {
  2134. protected:
  2135. ChunkedEncodingTest()
  2136. : cli_(HOST, PORT)
  2137. #ifdef CPPHTTPLIB_SSL_ENABLED
  2138. ,
  2139. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2140. #endif
  2141. {
  2142. cli_.set_connection_timeout(2);
  2143. #ifdef CPPHTTPLIB_SSL_ENABLED
  2144. cli_.enable_server_certificate_verification(false);
  2145. #endif
  2146. }
  2147. virtual void SetUp() {
  2148. read_file("./image.jpg", image_data_);
  2149. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2150. res.set_content("Hello World!", "text/plain");
  2151. });
  2152. svr_.Get(
  2153. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2154. res.set_chunked_content_provider(
  2155. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2156. size_t remaining = image_data_.size() - offset;
  2157. if (remaining == 0) {
  2158. sink.done();
  2159. } else {
  2160. constexpr size_t CHUNK_SIZE = 1024;
  2161. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2162. sink.write(&image_data_[offset], send_size);
  2163. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2164. }
  2165. return true;
  2166. });
  2167. });
  2168. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2169. svr_.wait_until_ready();
  2170. }
  2171. virtual void TearDown() {
  2172. svr_.stop();
  2173. if (!request_threads_.empty()) {
  2174. std::this_thread::sleep_for(std::chrono::seconds(1));
  2175. for (auto &t : request_threads_) {
  2176. t.join();
  2177. }
  2178. }
  2179. t_.join();
  2180. }
  2181. #ifdef CPPHTTPLIB_SSL_ENABLED
  2182. SSLClient cli_;
  2183. SSLServer svr_;
  2184. #else
  2185. Client cli_;
  2186. Server svr_;
  2187. #endif
  2188. thread t_;
  2189. std::vector<thread> request_threads_;
  2190. std::string image_data_;
  2191. };
  2192. TEST_F(ChunkedEncodingTest, NormalGet) {
  2193. auto res = cli_.Get("/chunked");
  2194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2195. std::string out;
  2196. read_file("./image.jpg", out);
  2197. EXPECT_EQ(StatusCode::OK_200, res->status);
  2198. EXPECT_EQ(out, res->body);
  2199. }
  2200. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2201. std::string body;
  2202. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2203. body.append(data, data_length);
  2204. return true;
  2205. });
  2206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2207. std::string out;
  2208. read_file("./image.jpg", out);
  2209. EXPECT_EQ(StatusCode::OK_200, res->status);
  2210. EXPECT_EQ(out, body);
  2211. }
  2212. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2213. std::string body;
  2214. auto res = cli_.Get(
  2215. "/chunked",
  2216. [&](const Response &response) {
  2217. EXPECT_EQ(StatusCode::OK_200, response.status);
  2218. return true;
  2219. },
  2220. [&](const char *data, size_t data_length) {
  2221. body.append(data, data_length);
  2222. return true;
  2223. });
  2224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2225. std::string out;
  2226. read_file("./image.jpg", out);
  2227. EXPECT_EQ(StatusCode::OK_200, res->status);
  2228. EXPECT_EQ(out, body);
  2229. }
  2230. TEST(RangeTest, FromHTTPBin_Online) {
  2231. auto host = "httpbingo.org";
  2232. auto path = std::string{"/range/32"};
  2233. #ifdef CPPHTTPLIB_SSL_ENABLED
  2234. auto port = 443;
  2235. SSLClient cli(host, port);
  2236. #else
  2237. auto port = 80;
  2238. Client cli(host, port);
  2239. #endif
  2240. cli.set_connection_timeout(5);
  2241. {
  2242. auto res = cli.Get(path);
  2243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. {
  2248. Headers headers = {make_range_header({{1, -1}})};
  2249. auto res = cli.Get(path, headers);
  2250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2251. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2252. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2253. }
  2254. {
  2255. Headers headers = {make_range_header({{1, 10}})};
  2256. auto res = cli.Get(path, headers);
  2257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2258. EXPECT_EQ("bcdefghijk", res->body);
  2259. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2260. }
  2261. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2262. // entire resource, while the original httpbin returned 200. Both are
  2263. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2264. {
  2265. Headers headers = {make_range_header({{0, 31}})};
  2266. auto res = cli.Get(path, headers);
  2267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2268. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2269. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2270. res->status == StatusCode::PartialContent_206);
  2271. }
  2272. {
  2273. Headers headers = {make_range_header({{0, -1}})};
  2274. auto res = cli.Get(path, headers);
  2275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2276. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2277. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2278. res->status == StatusCode::PartialContent_206);
  2279. }
  2280. // go-httpbin returns 206 with clamped range for over-range requests,
  2281. // while the original httpbin returned 416. Both behaviors are observed
  2282. // in real servers, so we only verify the request succeeds.
  2283. {
  2284. Headers headers = {make_range_header({{0, 32}})};
  2285. auto res = cli.Get(path, headers);
  2286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2287. }
  2288. }
  2289. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2290. auto host = "unresolvableaddress.local";
  2291. auto path = std::string{"/"};
  2292. #ifdef CPPHTTPLIB_SSL_ENABLED
  2293. auto port = 443;
  2294. SSLClient cli(host, port);
  2295. #else
  2296. auto port = 80;
  2297. Client cli(host, port);
  2298. #endif
  2299. cli.set_connection_timeout(1);
  2300. {
  2301. auto res = cli.Get(path);
  2302. ASSERT_FALSE(res);
  2303. }
  2304. std::this_thread::sleep_for(std::chrono::seconds(8));
  2305. }
  2306. #if defined(__linux__) && defined(__GLIBC__) && \
  2307. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2308. // Forward declaration: in split builds split.py strips `inline` and moves the
  2309. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2310. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2311. // against the symbol in both header-only and split builds.
  2312. namespace httplib {
  2313. namespace detail {
  2314. int getaddrinfo_with_timeout(const char *node, const char *service,
  2315. const struct addrinfo *hints,
  2316. struct addrinfo **res, time_t timeout_sec);
  2317. } // namespace detail
  2318. } // namespace httplib
  2319. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2320. //
  2321. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2322. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2323. // gai_suspend() call hits the connection timeout the function calls
  2324. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2325. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2326. // still alive and still references the now-destroyed stack frame.
  2327. //
  2328. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2329. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2330. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2331. // and runs them in a container.
  2332. namespace {
  2333. bool should_run_issue_2431_tests() {
  2334. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2335. return v && *v && std::string(v) != "0";
  2336. }
  2337. std::string unique_unresolvable_host(int n) {
  2338. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2339. // glibc still asks the configured nameserver — which is exactly the path
  2340. // we want to exercise. A unique label per call avoids the resolver cache.
  2341. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2342. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2343. std::to_string(n) + ".invalid";
  2344. }
  2345. } // namespace
  2346. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2347. if (!should_run_issue_2431_tests()) {
  2348. GTEST_SKIP()
  2349. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2350. }
  2351. for (int i = 0; i < 8; ++i) {
  2352. struct addrinfo hints;
  2353. memset(&hints, 0, sizeof(hints));
  2354. hints.ai_family = AF_UNSPEC;
  2355. hints.ai_socktype = SOCK_STREAM;
  2356. auto host = unique_unresolvable_host(i);
  2357. struct addrinfo *result = nullptr;
  2358. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2359. &result, /*timeout_sec=*/1);
  2360. if (rc == 0 && result) { freeaddrinfo(result); }
  2361. }
  2362. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2363. // stack region they still believe holds their gaicb.
  2364. std::this_thread::sleep_for(std::chrono::seconds(3));
  2365. }
  2366. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2367. if (!should_run_issue_2431_tests()) {
  2368. GTEST_SKIP()
  2369. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2370. }
  2371. std::atomic<bool> stop{false};
  2372. std::vector<std::thread> threads;
  2373. for (int t = 0; t < 8; ++t) {
  2374. threads.emplace_back([t, &stop] {
  2375. int i = 0;
  2376. while (!stop.load(std::memory_order_relaxed)) {
  2377. struct addrinfo hints;
  2378. memset(&hints, 0, sizeof(hints));
  2379. hints.ai_family = AF_UNSPEC;
  2380. hints.ai_socktype = SOCK_STREAM;
  2381. auto host = unique_unresolvable_host(t * 100000 + i++);
  2382. struct addrinfo *result = nullptr;
  2383. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2384. &result, /*timeout_sec=*/1);
  2385. if (rc == 0 && result) { freeaddrinfo(result); }
  2386. }
  2387. });
  2388. }
  2389. std::this_thread::sleep_for(std::chrono::seconds(8));
  2390. stop.store(true, std::memory_order_relaxed);
  2391. for (auto &th : threads) {
  2392. th.join();
  2393. }
  2394. std::this_thread::sleep_for(std::chrono::seconds(3));
  2395. }
  2396. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2397. if (!should_run_issue_2431_tests()) {
  2398. GTEST_SKIP()
  2399. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2400. }
  2401. std::atomic<bool> stop{false};
  2402. std::vector<std::thread> threads;
  2403. for (int t = 0; t < 8; ++t) {
  2404. threads.emplace_back([t, &stop] {
  2405. int i = 0;
  2406. while (!stop.load(std::memory_order_relaxed)) {
  2407. auto host = unique_unresolvable_host(t * 100000 + i++);
  2408. Client cli(host, 80);
  2409. cli.set_connection_timeout(1, 0);
  2410. cli.set_read_timeout(1, 0);
  2411. cli.set_write_timeout(1, 0);
  2412. (void)cli.Get("/");
  2413. }
  2414. });
  2415. }
  2416. std::this_thread::sleep_for(std::chrono::seconds(8));
  2417. stop.store(true, std::memory_order_relaxed);
  2418. for (auto &th : threads) {
  2419. th.join();
  2420. }
  2421. std::this_thread::sleep_for(std::chrono::seconds(3));
  2422. }
  2423. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2424. TEST(ConnectionErrorTest, InvalidHost) {
  2425. auto host = "-abcde.com";
  2426. #ifdef CPPHTTPLIB_SSL_ENABLED
  2427. auto port = 443;
  2428. SSLClient cli(host, port);
  2429. #else
  2430. auto port = 80;
  2431. Client cli(host, port);
  2432. #endif
  2433. cli.set_connection_timeout(std::chrono::seconds(2));
  2434. auto res = cli.Get("/");
  2435. ASSERT_TRUE(!res);
  2436. EXPECT_EQ(Error::Connection, res.error());
  2437. }
  2438. TEST(ConnectionErrorTest, InvalidHost2) {
  2439. auto host = "httpcan.org/";
  2440. #ifdef CPPHTTPLIB_SSL_ENABLED
  2441. SSLClient cli(host);
  2442. #else
  2443. Client cli(host);
  2444. #endif
  2445. cli.set_connection_timeout(std::chrono::seconds(2));
  2446. auto res = cli.Get("/");
  2447. ASSERT_TRUE(!res);
  2448. EXPECT_EQ(Error::Connection, res.error());
  2449. }
  2450. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2451. auto host = "httpcan.org/";
  2452. #ifdef CPPHTTPLIB_SSL_ENABLED
  2453. SSLClient cli(host);
  2454. #else
  2455. Client cli(host);
  2456. #endif
  2457. cli.set_connection_timeout(std::chrono::seconds(2));
  2458. auto res = cli.Get("/");
  2459. ASSERT_TRUE(!res);
  2460. stringstream s;
  2461. s << "error code: " << res.error();
  2462. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2463. }
  2464. TEST(ConnectionErrorTest, InvalidPort) {
  2465. auto host = "localhost";
  2466. auto port = 44380;
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. SSLClient cli(host, port);
  2469. #else
  2470. Client cli(host, port);
  2471. #endif
  2472. cli.set_connection_timeout(std::chrono::seconds(2));
  2473. auto res = cli.Get("/");
  2474. ASSERT_TRUE(!res);
  2475. EXPECT_TRUE(Error::Connection == res.error() ||
  2476. Error::ConnectionTimeout == res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, Timeout_Online) {
  2479. auto host = "google.com";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. auto port = 44380;
  2482. SSLClient cli(host, port);
  2483. #else
  2484. auto port = 8080;
  2485. Client cli(host, port);
  2486. #endif
  2487. cli.set_connection_timeout(std::chrono::seconds(2));
  2488. // only probe one address type so that the error reason
  2489. // correlates to the timed-out IPv4, not the unsupported
  2490. // IPv6 connection attempt
  2491. cli.set_address_family(AF_INET);
  2492. auto res = cli.Get("/");
  2493. ASSERT_TRUE(!res);
  2494. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2495. }
  2496. TEST(CancelTest, NoCancel_Online) {
  2497. auto host = "httpbingo.org";
  2498. auto path = std::string{"/range/32"};
  2499. #ifdef CPPHTTPLIB_SSL_ENABLED
  2500. auto port = 443;
  2501. SSLClient cli(host, port);
  2502. #else
  2503. auto port = 80;
  2504. Client cli(host, port);
  2505. #endif
  2506. cli.set_connection_timeout(std::chrono::seconds(5));
  2507. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2509. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2510. EXPECT_EQ(StatusCode::OK_200, res->status);
  2511. }
  2512. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2513. // Use /bytes with a large payload so that the DownloadProgress callback
  2514. // (which only fires for Content-Length responses) is invoked before the
  2515. // entire body is received, giving cancellation a chance to fire.
  2516. auto host = "httpbingo.org";
  2517. auto path = std::string{"/bytes/524288"};
  2518. #ifdef CPPHTTPLIB_SSL_ENABLED
  2519. auto port = 443;
  2520. SSLClient cli(host, port);
  2521. #else
  2522. auto port = 80;
  2523. Client cli(host, port);
  2524. #endif
  2525. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2526. cli.set_connection_timeout(std::chrono::seconds(5));
  2527. ASSERT_TRUE(!res);
  2528. EXPECT_EQ(Error::Canceled, res.error());
  2529. }
  2530. TEST(CancelTest, WithCancelLargePayload_Online) {
  2531. auto host = "httpbingo.org";
  2532. auto path = std::string{"/bytes/524288"};
  2533. #ifdef CPPHTTPLIB_SSL_ENABLED
  2534. auto port = 443;
  2535. SSLClient cli(host, port);
  2536. #else
  2537. auto port = 80;
  2538. Client cli(host, port);
  2539. #endif
  2540. cli.set_connection_timeout(std::chrono::seconds(5));
  2541. uint32_t count = 0;
  2542. auto res =
  2543. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2544. ASSERT_TRUE(!res);
  2545. EXPECT_EQ(Error::Canceled, res.error());
  2546. }
  2547. TEST(CancelTest, NoCancelPost) {
  2548. Server svr;
  2549. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2550. res.set_content("Hello World!", "text/plain");
  2551. });
  2552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli(HOST, PORT);
  2560. cli.set_connection_timeout(std::chrono::seconds(5));
  2561. auto res =
  2562. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2563. "application/json", [](uint64_t, uint64_t) { return true; });
  2564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2565. EXPECT_EQ("Hello World!", res->body);
  2566. EXPECT_EQ(StatusCode::OK_200, res->status);
  2567. }
  2568. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2569. Server svr;
  2570. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2571. res.set_content("Hello World!", "text/plain");
  2572. });
  2573. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2574. auto se = detail::scope_exit([&] {
  2575. svr.stop();
  2576. thread.join();
  2577. ASSERT_FALSE(svr.is_running());
  2578. });
  2579. svr.wait_until_ready();
  2580. Client cli(HOST, PORT);
  2581. cli.set_connection_timeout(std::chrono::seconds(5));
  2582. auto res =
  2583. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2584. "application/json", [](uint64_t, uint64_t) { return false; });
  2585. ASSERT_TRUE(!res);
  2586. EXPECT_EQ(Error::Canceled, res.error());
  2587. }
  2588. TEST(CancelTest, WithCancelLargePayloadPost) {
  2589. Server svr;
  2590. svr.set_payload_max_length(200 * 1024 * 1024);
  2591. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2592. res.set_content(LARGE_DATA, "text/plain");
  2593. });
  2594. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2595. auto se = detail::scope_exit([&] {
  2596. svr.stop();
  2597. thread.join();
  2598. ASSERT_FALSE(svr.is_running());
  2599. });
  2600. svr.wait_until_ready();
  2601. Client cli(HOST, PORT);
  2602. cli.set_payload_max_length(200 * 1024 * 1024);
  2603. cli.set_connection_timeout(std::chrono::seconds(5));
  2604. auto res =
  2605. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2606. "application/json", [](uint64_t, uint64_t) { return false; });
  2607. ASSERT_TRUE(!res);
  2608. EXPECT_EQ(Error::Canceled, res.error());
  2609. }
  2610. TEST(CancelTest, NoCancelPut) {
  2611. Server svr;
  2612. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2613. res.set_content("Hello World!", "text/plain");
  2614. });
  2615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2616. auto se = detail::scope_exit([&] {
  2617. svr.stop();
  2618. thread.join();
  2619. ASSERT_FALSE(svr.is_running());
  2620. });
  2621. svr.wait_until_ready();
  2622. Client cli(HOST, PORT);
  2623. cli.set_connection_timeout(std::chrono::seconds(5));
  2624. auto res =
  2625. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2626. "application/json", [](uint64_t, uint64_t) { return true; });
  2627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2628. EXPECT_EQ("Hello World!", res->body);
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. }
  2631. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2632. Server svr;
  2633. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2634. res.set_content("Hello World!", "text/plain");
  2635. });
  2636. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2637. auto se = detail::scope_exit([&] {
  2638. svr.stop();
  2639. thread.join();
  2640. ASSERT_FALSE(svr.is_running());
  2641. });
  2642. svr.wait_until_ready();
  2643. Client cli(HOST, PORT);
  2644. cli.set_connection_timeout(std::chrono::seconds(5));
  2645. auto res =
  2646. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2647. "application/json", [](uint64_t, uint64_t) { return false; });
  2648. ASSERT_TRUE(!res);
  2649. EXPECT_EQ(Error::Canceled, res.error());
  2650. }
  2651. TEST(CancelTest, WithCancelLargePayloadPut) {
  2652. Server svr;
  2653. svr.set_payload_max_length(200 * 1024 * 1024);
  2654. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2655. res.set_content(LARGE_DATA, "text/plain");
  2656. });
  2657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2658. auto se = detail::scope_exit([&] {
  2659. svr.stop();
  2660. thread.join();
  2661. ASSERT_FALSE(svr.is_running());
  2662. });
  2663. svr.wait_until_ready();
  2664. Client cli(HOST, PORT);
  2665. cli.set_payload_max_length(200 * 1024 * 1024);
  2666. cli.set_connection_timeout(std::chrono::seconds(5));
  2667. auto res =
  2668. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2669. "application/json", [](uint64_t, uint64_t) { return false; });
  2670. ASSERT_TRUE(!res);
  2671. EXPECT_EQ(Error::Canceled, res.error());
  2672. }
  2673. TEST(CancelTest, NoCancelPatch) {
  2674. Server svr;
  2675. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2676. res.set_content("Hello World!", "text/plain");
  2677. });
  2678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2679. auto se = detail::scope_exit([&] {
  2680. svr.stop();
  2681. thread.join();
  2682. ASSERT_FALSE(svr.is_running());
  2683. });
  2684. svr.wait_until_ready();
  2685. Client cli(HOST, PORT);
  2686. cli.set_connection_timeout(std::chrono::seconds(5));
  2687. auto res =
  2688. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2689. "application/json", [](uint64_t, uint64_t) { return true; });
  2690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2691. EXPECT_EQ("Hello World!", res->body);
  2692. EXPECT_EQ(StatusCode::OK_200, res->status);
  2693. }
  2694. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2695. Server svr;
  2696. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2697. res.set_content("Hello World!", "text/plain");
  2698. });
  2699. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2700. auto se = detail::scope_exit([&] {
  2701. svr.stop();
  2702. thread.join();
  2703. ASSERT_FALSE(svr.is_running());
  2704. });
  2705. svr.wait_until_ready();
  2706. Client cli(HOST, PORT);
  2707. cli.set_connection_timeout(std::chrono::seconds(5));
  2708. auto res =
  2709. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2710. "application/json", [](uint64_t, uint64_t) { return false; });
  2711. ASSERT_TRUE(!res);
  2712. EXPECT_EQ(Error::Canceled, res.error());
  2713. }
  2714. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2715. Server svr;
  2716. svr.set_payload_max_length(200 * 1024 * 1024);
  2717. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2718. res.set_content(LARGE_DATA, "text/plain");
  2719. });
  2720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2721. auto se = detail::scope_exit([&] {
  2722. svr.stop();
  2723. thread.join();
  2724. ASSERT_FALSE(svr.is_running());
  2725. });
  2726. svr.wait_until_ready();
  2727. Client cli(HOST, PORT);
  2728. cli.set_payload_max_length(200 * 1024 * 1024);
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. auto res =
  2731. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2732. "application/json", [](uint64_t, uint64_t) { return false; });
  2733. ASSERT_TRUE(!res);
  2734. EXPECT_EQ(Error::Canceled, res.error());
  2735. }
  2736. TEST(CancelTest, NoCancelDelete) {
  2737. Server svr;
  2738. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2739. res.set_content("Hello World!", "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. cli.set_connection_timeout(std::chrono::seconds(5));
  2750. auto res =
  2751. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2752. "application/json", [](uint64_t, uint64_t) { return true; });
  2753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2754. EXPECT_EQ("Hello World!", res->body);
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. }
  2757. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2758. Server svr;
  2759. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2760. res.set_content("Hello World!", "text/plain");
  2761. });
  2762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2763. auto se = detail::scope_exit([&] {
  2764. svr.stop();
  2765. thread.join();
  2766. ASSERT_FALSE(svr.is_running());
  2767. });
  2768. svr.wait_until_ready();
  2769. Client cli(HOST, PORT);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2778. Server svr;
  2779. svr.set_payload_max_length(200 * 1024 * 1024);
  2780. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2781. res.set_content(LARGE_DATA, "text/plain");
  2782. });
  2783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2784. auto se = detail::scope_exit([&] {
  2785. svr.stop();
  2786. thread.join();
  2787. ASSERT_FALSE(svr.is_running());
  2788. });
  2789. svr.wait_until_ready();
  2790. Client cli(HOST, PORT);
  2791. cli.set_payload_max_length(200 * 1024 * 1024);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return false; });
  2796. ASSERT_TRUE(!res);
  2797. EXPECT_EQ(Error::Canceled, res.error());
  2798. }
  2799. static std::string remove_whitespace(const std::string &input) {
  2800. std::string output;
  2801. output.reserve(input.size());
  2802. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2803. [](unsigned char c) { return !std::isspace(c); });
  2804. return output;
  2805. }
  2806. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2807. auto host = "httpbingo.org";
  2808. auto path = std::string{"/basic-auth/hello/world"};
  2809. #ifdef CPPHTTPLIB_SSL_ENABLED
  2810. auto port = 443;
  2811. SSLClient cli(host, port);
  2812. #else
  2813. auto port = 80;
  2814. Client cli(host, port);
  2815. #endif
  2816. {
  2817. auto res = cli.Get(path);
  2818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2819. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2820. }
  2821. {
  2822. auto res = cli.Get(
  2823. path, Headers{make_basic_authentication_header("hello", "world")});
  2824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2825. auto body = remove_whitespace(res->body);
  2826. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2827. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2828. EXPECT_EQ(StatusCode::OK_200, res->status);
  2829. }
  2830. {
  2831. cli.set_basic_auth("hello", "world");
  2832. auto res = cli.Get(path);
  2833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2834. auto body = remove_whitespace(res->body);
  2835. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2836. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2837. EXPECT_EQ(StatusCode::OK_200, res->status);
  2838. }
  2839. {
  2840. cli.set_basic_auth("hello", "bad");
  2841. auto res = cli.Get(path);
  2842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2843. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2844. }
  2845. {
  2846. cli.set_basic_auth("bad", "world");
  2847. auto res = cli.Get(path);
  2848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2849. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2850. }
  2851. }
  2852. #ifdef CPPHTTPLIB_SSL_ENABLED
  2853. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2854. auto host = "httpbingo.org";
  2855. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2856. auto paths = std::vector<std::string>{
  2857. "/digest-auth/auth/hello/world/MD5",
  2858. "/digest-auth/auth/hello/world/SHA-256",
  2859. };
  2860. auto port = 443;
  2861. SSLClient cli(host, port);
  2862. {
  2863. auto res = cli.Get(unauth_path);
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2866. }
  2867. {
  2868. cli.set_digest_auth("hello", "world");
  2869. for (const auto &path : paths) {
  2870. auto res = cli.Get(path.c_str());
  2871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2872. auto body = remove_whitespace(res->body);
  2873. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2874. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2875. EXPECT_EQ(StatusCode::OK_200, res->status);
  2876. }
  2877. cli.set_digest_auth("hello", "bad");
  2878. for (const auto &path : paths) {
  2879. auto res = cli.Get(path.c_str());
  2880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2881. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2882. }
  2883. }
  2884. }
  2885. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2886. // comma-separated list of challenges, and each challenge may itself carry a
  2887. // comma-separated auth-param list, so a server can legally offer Basic
  2888. // before Digest, either as two field lines or packed into one. Runs one 401
  2889. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2890. // value() joins them in receipt order) and checks that the retry carries a
  2891. // well-formed Digest Authorization header naming expected_realm.
  2892. static void
  2893. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2894. const std::string &expected_realm) {
  2895. std::atomic<int> hits{0};
  2896. Server svr;
  2897. svr.Get("/x", [&](const Request &req, Response &res) {
  2898. if (++hits == 1) {
  2899. res.status = StatusCode::Unauthorized_401;
  2900. for (const auto &challenge : challenges) {
  2901. res.set_header("WWW-Authenticate", challenge);
  2902. }
  2903. } else {
  2904. auto authorization = req.get_header_value("Authorization");
  2905. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2906. EXPECT_NE(std::string::npos,
  2907. authorization.find("realm=\"" + expected_realm + "\""));
  2908. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2909. res.set_content("ok", "text/plain");
  2910. }
  2911. });
  2912. auto port = svr.bind_to_any_port(HOST);
  2913. std::thread t([&]() { svr.listen_after_bind(); });
  2914. auto se = detail::scope_exit([&] {
  2915. svr.stop();
  2916. t.join();
  2917. });
  2918. svr.wait_until_ready();
  2919. Client cli(HOST, port);
  2920. cli.set_digest_auth("hello", "world");
  2921. auto res = cli.Get("/x");
  2922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2923. EXPECT_EQ(2, hits.load());
  2924. }
  2925. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2926. static const char *kDigestChallenge =
  2927. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2928. "algorithm=MD5";
  2929. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2930. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2931. "testrealm");
  2932. }
  2933. // Same challenge list with the schemes in the opposite order, to make sure
  2934. // the fix above didn't just special-case "Basic first".
  2935. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2936. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2937. "testrealm");
  2938. }
  2939. // A comma inside a quoted auth-param value must not be mistaken for the
  2940. // separator between two challenges (or two auth-params).
  2941. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2942. run_digest_challenge_list_test(
  2943. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2944. "algorithm=MD5"},
  2945. "test,realm");
  2946. }
  2947. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2948. // make_digest_authentication_header() dereferences both unconditionally, so
  2949. // a server sending a challenge missing either one must not be treated as
  2950. // usable -- doing so used to crash the client with std::out_of_range.
  2951. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2952. Server svr;
  2953. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2954. res.status = StatusCode::Unauthorized_401;
  2955. res.set_header("WWW-Authenticate", challenge);
  2956. });
  2957. auto port = svr.bind_to_any_port(HOST);
  2958. std::thread t([&]() { svr.listen_after_bind(); });
  2959. auto se = detail::scope_exit([&] {
  2960. svr.stop();
  2961. t.join();
  2962. });
  2963. svr.wait_until_ready();
  2964. Client cli(HOST, port);
  2965. cli.set_digest_auth("hello", "world");
  2966. auto res = cli.Get("/x");
  2967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2968. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2969. }
  2970. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2971. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2972. }
  2973. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2974. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2975. }
  2976. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2977. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2978. }
  2979. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2980. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2981. // when storing the values, so the header builder has to re-escape them (and
  2982. // keep algorithm a bare token); otherwise the value breaks out of its
  2983. // quoted-string and injects extra auth-params into the client's Authorization.
  2984. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2985. std::atomic<int> hits{0};
  2986. std::string authorization;
  2987. Server svr;
  2988. svr.Get("/x", [&](const Request &req, Response &res) {
  2989. if (++hits == 1) {
  2990. res.status = StatusCode::Unauthorized_401;
  2991. // On the wire the quotes embedded in the values are backslash-escaped.
  2992. res.set_header("WWW-Authenticate",
  2993. "Digest realm=\"testrealm\", "
  2994. "nonce=\"n\\\"; injected=\\\"x\", "
  2995. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2996. } else {
  2997. authorization = req.get_header_value("Authorization");
  2998. res.set_content("ok", "text/plain");
  2999. }
  3000. });
  3001. auto port = svr.bind_to_any_port(HOST);
  3002. std::thread t([&]() { svr.listen_after_bind(); });
  3003. auto se = detail::scope_exit([&] {
  3004. svr.stop();
  3005. t.join();
  3006. });
  3007. svr.wait_until_ready();
  3008. Client cli(HOST, port);
  3009. cli.set_digest_auth("hello", "world");
  3010. auto res = cli.Get("/x");
  3011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3012. EXPECT_EQ(2, hits.load());
  3013. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3014. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3015. // inside its quoted-string rather than starting an "injected" auth-param.
  3016. EXPECT_NE(std::string::npos,
  3017. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3018. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3019. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3020. }
  3021. #endif
  3022. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3023. auto host = "google.com";
  3024. auto another_host = "example.com";
  3025. auto wrong_ip = "0.0.0.0";
  3026. #ifdef CPPHTTPLIB_SSL_ENABLED
  3027. SSLClient cli(host);
  3028. #else
  3029. Client cli(host);
  3030. #endif
  3031. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3032. auto res = cli.Get("/");
  3033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3034. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3035. }
  3036. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3037. auto host = "google.com";
  3038. auto wrong_ip = "0.0.0.0";
  3039. #ifdef CPPHTTPLIB_SSL_ENABLED
  3040. SSLClient cli(host);
  3041. #else
  3042. Client cli(host);
  3043. #endif
  3044. cli.set_hostname_addr_map({{host, wrong_ip}});
  3045. auto res = cli.Get("/");
  3046. ASSERT_TRUE(!res);
  3047. EXPECT_EQ(Error::Connection, res.error());
  3048. }
  3049. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3050. // A mapped value that is not an IP literal must be resolved. "localhost"
  3051. // resolves from the hosts file, so this test needs no external DNS.
  3052. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3053. auto host = "target.invalid";
  3054. Server svr;
  3055. std::string received_host;
  3056. svr.Get("/hi", [&](const Request &req, Response &res) {
  3057. received_host = req.get_header_value("Host");
  3058. res.set_content("Hello World!", "text/plain");
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3062. auto se = detail::scope_exit([&] {
  3063. svr.stop();
  3064. thread.join();
  3065. ASSERT_FALSE(svr.is_running());
  3066. });
  3067. svr.wait_until_ready();
  3068. Client cli(host, port);
  3069. cli.set_hostname_addr_map({{host, HOST}});
  3070. auto res = cli.Get("/hi");
  3071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3072. EXPECT_EQ(StatusCode::OK_200, res->status);
  3073. // The mapping only redirects the connection; the identity stays host_.
  3074. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3075. }
  3076. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3077. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3078. auto host = "target.invalid";
  3079. Server svr;
  3080. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3081. res.set_content("Hello World!", "text/plain");
  3082. });
  3083. auto port = svr.bind_to_any_port("127.0.0.1");
  3084. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3085. auto se = detail::scope_exit([&] {
  3086. svr.stop();
  3087. thread.join();
  3088. ASSERT_FALSE(svr.is_running());
  3089. });
  3090. svr.wait_until_ready();
  3091. Client cli(host, port);
  3092. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3093. auto res = cli.Get("/hi");
  3094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3095. EXPECT_EQ(StatusCode::OK_200, res->status);
  3096. }
  3097. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3098. // An empty mapped value must leave host_ as the connection target. Without
  3099. // that guard the empty value would become the host argument, getaddrinfo
  3100. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3101. // loopback - silently connecting somewhere the caller never asked for.
  3102. // The server listens on loopback, so such a fallback would succeed and is
  3103. // therefore observable as a failure of this test.
  3104. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3105. Server svr;
  3106. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3107. res.set_content("Hello World!", "text/plain");
  3108. });
  3109. auto port = svr.bind_to_any_port(HOST);
  3110. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3111. auto se = detail::scope_exit([&] {
  3112. svr.stop();
  3113. thread.join();
  3114. ASSERT_FALSE(svr.is_running());
  3115. });
  3116. svr.wait_until_ready();
  3117. Client cli(blackhole, port);
  3118. cli.set_hostname_addr_map({{blackhole, ""}});
  3119. cli.set_connection_timeout(1);
  3120. auto res = cli.Get("/hi");
  3121. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3122. }
  3123. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3124. auto host = "httpbingo.org";
  3125. auto path = std::string{"/absolute-redirect/3"};
  3126. #ifdef CPPHTTPLIB_SSL_ENABLED
  3127. SSLClient cli(host);
  3128. #else
  3129. Client cli(host);
  3130. #endif
  3131. cli.set_follow_location(true);
  3132. auto res = cli.Get(path);
  3133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3134. EXPECT_EQ(StatusCode::OK_200, res->status);
  3135. }
  3136. TEST(RedirectTest, Redirect_Online) {
  3137. auto host = "httpbingo.org";
  3138. auto path = std::string{"/redirect/3"};
  3139. #ifdef CPPHTTPLIB_SSL_ENABLED
  3140. SSLClient cli(host);
  3141. #else
  3142. Client cli(host);
  3143. #endif
  3144. cli.set_follow_location(true);
  3145. auto res = cli.Get(path);
  3146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3147. EXPECT_EQ(StatusCode::OK_200, res->status);
  3148. }
  3149. TEST(RelativeRedirectTest, Redirect_Online) {
  3150. auto host = "httpbingo.org";
  3151. auto path = std::string{"/relative-redirect/3"};
  3152. #ifdef CPPHTTPLIB_SSL_ENABLED
  3153. SSLClient cli(host);
  3154. #else
  3155. Client cli(host);
  3156. #endif
  3157. cli.set_follow_location(true);
  3158. auto res = cli.Get(path);
  3159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3160. EXPECT_EQ(StatusCode::OK_200, res->status);
  3161. }
  3162. TEST(TooManyRedirectTest, Redirect_Online) {
  3163. auto host = "httpbingo.org";
  3164. auto path = std::string{"/redirect/21"};
  3165. #ifdef CPPHTTPLIB_SSL_ENABLED
  3166. SSLClient cli(host);
  3167. #else
  3168. Client cli(host);
  3169. #endif
  3170. cli.set_follow_location(true);
  3171. auto res = cli.Get(path);
  3172. ASSERT_TRUE(!res);
  3173. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3174. }
  3175. #ifdef CPPHTTPLIB_SSL_ENABLED
  3176. TEST(YahooRedirectTest, Redirect_Online) {
  3177. Client cli("yahoo.com");
  3178. auto res = cli.Get("/");
  3179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3180. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3181. cli.set_follow_location(true);
  3182. res = cli.Get("/");
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::OK_200, res->status);
  3185. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3186. }
  3187. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3188. #define REDIR_HOST "httpbingo.org"
  3189. #define REDIR_PATH "/redirect-to"
  3190. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3191. SSLClient cli(REDIR_HOST);
  3192. cli.set_follow_location(true);
  3193. auto res =
  3194. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3196. EXPECT_EQ(StatusCode::OK_200, res->status);
  3197. }
  3198. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3199. SSLClient cli(REDIR_HOST);
  3200. cli.set_follow_location(true);
  3201. Params params;
  3202. params.emplace("url", "http://example.com");
  3203. params.emplace("status_code", "302");
  3204. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3209. SSLClient cli(REDIR_HOST);
  3210. cli.set_follow_location(true);
  3211. Params params;
  3212. params.emplace("url", "http://example.com");
  3213. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. }
  3217. TEST(UrlWithSpace, Redirect_Online) {
  3218. SSLClient cli("edge.forgecdn.net");
  3219. cli.set_follow_location(true);
  3220. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::OK_200, res->status);
  3223. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3224. }
  3225. #endif
  3226. #if !defined(_WIN32) && !defined(_WIN64)
  3227. TEST(ReceiveSignals, Signal) {
  3228. auto setupSignalHandlers = []() {
  3229. struct sigaction act;
  3230. sigemptyset(&act.sa_mask);
  3231. act.sa_flags = SA_SIGINFO;
  3232. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3233. switch (sig) {
  3234. case SIGINT:
  3235. default: break;
  3236. }
  3237. };
  3238. ::sigaction(SIGINT, &act, nullptr);
  3239. };
  3240. Server svr;
  3241. int port = 0;
  3242. auto thread = std::thread([&]() {
  3243. setupSignalHandlers();
  3244. port = svr.bind_to_any_port(HOST);
  3245. svr.listen_after_bind();
  3246. });
  3247. auto se = detail::scope_exit([&] {
  3248. svr.stop();
  3249. thread.join();
  3250. ASSERT_FALSE(svr.is_running());
  3251. });
  3252. svr.wait_until_ready();
  3253. ASSERT_TRUE(svr.is_running());
  3254. pthread_kill(thread.native_handle(), SIGINT);
  3255. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3256. ASSERT_TRUE(svr.is_running());
  3257. }
  3258. #endif
  3259. TEST(RedirectToDifferentPort, Redirect) {
  3260. Server svr1;
  3261. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3262. res.set_content("Hello World!", "text/plain");
  3263. });
  3264. int svr1_port = 0;
  3265. auto thread1 = std::thread([&]() {
  3266. svr1_port = svr1.bind_to_any_port(HOST);
  3267. svr1.listen_after_bind();
  3268. });
  3269. Server svr2;
  3270. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3271. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3272. });
  3273. int svr2_port = 0;
  3274. auto thread2 = std::thread([&]() {
  3275. svr2_port = svr2.bind_to_any_port(HOST);
  3276. svr2.listen_after_bind();
  3277. });
  3278. auto se = detail::scope_exit([&] {
  3279. svr2.stop();
  3280. thread2.join();
  3281. svr1.stop();
  3282. thread1.join();
  3283. ASSERT_FALSE(svr2.is_running());
  3284. ASSERT_FALSE(svr1.is_running());
  3285. });
  3286. svr1.wait_until_ready();
  3287. svr2.wait_until_ready();
  3288. Client cli("localhost", svr2_port);
  3289. cli.set_follow_location(true);
  3290. auto res = cli.Get("/2");
  3291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3292. EXPECT_EQ(StatusCode::OK_200, res->status);
  3293. EXPECT_EQ("Hello World!", res->body);
  3294. }
  3295. // GET /redir on one server redirects to /target on another port, so the
  3296. // client follows it with a new client.
  3297. static Result
  3298. GetThroughRedirectToDifferentPort(Server::Handler target,
  3299. const std::function<void(Client &)> &setup,
  3300. const Headers &headers = Headers()) {
  3301. Server target_svr;
  3302. target_svr.Get("/target", target);
  3303. int target_port = 0;
  3304. auto target_thread = std::thread([&]() {
  3305. target_port = target_svr.bind_to_any_port(HOST);
  3306. target_svr.listen_after_bind();
  3307. });
  3308. Server origin_svr;
  3309. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3310. res.set_redirect(
  3311. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3312. });
  3313. int origin_port = 0;
  3314. auto origin_thread = std::thread([&]() {
  3315. origin_port = origin_svr.bind_to_any_port(HOST);
  3316. origin_svr.listen_after_bind();
  3317. });
  3318. auto se = detail::scope_exit([&] {
  3319. origin_svr.stop();
  3320. origin_thread.join();
  3321. target_svr.stop();
  3322. target_thread.join();
  3323. });
  3324. target_svr.wait_until_ready();
  3325. origin_svr.wait_until_ready();
  3326. Client cli("localhost", origin_port);
  3327. cli.set_follow_location(true);
  3328. setup(cli);
  3329. return cli.Get("/redir", headers);
  3330. }
  3331. static void
  3332. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3333. std::string captured_authorization;
  3334. auto result = GetThroughRedirectToDifferentPort(
  3335. [&](const Request &req, Response &res) {
  3336. captured_authorization = req.get_header_value("Authorization");
  3337. res.set_content("OK", "text/plain");
  3338. },
  3339. set_auth);
  3340. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3341. EXPECT_EQ(StatusCode::OK_200, result->status);
  3342. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3343. EXPECT_TRUE(captured_authorization.empty());
  3344. }
  3345. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3346. TestDoNotForwardCredentialsOnRedirect(
  3347. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3348. }
  3349. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3350. TestDoNotForwardCredentialsOnRedirect(
  3351. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3352. }
  3353. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3354. std::string captured_cookie;
  3355. auto result = GetThroughRedirectToDifferentPort(
  3356. [&](const Request &req, Response &res) {
  3357. captured_cookie = req.get_header_value("Cookie");
  3358. res.set_content("OK", "text/plain");
  3359. },
  3360. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3361. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3362. EXPECT_EQ(StatusCode::OK_200, result->status);
  3363. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3364. EXPECT_TRUE(captured_cookie.empty());
  3365. }
  3366. TEST(RedirectToSamePort, ForwardCookie) {
  3367. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3368. // header so that ordinary session flows keep working.
  3369. Server svr;
  3370. std::string captured_cookie;
  3371. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3372. res.set_redirect("/target", 302);
  3373. });
  3374. svr.Get("/target", [&](const Request &req, Response &res) {
  3375. captured_cookie = req.get_header_value("Cookie");
  3376. res.set_content("OK", "text/plain");
  3377. });
  3378. auto port = svr.bind_to_any_port(HOST);
  3379. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3380. auto se = detail::scope_exit([&] {
  3381. svr.stop();
  3382. thread.join();
  3383. ASSERT_FALSE(svr.is_running());
  3384. });
  3385. svr.wait_until_ready();
  3386. Client cli(HOST, port);
  3387. cli.set_follow_location(true);
  3388. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3389. auto res = cli.Get("/redir", headers);
  3390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3391. EXPECT_EQ(StatusCode::OK_200, res->status);
  3392. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3393. }
  3394. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3395. std::string authorization;
  3396. std::string trace_id;
  3397. auto result = GetThroughRedirectToDifferentPort(
  3398. [&](const Request &req, Response &res) {
  3399. authorization = req.get_header_value("Authorization");
  3400. trace_id = req.get_header_value("X-Trace-Id");
  3401. res.set_content("OK", "text/plain");
  3402. },
  3403. [](Client &cli) {
  3404. cli.set_default_headers(
  3405. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3406. });
  3407. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3408. EXPECT_EQ(StatusCode::OK_200, result->status);
  3409. // Like a header given with the request, a default one goes along unless it
  3410. // carries credentials (RFC 9110 15.4).
  3411. EXPECT_TRUE(authorization.empty());
  3412. EXPECT_EQ("42", trace_id);
  3413. }
  3414. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3415. auto result = GetThroughRedirectToDifferentPort(
  3416. [](const Request &, Response &res) {
  3417. res.set_content(std::string(2048, 'x'), "text/plain");
  3418. },
  3419. [](Client &cli) { cli.set_payload_max_length(1024); });
  3420. EXPECT_FALSE(result);
  3421. }
  3422. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3423. auto result = GetThroughRedirectToDifferentPort(
  3424. [](const Request &req, Response &res) {
  3425. // Answer after a second, or once the client gives up.
  3426. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3427. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3428. }
  3429. res.set_content("late", "text/plain");
  3430. },
  3431. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3432. ASSERT_FALSE(result);
  3433. EXPECT_EQ(Error::Read, result.error());
  3434. }
  3435. #ifdef CPPHTTPLIB_SSL_ENABLED
  3436. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3437. auto result = GetThroughRedirectToDifferentPort(
  3438. [](const Request &, Response &res) {
  3439. res.status = StatusCode::Unauthorized_401;
  3440. res.set_header("WWW-Authenticate",
  3441. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3442. },
  3443. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3444. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3445. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3446. }
  3447. #endif
  3448. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3449. Server svr;
  3450. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3451. // Port number that overflows int — should not crash
  3452. res.set_redirect("http://localhost:99999999999999999999/target");
  3453. });
  3454. auto port = svr.bind_to_any_port(HOST);
  3455. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3456. auto se = detail::scope_exit([&] {
  3457. svr.stop();
  3458. thread.join();
  3459. ASSERT_FALSE(svr.is_running());
  3460. });
  3461. svr.wait_until_ready();
  3462. Client cli(HOST, port);
  3463. cli.set_follow_location(true);
  3464. auto res = cli.Get("/redir");
  3465. // Should fail gracefully, not crash (no valid response due to bad port)
  3466. EXPECT_FALSE(res);
  3467. }
  3468. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3469. Server svr;
  3470. auto port = svr.bind_to_any_port(HOST);
  3471. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3472. // The server's own port followed by junk must not be followed
  3473. res.set_redirect("http://" + std::string(HOST) + ":" +
  3474. std::to_string(port) + "junk/target");
  3475. });
  3476. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3477. res.set_content("target", "text/plain");
  3478. });
  3479. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3480. auto se = detail::scope_exit([&] {
  3481. svr.stop();
  3482. thread.join();
  3483. ASSERT_FALSE(svr.is_running());
  3484. });
  3485. svr.wait_until_ready();
  3486. Client cli(HOST, port);
  3487. cli.set_follow_location(true);
  3488. auto res = cli.Get("/redir");
  3489. EXPECT_FALSE(res);
  3490. }
  3491. TEST(RedirectFromPageWithContent, Redirect) {
  3492. Server svr;
  3493. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3494. res.set_content("___", "text/plain");
  3495. res.set_redirect("/2");
  3496. });
  3497. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3498. res.set_content("Hello World!", "text/plain");
  3499. });
  3500. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3501. auto se = detail::scope_exit([&] {
  3502. svr.stop();
  3503. th.join();
  3504. ASSERT_FALSE(svr.is_running());
  3505. });
  3506. svr.wait_until_ready();
  3507. {
  3508. Client cli("localhost", PORT);
  3509. cli.set_follow_location(true);
  3510. std::string body;
  3511. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3512. body.append(data, data_length);
  3513. return true;
  3514. });
  3515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3516. EXPECT_EQ(StatusCode::OK_200, res->status);
  3517. EXPECT_EQ("Hello World!", body);
  3518. }
  3519. {
  3520. Client cli("localhost", PORT);
  3521. std::string body;
  3522. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3523. body.append(data, data_length);
  3524. return true;
  3525. });
  3526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3527. EXPECT_EQ(StatusCode::Found_302, res->status);
  3528. EXPECT_EQ("___", body);
  3529. }
  3530. }
  3531. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3532. Server svr;
  3533. auto port_str = std::to_string(PORT);
  3534. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3535. auto expected_host = "[::1]:" + port_str;
  3536. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3537. res.set_content("___", "text/plain");
  3538. // res.set_redirect("/2");
  3539. res.set_redirect(redirect_url);
  3540. });
  3541. svr.Get("/2", [&](const Request &req, Response &res) {
  3542. auto host_header = req.headers.find("Host");
  3543. ASSERT_TRUE(host_header != req.headers.end());
  3544. EXPECT_EQ(expected_host, host_header->second);
  3545. res.set_content("Hello World!", "text/plain");
  3546. });
  3547. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3548. auto se = detail::scope_exit([&] {
  3549. svr.stop();
  3550. th.join();
  3551. ASSERT_FALSE(svr.is_running());
  3552. });
  3553. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3554. // actually starts anything, so the condition !svr.is_running() will
  3555. // always remain true, and the loop never stops.
  3556. // This basically counts how many milliseconds have passed since the
  3557. // call to svr.listen(), and if after 5 seconds nothing started yet
  3558. // aborts the test.
  3559. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3560. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3561. ASSERT_LT(milliseconds, 5000U);
  3562. }
  3563. {
  3564. Client cli("::1", PORT);
  3565. cli.set_follow_location(true);
  3566. std::string body;
  3567. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3568. body.append(data, data_length);
  3569. return true;
  3570. });
  3571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3572. EXPECT_EQ(StatusCode::OK_200, res->status);
  3573. EXPECT_EQ("Hello World!", body);
  3574. }
  3575. {
  3576. Client cli("::1", PORT);
  3577. std::string body;
  3578. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3579. body.append(data, data_length);
  3580. return true;
  3581. });
  3582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3583. EXPECT_EQ(StatusCode::Found_302, res->status);
  3584. EXPECT_EQ("___", body);
  3585. }
  3586. }
  3587. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3588. Server svr;
  3589. svr.Get("/foo", [](const Request &req, Response &res) {
  3590. auto a = req.params.find("a");
  3591. if (a != req.params.end()) {
  3592. res.set_content((*a).second, "text/plain");
  3593. res.status = StatusCode::OK_200;
  3594. } else {
  3595. res.status = StatusCode::BadRequest_400;
  3596. }
  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("/foo?a=explicitly+encoded");
  3609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3610. EXPECT_EQ(StatusCode::OK_200, res->status);
  3611. // This expects it back with a space, as the `+` won't have been
  3612. // url-encoded, and server-side the params get decoded turning `+`
  3613. // into spaces.
  3614. EXPECT_EQ("explicitly encoded", res->body);
  3615. }
  3616. }
  3617. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3618. // When path encoding is disabled the client must transmit the supplied
  3619. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3620. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3621. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3622. // than a space (0x20). Assert on the raw wire target to catch this.
  3623. Server svr;
  3624. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3625. svr.Get("/foo", [&](const Request &req, Response &res) {
  3626. EXPECT_EQ(expected_target, req.target);
  3627. res.status = StatusCode::OK_200;
  3628. });
  3629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3630. auto se = detail::scope_exit([&] {
  3631. svr.stop();
  3632. thread.join();
  3633. ASSERT_FALSE(svr.is_running());
  3634. });
  3635. svr.wait_until_ready();
  3636. {
  3637. Client cli(HOST, PORT);
  3638. cli.set_path_encode(false);
  3639. auto res = cli.Get(expected_target.c_str());
  3640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3641. EXPECT_EQ(StatusCode::OK_200, res->status);
  3642. }
  3643. }
  3644. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3645. // `open_stream()` used to skip the path encoding that the buffered send
  3646. // path applies, so the same `path` produced different bytes in the request
  3647. // line depending on which API was used. Assert the two agree.
  3648. Server svr;
  3649. std::string target;
  3650. svr.Get(".*", [&](const Request &req, Response &res) {
  3651. target = req.target;
  3652. res.status = StatusCode::OK_200;
  3653. });
  3654. auto port = svr.bind_to_any_port(HOST);
  3655. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3656. auto se = detail::scope_exit([&] {
  3657. svr.stop();
  3658. thread.join();
  3659. ASSERT_FALSE(svr.is_running());
  3660. });
  3661. svr.wait_until_ready();
  3662. struct {
  3663. const char *path;
  3664. const char *expected;
  3665. } cases[] = {
  3666. {"/a b?x=1", "/a%20b?x=1"},
  3667. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3668. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3669. };
  3670. for (const auto &c : cases) {
  3671. Client cli(HOST, port);
  3672. target.clear();
  3673. auto res = cli.Get(c.path);
  3674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3675. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3676. auto buffered_target = target;
  3677. target.clear();
  3678. auto handle = cli.open_stream("GET", c.path);
  3679. EXPECT_TRUE(handle.is_valid())
  3680. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3681. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3682. }
  3683. }
  3684. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3685. // The `set_path_encode(false)` contract — transmit the supplied target
  3686. // verbatim — must hold for the streaming API too.
  3687. Server svr;
  3688. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3689. std::string target;
  3690. svr.Get("/foo", [&](const Request &req, Response &res) {
  3691. target = req.target;
  3692. res.status = StatusCode::OK_200;
  3693. });
  3694. auto port = svr.bind_to_any_port(HOST);
  3695. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3696. auto se = detail::scope_exit([&] {
  3697. svr.stop();
  3698. thread.join();
  3699. ASSERT_FALSE(svr.is_running());
  3700. });
  3701. svr.wait_until_ready();
  3702. {
  3703. Client cli(HOST, port);
  3704. cli.set_path_encode(false);
  3705. auto handle = cli.open_stream("GET", expected_target);
  3706. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3707. EXPECT_EQ(expected_target, target);
  3708. }
  3709. }
  3710. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3711. // With path encoding enabled a CR/LF in the target is percent-encoded
  3712. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3713. // write_request_line still backstops `set_path_encode(false)`, which is
  3714. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3715. Server svr;
  3716. // Captured before routing: the decoded path contains a newline, which a
  3717. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3718. std::string target;
  3719. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3720. target = req.target;
  3721. res.status = StatusCode::OK_200;
  3722. return Server::HandlerResponse::Handled;
  3723. });
  3724. auto port = svr.bind_to_any_port(HOST);
  3725. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3726. auto se = detail::scope_exit([&] {
  3727. svr.stop();
  3728. thread.join();
  3729. ASSERT_FALSE(svr.is_running());
  3730. });
  3731. svr.wait_until_ready();
  3732. {
  3733. Client cli(HOST, port);
  3734. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3735. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3736. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3737. }
  3738. }
  3739. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3740. // Every control character is percent-encoded, not just CR/LF, so the target
  3741. // passes the request-target check in write_request_line.
  3742. Server svr;
  3743. std::string target;
  3744. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3745. target = req.target;
  3746. res.status = StatusCode::OK_200;
  3747. return Server::HandlerResponse::Handled;
  3748. });
  3749. auto port = svr.bind_to_any_port(HOST);
  3750. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3751. auto se = detail::scope_exit([&] {
  3752. svr.stop();
  3753. thread.join();
  3754. ASSERT_FALSE(svr.is_running());
  3755. });
  3756. svr.wait_until_ready();
  3757. {
  3758. Client cli(HOST, port);
  3759. auto res = cli.Get("/a\tb\x1b\x7f");
  3760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3761. EXPECT_EQ("/a%09b%1B%7F", target);
  3762. }
  3763. }
  3764. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3765. // Nothing may reach the wire: a raw CR/LF target would split the request
  3766. // line and inject headers.
  3767. Server svr;
  3768. // Pre-routing so that "not called" means nothing reached the server at all,
  3769. // rather than merely failing to match a handler pattern.
  3770. auto handler_called = false;
  3771. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3772. handler_called = true;
  3773. res.status = StatusCode::OK_200;
  3774. return Server::HandlerResponse::Handled;
  3775. });
  3776. auto port = svr.bind_to_any_port(HOST);
  3777. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3778. auto se = detail::scope_exit([&] {
  3779. svr.stop();
  3780. thread.join();
  3781. ASSERT_FALSE(svr.is_running());
  3782. });
  3783. svr.wait_until_ready();
  3784. {
  3785. Client cli(HOST, port);
  3786. cli.set_path_encode(false);
  3787. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3788. EXPECT_FALSE(handle.is_valid());
  3789. EXPECT_EQ(Error::Write, handle.error);
  3790. EXPECT_FALSE(handler_called);
  3791. }
  3792. }
  3793. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3794. // Which of the two branches runs is decided by whether the query component
  3795. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3796. // an empty query and must still fall back to building one from
  3797. // `req.params`, while a non-empty query must win over `req.params`.
  3798. Server svr;
  3799. std::string target;
  3800. svr.Get("/foo", [&](const Request &req, Response &res) {
  3801. target = req.target;
  3802. res.status = StatusCode::OK_200;
  3803. });
  3804. auto port = svr.bind_to_any_port(HOST);
  3805. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3806. auto se = detail::scope_exit([&] {
  3807. svr.stop();
  3808. thread.join();
  3809. ASSERT_FALSE(svr.is_running());
  3810. });
  3811. svr.wait_until_ready();
  3812. {
  3813. // Trailing `?` -> empty query component -> `req.params` is used.
  3814. Client cli(HOST, port);
  3815. Request req;
  3816. req.method = "GET";
  3817. req.path = "/foo?";
  3818. req.params.emplace("a", "1");
  3819. target.clear();
  3820. auto res = cli.send(req);
  3821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3822. EXPECT_EQ("/foo?a=1", target);
  3823. }
  3824. {
  3825. // Non-empty query in `req.path` -> `req.params` is not appended.
  3826. Client cli(HOST, port);
  3827. Request req;
  3828. req.method = "GET";
  3829. req.path = "/foo?b=2";
  3830. req.params.emplace("a", "1");
  3831. target.clear();
  3832. auto res = cli.send(req);
  3833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3834. EXPECT_EQ("/foo?b=2", target);
  3835. }
  3836. }
  3837. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3838. Server svr;
  3839. svr.Get("/", [](const Request &req, Response &) {
  3840. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3841. });
  3842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3843. auto se = detail::scope_exit([&] {
  3844. svr.stop();
  3845. thread.join();
  3846. ASSERT_FALSE(svr.is_running());
  3847. });
  3848. svr.wait_until_ready();
  3849. {
  3850. Client cli(HOST, PORT);
  3851. cli.set_path_encode(false);
  3852. auto res = cli.Get("/?something=%0A");
  3853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3854. EXPECT_EQ(StatusCode::OK_200, res->status);
  3855. }
  3856. }
  3857. TEST(BindServerTest, BindDualStack) {
  3858. Server svr;
  3859. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3860. res.set_content("Hello World!", "text/plain");
  3861. });
  3862. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3863. auto se = detail::scope_exit([&] {
  3864. svr.stop();
  3865. thread.join();
  3866. ASSERT_FALSE(svr.is_running());
  3867. });
  3868. svr.wait_until_ready();
  3869. {
  3870. Client cli("127.0.0.1", PORT);
  3871. auto res = cli.Get("/1");
  3872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3873. EXPECT_EQ(StatusCode::OK_200, res->status);
  3874. EXPECT_EQ("Hello World!", res->body);
  3875. }
  3876. {
  3877. Client cli("::1", PORT);
  3878. auto res = cli.Get("/1");
  3879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3880. EXPECT_EQ(StatusCode::OK_200, res->status);
  3881. EXPECT_EQ("Hello World!", res->body);
  3882. }
  3883. }
  3884. TEST(BindServerTest, BindAndListenSeparately) {
  3885. Server svr;
  3886. int port = svr.bind_to_any_port("0.0.0.0");
  3887. ASSERT_TRUE(svr.is_valid());
  3888. ASSERT_TRUE(port > 0);
  3889. svr.stop();
  3890. }
  3891. // Reports whether anything is still listening on a loopback port. A plain
  3892. // connect() is used instead of a Client request because a socket left bound by
  3893. // mistake accepts the connection into its backlog and never answers, which
  3894. // would hang the test instead of failing it.
  3895. static bool is_loopback_port_accepting(int port) {
  3896. sockaddr_in addr{};
  3897. addr.sin_family = AF_INET;
  3898. addr.sin_port = htons(static_cast<uint16_t>(port));
  3899. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3900. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3901. EXPECT_NE(sock, INVALID_SOCKET);
  3902. if (sock == INVALID_SOCKET) { return false; }
  3903. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3904. static_cast<socklen_t>(sizeof(addr)));
  3905. detail::close_socket(sock);
  3906. return ret == 0;
  3907. }
  3908. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3909. Server svr;
  3910. auto port = svr.bind_to_any_port("127.0.0.1");
  3911. ASSERT_TRUE(port > 0);
  3912. svr.stop();
  3913. // bind_to_any_port() already called listen(2), so until stop() closed the
  3914. // descriptor the port kept accepting connections into the backlog. ASSERT
  3915. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3916. // below blocks forever in the accept loop.
  3917. ASSERT_FALSE(is_loopback_port_accepting(port));
  3918. // Nothing is left to accept on, so listen_after_bind() must report failure
  3919. // instead of returning success without ever serving.
  3920. EXPECT_FALSE(svr.listen_after_bind());
  3921. // The failed listen marks the server decommissioned, so a waiter returns
  3922. // instead of spinning forever.
  3923. svr.wait_until_ready();
  3924. }
  3925. #ifdef CPPHTTPLIB_SSL_ENABLED
  3926. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3928. CLIENT_CA_CERT_DIR);
  3929. int port = svr.bind_to_any_port("0.0.0.0");
  3930. ASSERT_TRUE(svr.is_valid());
  3931. ASSERT_TRUE(port > 0);
  3932. svr.stop();
  3933. }
  3934. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3935. // or a rejected CustomRoute() registration would not stop the server binding.
  3936. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3938. CLIENT_CA_CERT_DIR);
  3939. ASSERT_TRUE(svr.is_valid());
  3940. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3941. EXPECT_FALSE(svr.is_valid());
  3942. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3943. }
  3944. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3945. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3946. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3947. int port = svr.bind_to_any_port("0.0.0.0");
  3948. ASSERT_TRUE(svr.is_valid());
  3949. ASSERT_TRUE(port > 0);
  3950. svr.stop();
  3951. }
  3952. TEST(BindServerTest, UpdateCertsPem) {
  3953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3954. int port = svr.bind_to_any_port("0.0.0.0");
  3955. ASSERT_TRUE(svr.is_valid());
  3956. ASSERT_TRUE(port > 0);
  3957. // Read PEM files
  3958. std::string cert_pem, key_pem, ca_pem;
  3959. read_file(SERVER_CERT_FILE, cert_pem);
  3960. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3961. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3962. // Update server certificates using PEM API
  3963. ASSERT_TRUE(
  3964. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3965. ASSERT_TRUE(svr.is_valid());
  3966. svr.stop();
  3967. }
  3968. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3969. // Start server with client CA (enables client auth)
  3970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3971. ASSERT_TRUE(svr.is_valid());
  3972. bool handler_called = false;
  3973. svr.Get("/test", [&](const Request &req, Response &res) {
  3974. handler_called = true;
  3975. // Verify client certificate is present
  3976. auto cert = req.peer_cert();
  3977. EXPECT_TRUE(static_cast<bool>(cert));
  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. // Read PEM files
  3988. std::string cert_pem, key_pem, ca_pem;
  3989. read_file(SERVER_CERT_FILE, cert_pem);
  3990. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3991. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3992. // Update server certificates and client CA using PEM API while server running
  3993. ASSERT_TRUE(
  3994. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3995. // Connect with client certificate
  3996. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3997. cli.enable_server_certificate_verification(false);
  3998. cli.set_connection_timeout(30);
  3999. auto res = cli.Get("/test");
  4000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4001. ASSERT_EQ(StatusCode::OK_200, res->status);
  4002. ASSERT_TRUE(handler_called);
  4003. EXPECT_EQ("ok", res->body);
  4004. }
  4005. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4007. ASSERT_TRUE(svr.is_valid());
  4008. svr.Get("/test", [](const Request &, Response &res) {
  4009. res.set_content("ok", "text/plain");
  4010. });
  4011. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4012. auto se = detail::scope_exit([&] {
  4013. svr.stop();
  4014. t.join();
  4015. ASSERT_FALSE(svr.is_running());
  4016. });
  4017. svr.wait_until_ready();
  4018. auto get = [] {
  4019. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4020. cli.enable_server_certificate_verification(false);
  4021. return cli.Get("/test");
  4022. };
  4023. ASSERT_TRUE(get());
  4024. // A CA that did not sign the client's certificate takes the old one's place.
  4025. std::string cert_pem, key_pem, ca_pem;
  4026. read_file(SERVER_CERT_FILE, cert_pem);
  4027. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4028. read_file(SERVER_CERT2_FILE, ca_pem);
  4029. ASSERT_TRUE(
  4030. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4031. EXPECT_FALSE(get());
  4032. }
  4033. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4035. ASSERT_TRUE(svr.is_valid());
  4036. svr.Get("/test", [](const Request &, Response &res) {
  4037. res.set_content("ok", "text/plain");
  4038. });
  4039. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4040. auto se = detail::scope_exit([&] {
  4041. svr.stop();
  4042. t.join();
  4043. ASSERT_FALSE(svr.is_running());
  4044. });
  4045. svr.wait_until_ready();
  4046. // A connection that sends no ClientHello keeps its handshake in progress,
  4047. // once the server has had a moment to start it.
  4048. auto error = Error::Success;
  4049. auto sock = detail::create_client_socket(
  4050. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4051. /*connection_timeout_sec=*/5, 0,
  4052. /*read_timeout_sec=*/5, 0,
  4053. /*write_timeout_sec=*/5, 0, std::string(), error);
  4054. ASSERT_NE(INVALID_SOCKET, sock);
  4055. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4056. std::string cert_pem, key_pem;
  4057. read_file(SERVER_CERT_FILE, cert_pem);
  4058. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4059. auto update = std::async(std::launch::async, [&]() {
  4060. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4061. });
  4062. EXPECT_EQ(std::future_status::timeout,
  4063. update.wait_for(std::chrono::milliseconds(200)));
  4064. detail::close_socket(sock);
  4065. EXPECT_TRUE(update.get());
  4066. SSLClient cli(HOST, PORT);
  4067. cli.enable_server_certificate_verification(false);
  4068. auto res = cli.Get("/test");
  4069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4070. EXPECT_EQ(StatusCode::OK_200, res->status);
  4071. }
  4072. #endif
  4073. TEST(ErrorHandlerTest, ContentLength) {
  4074. Server svr;
  4075. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4076. res.status = StatusCode::OK_200;
  4077. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4078. "text/html"); // <= Content-Length still 13
  4079. });
  4080. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4081. res.set_content("Hello World!\n", "text/plain");
  4082. res.status = 524;
  4083. });
  4084. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4085. auto se = detail::scope_exit([&] {
  4086. svr.stop();
  4087. thread.join();
  4088. ASSERT_FALSE(svr.is_running());
  4089. });
  4090. svr.wait_until_ready();
  4091. {
  4092. Client cli(HOST, PORT);
  4093. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4095. EXPECT_EQ(StatusCode::OK_200, res->status);
  4096. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4097. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4098. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4099. }
  4100. }
  4101. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4102. TEST(ExceptionTest, WithoutExceptionHandler) {
  4103. Server svr;
  4104. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4105. throw std::runtime_error("exception...");
  4106. });
  4107. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4108. throw std::runtime_error("exception\r\n...");
  4109. });
  4110. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. listen_thread.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. svr.wait_until_ready();
  4117. Client cli("localhost", PORT);
  4118. {
  4119. auto res = cli.Get("/exception");
  4120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4121. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4122. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4123. }
  4124. {
  4125. auto res = cli.Get("/unknown");
  4126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4127. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4128. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4129. }
  4130. }
  4131. TEST(ExceptionTest, WithExceptionHandler) {
  4132. Server svr;
  4133. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4134. std::exception_ptr ep) {
  4135. EXPECT_FALSE(ep == nullptr);
  4136. try {
  4137. std::rethrow_exception(ep);
  4138. } catch (std::exception &e) {
  4139. EXPECT_EQ("abc", std::string(e.what()));
  4140. } catch (...) {}
  4141. res.status = StatusCode::InternalServerError_500;
  4142. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4143. "text/html"); // <= Content-Length still 13 at this point
  4144. });
  4145. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4146. res.set_content("Hello World!\n", "text/plain");
  4147. throw std::runtime_error("abc");
  4148. });
  4149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4150. auto se = detail::scope_exit([&] {
  4151. svr.stop();
  4152. thread.join();
  4153. ASSERT_FALSE(svr.is_running());
  4154. });
  4155. svr.wait_until_ready();
  4156. for (size_t i = 0; i < 10; i++) {
  4157. Client cli(HOST, PORT);
  4158. for (size_t j = 0; j < 100; j++) {
  4159. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4162. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4163. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4164. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4165. }
  4166. cli.set_keep_alive(true);
  4167. for (size_t j = 0; j < 100; j++) {
  4168. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4170. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4171. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4172. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4173. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4174. }
  4175. }
  4176. }
  4177. TEST(ExceptionTest, AndErrorHandler) {
  4178. Server svr;
  4179. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4180. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4181. });
  4182. svr.set_exception_handler(
  4183. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4184. EXPECT_FALSE(ep == nullptr);
  4185. try {
  4186. std::rethrow_exception(ep);
  4187. } catch (std::exception &e) {
  4188. res.set_content(e.what(), "text/html");
  4189. } catch (...) {}
  4190. res.status = StatusCode::InternalServerError_500;
  4191. });
  4192. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4193. throw std::runtime_error("EXCEPTION");
  4194. });
  4195. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4196. res.set_content("ERROR", "text/html");
  4197. res.status = StatusCode::InternalServerError_500;
  4198. });
  4199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4200. auto se = detail::scope_exit([&] {
  4201. svr.stop();
  4202. thread.join();
  4203. ASSERT_FALSE(svr.is_running());
  4204. });
  4205. svr.wait_until_ready();
  4206. Client cli(HOST, PORT);
  4207. {
  4208. auto res = cli.Get("/exception");
  4209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4210. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4211. EXPECT_EQ("EXCEPTION", res->body);
  4212. }
  4213. {
  4214. auto res = cli.Get("/error");
  4215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4216. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4217. EXPECT_EQ("ERROR", res->body);
  4218. }
  4219. {
  4220. auto res = cli.Get("/invalid");
  4221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4223. EXPECT_EQ("NOT_FOUND", res->body);
  4224. }
  4225. }
  4226. #endif
  4227. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4228. // process_request() wraps only routing() in a try/catch, so an exception from
  4229. // any other user callback used to unwind into the task queue - which does not
  4230. // catch - and terminate the process. Each test below runs the server on a
  4231. // single worker thread: a guard that catches the exception but still loses the
  4232. // thread would otherwise be hidden by a spare worker serving the follow-up
  4233. // request. Note that a regression here aborts the whole test binary rather
  4234. // than failing one test.
  4235. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4236. Server svr;
  4237. svr.new_task_queue = [] { return new ThreadPool(1); };
  4238. std::atomic<int> reported{0};
  4239. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4240. if (err == Error::UserCallbackException) { reported++; }
  4241. });
  4242. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4243. res.set_content_provider(
  4244. 1024, "text/plain",
  4245. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4246. sink.write("hello", 5);
  4247. throw std::runtime_error("from the content provider");
  4248. });
  4249. });
  4250. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4251. res.set_content("ok", "text/plain");
  4252. });
  4253. auto port = svr.bind_to_any_port(HOST);
  4254. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4255. auto se = detail::scope_exit([&] {
  4256. svr.stop();
  4257. listen_thread.join();
  4258. ASSERT_FALSE(svr.is_running());
  4259. });
  4260. svr.wait_until_ready();
  4261. {
  4262. Client cli(HOST, port);
  4263. cli.set_read_timeout(5, 0);
  4264. EXPECT_FALSE(cli.Get("/throw"));
  4265. }
  4266. EXPECT_TRUE(svr.is_running());
  4267. EXPECT_EQ(1, reported.load());
  4268. // A request on a fresh connection is still served.
  4269. {
  4270. Client cli(HOST, port);
  4271. auto res = cli.Get("/ok");
  4272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. EXPECT_EQ("ok", res->body);
  4275. }
  4276. }
  4277. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4278. Server svr;
  4279. svr.new_task_queue = [] { return new ThreadPool(1); };
  4280. std::atomic<bool> should_throw{true};
  4281. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4282. res.set_content("hi", "text/plain");
  4283. });
  4284. svr.set_post_routing_handler(
  4285. [&](const Request & /*req*/, Response & /*res*/) {
  4286. if (should_throw) {
  4287. throw std::runtime_error("from the post-routing handler");
  4288. }
  4289. });
  4290. auto port = svr.bind_to_any_port(HOST);
  4291. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4292. auto se = detail::scope_exit([&] {
  4293. svr.stop();
  4294. listen_thread.join();
  4295. ASSERT_FALSE(svr.is_running());
  4296. });
  4297. svr.wait_until_ready();
  4298. {
  4299. Client cli(HOST, port);
  4300. cli.set_read_timeout(5, 0);
  4301. EXPECT_FALSE(cli.Get("/hi"));
  4302. }
  4303. EXPECT_TRUE(svr.is_running());
  4304. should_throw = false;
  4305. {
  4306. Client cli(HOST, port);
  4307. auto res = cli.Get("/hi");
  4308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4309. EXPECT_EQ(StatusCode::OK_200, res->status);
  4310. EXPECT_EQ("hi", res->body);
  4311. }
  4312. }
  4313. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4314. // The guard reports the caught exception through the error logger, which is
  4315. // a user callback too. A logger that throws has to be contained as well, or
  4316. // the process would terminate from inside the catch.
  4317. Server svr;
  4318. svr.new_task_queue = [] { return new ThreadPool(1); };
  4319. std::atomic<int> reported{0};
  4320. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4321. if (err == Error::UserCallbackException) {
  4322. reported++;
  4323. throw std::runtime_error("from the error logger");
  4324. }
  4325. });
  4326. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4327. res.set_content_provider(
  4328. 1024, "text/plain",
  4329. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4330. sink.write("hello", 5);
  4331. throw std::runtime_error("from the content provider");
  4332. });
  4333. });
  4334. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4335. res.set_content("ok", "text/plain");
  4336. });
  4337. auto port = svr.bind_to_any_port(HOST);
  4338. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4339. auto se = detail::scope_exit([&] {
  4340. svr.stop();
  4341. listen_thread.join();
  4342. ASSERT_FALSE(svr.is_running());
  4343. });
  4344. svr.wait_until_ready();
  4345. {
  4346. Client cli(HOST, port);
  4347. cli.set_read_timeout(5, 0);
  4348. EXPECT_FALSE(cli.Get("/throw"));
  4349. }
  4350. EXPECT_TRUE(svr.is_running());
  4351. EXPECT_EQ(1, reported.load());
  4352. {
  4353. Client cli(HOST, port);
  4354. auto res = cli.Get("/ok");
  4355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4356. EXPECT_EQ(StatusCode::OK_200, res->status);
  4357. EXPECT_EQ("ok", res->body);
  4358. }
  4359. }
  4360. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4361. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4362. // so the exception unwinds through the ws::WebSocket object on its way to
  4363. // the guard. None of the HTTP cases above cross that.
  4364. Server svr;
  4365. svr.new_task_queue = [] { return new ThreadPool(1); };
  4366. std::atomic<int> reported{0};
  4367. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4368. if (err == Error::UserCallbackException) { reported++; }
  4369. });
  4370. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4371. throw std::runtime_error("from the WebSocket handler");
  4372. });
  4373. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4374. res.set_content("ok", "text/plain");
  4375. });
  4376. auto port = svr.bind_to_any_port(HOST);
  4377. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4378. auto se = detail::scope_exit([&] {
  4379. svr.stop();
  4380. listen_thread.join();
  4381. ASSERT_FALSE(svr.is_running());
  4382. });
  4383. svr.wait_until_ready();
  4384. {
  4385. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4386. "/ws");
  4387. auto res = client.connect();
  4388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4389. // The server dropped the connection instead of dying.
  4390. std::string msg;
  4391. EXPECT_FALSE(client.read(msg));
  4392. client.close();
  4393. }
  4394. EXPECT_TRUE(svr.is_running());
  4395. EXPECT_EQ(1, reported.load());
  4396. {
  4397. Client cli(HOST, port);
  4398. auto res = cli.Get("/ok");
  4399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. EXPECT_EQ("ok", res->body);
  4402. }
  4403. }
  4404. #ifdef CPPHTTPLIB_SSL_ENABLED
  4405. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4406. // SSLServer::process_and_close_socket() is a separate overload with its own
  4407. // guard, so it is exercised on its own.
  4408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4409. ASSERT_TRUE(svr.is_valid());
  4410. svr.new_task_queue = [] { return new ThreadPool(1); };
  4411. std::atomic<int> reported{0};
  4412. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4413. if (err == Error::UserCallbackException) { reported++; }
  4414. });
  4415. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4416. res.set_content_provider(
  4417. 1024, "text/plain",
  4418. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4419. sink.write("hello", 5);
  4420. throw std::runtime_error("from the content provider");
  4421. });
  4422. });
  4423. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4424. res.set_content("ok", "text/plain");
  4425. });
  4426. auto port = svr.bind_to_any_port(HOST);
  4427. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4428. auto se = detail::scope_exit([&] {
  4429. svr.stop();
  4430. listen_thread.join();
  4431. ASSERT_FALSE(svr.is_running());
  4432. });
  4433. svr.wait_until_ready();
  4434. {
  4435. SSLClient cli(HOST, port);
  4436. cli.enable_server_certificate_verification(false);
  4437. cli.set_read_timeout(5, 0);
  4438. EXPECT_FALSE(cli.Get("/throw"));
  4439. }
  4440. EXPECT_TRUE(svr.is_running());
  4441. EXPECT_EQ(1, reported.load());
  4442. {
  4443. SSLClient cli(HOST, port);
  4444. cli.enable_server_certificate_verification(false);
  4445. auto res = cli.Get("/ok");
  4446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4447. EXPECT_EQ(StatusCode::OK_200, res->status);
  4448. EXPECT_EQ("ok", res->body);
  4449. }
  4450. }
  4451. #endif
  4452. #endif
  4453. TEST(NoContentTest, ContentLength) {
  4454. Server svr;
  4455. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4456. res.status = StatusCode::NoContent_204;
  4457. });
  4458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4459. auto se = detail::scope_exit([&] {
  4460. svr.stop();
  4461. thread.join();
  4462. ASSERT_FALSE(svr.is_running());
  4463. });
  4464. svr.wait_until_ready();
  4465. {
  4466. Client cli(HOST, PORT);
  4467. auto res = cli.Get("/hi");
  4468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4469. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4470. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4471. }
  4472. }
  4473. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4474. #ifdef CPPHTTPLIB_SSL_ENABLED
  4475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4476. ASSERT_TRUE(svr.is_valid());
  4477. #else
  4478. Server svr;
  4479. #endif
  4480. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4481. if (req.path == "/routing_handler") {
  4482. res.set_header("PRE_ROUTING", "on");
  4483. res.set_content("Routing Handler", "text/plain");
  4484. return httplib::Server::HandlerResponse::Handled;
  4485. }
  4486. return httplib::Server::HandlerResponse::Unhandled;
  4487. });
  4488. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4489. res.set_content("Error", "text/html");
  4490. });
  4491. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4492. if (req.path == "/routing_handler") {
  4493. res.set_header("POST_ROUTING", "on");
  4494. }
  4495. });
  4496. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4497. res.set_content("Hello World!\n", "text/plain");
  4498. });
  4499. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4500. auto se = detail::scope_exit([&] {
  4501. svr.stop();
  4502. thread.join();
  4503. ASSERT_FALSE(svr.is_running());
  4504. });
  4505. svr.wait_until_ready();
  4506. {
  4507. #ifdef CPPHTTPLIB_SSL_ENABLED
  4508. SSLClient cli(HOST, PORT);
  4509. cli.enable_server_certificate_verification(false);
  4510. #else
  4511. Client cli(HOST, PORT);
  4512. #endif
  4513. auto res = cli.Get("/routing_handler");
  4514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. EXPECT_EQ("Routing Handler", res->body);
  4517. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4518. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4519. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4520. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4521. }
  4522. {
  4523. #ifdef CPPHTTPLIB_SSL_ENABLED
  4524. SSLClient cli(HOST, PORT);
  4525. cli.enable_server_certificate_verification(false);
  4526. #else
  4527. Client cli(HOST, PORT);
  4528. #endif
  4529. auto res = cli.Get("/hi");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. EXPECT_EQ("Hello World!\n", res->body);
  4533. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4534. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4535. }
  4536. {
  4537. #ifdef CPPHTTPLIB_SSL_ENABLED
  4538. SSLClient cli(HOST, PORT);
  4539. cli.enable_server_certificate_verification(false);
  4540. #else
  4541. Client cli(HOST, PORT);
  4542. #endif
  4543. auto res = cli.Get("/aaa");
  4544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4546. EXPECT_EQ("Error", res->body);
  4547. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4548. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4549. }
  4550. }
  4551. TEST(RequestHandlerTest, PreRequestHandler) {
  4552. auto route_path = "/user/:user";
  4553. Server svr;
  4554. svr.Get("/hi", [](const Request &, Response &res) {
  4555. res.set_content("hi", "text/plain");
  4556. });
  4557. svr.Get(route_path, [](const Request &req, Response &res) {
  4558. res.set_content(req.path_params.at("user"), "text/plain");
  4559. });
  4560. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4561. if (req.matched_route == route_path) {
  4562. auto user = req.path_params.at("user");
  4563. if (user != "john") {
  4564. res.status = StatusCode::Forbidden_403;
  4565. res.set_content("error", "text/html");
  4566. return Server::HandlerResponse::Handled;
  4567. }
  4568. }
  4569. return Server::HandlerResponse::Unhandled;
  4570. });
  4571. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4572. auto se = detail::scope_exit([&] {
  4573. svr.stop();
  4574. thread.join();
  4575. ASSERT_FALSE(svr.is_running());
  4576. });
  4577. svr.wait_until_ready();
  4578. Client cli(HOST, PORT);
  4579. {
  4580. auto res = cli.Get("/hi");
  4581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4582. EXPECT_EQ(StatusCode::OK_200, res->status);
  4583. EXPECT_EQ("hi", res->body);
  4584. }
  4585. {
  4586. auto res = cli.Get("/user/john");
  4587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4588. EXPECT_EQ(StatusCode::OK_200, res->status);
  4589. EXPECT_EQ("john", res->body);
  4590. }
  4591. {
  4592. auto res = cli.Get("/user/invalid-user");
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4595. EXPECT_EQ("error", res->body);
  4596. }
  4597. }
  4598. // The pre-request handler must run before the request body is read, so a
  4599. // rejected request never forces the server to buffer a (potentially large)
  4600. // body. Here the posted body is larger than the payload limit: if the body
  4601. // were read first the server would answer 413, but because the pre-request
  4602. // handler runs first it answers 403 and the body is never read.
  4603. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4604. Server svr;
  4605. svr.set_payload_max_length(8);
  4606. auto handler_ran = false;
  4607. svr.Post("/reject", [&](const Request &req, Response &res) {
  4608. handler_ran = true;
  4609. res.set_content(req.body, "text/plain");
  4610. });
  4611. svr.Post("/accept", [](const Request &req, Response &res) {
  4612. res.set_content(req.body, "text/plain");
  4613. });
  4614. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4615. if (req.matched_route == "/reject") {
  4616. res.status = StatusCode::Forbidden_403;
  4617. res.set_content("denied", "text/plain");
  4618. return Server::HandlerResponse::Handled;
  4619. }
  4620. return Server::HandlerResponse::Unhandled;
  4621. });
  4622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4623. auto se = detail::scope_exit([&] {
  4624. svr.stop();
  4625. thread.join();
  4626. ASSERT_FALSE(svr.is_running());
  4627. });
  4628. svr.wait_until_ready();
  4629. Client cli(HOST, PORT);
  4630. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4631. // rejects with 403 before the body is read, so 413 is never reached.
  4632. {
  4633. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4635. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4636. EXPECT_EQ("denied", res->body);
  4637. EXPECT_FALSE(handler_ran);
  4638. }
  4639. // An approved route still reads the body and enforces the payload limit.
  4640. {
  4641. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4643. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4644. }
  4645. }
  4646. TEST(UserDataTest, BasicOperations) {
  4647. httplib::UserData ud;
  4648. // Initially empty
  4649. EXPECT_FALSE(ud.has("key"));
  4650. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4651. // set and get
  4652. ud.set("key", 42);
  4653. EXPECT_TRUE(ud.has("key"));
  4654. auto *p = ud.get<int>("key");
  4655. ASSERT_NE(nullptr, p);
  4656. EXPECT_EQ(42, *p);
  4657. // Type mismatch → nullptr
  4658. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4659. // Overwrite with different type
  4660. ud.set("key", std::string("hello"));
  4661. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4662. auto *s = ud.get<std::string>("key");
  4663. ASSERT_NE(nullptr, s);
  4664. EXPECT_EQ("hello", *s);
  4665. // erase
  4666. ud.erase("key");
  4667. EXPECT_FALSE(ud.has("key"));
  4668. // clear
  4669. ud.set("a", 1);
  4670. ud.set("b", 2);
  4671. ud.clear();
  4672. EXPECT_FALSE(ud.has("a"));
  4673. EXPECT_FALSE(ud.has("b"));
  4674. }
  4675. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4676. struct AuthCtx {
  4677. std::string user_id;
  4678. };
  4679. Server svr;
  4680. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4681. res.user_data.set("auth", AuthCtx{"alice"});
  4682. return Server::HandlerResponse::Unhandled;
  4683. });
  4684. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4685. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4686. ASSERT_NE(nullptr, ctx);
  4687. res.set_content("Hello " + ctx->user_id, "text/plain");
  4688. });
  4689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4690. auto se = detail::scope_exit([&] {
  4691. svr.stop();
  4692. thread.join();
  4693. ASSERT_FALSE(svr.is_running());
  4694. });
  4695. svr.wait_until_ready();
  4696. Client cli(HOST, PORT);
  4697. auto res = cli.Get("/me");
  4698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4699. EXPECT_EQ(StatusCode::OK_200, res->status);
  4700. EXPECT_EQ("Hello alice", res->body);
  4701. }
  4702. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4703. struct RoleCtx {
  4704. std::string role;
  4705. };
  4706. Server svr;
  4707. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4708. res.user_data.set("role", RoleCtx{"admin"});
  4709. return Server::HandlerResponse::Unhandled;
  4710. });
  4711. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4712. auto *ctx = res.user_data.get<RoleCtx>("role");
  4713. ASSERT_NE(nullptr, ctx);
  4714. res.set_content(ctx->role, "text/plain");
  4715. });
  4716. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4717. auto se = detail::scope_exit([&] {
  4718. svr.stop();
  4719. thread.join();
  4720. ASSERT_FALSE(svr.is_running());
  4721. });
  4722. svr.wait_until_ready();
  4723. Client cli(HOST, PORT);
  4724. auto res = cli.Get("/role");
  4725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4726. EXPECT_EQ(StatusCode::OK_200, res->status);
  4727. EXPECT_EQ("admin", res->body);
  4728. }
  4729. TEST(InvalidFormatTest, StatusCode) {
  4730. Server svr;
  4731. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4732. res.set_content("Hello World!\n", "text/plain");
  4733. res.status = 9999; // Status should be a three-digit code...
  4734. });
  4735. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4736. auto se = detail::scope_exit([&] {
  4737. svr.stop();
  4738. thread.join();
  4739. ASSERT_FALSE(svr.is_running());
  4740. });
  4741. svr.wait_until_ready();
  4742. {
  4743. Client cli(HOST, PORT);
  4744. auto res = cli.Get("/hi");
  4745. ASSERT_FALSE(res);
  4746. }
  4747. }
  4748. TEST(URLFragmentTest, WithFragment) {
  4749. Server svr;
  4750. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4751. EXPECT_TRUE(req.target == "/hi");
  4752. });
  4753. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4754. auto se = detail::scope_exit([&] {
  4755. svr.stop();
  4756. thread.join();
  4757. ASSERT_FALSE(svr.is_running());
  4758. });
  4759. svr.wait_until_ready();
  4760. {
  4761. Client cli(HOST, PORT);
  4762. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4763. EXPECT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. res = cli.Get("/hi%23key1=val1=key2=val2");
  4766. EXPECT_TRUE(res);
  4767. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4768. }
  4769. }
  4770. TEST(HeaderWriter, SetHeaderWriter) {
  4771. Server svr;
  4772. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4773. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4774. return detail::write_headers(strm, hdrs);
  4775. });
  4776. svr.Get("/hi", [](const Request &req, Response &res) {
  4777. auto it = req.headers.find("CustomClientHeader");
  4778. EXPECT_TRUE(it != req.headers.end());
  4779. EXPECT_EQ(it->second, "CustomClientValue");
  4780. res.set_content("Hello World!\n", "text/plain");
  4781. });
  4782. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4783. auto se = detail::scope_exit([&] {
  4784. svr.stop();
  4785. thread.join();
  4786. ASSERT_FALSE(svr.is_running());
  4787. });
  4788. svr.wait_until_ready();
  4789. {
  4790. Client cli(HOST, PORT);
  4791. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4792. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4793. return detail::write_headers(strm, hdrs);
  4794. });
  4795. auto res = cli.Get("/hi");
  4796. EXPECT_TRUE(res);
  4797. EXPECT_EQ(StatusCode::OK_200, res->status);
  4798. auto it = res->headers.find("CustomServerHeader");
  4799. EXPECT_TRUE(it != res->headers.end());
  4800. EXPECT_EQ(it->second, "CustomServerValue");
  4801. }
  4802. }
  4803. class ServerTest : public ::testing::Test {
  4804. protected:
  4805. ServerTest()
  4806. : cli_(HOST, PORT)
  4807. #ifdef CPPHTTPLIB_SSL_ENABLED
  4808. ,
  4809. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4810. #endif
  4811. {
  4812. #ifdef CPPHTTPLIB_SSL_ENABLED
  4813. cli_.enable_server_certificate_verification(false);
  4814. #endif
  4815. // Allow LARGE_DATA (100MB) responses
  4816. cli_.set_payload_max_length(200 * 1024 * 1024);
  4817. }
  4818. virtual void SetUp() {
  4819. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4820. svr_.set_payload_max_length(200 * 1024 * 1024);
  4821. svr_.set_mount_point("/", "./www");
  4822. svr_.set_mount_point("/mount", "./www2");
  4823. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4824. svr_.Get("/hi",
  4825. [&](const Request & /*req*/, Response &res) {
  4826. res.set_content("Hello World!", "text/plain");
  4827. })
  4828. .Get("/file_content",
  4829. [&](const Request & /*req*/, Response &res) {
  4830. res.set_file_content("./www/dir/test.html");
  4831. })
  4832. .Get("/file_content_with_content_type",
  4833. [&](const Request & /*req*/, Response &res) {
  4834. res.set_file_content("./www/file", "text/plain");
  4835. })
  4836. .Get("/invalid_file_content",
  4837. [&](const Request & /*req*/, Response &res) {
  4838. res.set_file_content("./www/dir/invalid_file_path");
  4839. })
  4840. .Get("/http_response_splitting",
  4841. [&](const Request & /*req*/, Response &res) {
  4842. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4843. EXPECT_EQ(0U, res.headers.size());
  4844. EXPECT_FALSE(res.has_header("a"));
  4845. res.set_header("a", "1\nSet-Cookie: a=1");
  4846. EXPECT_EQ(0U, res.headers.size());
  4847. EXPECT_FALSE(res.has_header("a"));
  4848. res.set_header("a", "1\rSet-Cookie: a=1");
  4849. EXPECT_EQ(0U, res.headers.size());
  4850. EXPECT_FALSE(res.has_header("a"));
  4851. res.set_header("a\r\nb", "0");
  4852. EXPECT_EQ(0U, res.headers.size());
  4853. EXPECT_FALSE(res.has_header("a"));
  4854. res.set_header("a\rb", "0");
  4855. EXPECT_EQ(0U, res.headers.size());
  4856. EXPECT_FALSE(res.has_header("a"));
  4857. res.set_header("a\nb", "0");
  4858. EXPECT_EQ(0U, res.headers.size());
  4859. EXPECT_FALSE(res.has_header("a"));
  4860. res.set_redirect("1\r\nSet-Cookie: a=1");
  4861. EXPECT_EQ(0U, res.headers.size());
  4862. EXPECT_FALSE(res.has_header("Location"));
  4863. })
  4864. .Get("/slow",
  4865. [&](const Request & /*req*/, Response &res) {
  4866. std::this_thread::sleep_for(std::chrono::seconds(4));
  4867. res.set_content("slow", "text/plain");
  4868. })
  4869. #if 0
  4870. .Post("/slowpost",
  4871. [&](const Request & /*req*/, Response &res) {
  4872. std::this_thread::sleep_for(std::chrono::seconds(2));
  4873. res.set_content("slow", "text/plain");
  4874. })
  4875. #endif
  4876. .Get("/remote_addr",
  4877. [&](const Request &req, Response &res) {
  4878. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4879. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4880. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4881. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4882. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4883. #endif
  4884. res.set_content(req.remote_addr, "text/plain");
  4885. })
  4886. .Get("/local_addr",
  4887. [&](const Request &req, Response &res) {
  4888. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4889. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4890. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4891. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4892. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4893. #endif
  4894. auto local_addr = req.local_addr;
  4895. auto local_port = std::to_string(req.local_port);
  4896. res.set_content(local_addr.append(":").append(local_port),
  4897. "text/plain");
  4898. })
  4899. .Get("/endwith%",
  4900. [&](const Request & /*req*/, Response &res) {
  4901. res.set_content("Hello World!", "text/plain");
  4902. })
  4903. .Get("/a\\+\\+b",
  4904. [&](const Request &req, Response &res) {
  4905. ASSERT_TRUE(req.has_param("a +b"));
  4906. auto val = req.get_param_value("a +b");
  4907. res.set_content(val, "text/plain");
  4908. })
  4909. .Get("/", [&](const Request & /*req*/,
  4910. Response &res) { res.set_redirect("/hi"); })
  4911. .Post("/1",
  4912. [](const Request & /*req*/, Response &res) {
  4913. res.set_redirect("/2", StatusCode::SeeOther_303);
  4914. })
  4915. .Get("/2",
  4916. [](const Request & /*req*/, Response &res) {
  4917. res.set_content("redirected.", "text/plain");
  4918. res.status = StatusCode::OK_200;
  4919. })
  4920. .Post("/person",
  4921. [&](const Request &req, Response &res) {
  4922. if (req.has_param("name") && req.has_param("note")) {
  4923. persons_[req.get_param_value("name")] =
  4924. req.get_param_value("note");
  4925. } else {
  4926. res.status = StatusCode::BadRequest_400;
  4927. }
  4928. })
  4929. .Put("/person",
  4930. [&](const Request &req, Response &res) {
  4931. if (req.has_param("name") && req.has_param("note")) {
  4932. persons_[req.get_param_value("name")] =
  4933. req.get_param_value("note");
  4934. } else {
  4935. res.status = StatusCode::BadRequest_400;
  4936. }
  4937. })
  4938. .Get("/person/(.*)",
  4939. [&](const Request &req, Response &res) {
  4940. string name = req.matches[1];
  4941. if (persons_.find(name) != persons_.end()) {
  4942. auto note = persons_[name];
  4943. res.set_content(note, "text/plain");
  4944. } else {
  4945. res.status = StatusCode::NotFound_404;
  4946. }
  4947. })
  4948. .Delete("/person",
  4949. [&](const Request &req, Response &res) {
  4950. if (req.has_param("name")) {
  4951. string name = req.get_param_value("name");
  4952. if (persons_.find(name) != persons_.end()) {
  4953. persons_.erase(name);
  4954. res.set_content("DELETED", "text/plain");
  4955. } else {
  4956. res.status = StatusCode::NotFound_404;
  4957. }
  4958. } else {
  4959. res.status = StatusCode::BadRequest_400;
  4960. }
  4961. })
  4962. .Post("/x-www-form-urlencoded-json",
  4963. [&](const Request &req, Response &res) {
  4964. auto json = req.get_param_value("json");
  4965. ASSERT_EQ(JSON_DATA, json);
  4966. res.set_content(json, "appliation/json");
  4967. res.status = StatusCode::OK_200;
  4968. })
  4969. .Get("/streamed-chunked",
  4970. [&](const Request & /*req*/, Response &res) {
  4971. res.set_chunked_content_provider(
  4972. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4973. sink.os << "123";
  4974. sink.os << "456";
  4975. sink.os << "789";
  4976. sink.done();
  4977. return true;
  4978. });
  4979. })
  4980. .Get("/streamed-chunked-with-prohibited-trailer",
  4981. [&](const Request & /*req*/, Response &res) {
  4982. auto i = new int(0);
  4983. // Declare both a prohibited trailer (Content-Length) and an
  4984. // allowed one
  4985. res.set_header("Trailer", "Content-Length, X-Allowed");
  4986. res.set_chunked_content_provider(
  4987. "text/plain",
  4988. [i](size_t /*offset*/, DataSink &sink) {
  4989. switch (*i) {
  4990. case 0: sink.os << "123"; break;
  4991. case 1: sink.os << "456"; break;
  4992. case 2: sink.os << "789"; break;
  4993. case 3: {
  4994. sink.done_with_trailer(
  4995. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4996. } break;
  4997. }
  4998. (*i)++;
  4999. return true;
  5000. },
  5001. [i](bool success) {
  5002. EXPECT_TRUE(success);
  5003. delete i;
  5004. });
  5005. })
  5006. .Get("/streamed-chunked2",
  5007. [&](const Request & /*req*/, Response &res) {
  5008. auto i = new int(0);
  5009. res.set_chunked_content_provider(
  5010. "text/plain",
  5011. [i](size_t /*offset*/, DataSink &sink) {
  5012. switch (*i) {
  5013. case 0: sink.os << "123"; break;
  5014. case 1: sink.os << "456"; break;
  5015. case 2: sink.os << "789"; break;
  5016. case 3: sink.done(); break;
  5017. }
  5018. (*i)++;
  5019. return true;
  5020. },
  5021. [i](bool success) {
  5022. EXPECT_TRUE(success);
  5023. delete i;
  5024. });
  5025. })
  5026. .Get("/streamed-chunked-with-trailer",
  5027. [&](const Request & /*req*/, Response &res) {
  5028. auto i = new int(0);
  5029. res.set_header("Trailer", "Dummy1, Dummy2");
  5030. res.set_chunked_content_provider(
  5031. "text/plain",
  5032. [i](size_t /*offset*/, DataSink &sink) {
  5033. switch (*i) {
  5034. case 0: sink.os << "123"; break;
  5035. case 1: sink.os << "456"; break;
  5036. case 2: sink.os << "789"; break;
  5037. case 3: {
  5038. sink.done_with_trailer(
  5039. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5040. } break;
  5041. }
  5042. (*i)++;
  5043. return true;
  5044. },
  5045. [i](bool success) {
  5046. EXPECT_TRUE(success);
  5047. delete i;
  5048. });
  5049. })
  5050. .Get("/streamed",
  5051. [&](const Request & /*req*/, Response &res) {
  5052. res.set_content_provider(
  5053. 6, "text/plain",
  5054. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5055. sink.os << (offset < 3 ? "a" : "b");
  5056. return true;
  5057. });
  5058. })
  5059. .Get("/streamed-without-length",
  5060. [&](const Request & /*req*/, Response &res) {
  5061. auto data = new std::string("abcdefg");
  5062. res.set_content_provider(
  5063. "text/plain",
  5064. [data](size_t offset, DataSink &sink) {
  5065. if (offset < data->size()) {
  5066. sink.os << data->substr(offset);
  5067. }
  5068. sink.done();
  5069. return true;
  5070. },
  5071. [data](bool success) {
  5072. EXPECT_TRUE(success);
  5073. delete data;
  5074. });
  5075. })
  5076. .Get("/streamed-with-range",
  5077. [&](const Request &req, Response &res) {
  5078. auto data = new std::string("abcdefg");
  5079. // An explicit status keeps the server from picking the 206 it
  5080. // would otherwise choose for a ranged request, so the response
  5081. // is not a partial representation.
  5082. auto status = req.get_param_value("status");
  5083. if (status == "200") {
  5084. res.status = StatusCode::OK_200;
  5085. } else if (status == "403") {
  5086. res.status = StatusCode::Forbidden_403;
  5087. }
  5088. res.set_content_provider(
  5089. data->size(), "text/plain",
  5090. [data](size_t offset, size_t length, DataSink &sink) {
  5091. size_t DATA_CHUNK_SIZE = 4;
  5092. const auto &d = *data;
  5093. auto out_len =
  5094. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5095. auto ret =
  5096. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5097. EXPECT_TRUE(ret);
  5098. return true;
  5099. },
  5100. [data, &req](bool success) {
  5101. EXPECT_EQ(success, !req.has_param("error"));
  5102. delete data;
  5103. });
  5104. })
  5105. .Get("/streamed-cancel",
  5106. [&](const Request & /*req*/, Response &res) {
  5107. res.set_content_provider(
  5108. size_t(-1), "text/plain",
  5109. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5110. sink.os << "data_chunk";
  5111. return true;
  5112. });
  5113. })
  5114. .Get("/regex-with-delimiter",
  5115. [&](const Request &req, Response & /*res*/) {
  5116. ASSERT_TRUE(req.has_param("key"));
  5117. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5118. })
  5119. .Get("/with-range",
  5120. [&](const Request & /*req*/, Response &res) {
  5121. res.set_content("abcdefg", "text/plain");
  5122. })
  5123. .Get("/test-start-time",
  5124. [&](const Request &req, Response & /*res*/) {
  5125. EXPECT_NE(req.start_time_,
  5126. std::chrono::steady_clock::time_point::min());
  5127. })
  5128. .Get("/with-range-customized-response",
  5129. [&](const Request & /*req*/, Response &res) {
  5130. res.status = StatusCode::BadRequest_400;
  5131. res.set_content(JSON_DATA, "application/json");
  5132. })
  5133. .Post("/chunked",
  5134. [&](const Request &req, Response & /*res*/) {
  5135. EXPECT_EQ(req.body, "dechunked post body");
  5136. })
  5137. .Post("/large-chunked",
  5138. [&](const Request &req, Response & /*res*/) {
  5139. std::string expected(6 * 30 * 1024u, 'a');
  5140. EXPECT_EQ(req.body, expected);
  5141. })
  5142. .Post("/multipart",
  5143. [&](const Request &req, Response & /*res*/) {
  5144. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5145. req.form.get_field_count("text2") +
  5146. req.form.get_field_count("file3") +
  5147. req.form.get_field_count("file4"));
  5148. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5149. req.form.get_file_count("file2"));
  5150. ASSERT_TRUE(!req.form.has_file("???"));
  5151. ASSERT_TRUE(!req.form.has_field("???"));
  5152. ASSERT_TRUE(req.body.empty());
  5153. {
  5154. const auto &text = req.form.get_field("text1");
  5155. EXPECT_EQ("text default", text);
  5156. }
  5157. {
  5158. const auto &text = req.form.get_field("text2");
  5159. EXPECT_EQ("aωb", text);
  5160. }
  5161. {
  5162. const auto &file = req.form.get_file("file1");
  5163. EXPECT_EQ("hello.txt", file.filename);
  5164. EXPECT_EQ("text/plain", file.content_type);
  5165. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5166. }
  5167. {
  5168. const auto &file = req.form.get_file("file2");
  5169. EXPECT_EQ("world.json", file.filename);
  5170. EXPECT_EQ("application/json", file.content_type);
  5171. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5172. }
  5173. {
  5174. const auto &text = req.form.get_field("file3");
  5175. EXPECT_EQ(0u, text.size());
  5176. }
  5177. {
  5178. const auto &text = req.form.get_field("file4");
  5179. EXPECT_EQ(0u, text.size());
  5180. }
  5181. })
  5182. .Post("/multipart/multi_file_values",
  5183. [&](const Request &req, Response & /*res*/) {
  5184. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5185. req.form.get_field_count("multi_text1"));
  5186. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5187. ASSERT_TRUE(!req.form.has_file("???"));
  5188. ASSERT_TRUE(!req.form.has_field("???"));
  5189. ASSERT_TRUE(req.body.empty());
  5190. {
  5191. const auto &text = req.form.get_field("text");
  5192. EXPECT_EQ("default text", text);
  5193. }
  5194. {
  5195. const auto &text1_values = req.form.get_fields("multi_text1");
  5196. EXPECT_EQ(2u, text1_values.size());
  5197. EXPECT_EQ("aaaaa", text1_values[0]);
  5198. EXPECT_EQ("bbbbb", text1_values[1]);
  5199. }
  5200. {
  5201. const auto &file1_values = req.form.get_files("multi_file1");
  5202. EXPECT_EQ(2u, file1_values.size());
  5203. auto file1 = file1_values[0];
  5204. EXPECT_EQ(file1.filename, "hello.txt");
  5205. EXPECT_EQ(file1.content_type, "text/plain");
  5206. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5207. auto file2 = file1_values[1];
  5208. EXPECT_EQ(file2.filename, "world.json");
  5209. EXPECT_EQ(file2.content_type, "application/json");
  5210. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5211. }
  5212. })
  5213. .Post("/empty",
  5214. [&](const Request &req, Response &res) {
  5215. EXPECT_EQ(req.body, "");
  5216. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5217. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5218. res.set_content("empty", "text/plain");
  5219. })
  5220. .Post("/empty-no-content-type",
  5221. [&](const Request &req, Response &res) {
  5222. EXPECT_EQ(req.body, "");
  5223. EXPECT_FALSE(req.has_header("Content-Type"));
  5224. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5225. res.set_content("empty-no-content-type", "text/plain");
  5226. })
  5227. .Post("/path-only",
  5228. [&](const Request &req, Response &res) {
  5229. EXPECT_EQ(req.body, "");
  5230. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5231. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5232. res.set_content("path-only", "text/plain");
  5233. })
  5234. .Post("/path-headers-only",
  5235. [&](const Request &req, Response &res) {
  5236. EXPECT_EQ(req.body, "");
  5237. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5238. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5239. EXPECT_EQ("world", req.get_header_value("hello"));
  5240. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5241. res.set_content("path-headers-only", "text/plain");
  5242. })
  5243. .Post("/post-large",
  5244. [&](const Request &req, Response &res) {
  5245. EXPECT_EQ(req.body, LARGE_DATA);
  5246. res.set_content(req.body, "text/plain");
  5247. })
  5248. .Post("/post-loopback",
  5249. [&](const Request &, Response &res,
  5250. ContentReader const &content_reader) {
  5251. std::string body;
  5252. content_reader([&](const char *data, size_t data_length) {
  5253. body.append(data, data_length);
  5254. return true;
  5255. });
  5256. res.set_content(body, "text/plain");
  5257. })
  5258. .Put("/put-loopback",
  5259. [&](const Request &, Response &res,
  5260. ContentReader const &content_reader) {
  5261. std::string body;
  5262. content_reader([&](const char *data, size_t data_length) {
  5263. body.append(data, data_length);
  5264. return true;
  5265. });
  5266. res.set_content(body, "text/plain");
  5267. })
  5268. .Patch("/patch-loopback",
  5269. [&](const Request &, Response &res,
  5270. ContentReader const &content_reader) {
  5271. std::string body;
  5272. content_reader([&](const char *data, size_t data_length) {
  5273. body.append(data, data_length);
  5274. return true;
  5275. });
  5276. res.set_content(body, "text/plain");
  5277. })
  5278. .Put("/empty-no-content-type",
  5279. [&](const Request &req, Response &res) {
  5280. EXPECT_EQ(req.body, "");
  5281. EXPECT_FALSE(req.has_header("Content-Type"));
  5282. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5283. res.set_content("empty-no-content-type", "text/plain");
  5284. })
  5285. .Put("/put",
  5286. [&](const Request &req, Response &res) {
  5287. EXPECT_EQ(req.body, "PUT");
  5288. res.set_content(req.body, "text/plain");
  5289. })
  5290. .Put("/put-large",
  5291. [&](const Request &req, Response &res) {
  5292. EXPECT_EQ(req.body, LARGE_DATA);
  5293. res.set_content(req.body, "text/plain");
  5294. })
  5295. .Patch("/patch",
  5296. [&](const Request &req, Response &res) {
  5297. EXPECT_EQ(req.body, "PATCH");
  5298. res.set_content(req.body, "text/plain");
  5299. })
  5300. .Delete("/delete",
  5301. [&](const Request & /*req*/, Response &res) {
  5302. res.set_content("DELETE", "text/plain");
  5303. })
  5304. .Delete("/delete-body",
  5305. [&](const Request &req, Response &res) {
  5306. EXPECT_EQ(req.body, "content");
  5307. res.set_content(req.body, "text/plain");
  5308. })
  5309. .Options(R"(\*)",
  5310. [&](const Request & /*req*/, Response &res) {
  5311. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5312. })
  5313. .CustomRoute("PROPFIND", "/dav/:id",
  5314. [&](const Request &req, Response &res) {
  5315. res.set_header("x-body-size",
  5316. std::to_string(req.body.size()));
  5317. res.set_header("x-matched-route", req.matched_route);
  5318. res.set_header("x-dav-id", req.path_params.at("id"));
  5319. res.status = StatusCode::MultiStatus_207;
  5320. res.set_content(req.body, "application/xml");
  5321. })
  5322. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5323. [&](const Request &req, Response &res) {
  5324. res.set_header("x-dav-match", req.matches[1]);
  5325. res.status = StatusCode::MultiStatus_207;
  5326. })
  5327. .CustomRoute("MKCOL", "/dav-mkcol",
  5328. [&](const Request &req, Response &res) {
  5329. EXPECT_TRUE(req.body.empty());
  5330. res.status = StatusCode::Created_201;
  5331. })
  5332. .CustomRoute(
  5333. "REPORT", "/dav-report",
  5334. [&](const Request & /*req*/, Response &res,
  5335. const ContentReader &content_reader) {
  5336. std::string body;
  5337. content_reader([&](const char *data, size_t data_length) {
  5338. body.append(data, data_length);
  5339. return true;
  5340. });
  5341. res.set_header("x-body-size", std::to_string(body.size()));
  5342. res.status = StatusCode::MultiStatus_207;
  5343. res.set_content(body, "application/xml");
  5344. })
  5345. .Get("/request-target",
  5346. [&](const Request &req, Response & /*res*/) {
  5347. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5348. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5349. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5350. })
  5351. .Get("/long-query-value",
  5352. [&](const Request &req, Response & /*res*/) {
  5353. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5354. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5355. })
  5356. .Get("/too-long-query-value",
  5357. [&](const Request &req, Response & /*res*/) {
  5358. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5359. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5360. })
  5361. .Get("/array-param",
  5362. [&](const Request &req, Response & /*res*/) {
  5363. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5364. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5365. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5366. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5367. })
  5368. .Get("/array-param-values",
  5369. [&](const Request &req, Response & /*res*/) {
  5370. auto values = req.get_param_values("array");
  5371. EXPECT_EQ(3u, values.size());
  5372. EXPECT_EQ("value1", values[0]);
  5373. EXPECT_EQ("value2", values[1]);
  5374. EXPECT_EQ("value3", values[2]);
  5375. auto empty = req.get_param_values("nonexistent");
  5376. EXPECT_TRUE(empty.empty());
  5377. })
  5378. .Post("/validate-no-multiple-headers",
  5379. [&](const Request &req, Response & /*res*/) {
  5380. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5381. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5382. })
  5383. .Post("/content_receiver",
  5384. [&](const Request &req, Response &res,
  5385. const ContentReader &content_reader) {
  5386. if (req.is_multipart_form_data()) {
  5387. std::vector<FormData> items;
  5388. content_reader(
  5389. [&](const FormData &file) {
  5390. items.push_back(file);
  5391. return true;
  5392. },
  5393. [&](const char *data, size_t data_length) {
  5394. items.back().content.append(data, data_length);
  5395. return true;
  5396. });
  5397. EXPECT_EQ(5u, items.size());
  5398. {
  5399. const auto &file = get_file_value(items, "text1");
  5400. EXPECT_TRUE(file.filename.empty());
  5401. EXPECT_EQ("text default", file.content);
  5402. }
  5403. {
  5404. const auto &file = get_file_value(items, "text2");
  5405. EXPECT_TRUE(file.filename.empty());
  5406. EXPECT_EQ("aωb", file.content);
  5407. }
  5408. {
  5409. const auto &file = get_file_value(items, "file1");
  5410. EXPECT_EQ("hello.txt", file.filename);
  5411. EXPECT_EQ("text/plain", file.content_type);
  5412. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5413. }
  5414. {
  5415. const auto &file = get_file_value(items, "file2");
  5416. EXPECT_EQ("world.json", file.filename);
  5417. EXPECT_EQ("application/json", file.content_type);
  5418. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5419. }
  5420. {
  5421. const auto &file = get_file_value(items, "file3");
  5422. EXPECT_TRUE(file.filename.empty());
  5423. EXPECT_EQ("application/octet-stream", file.content_type);
  5424. EXPECT_EQ(0u, file.content.size());
  5425. }
  5426. } else {
  5427. std::string body;
  5428. content_reader([&](const char *data, size_t data_length) {
  5429. EXPECT_EQ(7U, data_length);
  5430. body.append(data, data_length);
  5431. return true;
  5432. });
  5433. EXPECT_EQ(body, "content");
  5434. res.set_content(body, "text/plain");
  5435. }
  5436. })
  5437. .Put("/content_receiver",
  5438. [&](const Request & /*req*/, Response &res,
  5439. const ContentReader &content_reader) {
  5440. std::string body;
  5441. content_reader([&](const char *data, size_t data_length) {
  5442. body.append(data, data_length);
  5443. return true;
  5444. });
  5445. EXPECT_EQ(body, "content");
  5446. res.set_content(body, "text/plain");
  5447. })
  5448. .Patch("/content_receiver",
  5449. [&](const Request & /*req*/, Response &res,
  5450. const ContentReader &content_reader) {
  5451. std::string body;
  5452. content_reader([&](const char *data, size_t data_length) {
  5453. body.append(data, data_length);
  5454. return true;
  5455. });
  5456. EXPECT_EQ(body, "content");
  5457. res.set_content(body, "text/plain");
  5458. })
  5459. .Post("/query-string-and-body",
  5460. [&](const Request &req, Response & /*res*/) {
  5461. ASSERT_TRUE(req.has_param("key"));
  5462. EXPECT_EQ(req.get_param_value("key"), "value");
  5463. EXPECT_EQ(req.body, "content");
  5464. })
  5465. .Get("/last-request",
  5466. [&](const Request &req, Response & /*res*/) {
  5467. EXPECT_EQ("close", req.get_header_value("Connection"));
  5468. })
  5469. .Get(R"(/redirect/(\d+))",
  5470. [&](const Request &req, Response &res) {
  5471. auto num = std::stoi(req.matches[1]) + 1;
  5472. std::string url = "/redirect/" + std::to_string(num);
  5473. res.set_redirect(url);
  5474. })
  5475. .Post("/binary",
  5476. [&](const Request &req, Response &res) {
  5477. EXPECT_EQ(4U, req.body.size());
  5478. EXPECT_EQ("application/octet-stream",
  5479. req.get_header_value("Content-Type"));
  5480. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5481. res.set_content(req.body, "application/octet-stream");
  5482. })
  5483. .Put("/binary",
  5484. [&](const Request &req, Response &res) {
  5485. EXPECT_EQ(4U, req.body.size());
  5486. EXPECT_EQ("application/octet-stream",
  5487. req.get_header_value("Content-Type"));
  5488. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5489. res.set_content(req.body, "application/octet-stream");
  5490. })
  5491. .Patch("/binary",
  5492. [&](const Request &req, Response &res) {
  5493. EXPECT_EQ(4U, req.body.size());
  5494. EXPECT_EQ("application/octet-stream",
  5495. req.get_header_value("Content-Type"));
  5496. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5497. res.set_content(req.body, "application/octet-stream");
  5498. })
  5499. .Delete("/binary",
  5500. [&](const Request &req, Response &res) {
  5501. EXPECT_EQ(4U, req.body.size());
  5502. EXPECT_EQ("application/octet-stream",
  5503. req.get_header_value("Content-Type"));
  5504. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5505. res.set_content(req.body, "application/octet-stream");
  5506. })
  5507. .Get("/issue1772",
  5508. [&](const Request & /*req*/, Response &res) {
  5509. res.status = 401;
  5510. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5511. })
  5512. .Delete("/issue609",
  5513. [](const httplib::Request &, httplib::Response &res,
  5514. const httplib::ContentReader &) {
  5515. res.set_content("ok", "text/plain");
  5516. })
  5517. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5518. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5519. .Get("/compress",
  5520. [&](const Request & /*req*/, Response &res) {
  5521. res.set_content(
  5522. "12345678901234567890123456789012345678901234567890123456789"
  5523. "01234567890123456789012345678901234567890",
  5524. "text/plain");
  5525. })
  5526. .Get("/compress-with-charset",
  5527. [&](const Request & /*req*/, Response &res) {
  5528. res.set_content(
  5529. "12345678901234567890123456789012345678901234567890123456789"
  5530. "01234567890123456789012345678901234567890",
  5531. "application/json; charset=utf-8");
  5532. })
  5533. .Get("/nocompress",
  5534. [&](const Request & /*req*/, Response &res) {
  5535. res.set_content(
  5536. "12345678901234567890123456789012345678901234567890123456789"
  5537. "01234567890123456789012345678901234567890",
  5538. "application/octet-stream");
  5539. })
  5540. .Post("/compress-multipart",
  5541. [&](const Request &req, Response & /*res*/) {
  5542. EXPECT_EQ(2u, req.form.fields.size());
  5543. ASSERT_TRUE(!req.form.has_field("???"));
  5544. {
  5545. const auto &text = req.form.get_field("key1");
  5546. EXPECT_EQ("test", text);
  5547. }
  5548. {
  5549. const auto &text = req.form.get_field("key2");
  5550. EXPECT_EQ("--abcdefg123", text);
  5551. }
  5552. })
  5553. #endif
  5554. ;
  5555. persons_["john"] = "programmer";
  5556. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5557. svr_.wait_until_ready();
  5558. }
  5559. virtual void TearDown() {
  5560. svr_.stop();
  5561. if (!request_threads_.empty()) {
  5562. std::this_thread::sleep_for(std::chrono::seconds(1));
  5563. for (auto &t : request_threads_) {
  5564. t.join();
  5565. }
  5566. }
  5567. t_.join();
  5568. }
  5569. map<string, string> persons_;
  5570. #ifdef CPPHTTPLIB_SSL_ENABLED
  5571. SSLClient cli_;
  5572. SSLServer svr_;
  5573. #else
  5574. Client cli_;
  5575. Server svr_;
  5576. #endif
  5577. thread t_;
  5578. std::vector<thread> request_threads_;
  5579. };
  5580. TEST_F(ServerTest, GetMethod200) {
  5581. auto res = cli_.Get("/hi");
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. EXPECT_EQ("HTTP/1.1", res->version);
  5584. EXPECT_EQ(StatusCode::OK_200, res->status);
  5585. EXPECT_EQ("OK", res->reason);
  5586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5587. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5588. EXPECT_EQ("Hello World!", res->body);
  5589. }
  5590. TEST_F(ServerTest, GetEmptyFile) {
  5591. auto res = cli_.Get("/empty_file");
  5592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5593. EXPECT_EQ(StatusCode::OK_200, res->status);
  5594. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5595. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5596. EXPECT_EQ("", res->body);
  5597. }
  5598. TEST_F(ServerTest, GetFileContent) {
  5599. auto res = cli_.Get("/file_content");
  5600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5601. EXPECT_EQ(StatusCode::OK_200, res->status);
  5602. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5603. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5604. EXPECT_EQ("test.html", res->body);
  5605. }
  5606. TEST_F(ServerTest, GetFileContentWithRange) {
  5607. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5610. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5611. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5612. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5613. EXPECT_EQ("est", res->body);
  5614. }
  5615. TEST_F(ServerTest, GetFileContentWithContentType) {
  5616. auto res = cli_.Get("/file_content_with_content_type");
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. EXPECT_EQ(StatusCode::OK_200, res->status);
  5619. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5620. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5621. EXPECT_EQ("file\n", res->body);
  5622. }
  5623. TEST_F(ServerTest, GetInvalidFileContent) {
  5624. auto res = cli_.Get("/invalid_file_content");
  5625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5627. }
  5628. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5629. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ("HTTP/1.1", res->version);
  5632. EXPECT_EQ(StatusCode::OK_200, res->status);
  5633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5634. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5635. EXPECT_EQ("Hello World!", res->body);
  5636. }
  5637. TEST_F(ServerTest, GetMethod302) {
  5638. auto res = cli_.Get("/");
  5639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5640. EXPECT_EQ(StatusCode::Found_302, res->status);
  5641. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5642. }
  5643. TEST_F(ServerTest, GetMethod302Redirect) {
  5644. cli_.set_follow_location(true);
  5645. auto res = cli_.Get("/");
  5646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5647. EXPECT_EQ(StatusCode::OK_200, res->status);
  5648. EXPECT_EQ("Hello World!", res->body);
  5649. EXPECT_EQ("/hi", res->location);
  5650. }
  5651. TEST_F(ServerTest, GetMethod404) {
  5652. auto res = cli_.Get("/invalid");
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5655. }
  5656. TEST_F(ServerTest, HeadMethod200) {
  5657. auto res = cli_.Head("/hi");
  5658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5659. EXPECT_EQ(StatusCode::OK_200, res->status);
  5660. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5661. EXPECT_TRUE(res->body.empty());
  5662. }
  5663. TEST_F(ServerTest, HeadMethod200Static) {
  5664. auto res = cli_.Head("/mount/dir/index.html");
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. EXPECT_EQ(StatusCode::OK_200, res->status);
  5667. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5668. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5669. EXPECT_TRUE(res->body.empty());
  5670. }
  5671. TEST_F(ServerTest, HeadMethod404) {
  5672. auto res = cli_.Head("/invalid");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5675. EXPECT_TRUE(res->body.empty());
  5676. }
  5677. TEST_F(ServerTest, GetMethodPersonJohn) {
  5678. auto res = cli_.Get("/person/john");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5682. EXPECT_EQ("programmer", res->body);
  5683. }
  5684. TEST_F(ServerTest, PostMethod1) {
  5685. auto res = cli_.Get("/person/john1");
  5686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5687. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5688. res = cli_.Post("/person", "name=john1&note=coder",
  5689. "application/x-www-form-urlencoded");
  5690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5691. ASSERT_EQ(StatusCode::OK_200, res->status);
  5692. res = cli_.Get("/person/john1");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::OK_200, res->status);
  5695. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5696. ASSERT_EQ("coder", res->body);
  5697. }
  5698. TEST_F(ServerTest, PostMethod2) {
  5699. auto res = cli_.Get("/person/john2");
  5700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5701. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5702. Params params;
  5703. params.emplace("name", "john2");
  5704. params.emplace("note", "coder");
  5705. res = cli_.Post("/person", params);
  5706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5707. ASSERT_EQ(StatusCode::OK_200, res->status);
  5708. res = cli_.Get("/person/john2");
  5709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5710. ASSERT_EQ(StatusCode::OK_200, res->status);
  5711. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5712. ASSERT_EQ("coder", res->body);
  5713. }
  5714. TEST_F(ServerTest, PutMethod3) {
  5715. auto res = cli_.Get("/person/john3");
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5718. Params params;
  5719. params.emplace("name", "john3");
  5720. params.emplace("note", "coder");
  5721. res = cli_.Put("/person", params);
  5722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5723. ASSERT_EQ(StatusCode::OK_200, res->status);
  5724. res = cli_.Get("/person/john3");
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. ASSERT_EQ(StatusCode::OK_200, res->status);
  5727. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5728. ASSERT_EQ("coder", res->body);
  5729. }
  5730. TEST_F(ServerTest, DeleteMethod1) {
  5731. auto res = cli_.Get("/person/john4");
  5732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5733. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5734. Params params;
  5735. params.emplace("name", "john4");
  5736. params.emplace("note", "coder");
  5737. res = cli_.Post("/person", params);
  5738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5739. ASSERT_EQ(StatusCode::OK_200, res->status);
  5740. res = cli_.Get("/person/john4");
  5741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5742. ASSERT_EQ(StatusCode::OK_200, res->status);
  5743. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5744. ASSERT_EQ("coder", res->body);
  5745. Params delete_params;
  5746. delete_params.emplace("name", "john4");
  5747. res = cli_.Delete("/person", delete_params);
  5748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5749. ASSERT_EQ(StatusCode::OK_200, res->status);
  5750. ASSERT_EQ("DELETED", res->body);
  5751. res = cli_.Get("/person/john4");
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5754. }
  5755. TEST_F(ServerTest, DeleteMethod2) {
  5756. auto res = cli_.Get("/person/john5");
  5757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5758. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5759. Params params;
  5760. params.emplace("name", "john5");
  5761. params.emplace("note", "developer");
  5762. res = cli_.Post("/person", params);
  5763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5764. ASSERT_EQ(StatusCode::OK_200, res->status);
  5765. res = cli_.Get("/person/john5");
  5766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5767. ASSERT_EQ(StatusCode::OK_200, res->status);
  5768. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5769. ASSERT_EQ("developer", res->body);
  5770. Params delete_params;
  5771. delete_params.emplace("name", "john5");
  5772. Headers headers;
  5773. headers.emplace("Custom-Header", "test-value");
  5774. res = cli_.Delete("/person", headers, delete_params);
  5775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5776. ASSERT_EQ(StatusCode::OK_200, res->status);
  5777. ASSERT_EQ("DELETED", res->body);
  5778. res = cli_.Get("/person/john5");
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5781. }
  5782. TEST_F(ServerTest, DeleteMethod3) {
  5783. auto res = cli_.Get("/person/john6");
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5786. Params params;
  5787. params.emplace("name", "john6");
  5788. params.emplace("note", "tester");
  5789. res = cli_.Post("/person", params);
  5790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5791. ASSERT_EQ(StatusCode::OK_200, res->status);
  5792. res = cli_.Get("/person/john6");
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. ASSERT_EQ(StatusCode::OK_200, res->status);
  5795. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5796. ASSERT_EQ("tester", res->body);
  5797. Params delete_params;
  5798. delete_params.emplace("name", "john6");
  5799. Headers headers;
  5800. headers.emplace("Custom-Header", "test-value");
  5801. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5803. ASSERT_EQ(StatusCode::OK_200, res->status);
  5804. ASSERT_EQ("DELETED", res->body);
  5805. res = cli_.Get("/person/john6");
  5806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5807. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5808. }
  5809. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5810. Params params;
  5811. params.emplace("json", JSON_DATA);
  5812. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5814. ASSERT_EQ(StatusCode::OK_200, res->status);
  5815. ASSERT_EQ(JSON_DATA, res->body);
  5816. }
  5817. TEST_F(ServerTest, PostEmptyContent) {
  5818. auto res = cli_.Post("/empty", "", "text/plain");
  5819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5820. ASSERT_EQ(StatusCode::OK_200, res->status);
  5821. ASSERT_EQ("empty", res->body);
  5822. }
  5823. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5824. auto res = cli_.Post("/empty-no-content-type");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. ASSERT_EQ(StatusCode::OK_200, res->status);
  5827. ASSERT_EQ("empty-no-content-type", res->body);
  5828. }
  5829. TEST_F(ServerTest, PostPathOnly) {
  5830. auto res = cli_.Post("/path-only");
  5831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5832. ASSERT_EQ(StatusCode::OK_200, res->status);
  5833. ASSERT_EQ("path-only", res->body);
  5834. }
  5835. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5836. auto res = cli_.Post("/path-headers-only",
  5837. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5839. ASSERT_EQ(StatusCode::OK_200, res->status);
  5840. ASSERT_EQ("path-headers-only", res->body);
  5841. }
  5842. TEST_F(ServerTest, PostLarge) {
  5843. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5845. ASSERT_EQ(StatusCode::OK_200, res->status);
  5846. EXPECT_EQ(LARGE_DATA, res->body);
  5847. }
  5848. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5849. auto res = cli_.Put("/empty-no-content-type");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. ASSERT_EQ(StatusCode::OK_200, res->status);
  5852. ASSERT_EQ("empty-no-content-type", res->body);
  5853. }
  5854. TEST_F(ServerTest, GetMethodDir) {
  5855. auto res = cli_.Get("/dir/");
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. EXPECT_EQ(StatusCode::OK_200, res->status);
  5858. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5859. auto body = R"(<html>
  5860. <head>
  5861. </head>
  5862. <body>
  5863. <a href="/dir/test.html">Test</a>
  5864. <a href="/hi">hi</a>
  5865. </body>
  5866. </html>
  5867. )";
  5868. EXPECT_EQ(body, res->body);
  5869. }
  5870. TEST_F(ServerTest, GetMethodDirTest) {
  5871. auto res = cli_.Get("/dir/test.html");
  5872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5873. EXPECT_EQ(StatusCode::OK_200, res->status);
  5874. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5875. EXPECT_EQ("test.html", res->body);
  5876. }
  5877. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5878. auto res = cli_.Get("/dir/../dir/test.html");
  5879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5880. EXPECT_EQ(StatusCode::OK_200, res->status);
  5881. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5882. EXPECT_EQ("test.html", res->body);
  5883. }
  5884. TEST_F(ServerTest, GetMethodInvalidPath) {
  5885. auto res = cli_.Get("/dir/../test.html");
  5886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5887. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5888. }
  5889. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5890. auto res = cli_.Get("/../www/dir/test.html");
  5891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5892. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5893. }
  5894. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5895. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5897. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5898. }
  5899. TEST_F(ServerTest, GetMethodDirMountTest) {
  5900. auto res = cli_.Get("/mount/dir/test.html");
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. EXPECT_EQ(StatusCode::OK_200, res->status);
  5903. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5904. EXPECT_EQ("test.html", res->body);
  5905. }
  5906. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5907. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5909. EXPECT_EQ(StatusCode::OK_200, res->status);
  5910. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5911. EXPECT_EQ("test.html", res->body);
  5912. }
  5913. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5914. auto res = cli_.Get("/mount/dir/../test.html");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5917. }
  5918. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5919. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5921. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5922. }
  5923. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5924. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5926. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5927. }
  5928. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5929. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5932. }
  5933. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5934. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5936. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5937. }
  5938. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5939. auto res = cli_.Get("/mount/dir");
  5940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5941. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5942. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5943. }
  5944. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5945. auto res = cli_.Get("//dir");
  5946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5947. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5948. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5949. }
  5950. TEST_F(ServerTest, PostMethod303) {
  5951. auto res = cli_.Post("/1", "body", "text/plain");
  5952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5953. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5954. EXPECT_EQ("/2", res->get_header_value("Location"));
  5955. }
  5956. TEST_F(ServerTest, PostMethod303Redirect) {
  5957. cli_.set_follow_location(true);
  5958. auto res = cli_.Post("/1", "body", "text/plain");
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. EXPECT_EQ(StatusCode::OK_200, res->status);
  5961. EXPECT_EQ("redirected.", res->body);
  5962. EXPECT_EQ("/2", res->location);
  5963. }
  5964. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5965. auto res = cli_.Get("/dir/test.abcde");
  5966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5969. EXPECT_EQ("abcde", res->body);
  5970. }
  5971. TEST_F(ServerTest, StaticFileRange) {
  5972. auto res =
  5973. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5975. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5976. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5977. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5978. EXPECT_EQ(true, res->has_header("Content-Range"));
  5979. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5980. EXPECT_EQ(std::string("cd"), res->body);
  5981. }
  5982. TEST_F(ServerTest, StaticFileRanges) {
  5983. auto res = cli_.Get("/dir/test.abcde",
  5984. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5987. EXPECT_TRUE(
  5988. res->get_header_value("Content-Type")
  5989. .find(
  5990. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5991. 0);
  5992. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5993. }
  5994. TEST_F(ServerTest, StaticFileRangeHead) {
  5995. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5998. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5999. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6000. EXPECT_EQ(true, res->has_header("Content-Range"));
  6001. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6002. }
  6003. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6004. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6007. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6008. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6009. EXPECT_EQ(true, res->has_header("Content-Range"));
  6010. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6011. res->get_header_value("Content-Range"));
  6012. EXPECT_EQ("LAST\n", res->body);
  6013. }
  6014. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6015. auto res =
  6016. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6019. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6020. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6021. EXPECT_EQ(true, res->has_header("Content-Range"));
  6022. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6023. }
  6024. TEST_F(ServerTest, StaticFileBigFile) {
  6025. auto res = cli_.Get("/dir/1MB.txt");
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::OK_200, res->status);
  6028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6030. }
  6031. TEST_F(ServerTest, InvalidBaseDirMount) {
  6032. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6033. }
  6034. TEST_F(ServerTest, Binary) {
  6035. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6036. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6037. "application/octet-stream");
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. ASSERT_EQ(StatusCode::OK_200, res->status);
  6040. ASSERT_EQ(4U, res->body.size());
  6041. res = cli_.Put("/binary", binary.data(), binary.size(),
  6042. "application/octet-stream");
  6043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6044. ASSERT_EQ(StatusCode::OK_200, res->status);
  6045. ASSERT_EQ(4U, res->body.size());
  6046. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6047. "application/octet-stream");
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. ASSERT_EQ(StatusCode::OK_200, res->status);
  6050. ASSERT_EQ(4U, res->body.size());
  6051. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6052. "application/octet-stream");
  6053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6054. ASSERT_EQ(StatusCode::OK_200, res->status);
  6055. ASSERT_EQ(4U, res->body.size());
  6056. }
  6057. TEST_F(ServerTest, BinaryString) {
  6058. auto binary = std::string("\x00\x01\x02\x03", 4);
  6059. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6061. ASSERT_EQ(StatusCode::OK_200, res->status);
  6062. ASSERT_EQ(4U, res->body.size());
  6063. res = cli_.Put("/binary", binary, "application/octet-stream");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. ASSERT_EQ(StatusCode::OK_200, res->status);
  6066. ASSERT_EQ(4U, res->body.size());
  6067. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. ASSERT_EQ(StatusCode::OK_200, res->status);
  6070. ASSERT_EQ(4U, res->body.size());
  6071. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6073. ASSERT_EQ(StatusCode::OK_200, res->status);
  6074. ASSERT_EQ(4U, res->body.size());
  6075. }
  6076. TEST_F(ServerTest, EmptyRequest) {
  6077. auto res = cli_.Get("");
  6078. ASSERT_TRUE(!res);
  6079. EXPECT_EQ(Error::Connection, res.error());
  6080. }
  6081. TEST_F(ServerTest, LongRequest) {
  6082. std::string request;
  6083. for (size_t i = 0; i < 545; i++) {
  6084. request += "/TooLongRequest";
  6085. }
  6086. request += "OK";
  6087. auto res = cli_.Get(request.c_str());
  6088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6089. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6090. }
  6091. TEST_F(ServerTest, TooLongRequest) {
  6092. std::string request;
  6093. for (size_t i = 0; i < 546; i++) {
  6094. request += "/TooLongRequest";
  6095. }
  6096. request += "_NG";
  6097. auto start = std::chrono::high_resolution_clock::now();
  6098. cli_.set_keep_alive(true);
  6099. auto res = cli_.Get(request.c_str());
  6100. auto end = std::chrono::high_resolution_clock::now();
  6101. auto elapsed =
  6102. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6103. .count();
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6106. EXPECT_LE(elapsed, 1000);
  6107. EXPECT_EQ("close", res->get_header_value("Connection"));
  6108. EXPECT_FALSE(cli_.is_socket_open());
  6109. }
  6110. TEST_F(ServerTest, AlmostTooLongRequest) {
  6111. // test for #2046 - URI length check shouldn't include other content on req
  6112. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6113. // leading /, space, HTTP/1.1)
  6114. std::string request =
  6115. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6116. auto res = cli_.Get(request.c_str());
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6119. }
  6120. TEST_F(ServerTest, LongHeader) {
  6121. Request req;
  6122. req.method = "GET";
  6123. req.path = "/hi";
  6124. std::string host_and_port;
  6125. host_and_port += HOST;
  6126. host_and_port += ":";
  6127. host_and_port += std::to_string(PORT);
  6128. req.headers.emplace("Host", host_and_port.c_str());
  6129. req.headers.emplace("Accept", "*/*");
  6130. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6131. req.headers.emplace(
  6132. "Header-Name",
  6133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@");
  6162. auto res = std::make_shared<Response>();
  6163. auto error = Error::Success;
  6164. auto ret = cli_.send(req, *res, error);
  6165. ASSERT_TRUE(ret);
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. }
  6168. TEST_F(ServerTest, LongQueryValue) {
  6169. auto start = std::chrono::high_resolution_clock::now();
  6170. cli_.set_keep_alive(true);
  6171. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6172. auto end = std::chrono::high_resolution_clock::now();
  6173. auto elapsed =
  6174. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6175. .count();
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6178. EXPECT_LE(elapsed, 1000);
  6179. EXPECT_EQ("close", res->get_header_value("Connection"));
  6180. EXPECT_FALSE(cli_.is_socket_open());
  6181. }
  6182. TEST_F(ServerTest, TooLongQueryValue) {
  6183. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6184. ASSERT_FALSE(res);
  6185. EXPECT_EQ(Error::Read, res.error());
  6186. }
  6187. TEST_F(ServerTest, TooLongHeader) {
  6188. Request req;
  6189. req.method = "GET";
  6190. req.path = "/hi";
  6191. std::string host_and_port;
  6192. host_and_port += HOST;
  6193. host_and_port += ":";
  6194. host_and_port += std::to_string(PORT);
  6195. req.headers.emplace("Host", host_and_port.c_str());
  6196. req.headers.emplace("Accept", "*/*");
  6197. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6198. req.headers.emplace(
  6199. "Header-Name",
  6200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6227. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6228. "@@@@@@@@@@@@@@@@@");
  6229. auto res = std::make_shared<Response>();
  6230. auto error = Error::Success;
  6231. auto ret = cli_.send(req, *res, error);
  6232. ASSERT_TRUE(ret);
  6233. EXPECT_EQ(StatusCode::OK_200, res->status);
  6234. }
  6235. TEST_F(ServerTest, HeaderCountAtLimit) {
  6236. // Test with headers just under the 100 limit
  6237. httplib::Headers headers;
  6238. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6239. // This should keep us just under the 100 header limit
  6240. for (int i = 0; i < 95; i++) {
  6241. std::string name = "X-Test-Header-" + std::to_string(i);
  6242. std::string value = "value" + std::to_string(i);
  6243. headers.emplace(name, value);
  6244. }
  6245. // This should work fine as we're under the limit
  6246. auto res = cli_.Get("/hi", headers);
  6247. EXPECT_TRUE(res);
  6248. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6249. }
  6250. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6251. // Test with many headers to exceed the 100 limit
  6252. httplib::Headers headers;
  6253. // Add 150 headers to definitely exceed the 100 limit
  6254. for (int i = 0; i < 150; i++) {
  6255. std::string name = "X-Test-Header-" + std::to_string(i);
  6256. std::string value = "value" + std::to_string(i);
  6257. headers.emplace(name, value);
  6258. }
  6259. // This should fail due to exceeding header count limit
  6260. cli_.set_keep_alive(true);
  6261. auto res = cli_.Get("/hi", headers);
  6262. // The server should respond with 400 Bad Request
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6265. EXPECT_EQ("close", res->get_header_value("Connection"));
  6266. EXPECT_FALSE(cli_.is_socket_open());
  6267. }
  6268. TEST_F(ServerTest, PercentEncoding) {
  6269. auto res = cli_.Get("/e%6edwith%");
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::OK_200, res->status);
  6272. }
  6273. TEST_F(ServerTest, PercentEncodingUnicode) {
  6274. auto res = cli_.Get("/e%u006edwith%");
  6275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. }
  6278. TEST_F(ServerTest, InvalidPercentEncoding) {
  6279. auto res = cli_.Get("/%endwith%");
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6282. }
  6283. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6284. auto res = cli_.Get("/%uendwith%");
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6287. }
  6288. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6289. auto res = cli_.Get("/hello?aaa=bbb%");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6292. }
  6293. TEST_F(ServerTest, PlusSignEncoding) {
  6294. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. EXPECT_EQ(StatusCode::OK_200, res->status);
  6297. EXPECT_EQ("a +b", res->body);
  6298. }
  6299. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6300. // This test simulates a potential DoS attack using many headers
  6301. // to verify our security fix prevents memory exhaustion
  6302. httplib::Headers attack_headers;
  6303. // Attempt to add many headers like an attacker would (200 headers to far
  6304. // exceed limit)
  6305. for (int i = 0; i < 200; i++) {
  6306. std::string name = "X-Attack-Header-" + std::to_string(i);
  6307. std::string value = "attack_payload_" + std::to_string(i);
  6308. attack_headers.emplace(name, value);
  6309. }
  6310. // Try to POST with excessive headers
  6311. cli_.set_keep_alive(true);
  6312. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6313. // Should either fail or return 400 Bad Request due to security limit
  6314. if (res) {
  6315. // If we get a response, it should be 400 Bad Request
  6316. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6317. EXPECT_EQ("close", res->get_header_value("Connection"));
  6318. }
  6319. EXPECT_FALSE(cli_.is_socket_open());
  6320. }
  6321. TEST_F(ServerTest, MultipartFormData) {
  6322. UploadFormDataItems items = {
  6323. {"text1", "text default", "", ""},
  6324. {"text2", "aωb", "", ""},
  6325. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6326. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6327. {"file3", "", "", "application/octet-stream"},
  6328. {"file4", "", "", " application/json tmp-string "}};
  6329. auto res = cli_.Post("/multipart", items);
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. EXPECT_EQ(StatusCode::OK_200, res->status);
  6332. }
  6333. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6334. UploadFormDataItems items = {
  6335. {"text", "default text", "", ""},
  6336. {"multi_text1", "aaaaa", "", ""},
  6337. {"multi_text1", "bbbbb", "", ""},
  6338. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6339. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6340. "application/json"},
  6341. };
  6342. auto res = cli_.Post("/multipart/multi_file_values", items);
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_EQ(StatusCode::OK_200, res->status);
  6345. }
  6346. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6347. auto res = cli_.Get("/hi");
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. EXPECT_EQ(StatusCode::OK_200, res->status);
  6350. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6351. EXPECT_EQ("Hello World!", res->body);
  6352. }
  6353. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6354. Request req;
  6355. req.method = "POST";
  6356. req.path = "/chunked";
  6357. std::string host_and_port;
  6358. host_and_port += HOST;
  6359. host_and_port += ":";
  6360. host_and_port += std::to_string(PORT);
  6361. req.headers.emplace("Host", host_and_port.c_str());
  6362. req.headers.emplace("Accept", "*/*");
  6363. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6364. req.headers.emplace("Content-Type", "text/plain");
  6365. req.headers.emplace("Content-Length", "0");
  6366. req.headers.emplace(
  6367. "Transfer-Encoding",
  6368. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6369. // Client does not chunk, so make a chunked body manually.
  6370. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6371. auto res = std::make_shared<Response>();
  6372. auto error = Error::Success;
  6373. auto ret = cli_.send(req, *res, error);
  6374. ASSERT_TRUE(ret);
  6375. EXPECT_EQ(StatusCode::OK_200, res->status);
  6376. }
  6377. template <typename ClientT>
  6378. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6379. int expected_status) {
  6380. Request req;
  6381. req.method = "POST";
  6382. req.path = "/chunked";
  6383. std::string host_and_port;
  6384. host_and_port += HOST;
  6385. host_and_port += ":";
  6386. host_and_port += std::to_string(PORT);
  6387. req.headers.emplace("Host", host_and_port.c_str());
  6388. req.headers.emplace("Content-Length", "0");
  6389. req.headers.emplace("Transfer-Encoding", "chunked");
  6390. req.body = body;
  6391. auto res = std::make_shared<Response>();
  6392. auto error = Error::Success;
  6393. ASSERT_TRUE(cli.send(req, *res, error));
  6394. EXPECT_EQ(expected_status, res->status);
  6395. }
  6396. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6397. // rather than treat them as valid lengths.
  6398. template <typename ClientT>
  6399. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6400. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6401. }
  6402. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6403. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6404. }
  6405. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6406. expect_chunked_body_rejected(
  6407. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6408. }
  6409. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6410. // chunk-size line carries no CR, LF or other control character ahead of its
  6411. // terminator. Such a line must be refused rather than read as extension text.
  6412. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6413. expect_chunked_body_rejected(
  6414. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6415. }
  6416. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6417. expect_chunked_body_rejected(
  6418. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6419. }
  6420. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6421. expect_chunked_body_rejected(
  6422. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6423. }
  6424. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6425. // The literal stays split: a hex escape consumes every hex digit that
  6426. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6427. expect_chunked_body_rejected(
  6428. cli_, "4;a\x01"
  6429. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6430. }
  6431. TEST_F(ServerTest, AcceptsChunkExtension) {
  6432. expect_chunked_body_status(cli_,
  6433. "4;name=value\r\ndech\r\n"
  6434. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6435. "0;last\r\n\r\n",
  6436. StatusCode::OK_200);
  6437. }
  6438. TEST_F(ServerTest, GetStreamed2) {
  6439. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6442. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6443. EXPECT_EQ(true, res->has_header("Content-Range"));
  6444. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6445. EXPECT_EQ(std::string("ab"), res->body);
  6446. }
  6447. TEST_F(ServerTest, GetStreamed) {
  6448. auto res = cli_.Get("/streamed");
  6449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6450. EXPECT_EQ(StatusCode::OK_200, res->status);
  6451. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6452. EXPECT_EQ(std::string("aaabbb"), res->body);
  6453. }
  6454. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6455. auto res = cli_.Get("/streamed-without-length",
  6456. Headers{make_range_header({{0, -1}})});
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::OK_200, res->status);
  6459. EXPECT_EQ(false, res->has_header("Content-Length"));
  6460. EXPECT_EQ(false, res->has_header("Content-Range"));
  6461. EXPECT_EQ(std::string("abcdefg"), res->body);
  6462. }
  6463. TEST_F(ServerTest, GetStreamedWithRange1) {
  6464. auto res =
  6465. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6468. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6469. EXPECT_EQ(true, res->has_header("Content-Range"));
  6470. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6471. EXPECT_EQ(std::string("def"), res->body);
  6472. }
  6473. TEST_F(ServerTest, GetStreamedWithRange2) {
  6474. auto res =
  6475. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6478. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6479. EXPECT_EQ(true, res->has_header("Content-Range"));
  6480. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6481. EXPECT_EQ(std::string("bcdefg"), res->body);
  6482. }
  6483. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6484. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6487. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6488. EXPECT_EQ(true, res->has_header("Content-Range"));
  6489. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6490. EXPECT_EQ(std::string("efg"), res->body);
  6491. }
  6492. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6493. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6494. // the entire representation.
  6495. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6496. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6499. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6500. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6501. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6502. }
  6503. }
  6504. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6505. auto res =
  6506. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6509. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6510. EXPECT_EQ(false, res->has_header("Content-Range"));
  6511. EXPECT_EQ(0U, res->body.size());
  6512. }
  6513. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6514. // Only a 206 is served as a partial representation. Under any other status
  6515. // `apply_ranges()` reported the full content length, so the body must match
  6516. // that header, and the content provider must never be asked for an offset
  6517. // outside the representation.
  6518. auto check = [&](int status, const char *range) {
  6519. auto path =
  6520. std::string("/streamed-with-range?status=") + std::to_string(status);
  6521. auto ctx = path + " Range: " + range;
  6522. auto res = cli_.Get(path, Headers{{"Range", range}});
  6523. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6524. EXPECT_EQ(status, res->status) << ctx;
  6525. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6526. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6527. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6528. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6529. };
  6530. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6531. check(403, "bytes=3-5");
  6532. // The offset is far past the representation.
  6533. check(403, "bytes=100000-100200");
  6534. // `first_pos` is still -1 here, and the bounds asserts in
  6535. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6536. check(403, "bytes=-3");
  6537. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6538. // multipart branch would have written one that is empty.
  6539. check(403, "bytes=1-2, 4-5");
  6540. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6541. // covers the whole representation.
  6542. check(200, "bytes=3-5");
  6543. check(200, "bytes=1-2, 4-5");
  6544. }
  6545. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6546. auto res =
  6547. cli_.Get("/streamed-with-range",
  6548. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6549. "92233720368547758079223372036854775807"}});
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6552. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6553. EXPECT_EQ(false, res->has_header("Content-Range"));
  6554. EXPECT_EQ(0U, res->body.size());
  6555. }
  6556. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6557. auto res = cli_.Get(
  6558. "/with-range",
  6559. Headers{{"Range",
  6560. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6561. {"Accept-Encoding", ""}});
  6562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6563. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6564. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6565. EXPECT_EQ(true, res->has_header("Content-Range"));
  6566. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6567. EXPECT_EQ(std::string("abcdefg"), res->body);
  6568. }
  6569. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6570. auto res = cli_.Get("/with-range", Headers{
  6571. {"Range", "bytes=0-"},
  6572. {"Accept-Encoding", ""},
  6573. });
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6576. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6577. EXPECT_EQ(true, res->has_header("Content-Range"));
  6578. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6579. EXPECT_EQ(std::string("abcdefg"), res->body);
  6580. }
  6581. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6582. auto res = cli_.Get("/streamed-with-range",
  6583. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6586. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6587. EXPECT_EQ(false, res->has_header("Content-Range"));
  6588. EXPECT_EQ(267U, res->body.size());
  6589. // Check that both range contents are present
  6590. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6591. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6592. // Check that Content-Range headers are present for both ranges
  6593. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6594. std::string::npos);
  6595. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6596. std::string::npos);
  6597. }
  6598. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6599. Ranges ranges;
  6600. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6601. ranges.emplace_back(0, -1);
  6602. }
  6603. auto res = cli_.Get("/streamed-with-range?error",
  6604. Headers{{make_range_header(ranges)}});
  6605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6606. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6607. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6608. EXPECT_EQ(false, res->has_header("Content-Range"));
  6609. EXPECT_EQ(0U, res->body.size());
  6610. }
  6611. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6612. auto res = cli_.Get("/streamed-with-range",
  6613. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6616. EXPECT_EQ(5U, res->body.size());
  6617. // Check that overlapping ranges are coalesced into a single range
  6618. EXPECT_EQ("bcdef", res->body);
  6619. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6620. // Should be single range, not multipart
  6621. EXPECT_TRUE(res->has_header("Content-Range"));
  6622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6623. }
  6624. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6625. auto res = cli_.Get("/streamed-with-range",
  6626. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6629. EXPECT_EQ(268U, res->body.size());
  6630. // Check that both range contents are present
  6631. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6632. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6633. // Check that Content-Range headers are present for both ranges
  6634. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6635. std::string::npos);
  6636. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6637. std::string::npos);
  6638. }
  6639. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6640. auto res = cli_.Get("/streamed-with-range",
  6641. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6644. EXPECT_EQ(269U, res->body.size());
  6645. // Check that both duplicate range contents are present
  6646. size_t first_abc = res->body.find("abc\r\n");
  6647. EXPECT_TRUE(first_abc != std::string::npos);
  6648. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6649. EXPECT_TRUE(second_abc != std::string::npos);
  6650. // Check that Content-Range headers are present for both ranges
  6651. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6652. EXPECT_TRUE(first_range != std::string::npos);
  6653. size_t second_range =
  6654. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6655. EXPECT_TRUE(second_range != std::string::npos);
  6656. }
  6657. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6658. auto res =
  6659. cli_.Get("/streamed-with-range?error",
  6660. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6663. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6664. EXPECT_EQ(false, res->has_header("Content-Range"));
  6665. EXPECT_EQ(0U, res->body.size());
  6666. }
  6667. TEST_F(ServerTest, GetStreamedEndless) {
  6668. uint64_t offset = 0;
  6669. auto res = cli_.Get("/streamed-cancel",
  6670. [&](const char * /*data*/, uint64_t data_length) {
  6671. if (offset < 100) {
  6672. offset += data_length;
  6673. return true;
  6674. }
  6675. return false;
  6676. });
  6677. ASSERT_TRUE(!res);
  6678. EXPECT_EQ(Error::Canceled, res.error());
  6679. }
  6680. TEST_F(ServerTest, ClientStop) {
  6681. std::atomic_size_t count{4};
  6682. std::vector<std::thread> threads;
  6683. for (auto i = count.load(); i != 0; --i) {
  6684. threads.emplace_back([&]() {
  6685. auto res = cli_.Get("/streamed-cancel",
  6686. [&](const char *, uint64_t) { return true; });
  6687. --count;
  6688. ASSERT_TRUE(!res);
  6689. EXPECT_TRUE(res.error() == Error::Canceled ||
  6690. res.error() == Error::Read || res.error() == Error::Write);
  6691. });
  6692. }
  6693. std::this_thread::sleep_for(std::chrono::seconds(2));
  6694. while (count != 0) {
  6695. cli_.stop();
  6696. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6697. }
  6698. for (auto &t : threads) {
  6699. t.join();
  6700. }
  6701. }
  6702. TEST_F(ServerTest, GetWithRange1) {
  6703. auto res = cli_.Get("/with-range", Headers{
  6704. make_range_header({{3, 5}}),
  6705. {"Accept-Encoding", ""},
  6706. });
  6707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6708. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6709. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6710. EXPECT_EQ(true, res->has_header("Content-Range"));
  6711. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6712. EXPECT_EQ(std::string("def"), res->body);
  6713. }
  6714. TEST_F(ServerTest, GetWithRange2) {
  6715. auto res = cli_.Get("/with-range", Headers{
  6716. make_range_header({{1, -1}}),
  6717. {"Accept-Encoding", ""},
  6718. });
  6719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6720. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6721. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6722. EXPECT_EQ(true, res->has_header("Content-Range"));
  6723. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6724. EXPECT_EQ(std::string("bcdefg"), res->body);
  6725. }
  6726. TEST_F(ServerTest, GetWithRange3) {
  6727. auto res = cli_.Get("/with-range", Headers{
  6728. make_range_header({{0, 0}}),
  6729. {"Accept-Encoding", ""},
  6730. });
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6733. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6734. EXPECT_EQ(true, res->has_header("Content-Range"));
  6735. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6736. EXPECT_EQ(std::string("a"), res->body);
  6737. }
  6738. TEST_F(ServerTest, GetWithRange4) {
  6739. auto res = cli_.Get("/with-range", Headers{
  6740. make_range_header({{-1, 2}}),
  6741. {"Accept-Encoding", ""},
  6742. });
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6745. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6746. EXPECT_EQ(true, res->has_header("Content-Range"));
  6747. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6748. EXPECT_EQ(std::string("fg"), res->body);
  6749. }
  6750. TEST_F(ServerTest, GetWithRange5) {
  6751. auto res = cli_.Get("/with-range", Headers{
  6752. make_range_header({{0, 5}}),
  6753. {"Accept-Encoding", ""},
  6754. });
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6757. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6758. EXPECT_EQ(true, res->has_header("Content-Range"));
  6759. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6760. EXPECT_EQ(std::string("abcdef"), res->body);
  6761. }
  6762. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6763. auto res =
  6764. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6767. }
  6768. TEST_F(ServerTest, GetWithRangeMultipart) {
  6769. auto res =
  6770. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6773. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6774. EXPECT_EQ(false, res->has_header("Content-Range"));
  6775. EXPECT_EQ(267U, res->body.size());
  6776. }
  6777. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6778. auto res = cli_.Get("/with-range",
  6779. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6782. }
  6783. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6784. auto res = cli_.Get("/with-range-customized-response",
  6785. Headers{{make_range_header({{1, 2}})}});
  6786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6787. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6788. EXPECT_EQ(true, res->has_header("Content-Length"));
  6789. EXPECT_EQ(false, res->has_header("Content-Range"));
  6790. EXPECT_EQ(JSON_DATA, res->body);
  6791. }
  6792. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6793. auto res = cli_.Get("/with-range-customized-response",
  6794. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6797. EXPECT_EQ(true, res->has_header("Content-Length"));
  6798. EXPECT_EQ(false, res->has_header("Content-Range"));
  6799. EXPECT_EQ(JSON_DATA, res->body);
  6800. }
  6801. TEST_F(ServerTest, Issue1772) {
  6802. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6805. }
  6806. TEST_F(ServerTest, Issue609) {
  6807. auto res = cli_.Delete("/issue609");
  6808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6809. EXPECT_EQ(StatusCode::OK_200, res->status);
  6810. EXPECT_EQ(std::string("ok"), res->body);
  6811. }
  6812. TEST_F(ServerTest, GetStreamedChunked) {
  6813. auto res = cli_.Get("/streamed-chunked");
  6814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6815. EXPECT_EQ(StatusCode::OK_200, res->status);
  6816. EXPECT_EQ(std::string("123456789"), res->body);
  6817. }
  6818. TEST_F(ServerTest, GetStreamedChunked2) {
  6819. auto res = cli_.Get("/streamed-chunked2");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. EXPECT_EQ(std::string("123456789"), res->body);
  6823. }
  6824. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6825. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. EXPECT_EQ(std::string("123456789"), res->body);
  6829. EXPECT_TRUE(res->has_header("Trailer"));
  6830. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6831. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6832. // Trailers are now stored separately from headers (security fix)
  6833. EXPECT_EQ(2U, res->trailers.size());
  6834. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6835. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6836. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6837. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6838. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6839. // Verify trailers are NOT in headers (security verification)
  6840. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6841. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6842. }
  6843. TEST_F(ServerTest, LargeChunkedPost) {
  6844. Request req;
  6845. req.method = "POST";
  6846. req.path = "/large-chunked";
  6847. std::string host_and_port;
  6848. host_and_port += HOST;
  6849. host_and_port += ":";
  6850. host_and_port += std::to_string(PORT);
  6851. req.headers.emplace("Host", host_and_port.c_str());
  6852. req.headers.emplace("Accept", "*/*");
  6853. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6854. req.headers.emplace("Content-Type", "text/plain");
  6855. req.headers.emplace("Content-Length", "0");
  6856. req.headers.emplace("Transfer-Encoding", "chunked");
  6857. std::string long_string(30 * 1024u, 'a');
  6858. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6859. // Attempt to make a large enough post to exceed OS buffers, to test that
  6860. // the server handles short reads if the full chunk data isn't available.
  6861. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6862. auto res = std::make_shared<Response>();
  6863. auto error = Error::Success;
  6864. auto ret = cli_.send(req, *res, error);
  6865. ASSERT_TRUE(ret);
  6866. EXPECT_EQ(StatusCode::OK_200, res->status);
  6867. }
  6868. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6869. auto res = cli_.Get("/remote_addr");
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. EXPECT_EQ(StatusCode::OK_200, res->status);
  6872. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6873. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6874. }
  6875. TEST_F(ServerTest, GetMethodLocalAddr) {
  6876. auto res = cli_.Get("/local_addr");
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. EXPECT_EQ(StatusCode::OK_200, res->status);
  6879. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6880. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6881. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6882. }
  6883. TEST_F(ServerTest, HTTPResponseSplitting) {
  6884. auto res = cli_.Get("/http_response_splitting");
  6885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6886. EXPECT_EQ(StatusCode::OK_200, res->status);
  6887. }
  6888. TEST_F(ServerTest, SlowRequest) {
  6889. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6890. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6891. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6892. }
  6893. #if 0
  6894. TEST_F(ServerTest, SlowPost) {
  6895. char buffer[64 * 1024];
  6896. memset(buffer, 0x42, sizeof(buffer));
  6897. auto res = cli_.Post(
  6898. "/slowpost", 64 * 1024 * 1024,
  6899. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6900. auto ret = sink.write(buffer, sizeof(buffer));
  6901. EXPECT_TRUE(ret);
  6902. return true;
  6903. },
  6904. "text/plain");
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. }
  6908. TEST_F(ServerTest, SlowPostFail) {
  6909. char buffer[64 * 1024];
  6910. memset(buffer, 0x42, sizeof(buffer));
  6911. cli_.set_write_timeout(std::chrono::seconds(0));
  6912. auto res = cli_.Post(
  6913. "/slowpost", 64 * 1024 * 1024,
  6914. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6915. sink.write(buffer, sizeof(buffer));
  6916. return true;
  6917. },
  6918. "text/plain");
  6919. ASSERT_TRUE(!res);
  6920. EXPECT_EQ(Error::Write, res.error());
  6921. }
  6922. #endif
  6923. TEST_F(ServerTest, Put) {
  6924. auto res = cli_.Put("/put", "PUT", "text/plain");
  6925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6926. EXPECT_EQ(StatusCode::OK_200, res->status);
  6927. EXPECT_EQ("PUT", res->body);
  6928. }
  6929. TEST_F(ServerTest, PutWithContentProvider) {
  6930. auto res = cli_.Put(
  6931. "/put", 3,
  6932. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6933. sink.os << "PUT";
  6934. return true;
  6935. },
  6936. "text/plain");
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. EXPECT_EQ("PUT", res->body);
  6940. }
  6941. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6942. auto res = cli_.Post(
  6943. "/post", 42,
  6944. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6945. return false;
  6946. },
  6947. "text/plain");
  6948. ASSERT_TRUE(!res);
  6949. EXPECT_EQ(Error::Canceled, res.error());
  6950. }
  6951. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6952. auto res = cli_.Put(
  6953. "/put",
  6954. [](size_t /*offset*/, DataSink &sink) {
  6955. sink.os << "PUT";
  6956. sink.done();
  6957. return true;
  6958. },
  6959. "text/plain");
  6960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6961. EXPECT_EQ(StatusCode::OK_200, res->status);
  6962. EXPECT_EQ("PUT", res->body);
  6963. }
  6964. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6965. auto res = cli_.Post(
  6966. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6967. "text/plain");
  6968. ASSERT_TRUE(!res);
  6969. EXPECT_EQ(Error::Canceled, res.error());
  6970. }
  6971. TEST_F(ServerTest, PostLoopBack) {
  6972. std::string body;
  6973. auto res = cli_.Post(
  6974. "/post-loopback", 9,
  6975. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6976. EXPECT_EQ(9u, length);
  6977. sink.write("123", 3);
  6978. sink.write("456", 3);
  6979. sink.write("789", 3);
  6980. return true;
  6981. },
  6982. "text/plain",
  6983. [&body](const char *data, size_t data_length) {
  6984. body.append(data, data_length);
  6985. return true;
  6986. });
  6987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6988. EXPECT_EQ(StatusCode::OK_200, res->status);
  6989. EXPECT_EQ("123456789", body);
  6990. }
  6991. TEST_F(ServerTest, PutLoopBack) {
  6992. std::string body;
  6993. auto res = cli_.Put(
  6994. "/put-loopback", 9,
  6995. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6996. EXPECT_EQ(9u, length);
  6997. sink.write("123", 3);
  6998. sink.write("456", 3);
  6999. sink.write("789", 3);
  7000. return true;
  7001. },
  7002. "text/plain",
  7003. [&body](const char *data, size_t data_length) {
  7004. body.append(data, data_length);
  7005. return true;
  7006. });
  7007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7008. EXPECT_EQ(StatusCode::OK_200, res->status);
  7009. EXPECT_EQ("123456789", body);
  7010. }
  7011. TEST_F(ServerTest, PatchLoopBack) {
  7012. std::string body;
  7013. auto res = cli_.Patch(
  7014. "/patch-loopback", 9,
  7015. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7016. EXPECT_EQ(9u, length);
  7017. sink.write("123", 3);
  7018. sink.write("456", 3);
  7019. sink.write("789", 3);
  7020. return true;
  7021. },
  7022. "text/plain",
  7023. [&body](const char *data, size_t data_length) {
  7024. body.append(data, data_length);
  7025. return true;
  7026. });
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::OK_200, res->status);
  7029. EXPECT_EQ("123456789", body);
  7030. }
  7031. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7032. std::string body;
  7033. auto res = cli_.Post(
  7034. "/post-loopback",
  7035. [](size_t /*offset*/, DataSink &sink) {
  7036. sink.write("123", 3);
  7037. sink.write("456", 3);
  7038. sink.write("789", 3);
  7039. sink.done();
  7040. return true;
  7041. },
  7042. "text/plain",
  7043. [&body](const char *data, size_t data_length) {
  7044. body.append(data, data_length);
  7045. return true;
  7046. });
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. EXPECT_EQ("123456789", body);
  7050. }
  7051. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7052. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7053. cli_.set_compress(true);
  7054. auto res = cli_.Put(
  7055. "/put", 3,
  7056. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7057. sink.os << "PUT";
  7058. return true;
  7059. },
  7060. "text/plain");
  7061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7062. EXPECT_EQ(StatusCode::OK_200, res->status);
  7063. EXPECT_EQ("PUT", res->body);
  7064. }
  7065. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7066. cli_.set_compress(true);
  7067. auto res = cli_.Post(
  7068. "/post", 42,
  7069. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7070. return false;
  7071. },
  7072. "text/plain");
  7073. ASSERT_TRUE(!res);
  7074. EXPECT_EQ(Error::Canceled, res.error());
  7075. }
  7076. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7077. cli_.set_compress(true);
  7078. auto res = cli_.Put(
  7079. "/put",
  7080. [](size_t /*offset*/, DataSink &sink) {
  7081. sink.os << "PUT";
  7082. sink.done();
  7083. return true;
  7084. },
  7085. "text/plain");
  7086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7087. EXPECT_EQ(StatusCode::OK_200, res->status);
  7088. EXPECT_EQ("PUT", res->body);
  7089. }
  7090. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7091. cli_.set_compress(true);
  7092. auto res = cli_.Post(
  7093. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7094. "text/plain");
  7095. ASSERT_TRUE(!res);
  7096. EXPECT_EQ(Error::Canceled, res.error());
  7097. }
  7098. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7099. cli_.set_compress(true);
  7100. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. EXPECT_EQ(StatusCode::OK_200, res->status);
  7103. EXPECT_EQ(LARGE_DATA, res->body);
  7104. }
  7105. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7106. #ifdef CPPHTTPLIB_SSL_ENABLED
  7107. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7108. Client cli(s.c_str());
  7109. cli.enable_server_certificate_verification(false);
  7110. #else
  7111. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7112. Client cli(s.c_str());
  7113. #endif
  7114. cli.set_compress(true);
  7115. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7117. EXPECT_EQ(StatusCode::OK_200, res->status);
  7118. EXPECT_EQ(LARGE_DATA, res->body);
  7119. // The compressed size should be less than a 10th of the original. May vary
  7120. // depending on the zlib library.
  7121. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7122. static_cast<uint64_t>(10 * 1024 * 1024));
  7123. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7124. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7125. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7126. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7127. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7128. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7129. #endif
  7130. }
  7131. TEST_F(ServerTest, PutContentWithDeflate) {
  7132. cli_.set_compress(false);
  7133. Headers headers;
  7134. headers.emplace("Content-Encoding", "deflate");
  7135. // PUT in deflate format:
  7136. auto res = cli_.Put("/put", headers,
  7137. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7139. EXPECT_EQ(StatusCode::OK_200, res->status);
  7140. EXPECT_EQ("PUT", res->body);
  7141. }
  7142. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7143. Headers headers;
  7144. headers.emplace("Accept-Encoding", "gzip, deflate");
  7145. auto res = cli_.Get("/streamed-chunked", headers);
  7146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7147. EXPECT_EQ(StatusCode::OK_200, res->status);
  7148. EXPECT_EQ(std::string("123456789"), res->body);
  7149. }
  7150. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7151. Headers headers;
  7152. headers.emplace("Accept-Encoding", "gzip, deflate");
  7153. auto res = cli_.Get("/streamed-chunked2", headers);
  7154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7155. EXPECT_EQ(StatusCode::OK_200, res->status);
  7156. EXPECT_EQ(std::string("123456789"), res->body);
  7157. }
  7158. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7159. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. EXPECT_EQ(StatusCode::OK_200, res->status);
  7162. }
  7163. TEST(GzipDecompressor, ChunkedDecompression) {
  7164. std::string data;
  7165. for (size_t i = 0; i < 32 * 1024; ++i) {
  7166. data.push_back(static_cast<char>('a' + i % 26));
  7167. }
  7168. std::string compressed_data;
  7169. {
  7170. httplib::detail::gzip_compressor compressor;
  7171. bool result = compressor.compress(
  7172. data.data(), data.size(),
  7173. /*last=*/true,
  7174. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7175. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7176. compressed_data_size);
  7177. return true;
  7178. });
  7179. ASSERT_TRUE(result);
  7180. }
  7181. std::string decompressed_data;
  7182. {
  7183. httplib::detail::gzip_decompressor decompressor;
  7184. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7185. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7186. size_t chunk_size = 130;
  7187. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7188. chunk_begin += chunk_size) {
  7189. size_t current_chunk_size =
  7190. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7191. bool result = decompressor.decompress(
  7192. compressed_data.data() + chunk_begin, current_chunk_size,
  7193. [&](const char *decompressed_data_chunk,
  7194. size_t decompressed_data_chunk_size) {
  7195. decompressed_data.insert(decompressed_data.size(),
  7196. decompressed_data_chunk,
  7197. decompressed_data_chunk_size);
  7198. return true;
  7199. });
  7200. ASSERT_TRUE(result);
  7201. }
  7202. }
  7203. ASSERT_EQ(data, decompressed_data);
  7204. }
  7205. TEST(GzipDecompressor, DeflateDecompression) {
  7206. std::string original_text = "Raw deflate without gzip";
  7207. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7208. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7209. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7210. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7211. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7212. std::string decompressed_data;
  7213. {
  7214. httplib::detail::gzip_decompressor decompressor;
  7215. bool result = decompressor.decompress(
  7216. compressed_data.data(), compressed_data.size(),
  7217. [&](const char *decompressed_data_chunk,
  7218. size_t decompressed_data_chunk_size) {
  7219. decompressed_data.insert(decompressed_data.size(),
  7220. decompressed_data_chunk,
  7221. decompressed_data_chunk_size);
  7222. return true;
  7223. });
  7224. ASSERT_TRUE(result);
  7225. }
  7226. ASSERT_EQ(original_text, decompressed_data);
  7227. }
  7228. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7229. std::string original_text = "Raw deflate without gzip";
  7230. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7231. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7232. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7233. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7234. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7235. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7236. std::string decompressed_data;
  7237. {
  7238. httplib::detail::gzip_decompressor decompressor;
  7239. bool result = decompressor.decompress(
  7240. compressed_data.data(), compressed_data.size(),
  7241. [&](const char *decompressed_data_chunk,
  7242. size_t decompressed_data_chunk_size) {
  7243. decompressed_data.insert(decompressed_data.size(),
  7244. decompressed_data_chunk,
  7245. decompressed_data_chunk_size);
  7246. return true;
  7247. });
  7248. ASSERT_TRUE(result);
  7249. }
  7250. ASSERT_EQ(original_text, decompressed_data);
  7251. }
  7252. #endif
  7253. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7254. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7255. Headers headers;
  7256. headers.emplace("Accept-Encoding", "br");
  7257. auto res = cli_.Get("/streamed-chunked", headers);
  7258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7259. EXPECT_EQ(StatusCode::OK_200, res->status);
  7260. EXPECT_EQ(std::string("123456789"), res->body);
  7261. }
  7262. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7263. Headers headers;
  7264. headers.emplace("Accept-Encoding", "br");
  7265. auto res = cli_.Get("/streamed-chunked2", headers);
  7266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7267. EXPECT_EQ(StatusCode::OK_200, res->status);
  7268. EXPECT_EQ(std::string("123456789"), res->body);
  7269. }
  7270. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7271. cli_.set_compress(true);
  7272. auto res = cli_.Put(
  7273. "/put", 3,
  7274. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7275. sink.os << "PUT";
  7276. return true;
  7277. },
  7278. "text/plain");
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. EXPECT_EQ("PUT", res->body);
  7282. }
  7283. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7284. cli_.set_compress(true);
  7285. auto res = cli_.Put(
  7286. "/put",
  7287. [](size_t /*offset*/, DataSink &sink) {
  7288. sink.os << "PUT";
  7289. sink.done();
  7290. return true;
  7291. },
  7292. "text/plain");
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::OK_200, res->status);
  7295. EXPECT_EQ("PUT", res->body);
  7296. }
  7297. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7298. cli_.set_compress(true);
  7299. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ(LARGE_DATA, res->body);
  7303. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7304. }
  7305. #endif
  7306. TEST_F(ServerTest, Patch) {
  7307. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. EXPECT_EQ(StatusCode::OK_200, res->status);
  7310. EXPECT_EQ("PATCH", res->body);
  7311. }
  7312. TEST_F(ServerTest, Delete) {
  7313. auto res = cli_.Delete("/delete");
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::OK_200, res->status);
  7316. EXPECT_EQ("DELETE", res->body);
  7317. }
  7318. TEST_F(ServerTest, DeleteContentReceiver) {
  7319. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7321. EXPECT_EQ(StatusCode::OK_200, res->status);
  7322. EXPECT_EQ("content", res->body);
  7323. }
  7324. TEST_F(ServerTest, Options) {
  7325. auto res = cli_.Options("*");
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::OK_200, res->status);
  7328. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7329. EXPECT_TRUE(res->body.empty());
  7330. }
  7331. TEST_F(ServerTest, URL) {
  7332. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. }
  7336. TEST_F(ServerTest, ArrayParam) {
  7337. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::OK_200, res->status);
  7340. }
  7341. TEST_F(ServerTest, ArrayParamValues) {
  7342. auto res =
  7343. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7345. EXPECT_EQ(StatusCode::OK_200, res->status);
  7346. }
  7347. TEST_F(ServerTest, NoMultipleHeaders) {
  7348. Headers headers = {{"Content-Length", "5"}};
  7349. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7350. "text/plain");
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::OK_200, res->status);
  7353. }
  7354. TEST_F(ServerTest, PostContentReceiver) {
  7355. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7357. ASSERT_EQ(StatusCode::OK_200, res->status);
  7358. ASSERT_EQ("content", res->body);
  7359. }
  7360. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7361. UploadFormDataItems items = {
  7362. {"text1", "text default", "", ""},
  7363. {"text2", "aωb", "", ""},
  7364. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7365. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7366. {"file3", "", "", "application/octet-stream"},
  7367. };
  7368. auto res = cli_.Post("/content_receiver", items);
  7369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7370. EXPECT_EQ(StatusCode::OK_200, res->status);
  7371. }
  7372. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7373. UploadFormDataItems items = {
  7374. {"text1", "text default", "", ""},
  7375. {"text2", "aωb", "", ""},
  7376. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7377. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7378. {"file3", "", "", "application/octet-stream"},
  7379. };
  7380. auto boundary = std::string("+++++");
  7381. std::string body;
  7382. for (const auto &item : items) {
  7383. body += "--" + boundary + "\r\n";
  7384. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7385. if (!item.filename.empty()) {
  7386. body += "; filename=\"" + item.filename + "\"";
  7387. }
  7388. body += "\r\n";
  7389. if (!item.content_type.empty()) {
  7390. body += "Content-Type: " + item.content_type + "\r\n";
  7391. }
  7392. body += "\r\n";
  7393. body += item.content + "\r\n";
  7394. }
  7395. body += "--" + boundary + "--\r\n";
  7396. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7397. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7399. EXPECT_EQ(StatusCode::OK_200, res->status);
  7400. }
  7401. TEST(MultipartFormDataTest, FieldEscaping) {
  7402. Server svr;
  7403. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7404. const ContentReader &content_reader) {
  7405. ASSERT_TRUE(req.is_multipart_form_data());
  7406. std::vector<FormData> received;
  7407. content_reader(
  7408. [&](const FormData &file) {
  7409. received.push_back(file);
  7410. return true;
  7411. },
  7412. [&](const char *data, size_t data_length) {
  7413. received.back().content.append(data, data_length);
  7414. return true;
  7415. });
  7416. // '"', CR and LF in names and filenames are escaped following the
  7417. // WHATWG HTML standard, so each part still parses as a single part
  7418. // with no injected headers. Content types get CR/LF escaped too,
  7419. // while '"' (legal there, e.g. quoted charset) is preserved.
  7420. ASSERT_EQ(4U, received.size());
  7421. EXPECT_EQ("na%22me", received[0].name);
  7422. EXPECT_EQ("quoted name", received[0].content);
  7423. EXPECT_EQ("file", received[1].name);
  7424. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7425. received[1].filename);
  7426. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7427. EXPECT_EQ("injected", received[1].content);
  7428. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7429. EXPECT_EQ("my%22file.txt", received[2].filename);
  7430. EXPECT_EQ("cr lf name", received[2].content);
  7431. EXPECT_EQ("typed", received[3].name);
  7432. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7433. received[3].content_type);
  7434. EXPECT_EQ("typed content", received[3].content);
  7435. });
  7436. auto port = svr.bind_to_any_port("localhost");
  7437. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7438. auto se = detail::scope_exit([&] {
  7439. svr.stop();
  7440. t.join();
  7441. ASSERT_FALSE(svr.is_running());
  7442. });
  7443. svr.wait_until_ready();
  7444. Client cli("localhost", port);
  7445. UploadFormDataItems items = {
  7446. {"na\"me", "quoted name", "", ""},
  7447. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7448. "application/octet-stream"},
  7449. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7450. {"typed", "typed content", "",
  7451. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7452. };
  7453. auto res = cli.Post("/post", items);
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. }
  7457. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7458. const UploadFormDataItems items = {
  7459. {"name1", "Content 1", "", ""},
  7460. {"name2", "Content 2", "file2.txt", "text/plain"},
  7461. };
  7462. Server svr;
  7463. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7464. const ContentReader &content_reader) {
  7465. ASSERT_TRUE(req.is_multipart_form_data());
  7466. std::vector<FormData> received;
  7467. content_reader(
  7468. [&](const FormData &file) {
  7469. received.push_back(file);
  7470. return true;
  7471. },
  7472. [&](const char *data, size_t data_length) {
  7473. received.back().content.append(data, data_length);
  7474. return true;
  7475. });
  7476. ASSERT_EQ(2U, received.size());
  7477. EXPECT_EQ("name1", received[0].name);
  7478. EXPECT_EQ("Content 1", received[0].content);
  7479. EXPECT_EQ("name2", received[1].name);
  7480. EXPECT_EQ("Content 2", received[1].content);
  7481. EXPECT_EQ("file2.txt", received[1].filename);
  7482. EXPECT_EQ("text/plain", received[1].content_type);
  7483. });
  7484. auto port = svr.bind_to_any_port("localhost");
  7485. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7486. auto se = detail::scope_exit([&] {
  7487. svr.stop();
  7488. t.join();
  7489. ASSERT_FALSE(svr.is_running());
  7490. });
  7491. svr.wait_until_ready();
  7492. Client cli("localhost", port);
  7493. // Whole-body serialization with a generated boundary
  7494. {
  7495. MultipartFormDataWriter writer;
  7496. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7497. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7498. writer.content_type());
  7499. auto body = writer.serialize(items);
  7500. EXPECT_EQ(body.size(), writer.content_length(items));
  7501. auto res = cli.Post("/post", body, writer.content_type());
  7502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7503. EXPECT_EQ(StatusCode::OK_200, res->status);
  7504. }
  7505. // Per-part framing with a custom boundary via a content provider
  7506. {
  7507. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7508. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7509. MultipartFormDataWriter writer("custom-boundary_123");
  7510. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7511. std::string body;
  7512. for (const auto &item : items) {
  7513. body += writer.item_begin(item);
  7514. body += item.content;
  7515. body += MultipartFormDataWriter::item_end();
  7516. }
  7517. body += writer.finish();
  7518. EXPECT_EQ(body.size(), writer.content_length(items));
  7519. auto res = cli.Post(
  7520. "/post", body.size(),
  7521. [&](size_t offset, size_t length, DataSink &sink) {
  7522. sink.write(body.data() + offset, length);
  7523. return true;
  7524. },
  7525. writer.content_type());
  7526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7527. EXPECT_EQ(StatusCode::OK_200, res->status);
  7528. }
  7529. }
  7530. TEST_F(ServerTest, PostContentReceiverGzip) {
  7531. cli_.set_compress(true);
  7532. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. ASSERT_EQ(StatusCode::OK_200, res->status);
  7535. ASSERT_EQ("content", res->body);
  7536. }
  7537. TEST_F(ServerTest, PutContentReceiver) {
  7538. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7540. ASSERT_EQ(StatusCode::OK_200, res->status);
  7541. ASSERT_EQ("content", res->body);
  7542. }
  7543. TEST_F(ServerTest, PatchContentReceiver) {
  7544. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7546. ASSERT_EQ(StatusCode::OK_200, res->status);
  7547. ASSERT_EQ("content", res->body);
  7548. }
  7549. template <typename ClientType>
  7550. void TestWithHeadersAndContentReceiver(
  7551. ClientType &cli,
  7552. std::function<Result(ClientType &, const std::string &, const Headers &,
  7553. const std::string &, const std::string &,
  7554. ContentReceiver, DownloadProgress)>
  7555. request_func) {
  7556. Headers headers;
  7557. headers.emplace("X-Custom-Header", "test-value");
  7558. std::string received_body;
  7559. auto res = request_func(
  7560. cli, "/content_receiver", headers, "content", "application/json",
  7561. [&](const char *data, size_t data_length) {
  7562. received_body.append(data, data_length);
  7563. return true;
  7564. },
  7565. nullptr);
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ(StatusCode::OK_200, res->status);
  7568. EXPECT_EQ("content", received_body);
  7569. }
  7570. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7571. #ifdef CPPHTTPLIB_SSL_ENABLED
  7572. using ClientT = SSLClient;
  7573. #else
  7574. using ClientT = Client;
  7575. #endif
  7576. TestWithHeadersAndContentReceiver<ClientT>(
  7577. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7578. const std::string &body, const std::string &content_type,
  7579. ContentReceiver receiver, DownloadProgress progress) {
  7580. return cli.Post(path, headers, body, content_type, receiver, progress);
  7581. });
  7582. }
  7583. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7584. #ifdef CPPHTTPLIB_SSL_ENABLED
  7585. using ClientT = SSLClient;
  7586. #else
  7587. using ClientT = Client;
  7588. #endif
  7589. TestWithHeadersAndContentReceiver<ClientT>(
  7590. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7591. const std::string &body, const std::string &content_type,
  7592. ContentReceiver receiver, DownloadProgress progress) {
  7593. return cli.Put(path, headers, body, content_type, receiver, progress);
  7594. });
  7595. }
  7596. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7597. #ifdef CPPHTTPLIB_SSL_ENABLED
  7598. using ClientT = SSLClient;
  7599. #else
  7600. using ClientT = Client;
  7601. #endif
  7602. TestWithHeadersAndContentReceiver<ClientT>(
  7603. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7604. const std::string &body, const std::string &content_type,
  7605. ContentReceiver receiver, DownloadProgress progress) {
  7606. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7607. });
  7608. }
  7609. template <typename ClientType>
  7610. void TestWithHeadersAndContentReceiverWithProgress(
  7611. ClientType &cli,
  7612. std::function<Result(ClientType &, const std::string &, const Headers &,
  7613. const std::string &, const std::string &,
  7614. ContentReceiver, DownloadProgress)>
  7615. request_func) {
  7616. Headers headers;
  7617. headers.emplace("X-Test-Header", "progress-test");
  7618. std::string received_body;
  7619. auto progress_called = false;
  7620. auto res = request_func(
  7621. cli, "/content_receiver", headers, "content", "text/plain",
  7622. [&](const char *data, size_t data_length) {
  7623. received_body.append(data, data_length);
  7624. return true;
  7625. },
  7626. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7627. progress_called = true;
  7628. return true;
  7629. });
  7630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7631. EXPECT_EQ(StatusCode::OK_200, res->status);
  7632. EXPECT_EQ("content", received_body);
  7633. EXPECT_TRUE(progress_called);
  7634. }
  7635. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7636. #ifdef CPPHTTPLIB_SSL_ENABLED
  7637. using ClientT = SSLClient;
  7638. #else
  7639. using ClientT = Client;
  7640. #endif
  7641. TestWithHeadersAndContentReceiverWithProgress<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, DownloadProgress progress) {
  7645. return cli.Post(path, headers, body, content_type, receiver, progress);
  7646. });
  7647. }
  7648. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7649. #ifdef CPPHTTPLIB_SSL_ENABLED
  7650. using ClientT = SSLClient;
  7651. #else
  7652. using ClientT = Client;
  7653. #endif
  7654. TestWithHeadersAndContentReceiverWithProgress<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, DownloadProgress progress) {
  7658. return cli.Put(path, headers, body, content_type, receiver, progress);
  7659. });
  7660. }
  7661. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7662. #ifdef CPPHTTPLIB_SSL_ENABLED
  7663. using ClientT = SSLClient;
  7664. #else
  7665. using ClientT = Client;
  7666. #endif
  7667. TestWithHeadersAndContentReceiverWithProgress<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, DownloadProgress progress) {
  7671. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7672. });
  7673. }
  7674. template <typename ClientType>
  7675. void TestWithHeadersAndContentReceiverError(
  7676. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7677. const Headers &, const std::string &,
  7678. const std::string &, ContentReceiver)>
  7679. request_func) {
  7680. Headers headers;
  7681. headers.emplace("X-Error-Test", "true");
  7682. std::string received_body;
  7683. auto receiver_failed = false;
  7684. auto res =
  7685. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7686. [&](const char *data, size_t data_length) {
  7687. received_body.append(data, data_length);
  7688. receiver_failed = true;
  7689. return false;
  7690. });
  7691. ASSERT_FALSE(res);
  7692. EXPECT_TRUE(receiver_failed);
  7693. }
  7694. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7695. #ifdef CPPHTTPLIB_SSL_ENABLED
  7696. using ClientT = SSLClient;
  7697. #else
  7698. using ClientT = Client;
  7699. #endif
  7700. TestWithHeadersAndContentReceiverError<ClientT>(
  7701. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7702. const std::string &body, const std::string &content_type,
  7703. ContentReceiver receiver) {
  7704. return cli.Post(path, headers, body, content_type, receiver);
  7705. });
  7706. }
  7707. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7708. #ifdef CPPHTTPLIB_SSL_ENABLED
  7709. using ClientT = SSLClient;
  7710. #else
  7711. using ClientT = Client;
  7712. #endif
  7713. TestWithHeadersAndContentReceiverError<ClientT>(
  7714. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7715. const std::string &body, const std::string &content_type,
  7716. ContentReceiver receiver) {
  7717. return cli.Put(path, headers, body, content_type, receiver);
  7718. });
  7719. }
  7720. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7721. #ifdef CPPHTTPLIB_SSL_ENABLED
  7722. using ClientT = SSLClient;
  7723. #else
  7724. using ClientT = Client;
  7725. #endif
  7726. TestWithHeadersAndContentReceiverError<ClientT>(
  7727. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7728. const std::string &body, const std::string &content_type,
  7729. ContentReceiver receiver) {
  7730. return cli.Patch(path, headers, body, content_type, receiver);
  7731. });
  7732. }
  7733. TEST_F(ServerTest, PostQueryStringAndBody) {
  7734. auto res =
  7735. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. ASSERT_EQ(StatusCode::OK_200, res->status);
  7738. }
  7739. TEST_F(ServerTest, HTTP2Magic) {
  7740. Request req;
  7741. req.method = "PRI";
  7742. req.path = "*";
  7743. req.body = "SM";
  7744. auto res = std::make_shared<Response>();
  7745. auto error = Error::Success;
  7746. auto ret = cli_.send(req, *res, error);
  7747. ASSERT_TRUE(ret);
  7748. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7749. }
  7750. TEST_F(ServerTest, KeepAlive) {
  7751. auto res = cli_.Get("/hi");
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7755. EXPECT_EQ("Hello World!", res->body);
  7756. res = cli_.Get("/hi");
  7757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7758. EXPECT_EQ(StatusCode::OK_200, res->status);
  7759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7760. EXPECT_EQ("Hello World!", res->body);
  7761. res = cli_.Get("/hi");
  7762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7763. EXPECT_EQ(StatusCode::OK_200, res->status);
  7764. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7765. EXPECT_EQ("Hello World!", res->body);
  7766. res = cli_.Get("/not-exist");
  7767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7768. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7769. res = cli_.Post("/empty", "", "text/plain");
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::OK_200, res->status);
  7772. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7773. EXPECT_EQ("empty", res->body);
  7774. EXPECT_EQ("close", res->get_header_value("Connection"));
  7775. res = cli_.Post(
  7776. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7777. "text/plain");
  7778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7779. EXPECT_EQ(StatusCode::OK_200, res->status);
  7780. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7781. EXPECT_EQ("empty", res->body);
  7782. cli_.set_keep_alive(false);
  7783. res = cli_.Get("/last-request");
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. EXPECT_EQ(StatusCode::OK_200, res->status);
  7786. EXPECT_EQ("close", res->get_header_value("Connection"));
  7787. }
  7788. TEST_F(ServerTest, TooManyRedirect) {
  7789. cli_.set_follow_location(true);
  7790. auto res = cli_.Get("/redirect/0");
  7791. ASSERT_TRUE(!res);
  7792. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7793. }
  7794. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7795. Request req;
  7796. req.method = "FOOBAR";
  7797. req.path = "/hi";
  7798. cli_.set_keep_alive(true);
  7799. auto res = cli_.send(req);
  7800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7801. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7802. EXPECT_EQ("close", res->get_header_value("Connection"));
  7803. EXPECT_FALSE(cli_.is_socket_open());
  7804. }
  7805. TEST_F(ServerTest, CustomRouteReadsBody) {
  7806. const std::string xml =
  7807. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7808. Request req;
  7809. req.method = "PROPFIND";
  7810. req.path = "/dav/dir";
  7811. req.set_header("Depth", "1");
  7812. req.body = xml;
  7813. auto res = cli_.send(req);
  7814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7815. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7816. EXPECT_EQ(xml, res->body);
  7817. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7818. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7819. }
  7820. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7821. Request req;
  7822. req.method = "PROPFIND";
  7823. req.path = "/dav/42";
  7824. auto res = cli_.send(req);
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7827. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7828. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7829. }
  7830. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7831. Request req;
  7832. req.method = "PROPFIND";
  7833. req.path = "/dav-re/123";
  7834. auto res = cli_.send(req);
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7837. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7838. }
  7839. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7840. Request req;
  7841. req.method = "MKCOL";
  7842. req.path = "/dav-mkcol";
  7843. auto res = cli_.send(req);
  7844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7845. EXPECT_EQ(StatusCode::Created_201, res->status);
  7846. }
  7847. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7848. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7849. Request req;
  7850. req.method = "REPORT";
  7851. req.path = "/dav-report";
  7852. req.body = xml;
  7853. auto res = cli_.send(req);
  7854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7855. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7856. EXPECT_EQ(xml, res->body);
  7857. }
  7858. // A content reader route must fire even when the request carries no body,
  7859. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7860. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7861. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7862. Request req;
  7863. req.method = "REPORT";
  7864. req.path = "/dav-report";
  7865. auto res = cli_.send(req);
  7866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7867. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7868. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7869. }
  7870. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7871. Request req;
  7872. req.method = "PROPFIND";
  7873. req.path = "/not-dav";
  7874. auto res = cli_.send(req);
  7875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7876. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7877. }
  7878. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7879. Request req;
  7880. req.method = "UNLOCK";
  7881. req.path = "/dav/dir";
  7882. cli_.set_keep_alive(true);
  7883. auto res = cli_.send(req);
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7886. EXPECT_EQ("close", res->get_header_value("Connection"));
  7887. EXPECT_FALSE(cli_.is_socket_open());
  7888. }
  7889. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7890. // The mount point serves this path, but only for GET and HEAD.
  7891. auto get_res = cli_.Get("/dir/index.html");
  7892. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7893. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7894. Request req;
  7895. req.method = "PROPFIND";
  7896. req.path = "/dir/index.html";
  7897. auto res = cli_.send(req);
  7898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7900. }
  7901. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7902. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7903. cli_.set_keep_alive(true);
  7904. for (auto i = 0; i < 2; i++) {
  7905. Request req;
  7906. req.method = "PROPFIND";
  7907. req.path = "/dav/dir";
  7908. req.body = xml;
  7909. auto res = cli_.send(req);
  7910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7911. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7912. EXPECT_EQ(xml, res->body);
  7913. EXPECT_TRUE(cli_.is_socket_open());
  7914. }
  7915. // A built-in method must still be served on the same connection.
  7916. cli_.set_keep_alive(false);
  7917. auto res = cli_.Get("/hi");
  7918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7919. EXPECT_EQ(StatusCode::OK_200, res->status);
  7920. EXPECT_EQ("close", res->get_header_value("Connection"));
  7921. }
  7922. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7923. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7924. Request req;
  7925. req.method = "PROPFIND";
  7926. req.path = "/dav/dir";
  7927. req.set_header("Expect", "100-continue");
  7928. req.body = xml;
  7929. auto res = cli_.send(req);
  7930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7931. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7932. EXPECT_EQ(xml, res->body);
  7933. }
  7934. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7935. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7936. TEST_F(ServerTest, Gzip) {
  7937. Headers headers;
  7938. headers.emplace("Accept-Encoding", "gzip, deflate");
  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("123456789012345678901234567890123456789012345678901234567890123456"
  7945. "7890123456789012345678901234567890",
  7946. res->body);
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. }
  7949. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7950. Headers headers;
  7951. headers.emplace("Accept-Encoding", "gzip, deflate");
  7952. auto res = cli_.Get("/compress-with-charset", headers);
  7953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7954. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7955. EXPECT_EQ("application/json; charset=utf-8",
  7956. res->get_header_value("Content-Type"));
  7957. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7958. "7890123456789012345678901234567890",
  7959. res->body);
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. }
  7962. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7963. Headers headers;
  7964. headers.emplace("Accept-Encoding", "");
  7965. auto res = cli_.Get("/compress", headers);
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7968. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7969. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7970. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7971. "7890123456789012345678901234567890",
  7972. res->body);
  7973. EXPECT_EQ(StatusCode::OK_200, res->status);
  7974. }
  7975. TEST_F(ServerTest, GzipWithContentReceiver) {
  7976. Headers headers;
  7977. headers.emplace("Accept-Encoding", "gzip, deflate");
  7978. std::string body;
  7979. auto res = cli_.Get("/compress", headers,
  7980. [&](const char *data, uint64_t data_length) {
  7981. EXPECT_EQ(100U, data_length);
  7982. body.append(data, data_length);
  7983. return true;
  7984. });
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7988. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7989. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7990. "7890123456789012345678901234567890",
  7991. body);
  7992. EXPECT_EQ(StatusCode::OK_200, res->status);
  7993. }
  7994. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7995. Headers headers;
  7996. headers.emplace("Accept-Encoding", "gzip, deflate");
  7997. cli_.set_decompress(false);
  7998. auto res = cli_.Get("/compress", headers);
  7999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8000. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8001. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8002. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8003. EXPECT_EQ(33U, res->body.size());
  8004. EXPECT_EQ(StatusCode::OK_200, res->status);
  8005. }
  8006. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8007. Headers headers;
  8008. headers.emplace("Accept-Encoding", "");
  8009. std::string body;
  8010. auto res = cli_.Get("/compress", headers,
  8011. [&](const char *data, uint64_t data_length) {
  8012. EXPECT_EQ(100U, data_length);
  8013. body.append(data, data_length);
  8014. return true;
  8015. });
  8016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8017. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8019. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8020. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8021. "7890123456789012345678901234567890",
  8022. body);
  8023. EXPECT_EQ(StatusCode::OK_200, res->status);
  8024. }
  8025. TEST_F(ServerTest, NoGzip) {
  8026. Headers headers;
  8027. headers.emplace("Accept-Encoding", "gzip, deflate");
  8028. auto res = cli_.Get("/nocompress", headers);
  8029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8030. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8031. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8032. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8033. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8034. "7890123456789012345678901234567890",
  8035. res->body);
  8036. EXPECT_EQ(StatusCode::OK_200, res->status);
  8037. }
  8038. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8039. Headers headers;
  8040. headers.emplace("Accept-Encoding", "gzip, deflate");
  8041. std::string body;
  8042. auto res = cli_.Get("/nocompress", headers,
  8043. [&](const char *data, uint64_t data_length) {
  8044. EXPECT_EQ(100U, data_length);
  8045. body.append(data, data_length);
  8046. return true;
  8047. });
  8048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8049. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8050. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8051. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8052. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8053. "7890123456789012345678901234567890",
  8054. body);
  8055. EXPECT_EQ(StatusCode::OK_200, res->status);
  8056. }
  8057. TEST_F(ServerTest, MultipartFormDataGzip) {
  8058. UploadFormDataItems items = {
  8059. {"key1", "test", "", ""},
  8060. {"key2", "--abcdefg123", "", ""},
  8061. };
  8062. cli_.set_compress(true);
  8063. auto res = cli_.Post("/compress-multipart", items);
  8064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8065. EXPECT_EQ(StatusCode::OK_200, res->status);
  8066. }
  8067. #endif
  8068. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8069. // Static file compression is opt-in, so these run their own server rather than
  8070. // flipping it on for the shared ServerTest fixture, which would silently
  8071. // rewrite what every other static file test is asserting.
  8072. class StaticFileCompressionTest : public ::testing::Test {
  8073. protected:
  8074. void TearDown() override {
  8075. if (t_.joinable()) {
  8076. svr_.stop();
  8077. t_.join();
  8078. }
  8079. }
  8080. int start(const std::function<void(Server &)> &configure = nullptr) {
  8081. // Serves the same tree as a directory of build-time compressed assets
  8082. // would be served: the mount point names the coding the files are already
  8083. // stored in. Registered before "/" so it is the one that matches.
  8084. svr_.set_mount_point("/pre-encoded", "./www",
  8085. {{"Content-Encoding", "gzip"}});
  8086. svr_.set_mount_point("/", "./www");
  8087. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8088. res.set_file_content("./www/dir/index.html", "text/html");
  8089. });
  8090. svr_.Get("/pre-encoded-file-content",
  8091. [](const Request & /*req*/, Response &res) {
  8092. res.set_header("Content-Encoding", "gzip");
  8093. res.set_file_content("./www/dir/index.html", "text/html");
  8094. });
  8095. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8096. res.set_content_provider(
  8097. 6, "text/plain",
  8098. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8099. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8100. return true;
  8101. });
  8102. });
  8103. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8104. res.set_content_provider(
  8105. 1000, "text/plain",
  8106. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8107. if (offset < 100) {
  8108. std::string data(100, 'A');
  8109. sink.write(data.data(), data.size());
  8110. return true;
  8111. }
  8112. std::this_thread::sleep_for(std::chrono::seconds(2));
  8113. std::string data(900, 'B');
  8114. sink.write(data.data(), data.size());
  8115. return true;
  8116. });
  8117. });
  8118. if (configure) { configure(svr_); }
  8119. auto port = svr_.bind_to_any_port(HOST);
  8120. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8121. svr_.wait_until_ready();
  8122. return port;
  8123. }
  8124. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8125. // Every file under ./www except 1MB.txt is smaller than the default
  8126. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8127. // it out of the way.
  8128. static void enable_without_floor(Server &svr) {
  8129. svr.set_static_file_compression(true);
  8130. svr.set_static_file_compression_min_length(0);
  8131. }
  8132. Server svr_;
  8133. std::thread t_;
  8134. };
  8135. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8136. auto port = start();
  8137. Client cli(HOST, port);
  8138. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(StatusCode::OK_200, res->status);
  8141. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8142. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8143. EXPECT_EQ(1048576U, res->body.size());
  8144. }
  8145. TEST_F(StaticFileCompressionTest, MountPoint) {
  8146. auto port = start(enable);
  8147. Client cli(HOST, port);
  8148. cli.set_decompress(false);
  8149. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. EXPECT_EQ(StatusCode::OK_200, res->status);
  8152. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8153. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8154. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8155. // The response stays self-delimiting: a length, not a chunked body.
  8156. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8157. EXPECT_EQ(std::to_string(res->body.size()),
  8158. res->get_header_value("Content-Length"));
  8159. EXPECT_LT(res->body.size(), 1048576U);
  8160. EXPECT_FALSE(res->body.empty());
  8161. }
  8162. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8163. auto port = start(enable);
  8164. Client cli(HOST, port);
  8165. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ(StatusCode::OK_200, res->status);
  8168. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8169. EXPECT_EQ(1048576U, res->body.size());
  8170. }
  8171. TEST_F(StaticFileCompressionTest, FileContent) {
  8172. auto port = start(enable_without_floor);
  8173. Client cli(HOST, port);
  8174. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8176. EXPECT_EQ(StatusCode::OK_200, res->status);
  8177. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8178. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8179. EXPECT_EQ(104U, res->body.size());
  8180. }
  8181. // A handler that serves an already-encoded file names the coding itself. The
  8182. // file-backed path decided its coding from Accept-Encoding and the content
  8183. // type alone, so it compressed the stored bytes a second time and appended a
  8184. // second Content-Encoding field line.
  8185. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8186. auto port = start(enable_without_floor);
  8187. Client cli(HOST, port);
  8188. cli.set_decompress(false);
  8189. auto res = cli.Get("/pre-encoded-file-content",
  8190. Headers{{"Accept-Encoding", "gzip"}});
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(StatusCode::OK_200, res->status);
  8193. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8194. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8195. // Vary belongs to a coding the server chose, and it chose none here.
  8196. EXPECT_FALSE(res->has_header("Vary"));
  8197. // The file travels exactly as it is stored on disk.
  8198. EXPECT_EQ(104U, res->body.size());
  8199. }
  8200. // The 1MB file clears the default floor, so this one runs the configuration a
  8201. // deployment would actually have.
  8202. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8203. auto port = start(enable);
  8204. Client cli(HOST, port);
  8205. cli.set_decompress(false);
  8206. auto res =
  8207. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8211. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8212. EXPECT_FALSE(res->has_header("Vary"));
  8213. EXPECT_EQ(1048576U, res->body.size());
  8214. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8215. }
  8216. TEST_F(StaticFileCompressionTest, Head) {
  8217. auto port = start(enable);
  8218. Client cli(HOST, port);
  8219. cli.set_decompress(false);
  8220. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8221. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8222. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8224. EXPECT_EQ(StatusCode::OK_200, res->status);
  8225. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8226. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8227. // HEAD still reports the size a GET would return.
  8228. EXPECT_EQ(get->get_header_value("Content-Length"),
  8229. res->get_header_value("Content-Length"));
  8230. EXPECT_TRUE(res->body.empty());
  8231. }
  8232. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8233. auto port = start(enable);
  8234. Client cli(HOST, port);
  8235. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8236. {"Accept-Encoding", "gzip"}});
  8237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8238. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8239. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8240. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8241. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8242. EXPECT_EQ("cd", res->body);
  8243. }
  8244. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8245. auto port = start(enable);
  8246. Client cli(HOST, port);
  8247. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8249. EXPECT_EQ(StatusCode::OK_200, res->status);
  8250. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8251. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8252. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8253. }
  8254. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8255. auto port = start(enable);
  8256. Client cli(HOST, port);
  8257. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8259. EXPECT_EQ(StatusCode::OK_200, res->status);
  8260. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8261. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8262. EXPECT_TRUE(res->body.empty());
  8263. }
  8264. TEST_F(StaticFileCompressionTest, MinLength) {
  8265. auto port = start(enable);
  8266. Client cli(HOST, port);
  8267. // 104 bytes, well under the default floor. Compressing it would add the
  8268. // gzip header and trailer to a body that already fits in one packet.
  8269. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8271. EXPECT_EQ(StatusCode::OK_200, res->status);
  8272. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8273. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8274. }
  8275. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8276. auto port = start([](Server &svr) {
  8277. svr.set_static_file_compression(true);
  8278. svr.set_static_file_compression_min_length(1);
  8279. });
  8280. Client cli(HOST, port);
  8281. cli.set_decompress(false);
  8282. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8284. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8285. // A 9-byte file comes back larger than it went in, because gzip's header and
  8286. // trailer outweigh anything deflate can save. That is the end of the range
  8287. // the floor exists to keep out.
  8288. EXPECT_GT(res->body.size(), 9U);
  8289. }
  8290. TEST_F(StaticFileCompressionTest, MaxLength) {
  8291. auto port = start([](Server &svr) {
  8292. svr.set_static_file_compression(true);
  8293. svr.set_static_file_compression_min_length(0);
  8294. svr.set_static_file_compression_max_length(1024);
  8295. });
  8296. Client cli(HOST, port);
  8297. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8298. // defines `small` as a macro on Windows.
  8299. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8300. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8301. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8302. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8303. // Under it: compressed.
  8304. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8305. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8306. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8307. }
  8308. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8309. auto port = start(enable_without_floor);
  8310. Client cli(HOST, port);
  8311. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8312. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8313. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8314. auto identity_etag = identity->get_header_value("ETag");
  8315. ASSERT_FALSE(identity_etag.empty());
  8316. auto gzipped =
  8317. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8318. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8319. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8320. auto gzip_etag = gzipped->get_header_value("ETag");
  8321. ASSERT_FALSE(gzip_etag.empty());
  8322. // Two representations, two validators.
  8323. EXPECT_NE(identity_etag, gzip_etag);
  8324. // Each one revalidates against the request that would produce it...
  8325. auto fresh =
  8326. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8327. {"If-None-Match", gzip_etag}});
  8328. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8329. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8330. auto fresh_identity =
  8331. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8332. {"If-None-Match", identity_etag}});
  8333. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8334. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8335. // ...and not against the other representation.
  8336. auto crossed =
  8337. cli.Get("/dir/index.html",
  8338. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8339. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8340. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8341. }
  8342. // The opt-in covers responses the server reads off disk itself. A caller's own
  8343. // known-length provider keeps its Content-Length and, more importantly, keeps
  8344. // delivering incrementally: routing it through a compressor would hold every
  8345. // write back until zlib's window filled.
  8346. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8347. auto port = start(enable);
  8348. Client cli(HOST, port);
  8349. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8351. EXPECT_EQ(StatusCode::OK_200, res->status);
  8352. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8353. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8354. EXPECT_EQ("aaabbb", res->body);
  8355. }
  8356. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8357. auto port = start(enable);
  8358. Client cli(HOST, port);
  8359. cli.set_read_timeout(1, 0);
  8360. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8361. Headers{{"Accept-Encoding", "gzip"}});
  8362. ASSERT_TRUE(handle.is_valid());
  8363. // The provider writes 100 bytes and then stalls for longer than the read
  8364. // timeout. Those first bytes have to arrive anyway: run the response through
  8365. // a compressor and zlib holds them until its window fills, so the read would
  8366. // come back empty instead.
  8367. char buf[256];
  8368. auto n = handle.read(buf, sizeof(buf));
  8369. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8370. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8371. }
  8372. #endif
  8373. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8374. TEST_F(ServerTest, Brotli) {
  8375. Headers headers;
  8376. headers.emplace("Accept-Encoding", "br");
  8377. auto res = cli_.Get("/compress", headers);
  8378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8379. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8380. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8381. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8382. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8383. "7890123456789012345678901234567890",
  8384. res->body);
  8385. EXPECT_EQ(StatusCode::OK_200, res->status);
  8386. }
  8387. #endif
  8388. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8389. TEST_F(ServerTest, Zstd) {
  8390. Headers headers;
  8391. headers.emplace("Accept-Encoding", "zstd");
  8392. auto res = cli_.Get("/compress", headers);
  8393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8394. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8395. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8396. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8397. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8398. "7890123456789012345678901234567890",
  8399. res->body);
  8400. EXPECT_EQ(StatusCode::OK_200, res->status);
  8401. }
  8402. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8403. Headers headers;
  8404. headers.emplace("Accept-Encoding", "");
  8405. auto res = cli_.Get("/compress", headers);
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8408. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8409. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8410. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8411. "7890123456789012345678901234567890",
  8412. res->body);
  8413. EXPECT_EQ(StatusCode::OK_200, res->status);
  8414. }
  8415. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8416. Headers headers;
  8417. headers.emplace("Accept-Encoding", "zstd");
  8418. std::string body;
  8419. auto res = cli_.Get("/compress", headers,
  8420. [&](const char *data, uint64_t data_length) {
  8421. EXPECT_EQ(100U, data_length);
  8422. body.append(data, data_length);
  8423. return true;
  8424. });
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8428. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8429. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8430. "7890123456789012345678901234567890",
  8431. body);
  8432. EXPECT_EQ(StatusCode::OK_200, res->status);
  8433. }
  8434. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8435. Headers headers;
  8436. headers.emplace("Accept-Encoding", "zstd");
  8437. cli_.set_decompress(false);
  8438. auto res = cli_.Get("/compress", headers);
  8439. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8440. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8441. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8442. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8444. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8445. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8446. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8447. EXPECT_EQ(StatusCode::OK_200, res->status);
  8448. ASSERT_EQ(26U, res->body.size());
  8449. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8450. 0);
  8451. }
  8452. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8453. Headers headers;
  8454. headers.emplace("Accept-Encoding", "");
  8455. std::string body;
  8456. auto res = cli_.Get("/compress", headers,
  8457. [&](const char *data, uint64_t data_length) {
  8458. EXPECT_EQ(100U, data_length);
  8459. body.append(data, data_length);
  8460. return true;
  8461. });
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8464. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8465. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8466. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8467. "7890123456789012345678901234567890",
  8468. body);
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. }
  8471. TEST_F(ServerTest, NoZstd) {
  8472. Headers headers;
  8473. headers.emplace("Accept-Encoding", "zstd");
  8474. auto res = cli_.Get("/nocompress", headers);
  8475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8476. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8477. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8478. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8479. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8480. "7890123456789012345678901234567890",
  8481. res->body);
  8482. EXPECT_EQ(StatusCode::OK_200, res->status);
  8483. }
  8484. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8485. Headers headers;
  8486. headers.emplace("Accept-Encoding", "zstd");
  8487. std::string body;
  8488. auto res = cli_.Get("/nocompress", headers,
  8489. [&](const char *data, uint64_t data_length) {
  8490. EXPECT_EQ(100U, data_length);
  8491. body.append(data, data_length);
  8492. return true;
  8493. });
  8494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8495. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8496. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8497. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8498. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8499. "7890123456789012345678901234567890",
  8500. body);
  8501. EXPECT_EQ(StatusCode::OK_200, res->status);
  8502. }
  8503. // TODO: How to enable zstd ??
  8504. TEST_F(ServerTest, MultipartFormDataZstd) {
  8505. UploadFormDataItems items = {
  8506. {"key1", "test", "", ""},
  8507. {"key2", "--abcdefg123", "", ""},
  8508. };
  8509. Headers headers;
  8510. headers.emplace("Accept-Encoding", "zstd");
  8511. cli_.set_compress(true);
  8512. auto res = cli_.Post("/compress-multipart", headers, items);
  8513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8514. EXPECT_EQ(StatusCode::OK_200, res->status);
  8515. }
  8516. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8517. Headers headers;
  8518. headers.emplace("Accept-Encoding", "zstd");
  8519. cli_.set_compress(true);
  8520. auto res = cli_.Put(
  8521. "/put", headers, 3,
  8522. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8523. sink.os << "PUT";
  8524. return true;
  8525. },
  8526. "text/plain");
  8527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8528. EXPECT_EQ(StatusCode::OK_200, res->status);
  8529. EXPECT_EQ("PUT", res->body);
  8530. }
  8531. // Pre-compression logging tests
  8532. TEST_F(ServerTest, PreCompressionLogging) {
  8533. // Test data for compression (matches the actual /compress endpoint content)
  8534. const std::string test_content =
  8535. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8536. "3456789012345678901234567890";
  8537. // Variables to capture logging data
  8538. std::string pre_compression_body;
  8539. std::string pre_compression_content_type;
  8540. std::string pre_compression_content_encoding;
  8541. std::string post_compression_body;
  8542. std::string post_compression_content_type;
  8543. std::string post_compression_content_encoding;
  8544. // Set up pre-compression logger
  8545. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8546. const Response &res) {
  8547. pre_compression_body = res.body;
  8548. pre_compression_content_type = res.get_header_value("Content-Type");
  8549. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8550. });
  8551. // Set up post-compression logger
  8552. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8553. post_compression_body = res.body;
  8554. post_compression_content_type = res.get_header_value("Content-Type");
  8555. post_compression_content_encoding =
  8556. res.get_header_value("Content-Encoding");
  8557. });
  8558. // Test with gzip compression
  8559. Headers headers;
  8560. headers.emplace("Accept-Encoding", "gzip");
  8561. auto res = cli_.Get("/compress", headers);
  8562. // Verify response was compressed
  8563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8564. EXPECT_EQ(StatusCode::OK_200, res->status);
  8565. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8566. // Verify pre-compression logger captured uncompressed content
  8567. EXPECT_EQ(test_content, pre_compression_body);
  8568. EXPECT_EQ("text/plain", pre_compression_content_type);
  8569. EXPECT_TRUE(pre_compression_content_encoding
  8570. .empty()); // No encoding header before compression
  8571. // Verify post-compression logger captured compressed content
  8572. EXPECT_NE(test_content,
  8573. post_compression_body); // Should be different after compression
  8574. EXPECT_EQ("text/plain", post_compression_content_type);
  8575. EXPECT_EQ("gzip", post_compression_content_encoding);
  8576. // Verify compressed content is smaller
  8577. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8578. }
  8579. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8580. const std::string test_content =
  8581. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8582. "3456789012345678901234567890";
  8583. std::string pre_compression_body;
  8584. std::string post_compression_body;
  8585. svr_.set_pre_compression_logger(
  8586. [&](const Request & /*req*/, const Response &res) {
  8587. pre_compression_body = res.body;
  8588. });
  8589. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8590. post_compression_body = res.body;
  8591. });
  8592. Headers headers;
  8593. headers.emplace("Accept-Encoding", "br");
  8594. auto res = cli_.Get("/compress", headers);
  8595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8596. EXPECT_EQ(StatusCode::OK_200, res->status);
  8597. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8598. // Verify pre-compression content is uncompressed
  8599. EXPECT_EQ(test_content, pre_compression_body);
  8600. // Verify post-compression content is compressed
  8601. EXPECT_NE(test_content, post_compression_body);
  8602. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8603. }
  8604. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8605. const std::string test_content =
  8606. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8607. "3456789012345678901234567890";
  8608. std::string pre_compression_body;
  8609. std::string post_compression_body;
  8610. svr_.set_pre_compression_logger(
  8611. [&](const Request & /*req*/, const Response &res) {
  8612. pre_compression_body = res.body;
  8613. });
  8614. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8615. post_compression_body = res.body;
  8616. });
  8617. // Request without compression (use /nocompress endpoint)
  8618. Headers headers;
  8619. auto res = cli_.Get("/nocompress", headers);
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ(StatusCode::OK_200, res->status);
  8622. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8623. // Pre-compression logger should not be called when no compression is applied
  8624. EXPECT_TRUE(
  8625. pre_compression_body.empty()); // Pre-compression logger not called
  8626. EXPECT_EQ(
  8627. test_content,
  8628. post_compression_body); // Post-compression logger captures final content
  8629. }
  8630. TEST_F(ServerTest, LoggerSeesContentLength) {
  8631. size_t logged_content_length = 0;
  8632. std::string logged_content_length_header;
  8633. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8634. logged_content_length = res.content_length_;
  8635. logged_content_length_header = res.get_header_value("Content-Length");
  8636. });
  8637. auto res = cli_.Get("/nocompress");
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ(StatusCode::OK_200, res->status);
  8640. EXPECT_EQ(res->body.size(), logged_content_length);
  8641. EXPECT_EQ(std::to_string(logged_content_length),
  8642. logged_content_length_header);
  8643. }
  8644. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8645. const std::string test_content =
  8646. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8647. "3456789012345678901234567890";
  8648. std::string pre_compression_body;
  8649. bool pre_logger_called = false;
  8650. // Set only pre-compression logger
  8651. svr_.set_pre_compression_logger(
  8652. [&](const Request & /*req*/, const Response &res) {
  8653. pre_compression_body = res.body;
  8654. pre_logger_called = true;
  8655. });
  8656. Headers headers;
  8657. headers.emplace("Accept-Encoding", "gzip");
  8658. auto res = cli_.Get("/compress", headers);
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8662. // Verify pre-compression logger was called
  8663. EXPECT_TRUE(pre_logger_called);
  8664. EXPECT_EQ(test_content, pre_compression_body);
  8665. }
  8666. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8667. {
  8668. // Test with Expect: 100-continue header - success case
  8669. // Server returns 100 Continue, client sends body, server returns 200 OK
  8670. Request req;
  8671. req.method = "POST";
  8672. req.path = "/post-large";
  8673. req.set_header("Expect", "100-continue");
  8674. req.body = LARGE_DATA;
  8675. Response res;
  8676. auto error = Error::Success;
  8677. cli_.set_keep_alive(true);
  8678. auto ret = cli_.send(req, res, error);
  8679. EXPECT_TRUE(ret);
  8680. EXPECT_EQ(StatusCode::OK_200, res.status);
  8681. EXPECT_EQ(LARGE_DATA, res.body);
  8682. }
  8683. {
  8684. // Test with Expect: 100-continue header - error case
  8685. // Client should not send the body when server returns an error
  8686. Request req;
  8687. req.method = "POST";
  8688. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8689. req.set_header("Expect", "100-continue");
  8690. req.body = LARGE_DATA;
  8691. Response res;
  8692. auto error = Error::Success;
  8693. auto start = std::chrono::high_resolution_clock::now();
  8694. cli_.set_keep_alive(true);
  8695. auto ret = cli_.send(req, res, error);
  8696. auto end = std::chrono::high_resolution_clock::now();
  8697. auto elapsed =
  8698. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8699. .count();
  8700. // With Expect: 100-continue, request completes successfully but with error
  8701. EXPECT_TRUE(ret);
  8702. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8703. EXPECT_EQ("close", res.get_header_value("Connection"));
  8704. EXPECT_FALSE(cli_.is_socket_open());
  8705. EXPECT_LE(elapsed, 2000);
  8706. }
  8707. {
  8708. // Send an extra GET request to ensure error recovery without hanging
  8709. Request req;
  8710. req.method = "GET";
  8711. req.path = "/hi";
  8712. auto start = std::chrono::high_resolution_clock::now();
  8713. auto res = cli_.send(req);
  8714. auto end = std::chrono::high_resolution_clock::now();
  8715. auto elapsed =
  8716. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8717. .count();
  8718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8719. EXPECT_EQ(StatusCode::OK_200, res->status);
  8720. EXPECT_EQ("Hello World!", res->body);
  8721. EXPECT_LE(elapsed, 500);
  8722. }
  8723. }
  8724. TEST(ZstdDecompressor, ChunkedDecompression) {
  8725. std::string data;
  8726. for (size_t i = 0; i < 32 * 1024; ++i) {
  8727. data.push_back(static_cast<char>('a' + i % 26));
  8728. }
  8729. std::string compressed_data;
  8730. {
  8731. httplib::detail::zstd_compressor compressor;
  8732. bool result = compressor.compress(
  8733. data.data(), data.size(),
  8734. /*last=*/true,
  8735. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8736. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8737. compressed_data_size);
  8738. return true;
  8739. });
  8740. ASSERT_TRUE(result);
  8741. }
  8742. std::string decompressed_data;
  8743. {
  8744. httplib::detail::zstd_decompressor decompressor;
  8745. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8746. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8747. size_t chunk_size = 130;
  8748. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8749. chunk_begin += chunk_size) {
  8750. size_t current_chunk_size =
  8751. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8752. bool result = decompressor.decompress(
  8753. compressed_data.data() + chunk_begin, current_chunk_size,
  8754. [&](const char *decompressed_data_chunk,
  8755. size_t decompressed_data_chunk_size) {
  8756. decompressed_data.insert(decompressed_data.size(),
  8757. decompressed_data_chunk,
  8758. decompressed_data_chunk_size);
  8759. return true;
  8760. });
  8761. ASSERT_TRUE(result);
  8762. }
  8763. }
  8764. ASSERT_EQ(data, decompressed_data);
  8765. }
  8766. TEST(ZstdDecompressor, Decompress) {
  8767. std::string original_text = "Compressed with ZSTD";
  8768. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8769. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8770. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8771. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8772. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8773. std::string decompressed_data;
  8774. {
  8775. httplib::detail::zstd_decompressor decompressor;
  8776. bool result = decompressor.decompress(
  8777. compressed_data.data(), compressed_data.size(),
  8778. [&](const char *decompressed_data_chunk,
  8779. size_t decompressed_data_chunk_size) {
  8780. decompressed_data.insert(decompressed_data.size(),
  8781. decompressed_data_chunk,
  8782. decompressed_data_chunk_size);
  8783. return true;
  8784. });
  8785. ASSERT_TRUE(result);
  8786. }
  8787. ASSERT_EQ(original_text, decompressed_data);
  8788. }
  8789. #endif
  8790. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8791. // separate chunks so that the server sees each part in its own read(). Used to
  8792. // place a read boundary at a specific offset of a request body.
  8793. static bool send_request_in_parts(time_t read_timeout_sec,
  8794. const std::vector<std::string> &parts,
  8795. std::string *resp = nullptr,
  8796. int port = PORT) {
  8797. auto error = Error::Success;
  8798. auto client_sock = detail::create_client_socket(
  8799. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8800. /*connection_timeout_sec=*/5, 0,
  8801. /*read_timeout_sec=*/5, 0,
  8802. /*write_timeout_sec=*/5, 0, std::string(), error);
  8803. if (client_sock == INVALID_SOCKET) { return false; }
  8804. auto ret = detail::process_client_socket(
  8805. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8806. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8807. for (size_t i = 0; i < parts.size(); i++) {
  8808. const auto &part = parts[i];
  8809. if (part.size() !=
  8810. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8811. return false;
  8812. }
  8813. if (i + 1 < parts.size()) {
  8814. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8815. }
  8816. }
  8817. char buf[512];
  8818. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8819. while (line_reader.getline()) {
  8820. if (resp) { *resp += line_reader.ptr(); }
  8821. }
  8822. return true;
  8823. });
  8824. detail::close_socket(client_sock);
  8825. return ret;
  8826. }
  8827. // Sends a raw request to a server listening at HOST:PORT.
  8828. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8829. std::string *resp = nullptr, int port = PORT) {
  8830. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8831. }
  8832. #ifdef CPPHTTPLIB_SSL_ENABLED
  8833. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8835. ASSERT_TRUE(svr.is_valid());
  8836. svr.set_read_timeout(1, 0);
  8837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8838. auto se = detail::scope_exit([&] {
  8839. svr.stop();
  8840. t.join();
  8841. ASSERT_FALSE(svr.is_running());
  8842. });
  8843. svr.wait_until_ready();
  8844. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8845. // keeps each wait well within the read timeout. The server gives up a
  8846. // second in, so the bytes sent after that fail.
  8847. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8848. parts.resize(26, std::string(1, '\0'));
  8849. EXPECT_FALSE(send_request_in_parts(5, parts));
  8850. }
  8851. #endif
  8852. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8853. Server svr;
  8854. std::string header_value;
  8855. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8856. header_value = req.get_header_value("foo");
  8857. res.set_content("ok", "text/plain");
  8858. });
  8859. thread t = thread([&] { svr.listen(HOST, PORT); });
  8860. auto se = detail::scope_exit([&] {
  8861. svr.stop();
  8862. t.join();
  8863. ASSERT_FALSE(svr.is_running());
  8864. });
  8865. svr.wait_until_ready();
  8866. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8867. // like characters are not treated the same - use vertical tab and escape.
  8868. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8869. "foo: \t \v bar \x1B\t \r\n"
  8870. "Connection: close\r\n"
  8871. "\r\n";
  8872. std::string res;
  8873. ASSERT_TRUE(send_request(5, req, &res));
  8874. EXPECT_EQ(header_value, "");
  8875. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8876. }
  8877. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8878. Server svr;
  8879. std::string received;
  8880. svr.Get("/order", [&](const Request &req, Response &res) {
  8881. received = entries_to_string(req.headers);
  8882. res.set_content("ok", "text/plain");
  8883. });
  8884. auto port = svr.bind_to_any_port(HOST);
  8885. thread t = thread([&] { svr.listen_after_bind(); });
  8886. auto se = detail::scope_exit([&] {
  8887. svr.stop();
  8888. t.join();
  8889. ASSERT_FALSE(svr.is_running());
  8890. });
  8891. svr.wait_until_ready();
  8892. const std::string req = "GET /order HTTP/1.1\r\n"
  8893. "Host: localhost\r\n"
  8894. "X-First: 1\r\n"
  8895. "X-Dup: a\r\n"
  8896. "X-Second: 2\r\n"
  8897. "X-Dup: b\r\n"
  8898. "Connection: close\r\n"
  8899. "\r\n";
  8900. std::string res;
  8901. ASSERT_TRUE(send_request(5, req, &res, port));
  8902. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8903. EXPECT_EQ(
  8904. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  8905. received);
  8906. }
  8907. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8908. Server svr;
  8909. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8910. res.set_header("Set-Cookie", "first=1");
  8911. res.set_header("X-Between", "y");
  8912. res.set_header("Set-Cookie", "second=2");
  8913. res.set_content("ok", "text/plain");
  8914. });
  8915. auto port = svr.bind_to_any_port(HOST);
  8916. thread t = thread([&] { svr.listen_after_bind(); });
  8917. auto se = detail::scope_exit([&] {
  8918. svr.stop();
  8919. t.join();
  8920. ASSERT_FALSE(svr.is_running());
  8921. });
  8922. svr.wait_until_ready();
  8923. Client cli(HOST, port);
  8924. auto res = cli.Get("/cookies");
  8925. ASSERT_TRUE(res);
  8926. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8927. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8928. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8929. }
  8930. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8931. Server svr;
  8932. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8933. auto i = new int(0);
  8934. res.set_header("Trailer", "X-Safe, X-Reflected");
  8935. res.set_chunked_content_provider(
  8936. "text/plain",
  8937. [i](size_t /*offset*/, DataSink &sink) {
  8938. if (*i == 0) {
  8939. sink.os << "body";
  8940. } else {
  8941. Headers trailer;
  8942. // A valid trailer that must survive.
  8943. trailer.emplace("X-Safe", "safe");
  8944. // Attacker-controlled value carrying CR/LF (response splitting).
  8945. trailer.emplace("X-Reflected",
  8946. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8947. // Attacker-controlled name carrying CR/LF.
  8948. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8949. sink.done_with_trailer(trailer);
  8950. }
  8951. (*i)++;
  8952. return true;
  8953. },
  8954. [i](bool /*success*/) { delete i; });
  8955. });
  8956. thread t = thread([&] { svr.listen(HOST, PORT); });
  8957. auto se = detail::scope_exit([&] {
  8958. svr.stop();
  8959. t.join();
  8960. ASSERT_FALSE(svr.is_running());
  8961. });
  8962. svr.wait_until_ready();
  8963. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8964. "Host: " + HOST +
  8965. "\r\n"
  8966. "Connection: close\r\n"
  8967. "\r\n";
  8968. std::string res;
  8969. ASSERT_TRUE(send_request(5, req, &res));
  8970. // The injected fields must not appear anywhere in the raw response.
  8971. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8972. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8973. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8974. // Invalid trailers are dropped entirely, matching set_header().
  8975. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8976. // The valid trailer still passes through.
  8977. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8978. }
  8979. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8980. Server svr;
  8981. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8982. // res.headers is a public field an application can populate directly,
  8983. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8984. // A valid header that must survive.
  8985. res.headers.emplace("X-Safe", "safe");
  8986. // Attacker-controlled value carrying CR/LF (response splitting).
  8987. res.headers.emplace("X-Reflected",
  8988. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8989. // Attacker-controlled name carrying CR/LF.
  8990. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8991. res.set_content("body", "text/plain");
  8992. });
  8993. thread t = thread([&] { svr.listen(HOST, PORT); });
  8994. auto se = detail::scope_exit([&] {
  8995. svr.stop();
  8996. t.join();
  8997. ASSERT_FALSE(svr.is_running());
  8998. });
  8999. svr.wait_until_ready();
  9000. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9001. "Host: " + HOST +
  9002. "\r\n"
  9003. "Connection: close\r\n"
  9004. "\r\n";
  9005. std::string res;
  9006. ASSERT_TRUE(send_request(5, req, &res));
  9007. // The injected fields must not appear anywhere in the raw response.
  9008. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9009. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9010. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9011. // Invalid headers are dropped entirely, matching set_header().
  9012. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9013. // The valid header still passes through.
  9014. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9015. }
  9016. // Forward declaration: in split builds split.py strips `inline` and moves the
  9017. // definition into httplib.cc, so detail::write_request_line is not visible from
  9018. // the public httplib.h. Re-declaring it here lets the tests link against the
  9019. // symbol in both header-only and split builds.
  9020. namespace httplib {
  9021. namespace detail {
  9022. ssize_t write_request_line(Stream &strm, const std::string &method,
  9023. const std::string &path);
  9024. } // namespace detail
  9025. } // namespace httplib
  9026. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9027. // A well-formed target is written verbatim.
  9028. {
  9029. detail::BufferStream strm;
  9030. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9031. EXPECT_GT(n, 0);
  9032. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9033. }
  9034. // A target carrying CR/LF, SP or other control octets must be rejected
  9035. // before anything reaches the wire, otherwise it splits the request line and
  9036. // injects a header or a whole request.
  9037. const std::string evil_targets[] = {
  9038. "/a\r\nInjected: pwned",
  9039. "/a\rInjected",
  9040. "/a\nInjected",
  9041. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9042. "/a b",
  9043. "/a\tb",
  9044. "/a\x7f",
  9045. };
  9046. for (const auto &evil : evil_targets) {
  9047. detail::BufferStream strm;
  9048. auto n = detail::write_request_line(strm, "GET", evil);
  9049. EXPECT_LT(n, 0);
  9050. EXPECT_TRUE(strm.get_buffer().empty());
  9051. }
  9052. }
  9053. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9054. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9055. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9056. // target reaches write_request. The client must fail cleanly with
  9057. // Error::Write instead of putting a request-line-less, header-injecting
  9058. // request on the wire.
  9059. Server svr;
  9060. svr.Get("/a", [](const Request &, Response &res) {
  9061. res.set_content("ok", "text/plain");
  9062. });
  9063. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9064. auto se = detail::scope_exit([&] {
  9065. svr.stop();
  9066. thread.join();
  9067. ASSERT_FALSE(svr.is_running());
  9068. });
  9069. svr.wait_until_ready();
  9070. {
  9071. Client cli(HOST, PORT);
  9072. cli.set_path_encode(false);
  9073. // The request is rejected before anything is written, so the connection
  9074. // stays silent and the subsequent response read would otherwise block for
  9075. // the full default read timeout. Shorten it -- the assertion is on the
  9076. // error, not the timeout.
  9077. cli.set_read_timeout(1, 0);
  9078. auto res = cli.Get("/a\r\nInjected: pwned");
  9079. EXPECT_FALSE(res);
  9080. EXPECT_EQ(Error::Write, res.error());
  9081. }
  9082. }
  9083. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9084. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9085. // including extension methods.
  9086. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9087. for (const auto &method : good_methods) {
  9088. detail::BufferStream strm;
  9089. auto n = detail::write_request_line(strm, method, "/");
  9090. EXPECT_GT(n, 0);
  9091. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9092. }
  9093. // A method carrying CR/LF would split the request line and smuggle a whole
  9094. // request ahead of the real one. A space or an empty method corrupts the
  9095. // request line. All must be rejected before anything reaches the wire.
  9096. const std::string evil_methods[] = {
  9097. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9098. "GET\r\nInjected: pwned",
  9099. "GET\r",
  9100. "GET\n",
  9101. "GE T",
  9102. "",
  9103. };
  9104. for (const auto &evil : evil_methods) {
  9105. detail::BufferStream strm;
  9106. auto n = detail::write_request_line(strm, evil, "/");
  9107. EXPECT_LT(n, 0);
  9108. EXPECT_TRUE(strm.get_buffer().empty());
  9109. }
  9110. }
  9111. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9112. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9113. // through Client::send must fail with Error::Write and no request, neither
  9114. // the smuggled one nor the real one, may reach the server.
  9115. Server svr;
  9116. std::atomic<int> request_count(0);
  9117. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9118. request_count++;
  9119. res.status = StatusCode::OK_200;
  9120. return Server::HandlerResponse::Handled;
  9121. });
  9122. auto port = svr.bind_to_any_port(HOST);
  9123. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9124. auto se = detail::scope_exit([&] {
  9125. svr.stop();
  9126. thread.join();
  9127. ASSERT_FALSE(svr.is_running());
  9128. });
  9129. svr.wait_until_ready();
  9130. {
  9131. Client cli(HOST, port);
  9132. const std::string evil_methods[] = {
  9133. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9134. "GE T",
  9135. "",
  9136. };
  9137. for (const auto &evil : evil_methods) {
  9138. Request req;
  9139. req.method = evil;
  9140. req.path = "/";
  9141. auto res = cli.send(req);
  9142. EXPECT_FALSE(res);
  9143. EXPECT_EQ(Error::Write, res.error());
  9144. }
  9145. auto handle =
  9146. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9147. EXPECT_FALSE(handle.is_valid());
  9148. EXPECT_EQ(Error::Write, handle.error);
  9149. // A valid request on the same client still goes through.
  9150. auto res = cli.Get("/");
  9151. ASSERT_TRUE(res);
  9152. EXPECT_EQ(StatusCode::OK_200, res->status);
  9153. }
  9154. EXPECT_EQ(1, request_count.load());
  9155. }
  9156. // Sends a raw request and verifies that there isn't a crash or exception.
  9157. static void test_raw_request(const std::string &req,
  9158. std::string *out = nullptr) {
  9159. Server svr;
  9160. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9161. res.set_content("ok", "text/plain");
  9162. });
  9163. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9164. res.set_content("ok", "text/plain");
  9165. });
  9166. svr.Get("/header_field_value_check",
  9167. [&](const Request & /*req*/, Response &res) {
  9168. res.set_content("ok", "text/plain");
  9169. });
  9170. svr.CustomRoute("PROPFIND", "/dav",
  9171. [&](const Request & /*req*/, Response &res) {
  9172. res.status = StatusCode::MultiStatus_207;
  9173. });
  9174. // Server read timeout must be longer than the client read timeout for the
  9175. // bug to reproduce, probably to force the server to process a request
  9176. // without a trailing blank line.
  9177. const time_t client_read_timeout_sec = 1;
  9178. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9179. bool listen_thread_ok = false;
  9180. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9181. auto se = detail::scope_exit([&] {
  9182. svr.stop();
  9183. t.join();
  9184. ASSERT_FALSE(svr.is_running());
  9185. EXPECT_TRUE(listen_thread_ok);
  9186. });
  9187. svr.wait_until_ready();
  9188. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9189. }
  9190. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9191. // A certain header line causes an exception if the header property is parsed
  9192. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9193. test_raw_request(
  9194. "GET /hi HTTP/1.1\r\n"
  9195. " : "
  9196. " "
  9197. " ");
  9198. }
  9199. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9200. // A certain header line causes an exception if the header property *name* is
  9201. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9202. // greedy matcher and requires backtracking when there are a lot of ":"
  9203. // characters.
  9204. // This occurs with libc++ but not libstdc++.
  9205. test_raw_request(
  9206. "GET /hi HTTP/1.1\r\n"
  9207. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9208. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9209. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9210. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9211. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9212. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9213. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9214. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9215. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9216. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9217. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9218. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9219. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9220. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9221. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9222. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9223. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9224. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9225. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9226. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9227. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9228. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9229. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9230. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9231. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9232. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9233. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9234. "&&&%%%");
  9235. }
  9236. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9237. // Make sure this doesn't crash the server.
  9238. // In a previous version of the header line regex, the "\r" rendered the line
  9239. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9240. // a new position where the leading white space ended and the field value
  9241. // began.
  9242. // The crash occurs with libc++ but not libstdc++.
  9243. test_raw_request("GET /hi HTTP/1.1\r\n"
  9244. "a:" +
  9245. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9246. "\r\n"
  9247. "\r\n");
  9248. }
  9249. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9250. const char *rejected[] = {
  9251. // RFC 9112 §3: one SP between the parts, and nothing else
  9252. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9253. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9254. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9255. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9256. // A request-target has no fragment
  9257. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9258. // An HTTP/1.1 request needs a Host
  9259. "GET /hi HTTP/1.1\r\n\r\n",
  9260. };
  9261. for (auto request : rejected) {
  9262. std::string out;
  9263. test_raw_request(request, &out);
  9264. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9265. }
  9266. std::string out;
  9267. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9268. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9269. }
  9270. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9271. // RFC 9112 §6.1
  9272. const char *requests[] = {
  9273. "PUT /put_hi HTTP/1.1\r\n"
  9274. "Host: localhost\r\n"
  9275. "Content-Length: 0\r\n"
  9276. "Transfer-Encoding: chunked\r\n"
  9277. "\r\n"
  9278. "0\r\n\r\n",
  9279. "PUT /put_hi HTTP/1.0\r\n"
  9280. "Connection: keep-alive\r\n"
  9281. "Transfer-Encoding: chunked\r\n"
  9282. "\r\n"
  9283. "0\r\n\r\n",
  9284. };
  9285. for (auto request : requests) {
  9286. std::string out;
  9287. test_raw_request(request, &out);
  9288. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9289. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9290. }
  9291. }
  9292. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9293. std::string out;
  9294. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9295. "Content-Type: text/plain\r\n"
  9296. "Transfer-Encoding: chunked\r\n"
  9297. "\r\n"
  9298. "nothex\r\n",
  9299. &out);
  9300. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9301. }
  9302. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9303. std::string out;
  9304. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9305. "Content-Type: text/plain\r\n"
  9306. "Transfer-Encoding: chunked\r\n"
  9307. "\r\n"
  9308. "3\r\n"
  9309. "xyz\r\n"
  9310. "NaN\r\n",
  9311. &out);
  9312. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9313. }
  9314. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9315. std::string out;
  9316. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9317. "Content-Type: text/plain\r\n"
  9318. "Transfer-Encoding: chunked\r\n"
  9319. "\r\n"
  9320. // Length is too large for 64 bits.
  9321. "1ffffffffffffffff\r\n"
  9322. "xyz\r\n",
  9323. &out);
  9324. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9325. }
  9326. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9327. test_raw_request("GET /hi HTTP/1.1\r\n"
  9328. "Content-Type: text/plain\r\n\r");
  9329. }
  9330. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9331. std::string out;
  9332. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9333. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9334. }
  9335. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9336. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9337. std::string out;
  9338. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9339. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9340. }
  9341. }
  9342. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9343. std::string out;
  9344. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9345. "Host: localhost\r\n"
  9346. "Connection: close\r\n\r\n",
  9347. &out);
  9348. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9349. }
  9350. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9351. Server svr;
  9352. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9353. EXPECT_TRUE(!req.remote_addr.empty());
  9354. });
  9355. thread t = thread([&] { svr.listen(HOST, PORT); });
  9356. auto se = detail::scope_exit([&] {
  9357. svr.stop();
  9358. t.join();
  9359. ASSERT_FALSE(svr.is_running());
  9360. });
  9361. svr.wait_until_ready();
  9362. // Send an invalid request line to trigger Bad Request
  9363. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9364. std::string out;
  9365. ASSERT_TRUE(send_request(5, bad_req, &out));
  9366. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9367. }
  9368. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9369. // answered right away rather than blocking on a read that waits for EOF.
  9370. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9371. std::string out;
  9372. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9373. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9374. }
  9375. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9376. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9377. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9378. for (const auto *method : methods) {
  9379. Server svr;
  9380. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9381. EXPECT_FALSE(svr.is_valid()) << method;
  9382. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9383. }
  9384. }
  9385. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9386. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9387. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9388. for (const auto *method : methods) {
  9389. Server svr;
  9390. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9391. EXPECT_FALSE(svr.is_valid()) << method;
  9392. }
  9393. }
  9394. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9395. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9396. "COPY", "MOVE", "LOCK",
  9397. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9398. Server svr;
  9399. for (const auto *method : methods) {
  9400. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9401. }
  9402. EXPECT_TRUE(svr.is_valid());
  9403. }
  9404. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9405. Server svr;
  9406. svr.CustomRoute("POST", "/x",
  9407. [](const Request &, Response &, const ContentReader &) {});
  9408. EXPECT_FALSE(svr.is_valid());
  9409. }
  9410. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9411. Server svr;
  9412. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9413. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9414. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9415. EXPECT_FALSE(svr.is_valid());
  9416. }
  9417. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9418. Server svr;
  9419. auto captured = Error::Success;
  9420. svr.set_error_logger(
  9421. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9422. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9423. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9424. }
  9425. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9426. std::string out;
  9427. std::string request(
  9428. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9429. test_raw_request(request, &out);
  9430. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9431. }
  9432. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9433. std::string out;
  9434. std::string request(
  9435. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9436. test_raw_request(request, &out);
  9437. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9438. }
  9439. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9440. std::string out;
  9441. std::string request(
  9442. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9443. test_raw_request(request, &out);
  9444. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9445. }
  9446. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9447. std::string out;
  9448. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9449. "Host: localhost\r\n"
  9450. "Test: \r\n\r\n",
  9451. &out);
  9452. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9453. }
  9454. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9455. Server svr;
  9456. std::string x_custom;
  9457. std::string cookie;
  9458. std::string xff;
  9459. std::string x_unicode;
  9460. std::string x_iis;
  9461. svr.Get("/check", [&](const Request &req, Response &res) {
  9462. x_custom = req.get_header_value("X-Custom");
  9463. cookie = req.get_header_value("Cookie");
  9464. xff = req.get_header_value("X-Forwarded-For");
  9465. x_unicode = req.get_header_value("X-Unicode");
  9466. x_iis = req.get_header_value("X-IIS");
  9467. res.set_content("ok", "text/plain");
  9468. });
  9469. thread t = thread([&] { svr.listen(HOST, PORT); });
  9470. auto se = detail::scope_exit([&] {
  9471. svr.stop();
  9472. t.join();
  9473. ASSERT_FALSE(svr.is_running());
  9474. });
  9475. svr.wait_until_ready();
  9476. const std::string req = "GET /check HTTP/1.1\r\n"
  9477. "Host: localhost\r\n"
  9478. "X-Custom: a%0D%0AInjected: b\r\n"
  9479. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9480. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9481. "X-Unicode: %E3%81%82\r\n"
  9482. "X-IIS: %u00E9\r\n"
  9483. "Connection: close\r\n"
  9484. "\r\n";
  9485. std::string res;
  9486. ASSERT_TRUE(send_request(5, req, &res));
  9487. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9488. // Every value must be returned verbatim (wire form), with no decoding.
  9489. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9490. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9491. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9492. EXPECT_EQ("%E3%81%82", x_unicode);
  9493. EXPECT_EQ("%u00E9", x_iis);
  9494. }
  9495. // Applications that previously relied on automatic percent-decoding can
  9496. // reproduce the old behavior by explicitly calling decode_path_component()
  9497. // or, for RFC 3986 conformance, decode_uri_component().
  9498. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9499. Server svr;
  9500. std::string decoded;
  9501. svr.Get("/check", [&](const Request &req, Response &res) {
  9502. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9503. res.set_content("ok", "text/plain");
  9504. });
  9505. thread t = thread([&] { svr.listen(HOST, PORT); });
  9506. auto se = detail::scope_exit([&] {
  9507. svr.stop();
  9508. t.join();
  9509. ASSERT_FALSE(svr.is_running());
  9510. });
  9511. svr.wait_until_ready();
  9512. const std::string req = "GET /check HTTP/1.1\r\n"
  9513. "Host: localhost\r\n"
  9514. "X-Custom: hello%20world\r\n"
  9515. "Connection: close\r\n"
  9516. "\r\n";
  9517. std::string res;
  9518. ASSERT_TRUE(send_request(5, req, &res));
  9519. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9520. EXPECT_EQ("hello world", decoded);
  9521. }
  9522. // Regression test for #2033. Browsers send Referer values that include
  9523. // percent-encoded characters such as %0A inside the URL. Decoding the
  9524. // header value would either trip the post-decode CR/LF/NUL guard (the
  9525. // original bug, returning 400) or, after that guard was relaxed, silently
  9526. // store a literal LF — both unacceptable. The wire form must round-trip.
  9527. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9528. Server svr;
  9529. std::string referer;
  9530. svr.Get("/check", [&](const Request &req, Response &res) {
  9531. referer = req.get_header_value("Referer");
  9532. res.set_content("ok", "text/plain");
  9533. });
  9534. thread t = thread([&] { svr.listen(HOST, PORT); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. t.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. const std::string req = "GET /check HTTP/1.1\r\n"
  9542. "Host: localhost\r\n"
  9543. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9544. "Connection: close\r\n"
  9545. "\r\n";
  9546. std::string res;
  9547. ASSERT_TRUE(send_request(5, req, &res));
  9548. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9549. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9550. }
  9551. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9552. Server svr;
  9553. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9554. res.set_header("Cache-Control", "no-cache");
  9555. res.set_chunked_content_provider(
  9556. "text/event-stream", [](size_t offset, DataSink &sink) {
  9557. std::string s = "data:";
  9558. s += std::to_string(offset);
  9559. s += "\n\n";
  9560. auto ret = sink.write(s.data(), s.size());
  9561. EXPECT_TRUE(ret);
  9562. std::this_thread::sleep_for(std::chrono::seconds(1));
  9563. return true;
  9564. });
  9565. });
  9566. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9567. svr.wait_until_ready();
  9568. Client client(HOST, PORT);
  9569. const Headers headers = {{"Accept", "text/event-stream"}};
  9570. auto get_thread = std::thread([&client, &headers]() {
  9571. auto res = client.Get(
  9572. "/events", headers,
  9573. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9574. });
  9575. auto se = detail::scope_exit([&] {
  9576. svr.stop();
  9577. get_thread.join();
  9578. listen_thread.join();
  9579. ASSERT_FALSE(svr.is_running());
  9580. });
  9581. // Give GET time to get a few messages.
  9582. std::this_thread::sleep_for(std::chrono::seconds(2));
  9583. }
  9584. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9585. httplib::Server svr;
  9586. svr.Post("/hi",
  9587. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9588. res.status = StatusCode::OK_200;
  9589. });
  9590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9591. svr.wait_until_ready();
  9592. Client cli(HOST, PORT);
  9593. auto res = cli.Post("/hi", "data", "text/plain");
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_EQ(StatusCode::OK_200, res->status);
  9596. svr.stop();
  9597. thread.join();
  9598. ASSERT_FALSE(svr.is_running());
  9599. res = cli.Post("/hi", "data", "text/plain");
  9600. ASSERT_FALSE(res);
  9601. }
  9602. TEST(ServerStopTest, ListenFailure) {
  9603. Server svr;
  9604. auto t = thread([&]() {
  9605. auto ret = svr.listen("????", PORT);
  9606. EXPECT_FALSE(ret);
  9607. });
  9608. svr.wait_until_ready();
  9609. svr.stop();
  9610. t.join();
  9611. }
  9612. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9613. TEST(ServerStopTest, Decommision) {
  9614. Server svr;
  9615. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9616. for (int i = 0; i < 4; i++) {
  9617. auto is_even = !(i % 2);
  9618. std::thread t{[&] {
  9619. try {
  9620. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9621. if (is_even) {
  9622. throw std::runtime_error("Some thing that happens to go wrong.");
  9623. }
  9624. svr.listen(HOST, PORT);
  9625. } catch (...) { svr.decommission(); }
  9626. }};
  9627. svr.wait_until_ready();
  9628. // Server is up
  9629. {
  9630. Client cli(HOST, PORT);
  9631. auto res = cli.Get("/hi");
  9632. if (is_even) {
  9633. EXPECT_FALSE(res);
  9634. } else {
  9635. EXPECT_TRUE(res);
  9636. EXPECT_EQ("hi...", res->body);
  9637. }
  9638. }
  9639. svr.stop();
  9640. t.join();
  9641. // Server is down...
  9642. {
  9643. Client cli(HOST, PORT);
  9644. auto res = cli.Get("/hi");
  9645. EXPECT_FALSE(res);
  9646. }
  9647. }
  9648. }
  9649. #endif
  9650. // Helper function for string body upload progress tests
  9651. template <typename SetupHandler, typename ClientCall>
  9652. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9653. ClientCall &&client_call,
  9654. const string &body) {
  9655. Server svr;
  9656. setup_handler(svr);
  9657. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9658. auto se = detail::scope_exit([&] {
  9659. svr.stop();
  9660. t.join();
  9661. });
  9662. svr.wait_until_ready();
  9663. Client cli(HOST, PORT);
  9664. vector<uint64_t> progress_values;
  9665. bool progress_called = false;
  9666. auto res =
  9667. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9668. progress_values.push_back(current);
  9669. progress_called = true;
  9670. return true;
  9671. });
  9672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9673. EXPECT_EQ(200, res->status);
  9674. EXPECT_TRUE(progress_called);
  9675. }
  9676. TEST(UploadProgressTest, PostStringBodyBasic) {
  9677. TestStringBodyUploadProgress(
  9678. [](Server &svr) {
  9679. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9680. res.set_content("received", "text/plain");
  9681. });
  9682. },
  9683. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9684. return cli.Post("/test", body, "text/plain", progress_callback);
  9685. },
  9686. "test data for upload progress");
  9687. }
  9688. TEST(UploadProgressTest, PutStringBodyBasic) {
  9689. TestStringBodyUploadProgress(
  9690. [](Server &svr) {
  9691. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9692. res.set_content("put received", "text/plain");
  9693. });
  9694. },
  9695. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9696. return cli.Put("/test", body, "text/plain", progress_callback);
  9697. },
  9698. "put test data for upload progress");
  9699. }
  9700. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9701. TestStringBodyUploadProgress(
  9702. [](Server &svr) {
  9703. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9704. res.set_content("patch received", "text/plain");
  9705. });
  9706. },
  9707. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9708. return cli.Patch("/test", body, "text/plain", progress_callback);
  9709. },
  9710. "patch test data for upload progress");
  9711. }
  9712. // Helper function for content provider upload progress tests
  9713. template <typename SetupHandler, typename ClientCall>
  9714. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9715. ClientCall &&client_call) {
  9716. Server svr;
  9717. setup_handler(svr);
  9718. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9719. auto se = detail::scope_exit([&] {
  9720. svr.stop();
  9721. t.join();
  9722. });
  9723. svr.wait_until_ready();
  9724. Client cli(HOST, PORT);
  9725. vector<uint64_t> progress_values;
  9726. auto res =
  9727. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9728. progress_values.push_back(current);
  9729. return true;
  9730. });
  9731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9732. EXPECT_EQ(200, res->status);
  9733. EXPECT_FALSE(progress_values.empty());
  9734. }
  9735. TEST(UploadProgressTest, PostContentProviderProgress) {
  9736. TestContentProviderUploadProgress(
  9737. [](Server &svr) {
  9738. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9739. res.set_content("provider received", "text/plain");
  9740. });
  9741. },
  9742. [](Client &cli, UploadProgress progress_callback) {
  9743. return cli.Post(
  9744. "/test", 10,
  9745. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9746. sink.os << "test data";
  9747. return true;
  9748. },
  9749. "text/plain", progress_callback);
  9750. });
  9751. }
  9752. // Helper function for multipart upload progress tests
  9753. template <typename SetupHandler, typename ClientCall>
  9754. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9755. ClientCall &&client_call,
  9756. const string &endpoint) {
  9757. Server svr;
  9758. setup_handler(svr);
  9759. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9760. auto se = detail::scope_exit([&] {
  9761. svr.stop();
  9762. t.join();
  9763. });
  9764. svr.wait_until_ready();
  9765. Client cli(HOST, PORT);
  9766. vector<uint64_t> progress_values;
  9767. UploadFormDataItems items = {
  9768. {"field1", "value1", "", ""},
  9769. {"field2", "longer value for progress tracking test", "", ""},
  9770. {"file1", "file content data for upload progress", "test.txt",
  9771. "text/plain"}};
  9772. auto res = client_call(cli, endpoint, items,
  9773. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9774. progress_values.push_back(current);
  9775. return true;
  9776. });
  9777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9778. EXPECT_EQ(200, res->status);
  9779. EXPECT_FALSE(progress_values.empty());
  9780. }
  9781. TEST(UploadProgressTest, PostMultipartProgress) {
  9782. TestMultipartUploadProgress(
  9783. [](Server &svr) {
  9784. svr.Post("/multipart", [](const Request &req, Response &res) {
  9785. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9786. res.set_content("multipart received", "text/plain");
  9787. });
  9788. },
  9789. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9790. UploadProgress progress_callback) {
  9791. return cli.Post(endpoint, items, progress_callback);
  9792. },
  9793. "/multipart");
  9794. }
  9795. // Helper function for basic download progress tests
  9796. template <typename SetupHandler, typename ClientCall>
  9797. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9798. ClientCall &&client_call, const string &endpoint,
  9799. size_t expected_content_size) {
  9800. Server svr;
  9801. setup_handler(svr);
  9802. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9803. auto se = detail::scope_exit([&] {
  9804. svr.stop();
  9805. t.join();
  9806. });
  9807. svr.wait_until_ready();
  9808. Client cli(HOST, PORT);
  9809. vector<uint64_t> progress_values;
  9810. auto res = client_call(cli, endpoint,
  9811. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9812. progress_values.push_back(current);
  9813. return true;
  9814. });
  9815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9816. EXPECT_EQ(200, res->status);
  9817. EXPECT_FALSE(progress_values.empty());
  9818. EXPECT_EQ(expected_content_size, res->body.size());
  9819. }
  9820. TEST(DownloadProgressTest, GetBasic) {
  9821. TestBasicDownloadProgress(
  9822. [](Server &svr) {
  9823. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9824. string content(1000, 'D');
  9825. res.set_content(content, "text/plain");
  9826. });
  9827. },
  9828. [](Client &cli, const string &endpoint,
  9829. DownloadProgress progress_callback) {
  9830. return cli.Get(endpoint, progress_callback);
  9831. },
  9832. "/download", 1000u);
  9833. }
  9834. // Helper function for content receiver download progress tests
  9835. template <typename SetupHandler, typename ClientCall>
  9836. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9837. ClientCall &&client_call,
  9838. const string &endpoint,
  9839. size_t expected_content_size) {
  9840. Server svr;
  9841. setup_handler(svr);
  9842. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9843. auto se = detail::scope_exit([&] {
  9844. svr.stop();
  9845. t.join();
  9846. });
  9847. svr.wait_until_ready();
  9848. Client cli(HOST, PORT);
  9849. vector<uint64_t> progress_values;
  9850. string received_body;
  9851. auto res = client_call(
  9852. cli, endpoint,
  9853. [&](const char *data, size_t data_length) -> bool {
  9854. received_body.append(data, data_length);
  9855. return true;
  9856. },
  9857. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9858. progress_values.push_back(current);
  9859. return true;
  9860. });
  9861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9862. EXPECT_EQ(200, res->status);
  9863. EXPECT_FALSE(progress_values.empty());
  9864. EXPECT_EQ(expected_content_size, received_body.size());
  9865. EXPECT_TRUE(res->body.empty());
  9866. }
  9867. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9868. TestContentReceiverDownloadProgress(
  9869. [](Server &svr) {
  9870. svr.Get("/download-receiver",
  9871. [](const Request & /*req*/, Response &res) {
  9872. string content(2000, 'R');
  9873. res.set_content(content, "text/plain");
  9874. });
  9875. },
  9876. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9877. DownloadProgress progress_callback) {
  9878. return cli.Get(endpoint, content_receiver, progress_callback);
  9879. },
  9880. "/download-receiver", 2000u);
  9881. }
  9882. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9883. // A provider reaching a pass with nothing to hand over - an empty buffer
  9884. // popped off a queue, say - must not be taken to mean the body is finished.
  9885. // It used to end the loop with the terminating chunk unwritten while the
  9886. // server still considered the response complete, so the peer waited for an
  9887. // end that never arrived.
  9888. Server svr;
  9889. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9890. auto step = std::make_shared<int>(0);
  9891. res.set_chunked_content_provider("text/plain",
  9892. [step](size_t /*offset*/, DataSink &sink) {
  9893. switch ((*step)++) {
  9894. case 0: sink.write("", 0); break;
  9895. case 1: sink.write("hello", 5); break;
  9896. default: sink.done(); break;
  9897. }
  9898. return true;
  9899. });
  9900. });
  9901. auto port = svr.bind_to_any_port(HOST);
  9902. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9903. auto listen_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. // Without the fix the body is never terminated, so bound the wait rather
  9911. // than letting the test hang on the default read timeout.
  9912. cli.set_read_timeout(5, 0);
  9913. auto res = cli.Get("/stream");
  9914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9915. EXPECT_EQ(StatusCode::OK_200, res->status);
  9916. EXPECT_EQ("hello", res->body);
  9917. }
  9918. TEST(StreamingTest, NoContentLengthStreaming) {
  9919. Server svr;
  9920. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9921. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9922. if (offset < 6) {
  9923. sink.os << (offset < 3 ? "a" : "b");
  9924. } else {
  9925. sink.done();
  9926. }
  9927. return true;
  9928. });
  9929. });
  9930. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9931. auto listen_se = detail::scope_exit([&] {
  9932. svr.stop();
  9933. listen_thread.join();
  9934. ASSERT_FALSE(svr.is_running());
  9935. });
  9936. svr.wait_until_ready();
  9937. Client client(HOST, PORT);
  9938. auto get_thread = std::thread([&client]() {
  9939. std::string s;
  9940. auto res =
  9941. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9942. s += std::string(data, len);
  9943. return true;
  9944. });
  9945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9946. EXPECT_EQ(StatusCode::OK_200, res->status);
  9947. EXPECT_EQ("aaabbb", s);
  9948. });
  9949. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9950. // Give GET time to get a few messages.
  9951. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9952. }
  9953. TEST(MountTest, Unmount) {
  9954. Server svr;
  9955. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9956. auto se = detail::scope_exit([&] {
  9957. svr.stop();
  9958. listen_thread.join();
  9959. ASSERT_FALSE(svr.is_running());
  9960. });
  9961. svr.wait_until_ready();
  9962. Client cli("localhost", PORT);
  9963. svr.set_mount_point("/mount2", "./www2");
  9964. auto res = cli.Get("/");
  9965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9966. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9967. res = cli.Get("/mount2/dir/test.html");
  9968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9969. EXPECT_EQ(StatusCode::OK_200, res->status);
  9970. svr.set_mount_point("/", "./www");
  9971. res = cli.Get("/dir/");
  9972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9973. EXPECT_EQ(StatusCode::OK_200, res->status);
  9974. svr.remove_mount_point("/");
  9975. res = cli.Get("/dir/");
  9976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9978. svr.remove_mount_point("/mount2");
  9979. res = cli.Get("/mount2/dir/test.html");
  9980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9981. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9982. }
  9983. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  9984. Server svr;
  9985. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  9986. svr.Get("/api/hello", [](const Request &, Response &res) {
  9987. res.set_content("api", "text/plain");
  9988. });
  9989. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9990. auto se = detail::scope_exit([&] {
  9991. svr.stop();
  9992. listen_thread.join();
  9993. ASSERT_FALSE(svr.is_running());
  9994. });
  9995. svr.wait_until_ready();
  9996. Client cli(HOST, PORT);
  9997. auto res = cli.Get("/dir/test.html");
  9998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9999. EXPECT_EQ(StatusCode::OK_200, res->status);
  10000. res = cli.Get("/api/hello");
  10001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10002. EXPECT_EQ(StatusCode::OK_200, res->status);
  10003. EXPECT_EQ("api", res->body);
  10004. }
  10005. TEST(MountTest, PathSegmentBoundary) {
  10006. Server svr;
  10007. svr.set_mount_point("/mount2", "./www2");
  10008. svr.set_mount_point("/", "./www");
  10009. auto port = svr.bind_to_any_port(HOST);
  10010. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. listen_thread.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. });
  10016. svr.wait_until_ready();
  10017. Client cli(HOST, port);
  10018. auto res = cli.Get("/mount2/dir/test.html");
  10019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10020. EXPECT_EQ(StatusCode::OK_200, res->status);
  10021. // "/mount2" must not match part-way through a path segment.
  10022. res = cli.Get("/mount2dir/test.html");
  10023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10024. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10025. // A mount point ending in '/' keeps matching every path below it.
  10026. res = cli.Get("/dir/test.html");
  10027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10028. EXPECT_EQ(StatusCode::OK_200, res->status);
  10029. }
  10030. TEST(MountTest, Redicect) {
  10031. Server svr;
  10032. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. listen_thread.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. });
  10038. svr.set_mount_point("/", "./www");
  10039. svr.wait_until_ready();
  10040. Client cli("localhost", PORT);
  10041. auto res = cli.Get("/dir/");
  10042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10043. EXPECT_EQ(StatusCode::OK_200, res->status);
  10044. res = cli.Get("/dir");
  10045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10046. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10047. res = cli.Get("/file");
  10048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10049. EXPECT_EQ(StatusCode::OK_200, res->status);
  10050. res = cli.Get("/file/");
  10051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10052. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10053. cli.set_follow_location(true);
  10054. res = cli.Get("/dir");
  10055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10056. EXPECT_EQ(StatusCode::OK_200, res->status);
  10057. }
  10058. TEST(MountTest, MultibytesPathName) {
  10059. Server svr;
  10060. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10061. auto se = detail::scope_exit([&] {
  10062. svr.stop();
  10063. listen_thread.join();
  10064. ASSERT_FALSE(svr.is_running());
  10065. });
  10066. svr.set_mount_point("/", "./www");
  10067. svr.wait_until_ready();
  10068. Client cli("localhost", PORT);
  10069. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10071. EXPECT_EQ(StatusCode::OK_200, res->status);
  10072. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10073. }
  10074. #ifdef _WIN32
  10075. // Issue #2435: mmap::open() must succeed even when another handle holds
  10076. // the file open for writing (e.g. an active log file).
  10077. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10078. const char *path = "mmap_concurrent_writer_test.txt";
  10079. const char *content = "hello";
  10080. {
  10081. std::ofstream f(path, std::ios::binary);
  10082. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10083. }
  10084. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10085. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10086. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10087. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10088. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10089. detail::mmap m(path);
  10090. ASSERT_TRUE(m.is_open());
  10091. EXPECT_EQ(strlen(content), m.size());
  10092. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10093. }
  10094. #endif
  10095. #ifndef _WIN32
  10096. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10097. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10098. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10099. TEST(MmapTest, FailedMappingIsNotOpen) {
  10100. const char *path = "./mmap_failed_mapping_test_dir";
  10101. ASSERT_EQ(0, ::mkdir(path, 0755));
  10102. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10103. detail::mmap m(path);
  10104. EXPECT_FALSE(m.is_open());
  10105. EXPECT_EQ(0U, m.size());
  10106. EXPECT_NE(static_cast<const void *>(m.data()),
  10107. static_cast<const void *>(MAP_FAILED));
  10108. }
  10109. #endif
  10110. TEST(KeepAliveTest, ReadTimeout) {
  10111. Server svr;
  10112. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10113. std::this_thread::sleep_for(std::chrono::seconds(2));
  10114. res.set_content("a", "text/plain");
  10115. });
  10116. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10117. res.set_content("b", "text/plain");
  10118. });
  10119. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10120. auto se = detail::scope_exit([&] {
  10121. svr.stop();
  10122. listen_thread.join();
  10123. ASSERT_FALSE(svr.is_running());
  10124. });
  10125. svr.wait_until_ready();
  10126. Client cli("localhost", PORT);
  10127. cli.set_keep_alive(true);
  10128. cli.set_read_timeout(std::chrono::seconds(1));
  10129. auto resa = cli.Get("/a");
  10130. ASSERT_FALSE(resa);
  10131. EXPECT_EQ(Error::Read, resa.error());
  10132. auto resb = cli.Get("/b");
  10133. ASSERT_TRUE(resb);
  10134. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10135. EXPECT_EQ("b", resb->body);
  10136. }
  10137. TEST(KeepAliveTest, MaxCount) {
  10138. size_t keep_alive_max_count = 3;
  10139. Server svr;
  10140. svr.set_keep_alive_max_count(keep_alive_max_count);
  10141. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10142. res.set_content("Hello World!", "text/plain");
  10143. });
  10144. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10145. auto se = detail::scope_exit([&] {
  10146. svr.stop();
  10147. listen_thread.join();
  10148. ASSERT_FALSE(svr.is_running());
  10149. });
  10150. svr.wait_until_ready();
  10151. Client cli(HOST, PORT);
  10152. cli.set_keep_alive(true);
  10153. for (size_t i = 0; i < 5; i++) {
  10154. auto result = cli.Get("/hi");
  10155. ASSERT_TRUE(result);
  10156. EXPECT_EQ(StatusCode::OK_200, result->status);
  10157. if (i == keep_alive_max_count - 1) {
  10158. EXPECT_EQ("close", result->get_header_value("Connection"));
  10159. } else {
  10160. EXPECT_FALSE(result->has_header("Connection"));
  10161. }
  10162. }
  10163. }
  10164. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10165. // can pull the next one into the server's buffer. The server must serve it
  10166. // without waiting for the socket to become readable again. The keep-alive
  10167. // timeout outlasts the client's read timeout, so a request left waiting for it
  10168. // shows up as a missing response.
  10169. static void serve_pipelining_routes(Server &svr,
  10170. const std::function<void(int)> &client) {
  10171. svr.set_keep_alive_timeout(5);
  10172. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10173. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10174. });
  10175. svr.Post("/echo", [](const Request &req, Response &res) {
  10176. res.set_content("echo " + req.body, "text/plain");
  10177. });
  10178. auto port = svr.bind_to_any_port(HOST);
  10179. thread t = thread([&] { svr.listen_after_bind(); });
  10180. auto se = detail::scope_exit([&] {
  10181. svr.stop();
  10182. t.join();
  10183. });
  10184. svr.wait_until_ready();
  10185. client(port);
  10186. }
  10187. static std::string
  10188. send_pipelined_requests(const std::vector<std::string> &parts) {
  10189. Server svr;
  10190. std::string res;
  10191. serve_pipelining_routes(svr, [&](int port) {
  10192. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10193. });
  10194. return res;
  10195. }
  10196. static void expect_in_order(const std::string &res,
  10197. const std::vector<std::string> &bodies) {
  10198. size_t pos = 0;
  10199. for (const auto &body : bodies) {
  10200. pos = res.find(body, pos);
  10201. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10202. pos += body.size();
  10203. }
  10204. }
  10205. TEST(KeepAliveTest, PipelinedRequests) {
  10206. auto res = send_pipelined_requests(
  10207. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10208. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10209. "Content-Length: 4\r\n\r\nbody"
  10210. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10211. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10212. }
  10213. // The second request starts in the server's buffer and ends on the socket.
  10214. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10215. auto res =
  10216. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10217. "GET /hi/2 HTTP/1.1\r\nHo",
  10218. "st: localhost\r\nConnection: close\r\n\r\n"});
  10219. expect_in_order(res, {"hi 1", "hi 2"});
  10220. }
  10221. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10222. // CRLF after a body does not turn into a 400 for the next request.
  10223. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10224. auto res = send_pipelined_requests(
  10225. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10226. "Content-Length: 4\r\n\r\nbody\r\n"
  10227. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10228. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10229. expect_in_order(res, {"echo body", "hi 2"});
  10230. }
  10231. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10232. // must not be served as the next request.
  10233. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10234. auto res = send_pipelined_requests(
  10235. {"INVALID REQUEST LINE\r\n\r\n"
  10236. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10237. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10238. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10239. }
  10240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10241. // Over TLS, the next request is held by the TLS library as already decrypted
  10242. // data rather than on the socket.
  10243. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10245. std::string res;
  10246. serve_pipelining_routes(svr, [&](int port) {
  10247. auto error = Error::Success;
  10248. auto sock = detail::create_client_socket(
  10249. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10250. /*connection_timeout_sec=*/5, 0,
  10251. /*read_timeout_sec=*/2, 0,
  10252. /*write_timeout_sec=*/5, 0, std::string(), error);
  10253. ASSERT_NE(INVALID_SOCKET, sock);
  10254. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10255. auto ctx = SSL_CTX_new(TLS_client_method());
  10256. auto ssl = SSL_new(ctx);
  10257. auto ssl_se = detail::scope_exit([&] {
  10258. SSL_free(ssl);
  10259. SSL_CTX_free(ctx);
  10260. });
  10261. SSL_set_fd(ssl, static_cast<int>(sock));
  10262. ASSERT_EQ(1, SSL_connect(ssl));
  10263. // One write, so all three requests arrive in one TLS record
  10264. const std::string req =
  10265. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10266. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10267. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10268. ASSERT_EQ(static_cast<int>(req.size()),
  10269. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10270. char buf[512];
  10271. int n;
  10272. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10273. res.append(buf, static_cast<size_t>(n));
  10274. }
  10275. });
  10276. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10277. }
  10278. #endif
  10279. TEST(KeepAliveTest, Issue1041) {
  10280. Server svr;
  10281. svr.set_keep_alive_timeout(3);
  10282. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10283. res.set_content("Hello World!", "text/plain");
  10284. });
  10285. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10286. auto se = detail::scope_exit([&] {
  10287. svr.stop();
  10288. listen_thread.join();
  10289. ASSERT_FALSE(svr.is_running());
  10290. });
  10291. svr.wait_until_ready();
  10292. Client cli(HOST, PORT);
  10293. cli.set_keep_alive(true);
  10294. auto result = cli.Get("/hi");
  10295. ASSERT_TRUE(result);
  10296. EXPECT_EQ(StatusCode::OK_200, result->status);
  10297. std::this_thread::sleep_for(std::chrono::seconds(5));
  10298. result = cli.Get("/hi");
  10299. ASSERT_TRUE(result);
  10300. EXPECT_EQ(StatusCode::OK_200, result->status);
  10301. }
  10302. TEST(KeepAliveTest, Issue1959) {
  10303. Server svr;
  10304. svr.set_keep_alive_timeout(5);
  10305. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10306. res.set_content("a", "text/plain");
  10307. });
  10308. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10309. auto se = detail::scope_exit([&] {
  10310. if (!svr.is_running()) return;
  10311. svr.stop();
  10312. listen_thread.join();
  10313. ASSERT_FALSE(svr.is_running());
  10314. });
  10315. svr.wait_until_ready();
  10316. Client cli("localhost", PORT);
  10317. cli.set_keep_alive(true);
  10318. using namespace std::chrono;
  10319. auto start = steady_clock::now();
  10320. cli.Get("/a");
  10321. svr.stop();
  10322. listen_thread.join();
  10323. auto end = steady_clock::now();
  10324. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10325. EXPECT_LT(elapsed, 5000);
  10326. }
  10327. #ifdef CPPHTTPLIB_SSL_ENABLED
  10328. TEST(KeepAliveTest, SSLClientReconnection) {
  10329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10330. ASSERT_TRUE(svr.is_valid());
  10331. svr.set_keep_alive_timeout(1);
  10332. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10333. res.set_content("Hello World!", "text/plain");
  10334. });
  10335. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10336. auto se = detail::scope_exit([&] {
  10337. svr.stop();
  10338. listen_thread.join();
  10339. ASSERT_FALSE(svr.is_running());
  10340. });
  10341. svr.wait_until_ready();
  10342. SSLClient cli(HOST, PORT);
  10343. cli.enable_server_certificate_verification(false);
  10344. cli.set_keep_alive(true);
  10345. auto result = cli.Get("/hi");
  10346. ASSERT_TRUE(result);
  10347. EXPECT_EQ(StatusCode::OK_200, result->status);
  10348. result = cli.Get("/hi");
  10349. ASSERT_TRUE(result);
  10350. EXPECT_EQ(StatusCode::OK_200, result->status);
  10351. std::this_thread::sleep_for(std::chrono::seconds(2));
  10352. // Recoonect
  10353. result = cli.Get("/hi");
  10354. ASSERT_TRUE(result);
  10355. EXPECT_EQ(StatusCode::OK_200, result->status);
  10356. result = cli.Get("/hi");
  10357. ASSERT_TRUE(result);
  10358. EXPECT_EQ(StatusCode::OK_200, result->status);
  10359. }
  10360. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10362. ASSERT_TRUE(svr.is_valid());
  10363. svr.set_keep_alive_timeout(1);
  10364. std::string content = "reconnect";
  10365. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10366. res.set_content("Hello World!", "text/plain");
  10367. });
  10368. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10369. auto se = detail::scope_exit([&] {
  10370. svr.stop();
  10371. listen_thread.join();
  10372. ASSERT_FALSE(svr.is_running());
  10373. });
  10374. svr.wait_until_ready();
  10375. SSLClient cli(HOST, PORT);
  10376. cli.enable_server_certificate_verification(false);
  10377. cli.set_keep_alive(true);
  10378. auto result = cli.Post(
  10379. "/hi", content.size(),
  10380. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10381. sink.write(content.c_str(), content.size());
  10382. return true;
  10383. },
  10384. "text/plain");
  10385. ASSERT_TRUE(result);
  10386. EXPECT_EQ(200, result->status);
  10387. std::this_thread::sleep_for(std::chrono::seconds(2));
  10388. // Recoonect
  10389. result = cli.Post(
  10390. "/hi", content.size(),
  10391. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10392. sink.write(content.c_str(), content.size());
  10393. return true;
  10394. },
  10395. "text/plain");
  10396. ASSERT_TRUE(result);
  10397. EXPECT_EQ(200, result->status);
  10398. result = cli.Post(
  10399. "/hi", content.size(),
  10400. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10401. sink.write(content.c_str(), content.size());
  10402. return true;
  10403. },
  10404. "text/plain");
  10405. ASSERT_TRUE(result);
  10406. EXPECT_EQ(200, result->status);
  10407. }
  10408. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10409. using namespace httplib::tls;
  10410. {
  10411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10412. ASSERT_TRUE(svr.is_valid());
  10413. svr.Get("/sni", [&](const Request &req, Response &res) {
  10414. std::string expected = req.sni();
  10415. EXPECT_EQ(expected, req.get_param_value("expected"));
  10416. res.set_content("ok", "text/plain");
  10417. });
  10418. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10419. auto se = detail::scope_exit([&] {
  10420. svr.stop();
  10421. listen_thread.join();
  10422. ASSERT_FALSE(svr.is_running());
  10423. });
  10424. svr.wait_until_ready();
  10425. {
  10426. SSLClient cli("localhost", PORT);
  10427. cli.enable_server_certificate_verification(false);
  10428. auto res = cli.Get("/sni?expected=localhost");
  10429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10430. }
  10431. {
  10432. SSLClient cli("::1", PORT);
  10433. cli.enable_server_certificate_verification(false);
  10434. auto res = cli.Get("/sni?expected=");
  10435. // NOTE: This may fail if the server is listening on IPv4 only
  10436. // (e.g., when localhost resolves to 127.0.0.1 only)
  10437. if (res) {
  10438. EXPECT_EQ(StatusCode::OK_200, res->status);
  10439. } else {
  10440. EXPECT_EQ(Error::Connection, res.error());
  10441. }
  10442. }
  10443. }
  10444. }
  10445. #endif
  10446. TEST(ClientProblemDetectionTest, ContentProvider) {
  10447. Server svr;
  10448. size_t content_length = 1024 * 1024;
  10449. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10450. res.set_content_provider(
  10451. content_length, "text/plain",
  10452. [&](size_t offset, size_t length, DataSink &sink) {
  10453. auto out_len = std::min(length, static_cast<size_t>(1024));
  10454. std::string out(out_len, '@');
  10455. sink.write(out.data(), out_len);
  10456. return offset < 4096;
  10457. },
  10458. [](bool success) { ASSERT_FALSE(success); });
  10459. });
  10460. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10461. res.set_content_provider(
  10462. 0, "text/plain",
  10463. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10464. EXPECT_TRUE(false);
  10465. return true;
  10466. },
  10467. [](bool success) { ASSERT_FALSE(success); });
  10468. });
  10469. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10470. auto se = detail::scope_exit([&] {
  10471. svr.stop();
  10472. listen_thread.join();
  10473. ASSERT_FALSE(svr.is_running());
  10474. });
  10475. svr.wait_until_ready();
  10476. Client cli("localhost", PORT);
  10477. {
  10478. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10479. size_t /*data_length*/) { return false; });
  10480. ASSERT_FALSE(res);
  10481. }
  10482. {
  10483. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10484. size_t /*data_length*/) { return false; });
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. }
  10487. }
  10488. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10489. // A provider that reports success without writing anything and without
  10490. // calling done() used to be handed the same offset and length again on every
  10491. // pass, so it spun for as long as the peer stayed connected.
  10492. Server svr;
  10493. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10494. res.set_content("ok", "text/plain");
  10495. });
  10496. auto port = svr.bind_to_any_port(HOST);
  10497. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10498. auto se = detail::scope_exit([&] {
  10499. svr.stop();
  10500. listen_thread.join();
  10501. ASSERT_FALSE(svr.is_running());
  10502. });
  10503. svr.wait_until_ready();
  10504. std::atomic<int> call_count{0};
  10505. Client cli(HOST, port);
  10506. auto res = cli.Post(
  10507. "/", 1024,
  10508. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10509. // Give up after enough passes to show the spin, so that losing the
  10510. // check below fails this test instead of hanging it.
  10511. return ++call_count < 100;
  10512. },
  10513. "text/plain");
  10514. ASSERT_FALSE(res);
  10515. EXPECT_EQ(Error::Write, res.error());
  10516. EXPECT_EQ(1, call_count.load());
  10517. }
  10518. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10519. // A writer only has to assign `write`. The other three used to be left as
  10520. // empty std::functions, so a provider calling one threw
  10521. // std::bad_function_call out of the thread running it and took the whole
  10522. // process down.
  10523. DataSink sink;
  10524. std::string written;
  10525. sink.write = [&](const char *data, size_t data_len) {
  10526. written.append(data, data_len);
  10527. return true;
  10528. };
  10529. EXPECT_TRUE(sink.is_writable());
  10530. sink.done();
  10531. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10532. EXPECT_TRUE(written.empty());
  10533. }
  10534. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10535. // A sink that cannot carry trailers still has to finish.
  10536. DataSink sink;
  10537. auto done_count = 0;
  10538. sink.done = [&]() { done_count++; };
  10539. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10540. EXPECT_EQ(1, done_count);
  10541. }
  10542. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10543. Server svr;
  10544. const std::string body(4096, 'x');
  10545. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10546. res.set_content_provider(body.size(), "text/plain",
  10547. [&](size_t offset, size_t length, DataSink &sink) {
  10548. sink.write(body.data() + offset, length);
  10549. sink.done();
  10550. return true;
  10551. });
  10552. });
  10553. auto port = svr.bind_to_any_port(HOST);
  10554. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10555. auto se = detail::scope_exit([&] {
  10556. svr.stop();
  10557. listen_thread.join();
  10558. ASSERT_FALSE(svr.is_running());
  10559. });
  10560. svr.wait_until_ready();
  10561. Client cli(HOST, port);
  10562. auto res = cli.Get("/");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::OK_200, res->status);
  10565. EXPECT_EQ(body, res->body);
  10566. }
  10567. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10568. Server svr;
  10569. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10570. res.set_content_provider(
  10571. 1024, "text/plain",
  10572. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10573. sink.write("hello", 5);
  10574. sink.done(); // short of the 1024 bytes the response promised
  10575. return true;
  10576. });
  10577. });
  10578. auto port = svr.bind_to_any_port(HOST);
  10579. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10580. auto se = detail::scope_exit([&] {
  10581. svr.stop();
  10582. listen_thread.join();
  10583. ASSERT_FALSE(svr.is_running());
  10584. });
  10585. svr.wait_until_ready();
  10586. Client cli(HOST, port);
  10587. cli.set_read_timeout(5, 0);
  10588. // The response is short of its Content-Length, so the client cannot read a
  10589. // complete body. What matters is that this returns at all: a no-op done()
  10590. // would leave the writer looping over a provider that never makes progress.
  10591. auto res = cli.Get("/");
  10592. EXPECT_FALSE(res);
  10593. }
  10594. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10595. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10596. // The compressed path builds the whole body before connecting, so this
  10597. // fails client-side and never reaches a server.
  10598. Client cli(HOST, PORT);
  10599. cli.set_compress(true);
  10600. auto res = cli.Post(
  10601. "/", 1024,
  10602. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10603. sink.write("hello", 5);
  10604. sink.done(); // short of the 1024 bytes the request announced
  10605. return true;
  10606. },
  10607. "text/plain");
  10608. ASSERT_FALSE(res);
  10609. EXPECT_EQ(Error::Write, res.error());
  10610. }
  10611. #endif
  10612. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10613. Server svr;
  10614. svr.set_error_handler([](Request const &, Response &res) -> void {
  10615. res.set_chunked_content_provider(
  10616. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10617. sink.os << "hello";
  10618. sink.os << "world";
  10619. sink.done();
  10620. return true;
  10621. });
  10622. });
  10623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10624. auto se = detail::scope_exit([&] {
  10625. svr.stop();
  10626. listen_thread.join();
  10627. ASSERT_FALSE(svr.is_running());
  10628. });
  10629. svr.wait_until_ready();
  10630. Client cli("localhost", PORT);
  10631. auto res = cli.Get("/");
  10632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10634. EXPECT_EQ("helloworld", res->body);
  10635. }
  10636. // A body set after a content provider must replace it, not be sent through it.
  10637. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10638. Server svr;
  10639. svr.set_mount_point("/", "./www");
  10640. svr.set_file_request_handler([](const Request &req, Response &res) {
  10641. if (req.path == "/dir/test.html") {
  10642. res.status = StatusCode::Forbidden_403;
  10643. res.set_content(std::string(5000, 'D'), "text/plain");
  10644. } else if (req.path == "/file") {
  10645. res.status = StatusCode::Forbidden_403;
  10646. res.body = "Denied";
  10647. }
  10648. });
  10649. auto port = svr.bind_to_any_port(HOST);
  10650. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10651. auto se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. t.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. Client cli(HOST, port);
  10658. {
  10659. auto res = cli.Get("/dir/test.html");
  10660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10661. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10662. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10663. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10664. }
  10665. {
  10666. auto res = cli.Get("/file");
  10667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10668. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10669. EXPECT_EQ("Denied", res->body);
  10670. }
  10671. {
  10672. auto res = cli.Get("/dir/index.html");
  10673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10674. EXPECT_EQ(StatusCode::OK_200, res->status);
  10675. EXPECT_EQ(0U, res->body.find("<html>"));
  10676. }
  10677. }
  10678. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10679. Server svr;
  10680. std::vector<bool> released;
  10681. std::mutex released_mutex;
  10682. auto releaser = [&](bool success) {
  10683. std::lock_guard<std::mutex> guard(released_mutex);
  10684. released.push_back(success);
  10685. };
  10686. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10687. return sink.write(&"hello"[offset], length);
  10688. };
  10689. svr.Get("/sized", [&](const Request &, Response &res) {
  10690. res.status = StatusCode::NotFound_404;
  10691. res.set_content_provider(5, "text/plain", provider, releaser);
  10692. });
  10693. svr.Get("/chunked", [&](const Request &, Response &res) {
  10694. res.status = StatusCode::ServiceUnavailable_503;
  10695. res.set_chunked_content_provider(
  10696. "text/plain",
  10697. [](size_t, DataSink &sink) {
  10698. sink.os << "chunk";
  10699. sink.done();
  10700. return true;
  10701. },
  10702. releaser);
  10703. });
  10704. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10705. res.set_content_provider(5, "text/plain", provider, releaser);
  10706. throw std::runtime_error("after the provider");
  10707. });
  10708. svr.set_error_handler([](const Request &req, Response &res) {
  10709. // Leave the exception handler's content to it.
  10710. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10711. res.set_content(std::string(1000, 'E'), "text/html");
  10712. return Server::HandlerResponse::Handled;
  10713. });
  10714. svr.set_exception_handler(
  10715. [](const Request &, Response &res, std::exception_ptr) {
  10716. res.status = StatusCode::InternalServerError_500;
  10717. res.set_content(std::string(1000, 'X'), "text/html");
  10718. });
  10719. auto port = svr.bind_to_any_port(HOST);
  10720. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10721. auto se = detail::scope_exit([&] {
  10722. svr.stop();
  10723. t.join();
  10724. ASSERT_FALSE(svr.is_running());
  10725. });
  10726. svr.wait_until_ready();
  10727. Client cli(HOST, port);
  10728. {
  10729. auto res = cli.Get("/sized");
  10730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10731. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10732. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10733. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10734. }
  10735. {
  10736. auto res = cli.Get("/chunked");
  10737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10738. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10739. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10740. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10741. }
  10742. {
  10743. auto res = cli.Get("/throw");
  10744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10745. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10746. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10747. }
  10748. std::lock_guard<std::mutex> guard(released_mutex);
  10749. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10750. }
  10751. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10752. Server svr;
  10753. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10754. return sink.write(&"abc"[offset], length);
  10755. };
  10756. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10757. res.set_file_content("./www/dir/test.html");
  10758. res.set_content("body", "text/plain");
  10759. });
  10760. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10761. res.set_content(std::string(100, 'B'), "text/plain");
  10762. res.set_file_content("./www/dir/test.html");
  10763. });
  10764. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10765. res.set_content(std::string(100, 'B'), "text/plain");
  10766. res.set_content_provider(3, "text/plain", abc);
  10767. });
  10768. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10769. res.set_content_provider(3, "text/plain", abc);
  10770. res.set_content(std::string(100, 'B'), "text/plain");
  10771. });
  10772. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10773. res.set_content_provider(3, "text/plain", abc);
  10774. res.body = "direct";
  10775. });
  10776. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10777. res.set_file_content("./www/dir/test.html");
  10778. res.body = "direct";
  10779. });
  10780. auto port = svr.bind_to_any_port(HOST);
  10781. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10782. auto se = detail::scope_exit([&] {
  10783. svr.stop();
  10784. t.join();
  10785. ASSERT_FALSE(svr.is_running());
  10786. });
  10787. svr.wait_until_ready();
  10788. Client cli(HOST, port);
  10789. auto expect_body = [&](const char *path, const std::string &body) {
  10790. // Uncompressed, so Content-Length can be compared with the body.
  10791. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10792. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10793. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10794. EXPECT_EQ(body, res->body) << path;
  10795. EXPECT_EQ(std::to_string(body.size()),
  10796. res->get_header_value("Content-Length"))
  10797. << path;
  10798. };
  10799. expect_body("/file-then-body", "body");
  10800. expect_body("/body-then-file", "test.html");
  10801. expect_body("/body-then-provider", "abc");
  10802. expect_body("/provider-then-body", std::string(100, 'B'));
  10803. expect_body("/provider-then-direct-body", "direct");
  10804. expect_body("/file-then-direct-body", "direct");
  10805. // Ranges are checked against the body, not the dropped provider.
  10806. {
  10807. auto res = cli.Get("/provider-then-direct-body",
  10808. Headers{{make_range_header({{1, 2}})}});
  10809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10810. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10811. EXPECT_EQ("ir", res->body);
  10812. }
  10813. {
  10814. auto res = cli.Get("/file-then-direct-body",
  10815. Headers{{make_range_header({{7, 8}})}});
  10816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10817. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10818. }
  10819. }
  10820. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  10821. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  10822. const char *path = "./truncated_while_served.txt";
  10823. const size_t size = 32 * 1024 * 1024;
  10824. {
  10825. std::ofstream f(path, std::ios::binary);
  10826. f << std::string(size, 'x');
  10827. }
  10828. auto se_file = detail::scope_exit([&] { std::remove(path); });
  10829. // Over TLS, where the bytes are encrypted in this process rather than
  10830. // copied by send().
  10831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10832. svr.Get("/file", [&](const Request &, Response &res) {
  10833. res.set_file_content(path, "text/plain");
  10834. });
  10835. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10836. auto se = detail::scope_exit([&] {
  10837. svr.stop();
  10838. thread.join();
  10839. ASSERT_FALSE(svr.is_running());
  10840. });
  10841. svr.wait_until_ready();
  10842. // The file shrinks once the first bytes are in, as a rewrite in place
  10843. // would, and reading the mapping past its new end used to raise SIGBUS.
  10844. SSLClient cli(HOST, PORT);
  10845. cli.enable_server_certificate_verification(false);
  10846. size_t received = 0;
  10847. auto res = cli.Get("/file", [&](const char *, size_t len) {
  10848. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  10849. received += len;
  10850. return true;
  10851. });
  10852. EXPECT_FALSE(res);
  10853. EXPECT_LT(received, size);
  10854. }
  10855. #endif
  10856. // Forward declaration (see the base64_encode note).
  10857. namespace httplib {
  10858. namespace detail {
  10859. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10860. const std::string &content_type,
  10861. EncodingType encoding);
  10862. } // namespace detail
  10863. } // namespace httplib
  10864. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10865. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10866. ASSERT_TRUE(mm->is_open());
  10867. Response res;
  10868. detail::set_file_content_provider(res, mm, "text/html",
  10869. detail::EncodingType::None);
  10870. std::string out;
  10871. DataSink sink;
  10872. sink.write = [&](const char *d, size_t l) {
  10873. out.append(d, l);
  10874. return true;
  10875. };
  10876. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10877. EXPECT_EQ("test.html", out);
  10878. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10879. EXPECT_EQ("test.html", out);
  10880. }
  10881. TEST(LongPollingTest, ClientCloseDetection) {
  10882. Server svr;
  10883. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10884. res.set_chunked_content_provider(
  10885. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10886. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10887. sink.os << "hello";
  10888. auto count = 10;
  10889. while (count > 0 && sink.is_writable()) {
  10890. this_thread::sleep_for(chrono::milliseconds(10));
  10891. count--;
  10892. }
  10893. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10894. return true;
  10895. });
  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. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10906. EXPECT_EQ("hello", string(data, data_length));
  10907. return false; // close the socket immediately.
  10908. });
  10909. ASSERT_FALSE(res);
  10910. }
  10911. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10912. Server svr;
  10913. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10914. res.set_chunked_content_provider(
  10915. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10916. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10917. sink.os << "hello";
  10918. EXPECT_TRUE(sink.os.good());
  10919. // Wait for the client to close the connection
  10920. auto count = 10;
  10921. while (count > 0 && sink.is_writable()) {
  10922. this_thread::sleep_for(chrono::milliseconds(10));
  10923. count--;
  10924. }
  10925. // After client disconnect, write repeatedly until the socket
  10926. // write actually fails (small writes may be absorbed by the
  10927. // kernel buffer)
  10928. std::string chunk(1024, 'x');
  10929. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10930. sink.os << chunk;
  10931. }
  10932. EXPECT_TRUE(sink.os.fail());
  10933. return true;
  10934. });
  10935. });
  10936. auto port = svr.bind_to_any_port("localhost");
  10937. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. listen_thread.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. });
  10943. svr.wait_until_ready();
  10944. Client cli("localhost", port);
  10945. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10946. EXPECT_EQ("hello", string(data, data_length));
  10947. return false; // close the socket immediately.
  10948. });
  10949. ASSERT_FALSE(res);
  10950. }
  10951. TEST(GetWithParametersTest, GetWithParameters) {
  10952. Server svr;
  10953. svr.Get("/", [&](const Request &req, Response &) {
  10954. EXPECT_EQ("world", req.get_param_value("hello"));
  10955. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10956. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10957. });
  10958. svr.Get("/params", [&](const Request &req, Response &) {
  10959. EXPECT_EQ("world", req.get_param_value("hello"));
  10960. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10961. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10962. });
  10963. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10964. EXPECT_EQ("resource-id", req.matches[1]);
  10965. EXPECT_EQ("foo", req.get_param_value("param1"));
  10966. EXPECT_EQ("bar", req.get_param_value("param2"));
  10967. });
  10968. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10969. EXPECT_EQ("user-id", req.path_params.at("id"));
  10970. EXPECT_EQ("foo", req.get_param_value("param1"));
  10971. EXPECT_EQ("bar", req.get_param_value("param2"));
  10972. });
  10973. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10974. auto se = detail::scope_exit([&] {
  10975. svr.stop();
  10976. listen_thread.join();
  10977. ASSERT_FALSE(svr.is_running());
  10978. });
  10979. svr.wait_until_ready();
  10980. {
  10981. Client cli(HOST, PORT);
  10982. Params params;
  10983. params.emplace("hello", "world");
  10984. params.emplace("hello2", "world2");
  10985. params.emplace("hello3", "world3");
  10986. auto res = cli.Get("/", params, Headers{});
  10987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10988. EXPECT_EQ(StatusCode::OK_200, res->status);
  10989. }
  10990. {
  10991. Client cli(HOST, PORT);
  10992. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10994. EXPECT_EQ(StatusCode::OK_200, res->status);
  10995. }
  10996. {
  10997. Client cli(HOST, PORT);
  10998. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11000. EXPECT_EQ(StatusCode::OK_200, res->status);
  11001. }
  11002. {
  11003. Client cli(HOST, PORT);
  11004. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11006. EXPECT_EQ(StatusCode::OK_200, res->status);
  11007. }
  11008. }
  11009. TEST(GetWithParametersTest, GetWithParameters2) {
  11010. Server svr;
  11011. svr.Get("/", [&](const Request &req, Response &res) {
  11012. auto text = req.get_param_value("hello");
  11013. res.set_content(text, "text/plain");
  11014. });
  11015. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11016. auto se = detail::scope_exit([&] {
  11017. svr.stop();
  11018. listen_thread.join();
  11019. ASSERT_FALSE(svr.is_running());
  11020. });
  11021. svr.wait_until_ready();
  11022. Client cli("localhost", PORT);
  11023. Params params;
  11024. params.emplace("hello", "world");
  11025. std::string body;
  11026. auto res = cli.Get("/", params, Headers{},
  11027. [&](const char *data, size_t data_length) {
  11028. body.append(data, data_length);
  11029. return true;
  11030. });
  11031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11032. EXPECT_EQ(StatusCode::OK_200, res->status);
  11033. EXPECT_EQ("world", body);
  11034. }
  11035. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11036. Server svr;
  11037. svr.Get("/search", [&](const Request &req, Response &res) {
  11038. auto q = req.get_param_value("q");
  11039. res.set_content(q, "text/plain");
  11040. });
  11041. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11042. auto se = detail::scope_exit([&] {
  11043. svr.stop();
  11044. listen_thread.join();
  11045. ASSERT_FALSE(svr.is_running());
  11046. });
  11047. svr.wait_until_ready();
  11048. Client cli("localhost", PORT);
  11049. // Verify that Get(path, params) works without requiring Headers argument
  11050. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11052. EXPECT_EQ(StatusCode::OK_200, res->status);
  11053. EXPECT_EQ("cpp-httplib", res->body);
  11054. }
  11055. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11056. auto host = "httpbingo.org";
  11057. auto path = std::string{"/range/32"};
  11058. #ifdef CPPHTTPLIB_SSL_ENABLED
  11059. SSLClient cli(host);
  11060. #else
  11061. Client cli(host);
  11062. #endif
  11063. cli.set_default_headers({make_range_header({{1, 10}})});
  11064. cli.set_connection_timeout(5);
  11065. {
  11066. auto res = cli.Get(path);
  11067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11068. EXPECT_EQ("bcdefghijk", res->body);
  11069. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11070. }
  11071. {
  11072. auto res = cli.Get(path);
  11073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11074. EXPECT_EQ("bcdefghijk", res->body);
  11075. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11076. }
  11077. }
  11078. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11079. Server svr;
  11080. svr.set_default_headers({{"Hello", "World"}});
  11081. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11082. res.set_content("ok", "text/plain");
  11083. });
  11084. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11085. auto se = detail::scope_exit([&] {
  11086. svr.stop();
  11087. listen_thread.join();
  11088. ASSERT_FALSE(svr.is_running());
  11089. });
  11090. svr.wait_until_ready();
  11091. Client cli("localhost", PORT);
  11092. auto res = cli.Get("/");
  11093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11094. EXPECT_EQ(StatusCode::OK_200, res->status);
  11095. EXPECT_EQ("ok", res->body);
  11096. EXPECT_EQ("World", res->get_header_value("Hello"));
  11097. }
  11098. #ifdef CPPHTTPLIB_SSL_ENABLED
  11099. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11101. ASSERT_TRUE(svr.is_valid());
  11102. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11103. std::this_thread::sleep_for(std::chrono::seconds(2));
  11104. res.set_content("a", "text/plain");
  11105. });
  11106. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11107. res.set_content("b", "text/plain");
  11108. });
  11109. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11110. auto se = detail::scope_exit([&] {
  11111. svr.stop();
  11112. listen_thread.join();
  11113. ASSERT_FALSE(svr.is_running());
  11114. });
  11115. svr.wait_until_ready();
  11116. SSLClient cli("localhost", PORT);
  11117. cli.enable_server_certificate_verification(false);
  11118. cli.set_keep_alive(true);
  11119. cli.set_read_timeout(std::chrono::seconds(1));
  11120. auto resa = cli.Get("/a");
  11121. ASSERT_TRUE(!resa);
  11122. EXPECT_EQ(Error::Read, resa.error());
  11123. auto resb = cli.Get("/b");
  11124. ASSERT_TRUE(resb);
  11125. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11126. EXPECT_EQ("b", resb->body);
  11127. }
  11128. // Closing an idle keep-alive connection sends close_notify and returns. The
  11129. // server must not wait for the client's close_notify: an idle client never
  11130. // sends one, so the worker would be held until the read timeout expires, and
  11131. // stop() would wait for it.
  11132. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11134. ASSERT_TRUE(svr.is_valid());
  11135. svr.set_keep_alive_timeout(1);
  11136. svr.set_read_timeout(10, 0);
  11137. svr.Get("/", [](const Request &, Response &res) {
  11138. res.set_content("ok", "text/plain");
  11139. });
  11140. auto port = svr.bind_to_any_port(HOST);
  11141. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11142. auto se = detail::scope_exit([&] {
  11143. if (listen_thread.joinable()) {
  11144. svr.stop();
  11145. listen_thread.join();
  11146. }
  11147. });
  11148. svr.wait_until_ready();
  11149. SSLClient cli(HOST, port);
  11150. cli.enable_server_certificate_verification(false);
  11151. cli.set_keep_alive(true);
  11152. auto res = cli.Get("/");
  11153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11154. EXPECT_EQ(StatusCode::OK_200, res->status);
  11155. // Stay idle past the keep-alive timeout so the server closes the connection.
  11156. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11157. auto start = std::chrono::steady_clock::now();
  11158. svr.stop();
  11159. listen_thread.join();
  11160. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11161. std::chrono::steady_clock::now() - start)
  11162. .count();
  11163. EXPECT_LT(elapsed, 3000);
  11164. }
  11165. #endif
  11166. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11167. protected:
  11168. ServerTestWithAI_PASSIVE()
  11169. : cli_(HOST, PORT)
  11170. #ifdef CPPHTTPLIB_SSL_ENABLED
  11171. ,
  11172. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11173. #endif
  11174. {
  11175. #ifdef CPPHTTPLIB_SSL_ENABLED
  11176. cli_.enable_server_certificate_verification(false);
  11177. #endif
  11178. }
  11179. virtual void SetUp() {
  11180. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11181. res.set_content("Hello World!", "text/plain");
  11182. });
  11183. t_ = thread(
  11184. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11185. svr_.wait_until_ready();
  11186. }
  11187. virtual void TearDown() {
  11188. svr_.stop();
  11189. t_.join();
  11190. }
  11191. #ifdef CPPHTTPLIB_SSL_ENABLED
  11192. SSLClient cli_;
  11193. SSLServer svr_;
  11194. #else
  11195. Client cli_;
  11196. Server svr_;
  11197. #endif
  11198. thread t_;
  11199. };
  11200. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11201. auto res = cli_.Get("/hi");
  11202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11203. EXPECT_EQ(StatusCode::OK_200, res->status);
  11204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11205. EXPECT_EQ("Hello World!", res->body);
  11206. }
  11207. class ServerUpDownTest : public ::testing::Test {
  11208. protected:
  11209. ServerUpDownTest() : cli_(HOST, PORT) {}
  11210. virtual void SetUp() {
  11211. t_ = thread([&]() {
  11212. svr_.bind_to_any_port(HOST);
  11213. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11214. ASSERT_TRUE(svr_.listen_after_bind());
  11215. });
  11216. svr_.wait_until_ready();
  11217. }
  11218. virtual void TearDown() {
  11219. svr_.stop();
  11220. t_.join();
  11221. }
  11222. Client cli_;
  11223. Server svr_;
  11224. thread t_;
  11225. };
  11226. TEST_F(ServerUpDownTest, QuickStartStop) {
  11227. // Should not crash, especially when run with
  11228. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11229. }
  11230. class PayloadMaxLengthTest : public ::testing::Test {
  11231. protected:
  11232. PayloadMaxLengthTest()
  11233. : cli_(HOST, PORT)
  11234. #ifdef CPPHTTPLIB_SSL_ENABLED
  11235. ,
  11236. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11237. #endif
  11238. {
  11239. #ifdef CPPHTTPLIB_SSL_ENABLED
  11240. cli_.enable_server_certificate_verification(false);
  11241. #endif
  11242. }
  11243. virtual void SetUp() {
  11244. svr_.set_payload_max_length(8);
  11245. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11246. res.set_content("test", "text/plain");
  11247. });
  11248. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11249. svr_.wait_until_ready();
  11250. }
  11251. virtual void TearDown() {
  11252. svr_.stop();
  11253. t_.join();
  11254. }
  11255. #ifdef CPPHTTPLIB_SSL_ENABLED
  11256. SSLClient cli_;
  11257. SSLServer svr_;
  11258. #else
  11259. Client cli_;
  11260. Server svr_;
  11261. #endif
  11262. thread t_;
  11263. };
  11264. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11265. auto res = cli_.Post("/test", "123456789", "text/plain");
  11266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11267. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11268. res = cli_.Post("/test", "12345678", "text/plain");
  11269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11270. EXPECT_EQ(StatusCode::OK_200, res->status);
  11271. }
  11272. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11273. // Test chunked encoding with payload exceeding the 8-byte limit
  11274. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11275. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11277. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11278. }
  11279. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11280. // Test chunked encoding with payload within the 8-byte limit
  11281. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11282. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11284. EXPECT_EQ(StatusCode::OK_200, res->status);
  11285. }
  11286. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11287. // Test using send_request to send chunked data exceeding payload limit
  11288. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11289. "Host: " +
  11290. std::string(HOST) + ":" + std::to_string(PORT) +
  11291. "\r\n"
  11292. "Transfer-Encoding: chunked\r\n"
  11293. "Connection: close\r\n"
  11294. "\r\n"
  11295. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11296. "0123456789\r\n"
  11297. "0\r\n" // End chunk
  11298. "\r\n";
  11299. std::string response;
  11300. bool result = send_request(1, chunked_request, &response);
  11301. if (!result) {
  11302. // If send_request fails, it might be because the server closed the
  11303. // connection due to payload limit enforcement, which is acceptable
  11304. SUCCEED()
  11305. << "Server rejected oversized chunked request (connection closed)";
  11306. } else {
  11307. // If we got a response, check if it's an error response or connection was
  11308. // closed early Short response length indicates connection was closed due to
  11309. // payload limit
  11310. if (response.length() <= 10) {
  11311. SUCCEED() << "Server closed connection for oversized chunked request";
  11312. } else {
  11313. // Check for error status codes
  11314. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11315. response.find("Payload Too Large") != std::string::npos ||
  11316. response.find("400") != std::string::npos);
  11317. }
  11318. }
  11319. }
  11320. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11321. // Test request without Content-Length header exceeding payload limit
  11322. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11323. "Host: " +
  11324. std::string(HOST) + ":" +
  11325. std::to_string(PORT) +
  11326. "\r\n"
  11327. "Connection: close\r\n"
  11328. "\r\n";
  11329. // Add payload exceeding the 8-byte limit
  11330. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11331. request_without_content_length += large_payload;
  11332. std::string response;
  11333. bool result = send_request(1, request_without_content_length, &response);
  11334. if (!result) {
  11335. // If send_request fails, server likely closed connection due to payload
  11336. // limit
  11337. SUCCEED() << "Server rejected oversized request without Content-Length "
  11338. "(connection closed)";
  11339. } else {
  11340. // Check if server responded with error or closed connection early
  11341. if (response.length() <= 10) {
  11342. SUCCEED() << "Server closed connection for oversized request without "
  11343. "Content-Length";
  11344. } else {
  11345. // Check for error status codes
  11346. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11347. response.find("Payload Too Large") != std::string::npos ||
  11348. response.find("400") != std::string::npos);
  11349. }
  11350. }
  11351. }
  11352. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11353. // Test request without Content-Length header within payload limit
  11354. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11355. "Host: " +
  11356. std::string(HOST) + ":" +
  11357. std::to_string(PORT) +
  11358. "\r\n"
  11359. "Connection: close\r\n"
  11360. "\r\n";
  11361. // Add payload within the 8-byte limit
  11362. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11363. request_without_content_length += small_payload;
  11364. std::string response;
  11365. bool result = send_request(1, request_without_content_length, &response);
  11366. // For requests without Content-Length, the server may have different behavior
  11367. // The key is that it should not reject due to payload limit for small
  11368. // payloads
  11369. if (result) {
  11370. // Check for any HTTP response (success or error, but not connection closed)
  11371. if (response.length() > 10) {
  11372. SUCCEED()
  11373. << "Server processed request without Content-Length within limit";
  11374. } else {
  11375. // Short response might indicate connection closed, which is acceptable
  11376. SUCCEED() << "Server closed connection for request without "
  11377. "Content-Length (acceptable behavior)";
  11378. }
  11379. } else {
  11380. // Connection failure might be due to protocol requirements
  11381. SUCCEED() << "Connection issue with request without Content-Length "
  11382. "(environment-specific)";
  11383. }
  11384. }
  11385. class LargePayloadMaxLengthTest : public ::testing::Test {
  11386. protected:
  11387. LargePayloadMaxLengthTest()
  11388. : cli_(HOST, PORT)
  11389. #ifdef CPPHTTPLIB_SSL_ENABLED
  11390. ,
  11391. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11392. #endif
  11393. {
  11394. #ifdef CPPHTTPLIB_SSL_ENABLED
  11395. cli_.enable_server_certificate_verification(false);
  11396. #endif
  11397. }
  11398. virtual void SetUp() {
  11399. // Set 10MB payload limit
  11400. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11401. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11402. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11403. res.set_content("Large payload test", "text/plain");
  11404. });
  11405. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11406. svr_.wait_until_ready();
  11407. }
  11408. virtual void TearDown() {
  11409. svr_.stop();
  11410. t_.join();
  11411. }
  11412. #ifdef CPPHTTPLIB_SSL_ENABLED
  11413. SSLClient cli_;
  11414. SSLServer svr_;
  11415. #else
  11416. Client cli_;
  11417. Server svr_;
  11418. #endif
  11419. thread t_;
  11420. };
  11421. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11422. // Test chunked encoding with payload within 10MB limit
  11423. std::string medium_payload(5 * 1024 * 1024,
  11424. 'A'); // 5MB payload, within 10MB limit
  11425. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11427. EXPECT_EQ(StatusCode::OK_200, res->status);
  11428. }
  11429. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11430. // Test chunked encoding with payload exceeding 10MB limit
  11431. std::string large_payload(12 * 1024 * 1024,
  11432. 'B'); // 12MB payload, exceeds 10MB limit
  11433. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11434. // Server may either return 413 or close the connection
  11435. if (res) {
  11436. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11437. } else {
  11438. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11439. }
  11440. }
  11441. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11442. // Test request without Content-Length header within 10MB limit
  11443. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11444. "Host: " +
  11445. std::string(HOST) + ":" +
  11446. std::to_string(PORT) +
  11447. "\r\n"
  11448. "Connection: close\r\n"
  11449. "\r\n";
  11450. // Add 1MB payload (within 10MB limit)
  11451. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11452. request_without_content_length += medium_payload;
  11453. std::string response;
  11454. bool result = send_request(5, request_without_content_length, &response);
  11455. if (result) {
  11456. // Should get a proper HTTP response for payloads within limit
  11457. if (response.length() > 10) {
  11458. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11459. "10MB limit";
  11460. } else {
  11461. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11462. "Content-Length)";
  11463. }
  11464. } else {
  11465. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11466. }
  11467. }
  11468. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11469. // Test request without Content-Length header exceeding 10MB limit
  11470. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11471. "Host: " +
  11472. std::string(HOST) + ":" +
  11473. std::to_string(PORT) +
  11474. "\r\n"
  11475. "Connection: close\r\n"
  11476. "\r\n";
  11477. // Add 12MB payload (exceeds 10MB limit)
  11478. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11479. request_without_content_length += large_payload;
  11480. std::string response;
  11481. bool result = send_request(10, request_without_content_length, &response);
  11482. if (!result) {
  11483. // Server should close connection due to payload limit
  11484. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11485. "(connection closed)";
  11486. } else {
  11487. // Check for error response
  11488. if (response.length() <= 10) {
  11489. SUCCEED()
  11490. << "Server closed connection for 12MB request exceeding 10MB limit";
  11491. } else {
  11492. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11493. response.find("Payload Too Large") != std::string::npos ||
  11494. response.find("400") != std::string::npos);
  11495. }
  11496. }
  11497. }
  11498. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11499. Server svr;
  11500. svr.Get("/", [](const Request &, Response &res) {
  11501. // Claims far more than it sends, then drops the connection.
  11502. res.set_content_provider(size_t(1) << 41, "text/plain",
  11503. [](size_t, size_t, DataSink &sink) {
  11504. sink.write("abc", 3);
  11505. return false;
  11506. });
  11507. });
  11508. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11509. auto se = detail::scope_exit([&] {
  11510. svr.stop();
  11511. thread.join();
  11512. ASSERT_FALSE(svr.is_running());
  11513. });
  11514. svr.wait_until_ready();
  11515. Client cli(HOST, PORT);
  11516. cli.set_payload_max_length(0);
  11517. EXPECT_FALSE(cli.Get("/"));
  11518. }
  11519. // Accepts one connection on 127.0.0.1:port, reads the request head and sends
  11520. // back the given bytes, which httplib::Server could not be made to send.
  11521. static void serve_raw_once(int port, const std::string &response) {
  11522. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11523. default_socket_options(srv);
  11524. sockaddr_in addr{};
  11525. addr.sin_family = AF_INET;
  11526. addr.sin_port = htons(static_cast<uint16_t>(port));
  11527. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11528. int opt = 1;
  11529. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11530. #ifdef _WIN32
  11531. reinterpret_cast<const char *>(&opt),
  11532. #else
  11533. &opt,
  11534. #endif
  11535. sizeof(opt));
  11536. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11537. ::listen(srv, 1);
  11538. auto cli = ::accept(srv, nullptr, nullptr);
  11539. if (cli != INVALID_SOCKET) {
  11540. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11541. std::string head;
  11542. char c;
  11543. while (head.find("\r\n\r\n") == std::string::npos &&
  11544. ::recv(cli, &c, 1, 0) == 1) {
  11545. head += c;
  11546. }
  11547. ::send(cli, response.data(), static_cast<int>(response.size()), 0);
  11548. detail::close_socket(cli);
  11549. }
  11550. detail::close_socket(srv);
  11551. }
  11552. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  11553. const char *responses[] = {
  11554. "HTTP/1.1 103 Early Hints\r\n"
  11555. "Link: </style.css>; rel=preload\r\n"
  11556. "\r\n"
  11557. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11558. "HTTP/1.1 100 Continue\r\n"
  11559. "X-Note: interim\r\n"
  11560. "\r\n"
  11561. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11562. };
  11563. for (auto response : responses) {
  11564. std::thread t([&]() { serve_raw_once(PORT, response); });
  11565. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11566. Client cli("127.0.0.1", PORT);
  11567. auto res = cli.Get("/");
  11568. t.join();
  11569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11570. EXPECT_EQ(StatusCode::OK_200, res->status);
  11571. EXPECT_EQ("ok", res->body);
  11572. }
  11573. }
  11574. #ifdef CPPHTTPLIB_SSL_ENABLED
  11575. TEST(ProxyConnectTest, OnlyARefusalIsPassedOn) {
  11576. // Anything but 200 or a refusal would read as the origin's own response.
  11577. {
  11578. std::thread t([] {
  11579. serve_raw_once(PORT, "HTTP/1.1 201 Created\r\n"
  11580. "Set-Cookie: session=from-proxy\r\n"
  11581. "Content-Length: 0\r\n\r\n");
  11582. });
  11583. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11584. SSLClient cli("example.com", 443);
  11585. cli.set_proxy("127.0.0.1", PORT);
  11586. auto res = cli.Get("/");
  11587. t.join();
  11588. EXPECT_FALSE(res);
  11589. EXPECT_EQ(Error::ProxyConnection, res.error());
  11590. }
  11591. {
  11592. std::thread t([] {
  11593. serve_raw_once(PORT, "HTTP/1.1 407 Proxy Authentication Required\r\n"
  11594. "Content-Length: 0\r\n\r\n");
  11595. });
  11596. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11597. SSLClient cli("example.com", 443);
  11598. cli.set_proxy("127.0.0.1", PORT);
  11599. auto res = cli.Get("/");
  11600. t.join();
  11601. ASSERT_TRUE(res);
  11602. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  11603. }
  11604. }
  11605. #endif
  11606. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  11607. std::atomic<bool> closed_by_client{false};
  11608. auto server_thread = std::thread([&] {
  11609. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11610. default_socket_options(srv);
  11611. sockaddr_in addr{};
  11612. addr.sin_family = AF_INET;
  11613. addr.sin_port = htons(static_cast<uint16_t>(PORT));
  11614. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11615. int opt = 1;
  11616. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11617. #ifdef _WIN32
  11618. reinterpret_cast<const char *>(&opt),
  11619. #else
  11620. &opt,
  11621. #endif
  11622. sizeof(opt));
  11623. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11624. ::listen(srv, 1);
  11625. auto cli = ::accept(srv, nullptr, nullptr);
  11626. if (cli != INVALID_SOCKET) {
  11627. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11628. // Answer the head without asking for the body, and keep the connection.
  11629. std::string head;
  11630. char c;
  11631. while (head.find("\r\n\r\n") == std::string::npos &&
  11632. ::recv(cli, &c, 1, 0) == 1) {
  11633. head += c;
  11634. }
  11635. std::string res =
  11636. "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n";
  11637. ::send(cli, res.data(), static_cast<int>(res.size()), 0);
  11638. // Bytes here would be read as the body the first request declared.
  11639. char buf[256];
  11640. closed_by_client = ::recv(cli, buf, sizeof(buf), 0) == 0;
  11641. detail::close_socket(cli);
  11642. }
  11643. detail::close_socket(srv);
  11644. });
  11645. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11646. Client cli("127.0.0.1", PORT);
  11647. cli.set_keep_alive(true);
  11648. cli.set_read_timeout(1, 0);
  11649. // Long enough for the client to send Expect: 100-continue.
  11650. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  11651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11652. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  11653. cli.Get("/second");
  11654. server_thread.join();
  11655. EXPECT_TRUE(closed_by_client);
  11656. }
  11657. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11658. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11659. // path.
  11660. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11661. Server svr;
  11662. const size_t LIMIT = 64 * 1024; // 64KB
  11663. svr.set_payload_max_length(LIMIT);
  11664. size_t total = 0;
  11665. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11666. const ContentReader &content_reader) {
  11667. content_reader([&](const char * /*data*/, size_t len) {
  11668. total += len;
  11669. return true;
  11670. });
  11671. res.status = 200;
  11672. res.set_content("stream_ok", "text/plain");
  11673. });
  11674. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11675. auto se = detail::scope_exit([&] {
  11676. svr.stop();
  11677. thread.join();
  11678. ASSERT_FALSE(svr.is_running());
  11679. });
  11680. svr.wait_until_ready();
  11681. // Prepare 256KB raw data and gzip-compress it
  11682. std::string raw(256 * 1024, 'A');
  11683. std::string gz;
  11684. {
  11685. z_stream zs{};
  11686. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11687. Z_DEFAULT_STRATEGY);
  11688. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11689. zs.avail_in = static_cast<uInt>(raw.size());
  11690. char outbuf[4096];
  11691. int ret;
  11692. do {
  11693. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11694. zs.avail_out = sizeof(outbuf);
  11695. ret = deflate(&zs, Z_FINISH);
  11696. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11697. } while (ret != Z_STREAM_END);
  11698. deflateEnd(&zs);
  11699. }
  11700. Client cli(HOST, PORT);
  11701. cli.set_connection_timeout(std::chrono::seconds(5));
  11702. Headers headers = {{"Content-Encoding", "gzip"}};
  11703. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11704. "application/octet-stream");
  11705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11706. // Server must reject oversized decompressed payloads with 413.
  11707. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11708. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11709. EXPECT_LE(total, LIMIT);
  11710. }
  11711. #ifndef CPPHTTPLIB_SSL_ENABLED
  11712. // For a request with neither Content-Length nor Transfer-Encoding, the
  11713. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11714. // compressed wire bytes straight to the ContentReader without ever routing
  11715. // them through the decompressor, so payload_max_length_ only bounded the
  11716. // compressed size on the wire, not the decompressed size.
  11717. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11718. Server svr;
  11719. const size_t LIMIT = 64 * 1024; // 64KB
  11720. svr.set_payload_max_length(LIMIT);
  11721. size_t total = 0;
  11722. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11723. const ContentReader &content_reader) {
  11724. content_reader([&](const char * /*data*/, size_t len) {
  11725. total += len;
  11726. return true;
  11727. });
  11728. res.status = 200;
  11729. res.set_content("stream_ok", "text/plain");
  11730. });
  11731. auto port = svr.bind_to_any_port(HOST);
  11732. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11733. auto se = detail::scope_exit([&] {
  11734. svr.stop();
  11735. thread.join();
  11736. ASSERT_FALSE(svr.is_running());
  11737. });
  11738. svr.wait_until_ready();
  11739. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11740. // StreamingGzipDecompression test above.
  11741. std::string raw(256 * 1024, 'A');
  11742. std::string gz;
  11743. {
  11744. httplib::detail::gzip_compressor compressor;
  11745. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11746. [&](const char *chunk, size_t len) {
  11747. gz.append(chunk, len);
  11748. return true;
  11749. });
  11750. ASSERT_TRUE(result);
  11751. }
  11752. // Send the gzip body over raw TCP with neither Content-Length nor
  11753. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11754. // kicks in.
  11755. std::string req = "POST /stream HTTP/1.1\r\n"
  11756. "Host: " +
  11757. std::string(HOST) + ":" + std::to_string(port) +
  11758. "\r\n"
  11759. "Content-Encoding: gzip\r\n"
  11760. "Connection: close\r\n"
  11761. "\r\n" +
  11762. gz;
  11763. std::string response;
  11764. ASSERT_TRUE(send_request(5, req, &response, port));
  11765. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11766. EXPECT_LE(total, LIMIT);
  11767. }
  11768. #endif
  11769. #endif
  11770. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11771. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11772. // the payload must be passed through untouched instead of being rejected.
  11773. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11774. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11775. Server svr;
  11776. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11777. res.set_content(body, "image/jpeg");
  11778. res.set_header("Content-Encoding", "UTF-8");
  11779. });
  11780. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11781. res.set_content(body, "image/jpeg");
  11782. res.set_header("Content-Encoding", "identity");
  11783. });
  11784. svr.Post("/echo", [](const Request &req, Response &res) {
  11785. res.set_content(req.body, "image/jpeg");
  11786. });
  11787. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11788. auto se = detail::scope_exit([&] {
  11789. svr.stop();
  11790. t.join();
  11791. ASSERT_FALSE(svr.is_running());
  11792. });
  11793. svr.wait_until_ready();
  11794. Client cli(HOST, PORT);
  11795. {
  11796. auto res = cli.Get("/image");
  11797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11798. EXPECT_EQ(StatusCode::OK_200, res->status);
  11799. EXPECT_EQ(body, res->body);
  11800. }
  11801. {
  11802. auto res = cli.Get("/identity");
  11803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11804. EXPECT_EQ(StatusCode::OK_200, res->status);
  11805. EXPECT_EQ(body, res->body);
  11806. }
  11807. {
  11808. // The same applies to a request body reaching the server.
  11809. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11810. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11812. EXPECT_EQ(StatusCode::OK_200, res->status);
  11813. EXPECT_EQ(body, res->body);
  11814. }
  11815. }
  11816. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11817. // gzip-encoded response even when the build has no zlib support.
  11818. static const char GZIPPED_HELLO_WORLD[] = {
  11819. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11820. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11821. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11822. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11823. // A content coding is a whole token, not something the field value merely
  11824. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11825. // as "fibre" look like Brotli, and turned a multi-coding value like
  11826. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11827. // it was never meant to see.
  11828. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11829. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11830. Server svr;
  11831. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11832. res.set_content(body, "image/jpeg");
  11833. res.set_header("Content-Encoding", "fibre");
  11834. });
  11835. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11836. res.set_content(body, "image/jpeg");
  11837. res.set_header("Content-Encoding", "gzip, br");
  11838. });
  11839. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11840. res.set_content(body, "image/jpeg");
  11841. res.set_header("Content-Encoding", "x-zstd-ish");
  11842. });
  11843. auto port = svr.bind_to_any_port(HOST);
  11844. thread t = thread([&]() { svr.listen_after_bind(); });
  11845. auto se = detail::scope_exit([&] {
  11846. svr.stop();
  11847. t.join();
  11848. ASSERT_FALSE(svr.is_running());
  11849. });
  11850. svr.wait_until_ready();
  11851. Client cli(HOST, port);
  11852. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11853. auto res = cli.Get(path);
  11854. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11855. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11856. // Not a coding we recognize, so the payload comes back untouched
  11857. EXPECT_EQ(body, res->body) << path;
  11858. }
  11859. }
  11860. // A content coding cpp-httplib recognizes but was not built with must be
  11861. // reported as such. Handing the still-compressed payload back to the caller
  11862. // would silently corrupt it.
  11863. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11864. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11865. Server svr;
  11866. // "image/jpeg" keeps the server from applying a content coding of its own,
  11867. // so the hand-crafted Content-Encoding below survives.
  11868. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11869. res.set_content(gzipped, "image/jpeg");
  11870. res.set_header("Content-Encoding", "gzip");
  11871. });
  11872. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11873. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11874. res.set_content(gzipped, "image/jpeg");
  11875. res.set_header("Content-Encoding", "GZIP");
  11876. });
  11877. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11878. auto se = detail::scope_exit([&] {
  11879. svr.stop();
  11880. t.join();
  11881. ASSERT_FALSE(svr.is_running());
  11882. });
  11883. svr.wait_until_ready();
  11884. Client cli(HOST, PORT);
  11885. {
  11886. auto res = cli.Get("/gzipped");
  11887. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11889. EXPECT_EQ("Hello World!", res->body);
  11890. #else
  11891. ASSERT_FALSE(res);
  11892. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11893. #endif
  11894. }
  11895. {
  11896. // open_stream() must behave the same way.
  11897. auto handle = cli.open_stream("GET", "/gzipped");
  11898. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11899. ASSERT_TRUE(handle.is_valid());
  11900. std::string received;
  11901. char buf[256];
  11902. ssize_t n;
  11903. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11904. received.append(buf, static_cast<size_t>(n));
  11905. }
  11906. EXPECT_EQ("Hello World!", received);
  11907. #else
  11908. EXPECT_FALSE(handle.is_valid());
  11909. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11910. #endif
  11911. }
  11912. {
  11913. // A differently-cased coding must not be mistaken for an unknown one, or
  11914. // the body would be handed back still compressed.
  11915. auto res = cli.Get("/gzipped-uppercase");
  11916. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11918. EXPECT_EQ("Hello World!", res->body);
  11919. #else
  11920. ASSERT_FALSE(res);
  11921. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11922. #endif
  11923. }
  11924. }
  11925. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11926. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11927. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11928. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11929. // body a second time and appending a second Content-Encoding field line, so
  11930. // clients that decode one coding per listed value handed back raw gzip bytes.
  11931. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11932. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11933. Server svr;
  11934. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11935. // keeps the server from applying a coding of its own.
  11936. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11937. res.set_content(gzipped, "text/plain");
  11938. res.set_header("Content-Encoding", "gzip");
  11939. });
  11940. auto port = svr.bind_to_any_port(HOST);
  11941. thread t = thread([&]() { svr.listen_after_bind(); });
  11942. auto se = detail::scope_exit([&] {
  11943. svr.stop();
  11944. t.join();
  11945. ASSERT_FALSE(svr.is_running());
  11946. });
  11947. svr.wait_until_ready();
  11948. Client cli(HOST, port);
  11949. Headers headers = {{"Accept-Encoding", "gzip"}};
  11950. auto res = cli.Get("/pre-gzipped", headers);
  11951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11952. EXPECT_EQ(StatusCode::OK_200, res->status);
  11953. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11954. EXPECT_EQ("Hello World!", res->body);
  11955. }
  11956. // A chunked provider settles its coding where the headers are written and
  11957. // reuses it at write time. Both ends of that have to hold: a handler's own
  11958. // Content-Encoding suppresses the coding, and a response without one is still
  11959. // compressed as it always was.
  11960. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11961. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11962. const std::string plain = "Hello World! Hello World! Hello World!";
  11963. Server svr;
  11964. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11965. res.set_header("Content-Encoding", "gzip");
  11966. res.set_chunked_content_provider(
  11967. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11968. sink.write(gzipped.data(), gzipped.size());
  11969. sink.done();
  11970. return true;
  11971. });
  11972. });
  11973. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11974. res.set_chunked_content_provider(
  11975. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11976. sink.write(plain.data(), plain.size());
  11977. sink.done();
  11978. return true;
  11979. });
  11980. });
  11981. auto port = svr.bind_to_any_port(HOST);
  11982. thread t = thread([&]() { svr.listen_after_bind(); });
  11983. auto se = detail::scope_exit([&] {
  11984. svr.stop();
  11985. t.join();
  11986. ASSERT_FALSE(svr.is_running());
  11987. });
  11988. svr.wait_until_ready();
  11989. Client cli(HOST, port);
  11990. Headers headers = {{"Accept-Encoding", "gzip"}};
  11991. {
  11992. auto res = cli.Get("/pre-gzipped", headers);
  11993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11994. EXPECT_EQ(StatusCode::OK_200, res->status);
  11995. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11996. EXPECT_EQ("Hello World!", res->body);
  11997. }
  11998. {
  11999. auto res = cli.Get("/negotiated", headers);
  12000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12001. EXPECT_EQ(StatusCode::OK_200, res->status);
  12002. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12003. EXPECT_EQ(plain, res->body);
  12004. }
  12005. }
  12006. #endif
  12007. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12008. // the same message as the comma-joined one, so both have to be read the same
  12009. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12010. // single gzip coding, and a body the sender says was encoded twice was handed
  12011. // back after one pass, still compressed but presented as decoded.
  12012. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12013. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12014. Server svr;
  12015. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12016. res.set_content(body, "image/jpeg");
  12017. res.headers.emplace("Content-Encoding", "gzip");
  12018. res.headers.emplace("Content-Encoding", "gzip");
  12019. });
  12020. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12021. res.set_content(body, "image/jpeg");
  12022. res.set_header("Content-Encoding", "gzip, gzip");
  12023. });
  12024. auto port = svr.bind_to_any_port(HOST);
  12025. thread t = thread([&]() { svr.listen_after_bind(); });
  12026. auto se = detail::scope_exit([&] {
  12027. svr.stop();
  12028. t.join();
  12029. ASSERT_FALSE(svr.is_running());
  12030. });
  12031. svr.wait_until_ready();
  12032. Client cli(HOST, port);
  12033. // Two codings is not something cpp-httplib decodes, so both representations
  12034. // take the pass-through path rather than one of them being gunzipped once.
  12035. for (const char *path : {"/split", "/joined"}) {
  12036. auto res = cli.Get(path);
  12037. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12038. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12039. EXPECT_EQ(body, res->body) << path;
  12040. }
  12041. }
  12042. // Regression test for DoS vulnerability: a malicious server sending a response
  12043. // without Content-Length header must not cause unbounded memory consumption on
  12044. // the client side. The client should stop reading after a reasonable limit,
  12045. // similar to the server-side set_payload_max_length protection.
  12046. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12047. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12048. #ifndef _WIN32
  12049. signal(SIGPIPE, SIG_IGN);
  12050. #endif
  12051. auto server_thread = std::thread([] {
  12052. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12053. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12054. default_socket_options(srv);
  12055. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12056. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12057. sockaddr_in addr{};
  12058. addr.sin_family = AF_INET;
  12059. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12060. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12061. int opt = 1;
  12062. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12063. #ifdef _WIN32
  12064. reinterpret_cast<const char *>(&opt),
  12065. #else
  12066. &opt,
  12067. #endif
  12068. sizeof(opt));
  12069. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12070. ::listen(srv, 1);
  12071. sockaddr_in cli_addr{};
  12072. socklen_t cli_len = sizeof(cli_addr);
  12073. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12074. if (cli != INVALID_SOCKET) {
  12075. char buf[4096];
  12076. ::recv(cli, buf, sizeof(buf), 0);
  12077. // Malicious response: no Content-Length, no chunked encoding
  12078. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12079. "Connection: close\r\n"
  12080. "\r\n";
  12081. ::send(cli,
  12082. #ifdef _WIN32
  12083. static_cast<const char *>(response_header.c_str()),
  12084. static_cast<int>(response_header.size()),
  12085. #else
  12086. response_header.c_str(), response_header.size(),
  12087. #endif
  12088. 0);
  12089. // Send 10MB of data
  12090. std::string chunk(64 * 1024, 'A');
  12091. size_t total_sent = 0;
  12092. while (total_sent < MALICIOUS_DATA_SIZE) {
  12093. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12094. auto sent = ::send(cli,
  12095. #ifdef _WIN32
  12096. static_cast<const char *>(chunk.c_str()),
  12097. static_cast<int>(to_send),
  12098. #else
  12099. chunk.c_str(), to_send,
  12100. #endif
  12101. 0);
  12102. if (sent <= 0) break;
  12103. total_sent += static_cast<size_t>(sent);
  12104. }
  12105. detail::close_socket(cli);
  12106. }
  12107. detail::close_socket(srv);
  12108. });
  12109. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12110. size_t total_read = 0;
  12111. {
  12112. Client cli("127.0.0.1", PORT + 2);
  12113. cli.set_read_timeout(5, 0);
  12114. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12115. auto stream = cli.open_stream("GET", "/malicious");
  12116. ASSERT_TRUE(stream.is_valid());
  12117. char buffer[64 * 1024];
  12118. ssize_t n;
  12119. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12120. total_read += static_cast<size_t>(n);
  12121. }
  12122. } // StreamHandle and Client destroyed here, closing the socket
  12123. server_thread.join();
  12124. // With set_payload_max_length, the client must stop reading before consuming
  12125. // all 10MB. The read loop should be cut off at or near the configured limit.
  12126. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12127. << "Client read " << total_read << " bytes, exceeding the configured "
  12128. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12129. }
  12130. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12131. // the entire response body without truncation.
  12132. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12133. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12134. #ifndef _WIN32
  12135. signal(SIGPIPE, SIG_IGN);
  12136. #endif
  12137. auto server_thread = std::thread([] {
  12138. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12139. default_socket_options(srv);
  12140. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12141. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12142. sockaddr_in addr{};
  12143. addr.sin_family = AF_INET;
  12144. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12145. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12146. int opt = 1;
  12147. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12148. #ifdef _WIN32
  12149. reinterpret_cast<const char *>(&opt),
  12150. #else
  12151. &opt,
  12152. #endif
  12153. sizeof(opt));
  12154. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12155. ::listen(srv, 1);
  12156. sockaddr_in cli_addr{};
  12157. socklen_t cli_len = sizeof(cli_addr);
  12158. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12159. if (cli != INVALID_SOCKET) {
  12160. char buf[4096];
  12161. ::recv(cli, buf, sizeof(buf), 0);
  12162. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12163. "Connection: close\r\n"
  12164. "\r\n";
  12165. ::send(cli,
  12166. #ifdef _WIN32
  12167. static_cast<const char *>(response_header.c_str()),
  12168. static_cast<int>(response_header.size()),
  12169. #else
  12170. response_header.c_str(), response_header.size(),
  12171. #endif
  12172. 0);
  12173. std::string chunk(64 * 1024, 'A');
  12174. size_t total_sent = 0;
  12175. while (total_sent < DATA_SIZE) {
  12176. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12177. auto sent = ::send(cli,
  12178. #ifdef _WIN32
  12179. static_cast<const char *>(chunk.c_str()),
  12180. static_cast<int>(to_send),
  12181. #else
  12182. chunk.c_str(), to_send,
  12183. #endif
  12184. 0);
  12185. if (sent <= 0) break;
  12186. total_sent += static_cast<size_t>(sent);
  12187. }
  12188. #ifdef _WIN32
  12189. ::shutdown(cli, SD_SEND);
  12190. #else
  12191. ::shutdown(cli, SHUT_WR);
  12192. #endif
  12193. // Drain until the client closes its end, ensuring all data is delivered
  12194. char drain[1024];
  12195. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12196. detail::close_socket(cli);
  12197. }
  12198. detail::close_socket(srv);
  12199. });
  12200. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12201. size_t total_read = 0;
  12202. {
  12203. Client cli("127.0.0.1", PORT + 2);
  12204. cli.set_read_timeout(5, 0);
  12205. cli.set_payload_max_length(0); // 0 means no limit
  12206. auto stream = cli.open_stream("GET", "/data");
  12207. ASSERT_TRUE(stream.is_valid());
  12208. char buffer[64 * 1024];
  12209. ssize_t n;
  12210. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12211. total_read += static_cast<size_t>(n);
  12212. }
  12213. }
  12214. server_thread.join();
  12215. EXPECT_EQ(total_read, DATA_SIZE)
  12216. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12217. << " bytes without truncation, but only read " << total_read << " bytes.";
  12218. }
  12219. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12220. // enormous Content-Length must not cause the client to pre-allocate a huge
  12221. // response body buffer. The reservation is capped at payload_max_length_, and
  12222. // the read itself fails when the body exceeds the limit.
  12223. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12224. #ifndef _WIN32
  12225. signal(SIGPIPE, SIG_IGN);
  12226. #endif
  12227. auto server_thread = std::thread([] {
  12228. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12229. default_socket_options(srv);
  12230. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12231. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12232. sockaddr_in addr{};
  12233. addr.sin_family = AF_INET;
  12234. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12235. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12236. int opt = 1;
  12237. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12238. #ifdef _WIN32
  12239. reinterpret_cast<const char *>(&opt),
  12240. #else
  12241. &opt,
  12242. #endif
  12243. sizeof(opt));
  12244. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12245. ::listen(srv, 1);
  12246. sockaddr_in cli_addr{};
  12247. socklen_t cli_len = sizeof(cli_addr);
  12248. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12249. if (cli != INVALID_SOCKET) {
  12250. char buf[4096];
  12251. ::recv(cli, buf, sizeof(buf), 0);
  12252. // Malicious response: claim a 20GB body but send only a tiny payload.
  12253. std::string response = "HTTP/1.1 200 OK\r\n"
  12254. "Content-Length: 20000000000\r\n"
  12255. "\r\n"
  12256. "abc";
  12257. ::send(cli,
  12258. #ifdef _WIN32
  12259. static_cast<const char *>(response.c_str()),
  12260. static_cast<int>(response.size()),
  12261. #else
  12262. response.c_str(), response.size(),
  12263. #endif
  12264. 0);
  12265. detail::close_socket(cli);
  12266. }
  12267. detail::close_socket(srv);
  12268. });
  12269. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12270. {
  12271. Client cli("127.0.0.1", PORT + 2);
  12272. cli.set_read_timeout(5, 0);
  12273. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12274. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12275. // (server claims more bytes than payload_max_length permits), but it must
  12276. // not exhaust memory before getting there.
  12277. auto res = cli.Get("/malicious");
  12278. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12279. }
  12280. server_thread.join();
  12281. }
  12282. // Verify that content_receiver bypasses the default payload_max_length,
  12283. // allowing streaming downloads larger than 100MB without requiring an explicit
  12284. // set_payload_max_length call.
  12285. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12286. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12287. #ifndef _WIN32
  12288. signal(SIGPIPE, SIG_IGN);
  12289. #endif
  12290. auto server_thread = std::thread([] {
  12291. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12292. default_socket_options(srv);
  12293. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12294. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12295. sockaddr_in addr{};
  12296. addr.sin_family = AF_INET;
  12297. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12298. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12299. int opt = 1;
  12300. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12301. #ifdef _WIN32
  12302. reinterpret_cast<const char *>(&opt),
  12303. #else
  12304. &opt,
  12305. #endif
  12306. sizeof(opt));
  12307. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12308. ::listen(srv, 1);
  12309. sockaddr_in cli_addr{};
  12310. socklen_t cli_len = sizeof(cli_addr);
  12311. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12312. if (cli != INVALID_SOCKET) {
  12313. char buf[4096];
  12314. ::recv(cli, buf, sizeof(buf), 0);
  12315. // Response with Content-Length larger than default 100MB limit
  12316. auto content_length = std::to_string(DATA_SIZE);
  12317. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12318. "Content-Length: " +
  12319. content_length +
  12320. "\r\n"
  12321. "Connection: close\r\n"
  12322. "\r\n";
  12323. ::send(cli,
  12324. #ifdef _WIN32
  12325. static_cast<const char *>(response_header.c_str()),
  12326. static_cast<int>(response_header.size()),
  12327. #else
  12328. response_header.c_str(), response_header.size(),
  12329. #endif
  12330. 0);
  12331. std::string chunk(64 * 1024, 'A');
  12332. size_t total_sent = 0;
  12333. while (total_sent < DATA_SIZE) {
  12334. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12335. auto sent = ::send(cli,
  12336. #ifdef _WIN32
  12337. static_cast<const char *>(chunk.c_str()),
  12338. static_cast<int>(to_send),
  12339. #else
  12340. chunk.c_str(), to_send,
  12341. #endif
  12342. 0);
  12343. if (sent <= 0) break;
  12344. total_sent += static_cast<size_t>(sent);
  12345. }
  12346. detail::close_socket(cli);
  12347. }
  12348. detail::close_socket(srv);
  12349. });
  12350. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12351. size_t total_received = 0;
  12352. {
  12353. Client cli("127.0.0.1", PORT + 2);
  12354. cli.set_read_timeout(10, 0);
  12355. // Do NOT call set_payload_max_length — use the default 100MB limit
  12356. auto res =
  12357. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12358. total_received += data_length;
  12359. return true;
  12360. });
  12361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12362. EXPECT_EQ(StatusCode::OK_200, res->status);
  12363. }
  12364. server_thread.join();
  12365. EXPECT_EQ(total_received, DATA_SIZE)
  12366. << "With content_receiver, the client should read all " << DATA_SIZE
  12367. << " bytes despite the default 100MB payload_max_length, but only read "
  12368. << total_received << " bytes.";
  12369. }
  12370. // Verify that an explicit set_payload_max_length smaller than the response is
  12371. // enforced even when a content_receiver is used.
  12372. TEST(ClientVulnerabilityTest,
  12373. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12374. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12375. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12376. #ifndef _WIN32
  12377. signal(SIGPIPE, SIG_IGN);
  12378. #endif
  12379. auto server_thread = std::thread([] {
  12380. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12381. default_socket_options(srv);
  12382. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12383. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12384. sockaddr_in addr{};
  12385. addr.sin_family = AF_INET;
  12386. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12387. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12388. int opt = 1;
  12389. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12390. #ifdef _WIN32
  12391. reinterpret_cast<const char *>(&opt),
  12392. #else
  12393. &opt,
  12394. #endif
  12395. sizeof(opt));
  12396. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12397. ::listen(srv, 1);
  12398. sockaddr_in cli_addr{};
  12399. socklen_t cli_len = sizeof(cli_addr);
  12400. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12401. if (cli != INVALID_SOCKET) {
  12402. char buf[4096];
  12403. ::recv(cli, buf, sizeof(buf), 0);
  12404. auto content_length = std::to_string(DATA_SIZE);
  12405. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12406. "Content-Length: " +
  12407. content_length +
  12408. "\r\n"
  12409. "Connection: close\r\n"
  12410. "\r\n";
  12411. ::send(cli,
  12412. #ifdef _WIN32
  12413. static_cast<const char *>(response_header.c_str()),
  12414. static_cast<int>(response_header.size()),
  12415. #else
  12416. response_header.c_str(), response_header.size(),
  12417. #endif
  12418. 0);
  12419. std::string chunk(64 * 1024, 'A');
  12420. size_t total_sent = 0;
  12421. while (total_sent < DATA_SIZE) {
  12422. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12423. auto sent = ::send(cli,
  12424. #ifdef _WIN32
  12425. static_cast<const char *>(chunk.c_str()),
  12426. static_cast<int>(to_send),
  12427. #else
  12428. chunk.c_str(), to_send,
  12429. #endif
  12430. 0);
  12431. if (sent <= 0) break;
  12432. total_sent += static_cast<size_t>(sent);
  12433. }
  12434. detail::close_socket(cli);
  12435. }
  12436. detail::close_socket(srv);
  12437. });
  12438. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12439. size_t total_received = 0;
  12440. {
  12441. Client cli("127.0.0.1", PORT + 2);
  12442. cli.set_read_timeout(10, 0);
  12443. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12444. auto res =
  12445. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12446. total_received += data_length;
  12447. return true;
  12448. });
  12449. // Should fail because 200MB exceeds the explicit 150MB limit
  12450. EXPECT_FALSE(res);
  12451. }
  12452. server_thread.join();
  12453. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12454. << "Client with content_receiver should respect the explicit "
  12455. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12456. << total_received << " bytes.";
  12457. }
  12458. // Verify that an explicit set_payload_max_length larger than the response
  12459. // allows the content_receiver to read all data successfully.
  12460. TEST(ClientVulnerabilityTest,
  12461. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12462. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12463. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12464. #ifndef _WIN32
  12465. signal(SIGPIPE, SIG_IGN);
  12466. #endif
  12467. auto server_thread = std::thread([] {
  12468. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12469. default_socket_options(srv);
  12470. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12471. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12472. sockaddr_in addr{};
  12473. addr.sin_family = AF_INET;
  12474. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12475. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12476. int opt = 1;
  12477. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12478. #ifdef _WIN32
  12479. reinterpret_cast<const char *>(&opt),
  12480. #else
  12481. &opt,
  12482. #endif
  12483. sizeof(opt));
  12484. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12485. ::listen(srv, 1);
  12486. sockaddr_in cli_addr{};
  12487. socklen_t cli_len = sizeof(cli_addr);
  12488. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12489. if (cli != INVALID_SOCKET) {
  12490. char buf[4096];
  12491. ::recv(cli, buf, sizeof(buf), 0);
  12492. auto content_length = std::to_string(DATA_SIZE);
  12493. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12494. "Content-Length: " +
  12495. content_length +
  12496. "\r\n"
  12497. "Connection: close\r\n"
  12498. "\r\n";
  12499. ::send(cli,
  12500. #ifdef _WIN32
  12501. static_cast<const char *>(response_header.c_str()),
  12502. static_cast<int>(response_header.size()),
  12503. #else
  12504. response_header.c_str(), response_header.size(),
  12505. #endif
  12506. 0);
  12507. std::string chunk(64 * 1024, 'A');
  12508. size_t total_sent = 0;
  12509. while (total_sent < DATA_SIZE) {
  12510. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12511. auto sent = ::send(cli,
  12512. #ifdef _WIN32
  12513. static_cast<const char *>(chunk.c_str()),
  12514. static_cast<int>(to_send),
  12515. #else
  12516. chunk.c_str(), to_send,
  12517. #endif
  12518. 0);
  12519. if (sent <= 0) break;
  12520. total_sent += static_cast<size_t>(sent);
  12521. }
  12522. #ifdef _WIN32
  12523. ::shutdown(cli, SD_SEND);
  12524. #else
  12525. ::shutdown(cli, SHUT_WR);
  12526. #endif
  12527. char drain[1024];
  12528. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12529. detail::close_socket(cli);
  12530. }
  12531. detail::close_socket(srv);
  12532. });
  12533. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12534. size_t total_received = 0;
  12535. {
  12536. Client cli("127.0.0.1", PORT + 2);
  12537. cli.set_read_timeout(10, 0);
  12538. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12539. auto res =
  12540. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12541. total_received += data_length;
  12542. return true;
  12543. });
  12544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12545. EXPECT_EQ(StatusCode::OK_200, res->status);
  12546. }
  12547. server_thread.join();
  12548. EXPECT_EQ(total_received, DATA_SIZE)
  12549. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12550. << " bytes (larger than " << DATA_SIZE
  12551. << " bytes response), content_receiver should read all data, but only "
  12552. "read "
  12553. << total_received << " bytes.";
  12554. }
  12555. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12556. // Regression test for "zip bomb" attack on the client side: a malicious server
  12557. // sends a small gzip-compressed response that decompresses to a huge payload.
  12558. // The client must enforce payload_max_length on the decompressed size.
  12559. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12560. constexpr size_t DECOMPRESSED_SIZE =
  12561. 10 * 1024 * 1024; // 10MB after decompression
  12562. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12563. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12564. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12565. std::string compressed;
  12566. {
  12567. httplib::detail::gzip_compressor compressor;
  12568. bool ok =
  12569. compressor.compress(uncompressed.data(), uncompressed.size(),
  12570. /*last=*/true, [&](const char *buf, size_t len) {
  12571. compressed.append(buf, len);
  12572. return true;
  12573. });
  12574. ASSERT_TRUE(ok);
  12575. }
  12576. // Sanity: compressed data should be much smaller than the decompressed size
  12577. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12578. #ifndef _WIN32
  12579. signal(SIGPIPE, SIG_IGN);
  12580. #endif
  12581. // Set up the listening socket in the main thread so the server is guaranteed
  12582. // to be ready before the client connects (eliminates race condition).
  12583. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12584. default_socket_options(srv);
  12585. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12586. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12587. sockaddr_in addr{};
  12588. addr.sin_family = AF_INET;
  12589. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12590. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12591. int opt = 1;
  12592. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12593. #ifdef _WIN32
  12594. reinterpret_cast<const char *>(&opt),
  12595. #else
  12596. &opt,
  12597. #endif
  12598. sizeof(opt));
  12599. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12600. ASSERT_EQ(0, ::listen(srv, 1));
  12601. auto server_thread = std::thread([&compressed, srv] {
  12602. sockaddr_in cli_addr{};
  12603. socklen_t cli_len = sizeof(cli_addr);
  12604. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12605. if (cli != INVALID_SOCKET) {
  12606. // Read the full HTTP request (until \r\n\r\n)
  12607. char buf[4096];
  12608. size_t total = 0;
  12609. while (total < sizeof(buf)) {
  12610. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12611. if (n <= 0) break;
  12612. total += static_cast<size_t>(n);
  12613. // Check for end of headers
  12614. if (total >= 4) {
  12615. std::string req(buf, total);
  12616. if (req.find("\r\n\r\n") != std::string::npos) break;
  12617. }
  12618. }
  12619. // Malicious response: gzip-compressed body, no Content-Length
  12620. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12621. "Content-Encoding: gzip\r\n"
  12622. "Connection: close\r\n"
  12623. "\r\n";
  12624. ::send(cli,
  12625. #ifdef _WIN32
  12626. static_cast<const char *>(response_header.c_str()),
  12627. static_cast<int>(response_header.size()),
  12628. #else
  12629. response_header.c_str(), response_header.size(),
  12630. #endif
  12631. 0);
  12632. // Send the compressed payload (small on the wire, huge when decompressed)
  12633. size_t total_sent = 0;
  12634. while (total_sent < compressed.size()) {
  12635. auto to_send = std::min(compressed.size() - total_sent,
  12636. static_cast<size_t>(64 * 1024));
  12637. auto sent =
  12638. ::send(cli,
  12639. #ifdef _WIN32
  12640. static_cast<const char *>(compressed.c_str() + total_sent),
  12641. static_cast<int>(to_send),
  12642. #else
  12643. compressed.c_str() + total_sent, to_send,
  12644. #endif
  12645. 0);
  12646. if (sent <= 0) break;
  12647. total_sent += static_cast<size_t>(sent);
  12648. }
  12649. detail::close_socket(cli);
  12650. }
  12651. });
  12652. auto se = detail::scope_exit([&] {
  12653. detail::close_socket(srv);
  12654. server_thread.join();
  12655. });
  12656. size_t total_decompressed = 0;
  12657. {
  12658. Client cli("127.0.0.1", PORT + 3);
  12659. cli.set_read_timeout(5, 0);
  12660. cli.set_decompress(true);
  12661. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12662. auto stream = cli.open_stream("GET", "/zipbomb");
  12663. ASSERT_TRUE(stream.is_valid());
  12664. char buffer[64 * 1024];
  12665. ssize_t n;
  12666. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12667. total_decompressed += static_cast<size_t>(n);
  12668. }
  12669. }
  12670. // The decompressed size must be capped by payload_max_length. Without
  12671. // protection, the client would decompress the full 10MB from a tiny
  12672. // compressed payload, enabling a zip bomb DoS attack.
  12673. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12674. << "Client decompressed " << total_decompressed
  12675. << " bytes from a gzip response. The decompressed size should be "
  12676. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12677. }
  12678. #endif
  12679. TEST(HostAndPortPropertiesTest, NoSSL) {
  12680. httplib::Client cli("www.google.com", 1234);
  12681. ASSERT_EQ("www.google.com", cli.host());
  12682. ASSERT_EQ(1234, cli.port());
  12683. }
  12684. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12685. httplib::Client cli("www.google.com:1234");
  12686. ASSERT_EQ("www.google.com", cli.host());
  12687. ASSERT_EQ(1234, cli.port());
  12688. }
  12689. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12690. // Port number that overflows int — should not crash, client becomes invalid
  12691. httplib::Client cli("http://www.google.com:99999999999999999999");
  12692. ASSERT_FALSE(cli.is_valid());
  12693. }
  12694. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12695. // Port 99999 exceeds valid range (1-65535) — should not crash
  12696. httplib::Client cli("http://www.google.com:99999");
  12697. ASSERT_FALSE(cli.is_valid());
  12698. auto res = cli.Get("/");
  12699. EXPECT_FALSE(res);
  12700. EXPECT_EQ(Error::Connection, res.error());
  12701. }
  12702. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12703. httplib::Client cli("http://www.google.com:80abc");
  12704. ASSERT_FALSE(cli.is_valid());
  12705. }
  12706. #ifdef CPPHTTPLIB_SSL_ENABLED
  12707. TEST(HostAndPortPropertiesTest, SSL) {
  12708. httplib::SSLClient cli("www.google.com");
  12709. ASSERT_EQ("www.google.com", cli.host());
  12710. ASSERT_EQ(443, cli.port());
  12711. }
  12712. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12713. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12714. std::string cert;
  12715. read_file(CA_CERT_FILE, cert);
  12716. httplib::SSLClient httplib_client("www.google.com");
  12717. // Load CA store first time
  12718. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12719. // Load CA store second time (update)
  12720. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12721. // Verify client is still valid and can make connections
  12722. httplib_client.enable_server_certificate_verification(true);
  12723. auto res = httplib_client.Get("/");
  12724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12725. // Google may return 200 or 301 depending on various factors
  12726. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12727. res->status == StatusCode::MovedPermanently_301);
  12728. }
  12729. TEST(SSLClientTest, ServerNameIndication_Online) {
  12730. auto host = "httpbingo.org";
  12731. auto path = std::string{"/get"};
  12732. SSLClient cli(host, 443);
  12733. auto res = cli.Get(path);
  12734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12735. ASSERT_EQ(StatusCode::OK_200, res->status);
  12736. }
  12737. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12738. // Use a site that will cause SSL verification failure due to self-signed cert
  12739. SSLClient cli("self-signed.badssl.com", 443);
  12740. cli.enable_server_certificate_verification(true);
  12741. auto res = cli.Get("/");
  12742. ASSERT_TRUE(!res);
  12743. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12744. // Verify backend error is captured for SSLServerVerification
  12745. // This occurs when certificate verification fails
  12746. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12747. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12748. EXPECT_NE(0UL, res.ssl_backend_error());
  12749. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12750. // For OpenSSL, ssl_error is 0 for verification errors
  12751. EXPECT_EQ(0, res.ssl_error());
  12752. #if !defined(_WIN32) || \
  12753. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12754. // On non-Windows or when Windows Schannel is disabled, the error comes
  12755. // from OpenSSL's verification
  12756. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12757. res.ssl_backend_error());
  12758. #endif
  12759. #endif
  12760. }
  12761. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12762. // Use a site where hostname doesn't match the certificate
  12763. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12764. SSLClient cli("wrong.host.badssl.com", 443);
  12765. cli.enable_server_certificate_verification(true);
  12766. cli.enable_server_hostname_verification(true);
  12767. auto res = cli.Get("/");
  12768. ASSERT_TRUE(!res);
  12769. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12770. // Verify backend error is captured for hostname verification failure
  12771. EXPECT_NE(0UL, res.ssl_backend_error());
  12772. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12773. // For OpenSSL, ssl_error is 0 for verification errors
  12774. EXPECT_EQ(0, res.ssl_error());
  12775. #if !defined(_WIN32) || \
  12776. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12777. // On non-Windows or when Windows Schannel is disabled, the error comes
  12778. // from OpenSSL's hostname verification
  12779. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12780. res.ssl_backend_error());
  12781. #endif
  12782. #endif
  12783. }
  12784. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12785. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12786. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12787. SSLClient cli("www.google.com", 443);
  12788. cli.enable_server_certificate_verification(true);
  12789. auto res = cli.Get("/");
  12790. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12791. }
  12792. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12793. SSLClient cli("www.google.com", 443);
  12794. cli.enable_server_certificate_verification(true);
  12795. cli.enable_windows_certificate_verification(false);
  12796. auto res = cli.Get("/");
  12797. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12798. }
  12799. // The server sends an intermediate cross-signed by a root Windows trusts,
  12800. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12801. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12802. SSLClient cli("accounts.spotify.com", 443);
  12803. auto res = cli.Get("/");
  12804. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12805. << " ssl_backend_error=" << res.ssl_backend_error();
  12806. }
  12807. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12808. // policy status, which no backend reports for a self-signed certificate.
  12809. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12810. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12811. ASSERT_TRUE(svr.is_valid());
  12812. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12813. auto se = detail::scope_exit([&] {
  12814. svr.stop();
  12815. t.join();
  12816. ASSERT_FALSE(svr.is_running());
  12817. });
  12818. svr.wait_until_ready();
  12819. SSLClient cli("127.0.0.1", PORT);
  12820. cli.set_connection_timeout(30);
  12821. auto res = cli.Get("/");
  12822. ASSERT_FALSE(res);
  12823. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12824. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12825. }
  12826. #endif
  12827. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12828. Client cli("https://google.com");
  12829. auto res = cli.Get("/");
  12830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12831. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12832. }
  12833. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12834. SSLClient cli("google.com");
  12835. cli.set_ca_cert_path(CA_CERT_FILE);
  12836. auto res = cli.Get("/");
  12837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12838. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12839. }
  12840. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12841. SSLClient cli("google.com");
  12842. cli.enable_server_certificate_verification(true);
  12843. cli.set_ca_cert_path("hello");
  12844. auto res = cli.Get("/");
  12845. ASSERT_TRUE(!res);
  12846. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12847. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12848. // should be set
  12849. EXPECT_EQ(0, res.ssl_error());
  12850. // Verify backend error is captured for SSLLoadingCerts
  12851. // This error occurs when loading CA certificates fails
  12852. EXPECT_NE(0UL, res.ssl_backend_error());
  12853. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12854. // OpenSSL specific error codes:
  12855. // > openssl errstr 0x80000002
  12856. // error:80000002:system library::No such file or directory
  12857. // > openssl errstr 0xA000126
  12858. // error:0A000126:SSL routines::unexpected eof while reading
  12859. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12860. res.ssl_backend_error() == 0xA000126);
  12861. #endif
  12862. }
  12863. TEST(SSLClientTest, ServerCertificateVerification4) {
  12864. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12865. ASSERT_TRUE(svr.is_valid());
  12866. svr.Get("/test", [&](const Request &, Response &res) {
  12867. res.set_content("test", "text/plain");
  12868. svr.stop();
  12869. ASSERT_TRUE(true);
  12870. });
  12871. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12872. auto se = detail::scope_exit([&] {
  12873. t.join();
  12874. ASSERT_FALSE(svr.is_running());
  12875. });
  12876. svr.wait_until_ready();
  12877. SSLClient cli("127.0.0.1", PORT);
  12878. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12879. cli.enable_server_certificate_verification(true);
  12880. cli.set_connection_timeout(30);
  12881. auto res = cli.Get("/test");
  12882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12883. ASSERT_EQ(StatusCode::OK_200, res->status);
  12884. }
  12885. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12886. std::string cert;
  12887. read_file(CA_CERT_FILE, cert);
  12888. SSLClient cli("google.com");
  12889. cli.load_ca_cert_store(cert.data(), cert.size());
  12890. const auto res = cli.Get("/");
  12891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12892. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12893. }
  12894. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12895. // clang-format off
  12896. static constexpr char cert[] =
  12897. "GlobalSign Root CA\n"
  12898. "==================\n"
  12899. "-----BEGIN CERTIFICATE-----\n"
  12900. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12901. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12902. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12903. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12904. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12905. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12906. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12907. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12908. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12909. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12910. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12911. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12912. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12913. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12914. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12915. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12916. "-----END CERTIFICATE-----\n";
  12917. // clang-format on
  12918. SSLClient cli("google.com");
  12919. cli.load_ca_cert_store(cert, sizeof(cert));
  12920. const auto res = cli.Get("/");
  12921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12922. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12923. }
  12924. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12925. SSLClient cli("www.youtube.com");
  12926. cli.set_ca_cert_path(CA_CERT_FILE);
  12927. cli.enable_server_certificate_verification(true);
  12928. cli.set_follow_location(true);
  12929. auto res = cli.Get("/");
  12930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12931. ASSERT_EQ(StatusCode::OK_200, res->status);
  12932. }
  12933. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12934. SSLClient cli("wWw.YouTube.Com");
  12935. cli.set_ca_cert_path(CA_CERT_FILE);
  12936. cli.enable_server_certificate_verification(true);
  12937. cli.enable_server_hostname_verification(true);
  12938. cli.set_follow_location(true);
  12939. auto res = cli.Get("/");
  12940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12941. ASSERT_EQ(StatusCode::OK_200, res->status);
  12942. }
  12943. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12944. SSLClient cli("gOoGlE.COm");
  12945. cli.enable_server_certificate_verification(true);
  12946. cli.enable_server_hostname_verification(true);
  12947. cli.set_follow_location(true);
  12948. auto res = cli.Get("/");
  12949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12950. ASSERT_EQ(StatusCode::OK_200, res->status);
  12951. }
  12952. TEST(SSLClientTest, Issue2004_Online) {
  12953. Client client("https://google.com");
  12954. client.set_follow_location(true);
  12955. auto res = client.Get("/");
  12956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12957. ASSERT_EQ(StatusCode::OK_200, res->status);
  12958. auto body = res->body;
  12959. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12960. }
  12961. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12962. // Create SSLClient with invalid cert/key to make is_valid() return false
  12963. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12964. "nonexistent_key.pem");
  12965. // is_valid() should be false due to cert loading failure
  12966. ASSERT_FALSE(cli.is_valid());
  12967. auto res = cli.Get("/");
  12968. ASSERT_FALSE(res);
  12969. EXPECT_EQ(Error::SSLConnection, res.error());
  12970. }
  12971. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12972. // Test for Issue #2251: SSL error not properly reported when client cert
  12973. // and key paths are swapped or mismatched
  12974. // This simulates the scenario where user accidentally swaps the cert and key
  12975. // files
  12976. // Using client cert file as private key and vice versa (completely wrong)
  12977. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12978. // Should fail validation due to cert/key mismatch
  12979. ASSERT_FALSE(cli.is_valid());
  12980. // Attempt to make a request should fail with proper error
  12981. auto res = cli.Get("/");
  12982. ASSERT_FALSE(res);
  12983. EXPECT_EQ(Error::SSLConnection, res.error());
  12984. // SSL error should be recorded in the Result object (this is the key fix for
  12985. // Issue #2251)
  12986. auto backend_error = res.ssl_backend_error();
  12987. EXPECT_NE(0u, backend_error);
  12988. }
  12989. // Tests cert/key mismatch detection at the TLS context level
  12990. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12991. // Test that using mismatched cert/key causes connection failure.
  12992. // We verify this at the SSLClient level rather than through internal
  12993. // TLS API functions.
  12994. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12995. cli.enable_server_certificate_verification(false);
  12996. cli.set_connection_timeout(2);
  12997. // The mismatch should cause a connection or handshake error
  12998. auto res = cli.Get("/test");
  12999. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13000. // Either way, the request should fail
  13001. EXPECT_FALSE(res);
  13002. }
  13003. #endif
  13004. #if 0
  13005. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13006. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13007. ASSERT_TRUE(cli != nullptr);
  13008. cli->set_address_family(AF_INET6);
  13009. cli->set_interface("en0");
  13010. auto res = cli->Get("/get");
  13011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13012. ASSERT_EQ(StatusCode::OK_200, res->status);
  13013. }
  13014. #endif
  13015. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13016. #ifdef CPPHTTPLIB_SSL_ENABLED
  13017. void ClientCertPresent(
  13018. const std::string &client_cert_file,
  13019. const std::string &client_private_key_file,
  13020. const std::string &client_encrypted_private_key_pass = std::string()) {
  13021. using namespace httplib::tls;
  13022. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13023. CLIENT_CA_CERT_DIR);
  13024. ASSERT_TRUE(svr.is_valid());
  13025. svr.Get("/test", [&](const Request &req, Response &res) {
  13026. res.set_content("test", "text/plain");
  13027. auto cert = req.peer_cert();
  13028. ASSERT_TRUE(static_cast<bool>(cert));
  13029. std::string common_name = cert.subject_cn();
  13030. EXPECT_EQ("Common Name", common_name);
  13031. });
  13032. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13033. auto se = detail::scope_exit([&] {
  13034. svr.stop();
  13035. t.join();
  13036. ASSERT_FALSE(svr.is_running());
  13037. });
  13038. svr.wait_until_ready();
  13039. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13040. client_encrypted_private_key_pass);
  13041. cli.enable_server_certificate_verification(false);
  13042. cli.set_connection_timeout(30);
  13043. auto res = cli.Get("/test");
  13044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13045. ASSERT_EQ(StatusCode::OK_200, res->status);
  13046. }
  13047. TEST(SSLClientServerTest, ClientCertPresent) {
  13048. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13049. }
  13050. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13051. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13052. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13053. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13054. }
  13055. // PEM memory-based constructor tests (works with all TLS backends)
  13056. void PemMemoryClientCertPresent(
  13057. const std::string &client_cert_file,
  13058. const std::string &client_private_key_file,
  13059. const std::string &client_encrypted_private_key_pass = std::string()) {
  13060. // Read PEM files into memory
  13061. std::string server_cert_pem, server_key_pem;
  13062. std::string client_ca_pem;
  13063. std::string client_cert_pem, client_key_pem;
  13064. read_file(SERVER_CERT_FILE, server_cert_pem);
  13065. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13066. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13067. read_file(client_cert_file, client_cert_pem);
  13068. read_file(client_private_key_file, client_key_pem);
  13069. // Create server with PEM memory
  13070. SSLServer::PemMemory server_pem = {
  13071. server_cert_pem.c_str(),
  13072. server_cert_pem.size(),
  13073. server_key_pem.c_str(),
  13074. server_key_pem.size(),
  13075. client_ca_pem.c_str(),
  13076. client_ca_pem.size(),
  13077. nullptr // no password for server key
  13078. };
  13079. SSLServer svr(server_pem);
  13080. ASSERT_TRUE(svr.is_valid());
  13081. svr.Get("/test", [&](const Request &, Response &res) {
  13082. res.set_content("test", "text/plain");
  13083. });
  13084. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13085. auto se = detail::scope_exit([&] {
  13086. svr.stop();
  13087. t.join();
  13088. ASSERT_FALSE(svr.is_running());
  13089. });
  13090. svr.wait_until_ready();
  13091. // Create client with PEM memory
  13092. const char *password = client_encrypted_private_key_pass.empty()
  13093. ? nullptr
  13094. : client_encrypted_private_key_pass.c_str();
  13095. SSLClient::PemMemory client_pem = {
  13096. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13097. client_key_pem.size(), password};
  13098. SSLClient cli(HOST, PORT, client_pem);
  13099. cli.enable_server_certificate_verification(false);
  13100. cli.set_connection_timeout(30);
  13101. auto res = cli.Get("/test");
  13102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13103. ASSERT_EQ(StatusCode::OK_200, res->status);
  13104. }
  13105. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13106. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13107. }
  13108. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13109. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13110. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13111. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13112. }
  13113. TEST(SSLClientServerTest, ClientCertMissing) {
  13114. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13115. CLIENT_CA_CERT_DIR);
  13116. ASSERT_TRUE(svr.is_valid());
  13117. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13118. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13119. auto se = detail::scope_exit([&] {
  13120. svr.stop();
  13121. t.join();
  13122. ASSERT_FALSE(svr.is_running());
  13123. });
  13124. svr.wait_until_ready();
  13125. SSLClient cli(HOST, PORT);
  13126. cli.set_connection_timeout(30);
  13127. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13128. // the chain check on Windows, so the result does not depend on the order.
  13129. cli.enable_server_hostname_verification(false);
  13130. auto res = cli.Get("/test");
  13131. ASSERT_TRUE(!res);
  13132. // When client cert is missing and server requires it, connection fails
  13133. // Error type depends on backend implementation
  13134. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13135. res.error() == Error::SSLConnection);
  13136. // Verify backend error is captured
  13137. // Note: This test may have different error codes depending on the exact
  13138. // verification failure
  13139. EXPECT_NE(0UL, res.ssl_backend_error());
  13140. }
  13141. TEST(SSLClientServerTest, TrustDirOptional) {
  13142. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13143. ASSERT_TRUE(svr.is_valid());
  13144. svr.Get("/test", [&](const Request &, Response &res) {
  13145. res.set_content("test", "text/plain");
  13146. });
  13147. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13148. auto se = detail::scope_exit([&] {
  13149. svr.stop();
  13150. t.join();
  13151. ASSERT_FALSE(svr.is_running());
  13152. });
  13153. svr.wait_until_ready();
  13154. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13155. cli.enable_server_certificate_verification(false);
  13156. cli.set_connection_timeout(30);
  13157. auto res = cli.Get("/test");
  13158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13159. ASSERT_EQ(StatusCode::OK_200, res->status);
  13160. }
  13161. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13162. class NoListenSSLServer : public SSLServer {
  13163. public:
  13164. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13165. const char *client_ca_cert_file_path,
  13166. const char *client_ca_cert_dir_path = nullptr)
  13167. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13168. client_ca_cert_dir_path),
  13169. stop_(false) {}
  13170. std::atomic_bool stop_;
  13171. private:
  13172. bool process_and_close_socket(socket_t /*sock*/) override {
  13173. // Don't create SSL context
  13174. while (!stop_.load()) {
  13175. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13176. }
  13177. return true;
  13178. }
  13179. };
  13180. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13181. CLIENT_CA_CERT_FILE);
  13182. ASSERT_TRUE(svr.is_valid());
  13183. svr.Get("/test", [&](const Request &, Response &res) {
  13184. res.set_content("test", "text/plain");
  13185. });
  13186. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13187. auto se = detail::scope_exit([&] {
  13188. svr.stop_ = true;
  13189. svr.stop();
  13190. t.join();
  13191. ASSERT_FALSE(svr.is_running());
  13192. });
  13193. svr.wait_until_ready();
  13194. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13195. cli.enable_server_certificate_verification(false);
  13196. cli.set_connection_timeout(1);
  13197. auto res = cli.Get("/test");
  13198. ASSERT_TRUE(!res);
  13199. EXPECT_EQ(Error::SSLConnection, res.error());
  13200. // Timeout results in WantRead error code (maps to backend-specific value)
  13201. EXPECT_NE(0, res.ssl_error());
  13202. }
  13203. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13204. // Test SSLServer with client certificate verification using the standard
  13205. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13207. CLIENT_CA_CERT_DIR);
  13208. ASSERT_TRUE(svr.is_valid());
  13209. svr.Get("/test", [&](const Request &req, Response &res) {
  13210. res.set_content("test", "text/plain");
  13211. auto cert = req.peer_cert();
  13212. ASSERT_TRUE(static_cast<bool>(cert));
  13213. auto common_name = cert.subject_cn();
  13214. EXPECT_EQ("Common Name", common_name);
  13215. });
  13216. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13217. auto se = detail::scope_exit([&] {
  13218. svr.stop();
  13219. t.join();
  13220. ASSERT_FALSE(svr.is_running());
  13221. });
  13222. svr.wait_until_ready();
  13223. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13224. cli.enable_server_certificate_verification(false);
  13225. cli.set_connection_timeout(30);
  13226. auto res = cli.Get("/test");
  13227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13228. ASSERT_EQ(StatusCode::OK_200, res->status);
  13229. }
  13230. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13231. // Verifies that wildcard matching and exact matching work consistently
  13232. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13233. using namespace httplib::tls;
  13234. // We need a running server to test against
  13235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13236. ASSERT_TRUE(svr.is_valid());
  13237. svr.Get("/test", [](const Request &, Response &res) {
  13238. res.set_content("ok", "text/plain");
  13239. });
  13240. thread t([&]() { svr.listen(HOST, PORT); });
  13241. auto se = detail::scope_exit([&] {
  13242. svr.stop();
  13243. t.join();
  13244. });
  13245. svr.wait_until_ready();
  13246. bool verify_callback_called = false;
  13247. bool verify_result_wrong = false;
  13248. SSLClient cli(HOST, PORT);
  13249. cli.enable_server_certificate_verification(true);
  13250. cli.set_ca_cert_path(CA_CERT_FILE);
  13251. cli.set_connection_timeout(5);
  13252. // Note: Test certificate has CN="Common Name", not "localhost"
  13253. bool verify_result_cn = false;
  13254. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13255. verify_callback_called = true;
  13256. if (!ctx.cert) return false;
  13257. // Test 1: "Common Name" should match (our test server cert CN)
  13258. verify_result_cn = ctx.check_hostname("Common Name");
  13259. // Test 2: wrong hostname should not match
  13260. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13261. return true; // Accept for the purpose of this test
  13262. });
  13263. auto res = cli.Get("/test");
  13264. // The request may succeed or fail depending on cert configuration
  13265. // but the callback should have been called
  13266. ASSERT_TRUE(verify_callback_called)
  13267. << "Verify callback should have been called";
  13268. // CN="Common Name" should match our test certificate
  13269. //
  13270. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13271. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13272. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13273. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13274. // <openssl/base.h>, which is included transitively when
  13275. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13276. #if defined(OPENSSL_IS_BORINGSSL)
  13277. EXPECT_FALSE(verify_result_cn)
  13278. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13279. #else
  13280. EXPECT_TRUE(verify_result_cn)
  13281. << "verify_hostname should match 'Common Name' (certificate CN)";
  13282. #endif
  13283. // Wrong hostname should not match
  13284. EXPECT_FALSE(verify_result_wrong)
  13285. << "verify_hostname should not match 'wronghost.example.com'";
  13286. }
  13287. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13288. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13289. // X509_check_ip behavior and must hold for every backend.
  13290. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13291. using namespace httplib::tls;
  13292. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13293. SSLServer svr(SERVER_CERT_IP_CN_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([&]() { svr.listen(HOST, PORT); });
  13299. auto se = detail::scope_exit([&] {
  13300. svr.stop();
  13301. t.join();
  13302. });
  13303. svr.wait_until_ready();
  13304. bool verify_callback_called = false;
  13305. bool ip_matched_via_cn = true;
  13306. SSLClient cli(HOST, PORT);
  13307. cli.enable_server_certificate_verification(true);
  13308. cli.set_ca_cert_path(CA_CERT_FILE);
  13309. cli.set_connection_timeout(5);
  13310. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13311. verify_callback_called = true;
  13312. if (!ctx.cert) return false;
  13313. // The IP appears only in the CN, so it must NOT be accepted.
  13314. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13315. return true; // Accept for the purpose of this test
  13316. });
  13317. cli.Get("/test");
  13318. ASSERT_TRUE(verify_callback_called)
  13319. << "Verify callback should have been called";
  13320. EXPECT_FALSE(ip_matched_via_cn)
  13321. << "An IP host must not be authenticated via the certificate CN";
  13322. }
  13323. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13324. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13325. using namespace httplib::tls;
  13326. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13327. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13328. ASSERT_TRUE(svr.is_valid());
  13329. svr.Get("/test", [](const Request &, Response &res) {
  13330. res.set_content("ok", "text/plain");
  13331. });
  13332. thread t([&]() { svr.listen(HOST, PORT); });
  13333. auto se = detail::scope_exit([&] {
  13334. svr.stop();
  13335. t.join();
  13336. });
  13337. svr.wait_until_ready();
  13338. bool verify_callback_called = false;
  13339. bool san_matched = false;
  13340. bool wrong_ipv6_matched = true;
  13341. bool cn_ipv6_matched = true;
  13342. SSLClient cli(HOST, PORT);
  13343. cli.enable_server_certificate_verification(true);
  13344. cli.set_ca_cert_path(CA_CERT_FILE);
  13345. cli.set_connection_timeout(5);
  13346. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13347. verify_callback_called = true;
  13348. if (!ctx.cert) return false;
  13349. // Matches the IPv6 iPAddress SAN.
  13350. san_matched = ctx.check_hostname("2001:db8::1");
  13351. // A different IPv6 address must not match.
  13352. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13353. // "::1" lives only in the CN, so it must not be accepted.
  13354. cn_ipv6_matched = ctx.check_hostname("::1");
  13355. return true; // Accept for the purpose of this test
  13356. });
  13357. cli.Get("/test");
  13358. ASSERT_TRUE(verify_callback_called)
  13359. << "Verify callback should have been called";
  13360. EXPECT_TRUE(san_matched)
  13361. << "verify_hostname should match an IPv6 iPAddress SAN";
  13362. EXPECT_FALSE(wrong_ipv6_matched)
  13363. << "verify_hostname should not match a non-matching IPv6 address";
  13364. EXPECT_FALSE(cn_ipv6_matched)
  13365. << "An IPv6 host must not be authenticated via the certificate CN";
  13366. }
  13367. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13368. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13369. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13370. using namespace httplib::tls;
  13371. // SANs: DNS:a.zz, IP:42.46.122.122
  13372. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13373. ASSERT_TRUE(svr.is_valid());
  13374. svr.Get("/test", [](const Request &, Response &res) {
  13375. res.set_content("ok", "text/plain");
  13376. });
  13377. auto port = svr.bind_to_any_port(HOST);
  13378. thread t([&]() { svr.listen_after_bind(); });
  13379. auto se = detail::scope_exit([&] {
  13380. svr.stop();
  13381. t.join();
  13382. });
  13383. svr.wait_until_ready();
  13384. bool verify_callback_called = false;
  13385. bool dns_san_matched = false;
  13386. bool ip_san_matched = false;
  13387. bool ip_matched_via_dns_san = true;
  13388. bool dns_matched_via_ip_san = true;
  13389. SSLClient cli(HOST, port);
  13390. cli.enable_server_certificate_verification(true);
  13391. cli.set_ca_cert_path(CA_CERT_FILE);
  13392. cli.set_connection_timeout(5);
  13393. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13394. verify_callback_called = true;
  13395. if (!ctx.cert) return false;
  13396. dns_san_matched = ctx.check_hostname("a.zz");
  13397. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13398. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13399. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13400. return true; // Accept for the purpose of this test
  13401. });
  13402. cli.Get("/test");
  13403. ASSERT_TRUE(verify_callback_called)
  13404. << "Verify callback should have been called";
  13405. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13406. EXPECT_TRUE(ip_san_matched)
  13407. << "verify_hostname should match an iPAddress SAN";
  13408. EXPECT_FALSE(ip_matched_via_dns_san)
  13409. << "An IP host must not be authenticated via a dNSName SAN";
  13410. EXPECT_FALSE(dns_matched_via_ip_san)
  13411. << "A DNS host must not be authenticated via an iPAddress SAN";
  13412. }
  13413. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13414. // "www.*.example.test" names one host and not every host under example.test.
  13415. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13416. using namespace httplib::tls;
  13417. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13418. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13419. ASSERT_TRUE(svr.is_valid());
  13420. svr.Get("/test", [](const Request &, Response &res) {
  13421. res.set_content("ok", "text/plain");
  13422. });
  13423. auto port = svr.bind_to_any_port(HOST);
  13424. thread t([&]() { svr.listen_after_bind(); });
  13425. auto se = detail::scope_exit([&] {
  13426. svr.stop();
  13427. t.join();
  13428. });
  13429. svr.wait_until_ready();
  13430. bool verify_callback_called = false;
  13431. bool leftmost_wildcard_matched = false;
  13432. bool wildcard_spanned_labels = true;
  13433. bool inner_wildcard_matched = true;
  13434. SSLClient cli(HOST, port);
  13435. cli.enable_server_certificate_verification(true);
  13436. cli.set_ca_cert_path(CA_CERT_FILE);
  13437. cli.set_connection_timeout(5);
  13438. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13439. verify_callback_called = true;
  13440. if (!ctx.cert) return false;
  13441. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13442. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13443. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13444. return true; // Accept for the purpose of this test
  13445. });
  13446. cli.Get("/test");
  13447. ASSERT_TRUE(verify_callback_called)
  13448. << "Verify callback should have been called";
  13449. EXPECT_TRUE(leftmost_wildcard_matched)
  13450. << "A leftmost wildcard should match a single label";
  13451. EXPECT_FALSE(wildcard_spanned_labels)
  13452. << "A wildcard label must not match more than one label";
  13453. EXPECT_FALSE(inner_wildcard_matched)
  13454. << "A wildcard outside the leftmost label must not be honoured";
  13455. }
  13456. // sans() must report each SAN entry under its own type.
  13457. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13458. using namespace httplib::tls;
  13459. // SANs: DNS:a.zz, IP:42.46.122.122
  13460. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13461. ASSERT_TRUE(svr.is_valid());
  13462. svr.Get("/test", [](const Request &, Response &res) {
  13463. res.set_content("ok", "text/plain");
  13464. });
  13465. auto port = svr.bind_to_any_port(HOST);
  13466. thread t([&]() { svr.listen_after_bind(); });
  13467. auto se = detail::scope_exit([&] {
  13468. svr.stop();
  13469. t.join();
  13470. });
  13471. svr.wait_until_ready();
  13472. bool verify_callback_called = false;
  13473. std::vector<SanEntry> sans;
  13474. SSLClient cli(HOST, port);
  13475. cli.enable_server_certificate_verification(true);
  13476. cli.set_ca_cert_path(CA_CERT_FILE);
  13477. cli.set_connection_timeout(5);
  13478. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13479. verify_callback_called = true;
  13480. if (!ctx.cert) return false;
  13481. sans = ctx.sans();
  13482. return true; // Accept for the purpose of this test
  13483. });
  13484. cli.Get("/test");
  13485. ASSERT_TRUE(verify_callback_called)
  13486. << "Verify callback should have been called";
  13487. auto has_san = [&](SanType type, const std::string &value) {
  13488. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13489. return san.type == type && san.value == value;
  13490. });
  13491. };
  13492. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13493. << "sans() should report the dNSName SAN";
  13494. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13495. << "sans() should report the iPAddress SAN";
  13496. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13497. << "sans() must not report the dNSName SAN as an address";
  13498. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13499. << "sans() must not report the iPAddress SAN as a DNS name";
  13500. }
  13501. #endif
  13502. // mbedTLS-specific callback constructor test
  13503. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13504. #ifdef CPPHTTPLIB_SSL_ENABLED
  13505. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13507. ASSERT_TRUE(svr.is_valid());
  13508. // Set up a handler to verify client certificate is present
  13509. bool client_cert_verified = false;
  13510. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13511. // Verify that client certificate was provided
  13512. client_cert_verified = true;
  13513. res.set_content("success", "text/plain");
  13514. });
  13515. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13516. auto se = detail::scope_exit([&] {
  13517. svr.stop();
  13518. t.join();
  13519. ASSERT_FALSE(svr.is_running());
  13520. });
  13521. svr.wait_until_ready();
  13522. // Client with certificate
  13523. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13524. cli.enable_server_certificate_verification(false);
  13525. cli.set_connection_timeout(30);
  13526. auto res = cli.Get("/test");
  13527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13528. ASSERT_EQ(StatusCode::OK_200, res->status);
  13529. ASSERT_TRUE(client_cert_verified);
  13530. EXPECT_EQ("success", res->body);
  13531. }
  13532. #endif
  13533. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13534. // backends
  13535. #ifdef CPPHTTPLIB_SSL_ENABLED
  13536. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13537. using namespace httplib::tls;
  13538. // Test that when client CA cert file is provided,
  13539. // the server properly requests and validates client certificates
  13540. // Create a server with client authentication
  13541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13542. ASSERT_TRUE(svr.is_valid());
  13543. bool handler_called = false;
  13544. svr.Get("/test", [&](const Request &req, Response &res) {
  13545. handler_called = true;
  13546. // Verify that a client certificate was provided
  13547. auto cert = req.peer_cert();
  13548. ASSERT_TRUE(static_cast<bool>(cert));
  13549. // Get the issuer name
  13550. std::string issuer_str = cert.issuer_name();
  13551. ASSERT_FALSE(issuer_str.empty());
  13552. // The client certificate should be issued by our test CA
  13553. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13554. res.set_content("authenticated", "text/plain");
  13555. });
  13556. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13557. auto se = detail::scope_exit([&] {
  13558. svr.stop();
  13559. t.join();
  13560. ASSERT_FALSE(svr.is_running());
  13561. });
  13562. svr.wait_until_ready();
  13563. // Connect with a client certificate issued by the CA
  13564. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13565. cli.enable_server_certificate_verification(false);
  13566. cli.set_connection_timeout(30);
  13567. auto res = cli.Get("/test");
  13568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13569. ASSERT_EQ(StatusCode::OK_200, res->status);
  13570. ASSERT_TRUE(handler_called);
  13571. EXPECT_EQ("authenticated", res->body);
  13572. }
  13573. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13574. using namespace httplib::tls;
  13575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13576. ASSERT_TRUE(svr.is_valid());
  13577. svr.Get("/test", [](const Request &, Response &res) {
  13578. res.set_content("ok", "text/plain");
  13579. });
  13580. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13581. auto se = detail::scope_exit([&] {
  13582. svr.stop();
  13583. t.join();
  13584. });
  13585. svr.wait_until_ready();
  13586. SSLClient cli(HOST, PORT);
  13587. cli.enable_server_certificate_verification(false);
  13588. cli.set_connection_timeout(30);
  13589. bool cert_checked = false;
  13590. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13591. if (ctx.cert) {
  13592. auto sans = ctx.sans();
  13593. // Test certificate may or may not have SANs - just verify the API
  13594. // works If SANs exist, verify the types are valid
  13595. for (const auto &san : sans) {
  13596. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13597. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13598. san.type == SanType::OTHER);
  13599. EXPECT_FALSE(san.value.empty());
  13600. }
  13601. cert_checked = true;
  13602. }
  13603. return true;
  13604. });
  13605. auto res = cli.Get("/test");
  13606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13607. EXPECT_TRUE(cert_checked);
  13608. }
  13609. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13610. using namespace httplib::tls;
  13611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13612. ASSERT_TRUE(svr.is_valid());
  13613. svr.Get("/test", [](const Request &, Response &res) {
  13614. res.set_content("ok", "text/plain");
  13615. });
  13616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13617. auto se = detail::scope_exit([&] {
  13618. svr.stop();
  13619. t.join();
  13620. });
  13621. svr.wait_until_ready();
  13622. SSLClient cli(HOST, PORT);
  13623. cli.enable_server_certificate_verification(false);
  13624. cli.set_connection_timeout(30);
  13625. bool validity_checked = false;
  13626. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13627. if (ctx.cert) {
  13628. time_t not_before = 0, not_after = 0;
  13629. bool result = ctx.validity(not_before, not_after);
  13630. EXPECT_TRUE(result);
  13631. // Verify that not_before < now < not_after for a valid cert
  13632. time_t now = time(nullptr);
  13633. EXPECT_LT(not_before, now);
  13634. EXPECT_GT(not_after, now);
  13635. validity_checked = true;
  13636. }
  13637. return true;
  13638. });
  13639. auto res = cli.Get("/test");
  13640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13641. EXPECT_TRUE(validity_checked);
  13642. }
  13643. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13644. using namespace httplib::tls;
  13645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13646. ASSERT_TRUE(svr.is_valid());
  13647. svr.Get("/test", [](const Request &, Response &res) {
  13648. res.set_content("ok", "text/plain");
  13649. });
  13650. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13651. auto se = detail::scope_exit([&] {
  13652. svr.stop();
  13653. t.join();
  13654. });
  13655. svr.wait_until_ready();
  13656. SSLClient cli(HOST, PORT);
  13657. cli.enable_server_certificate_verification(false);
  13658. cli.set_connection_timeout(30);
  13659. bool serial_checked = false;
  13660. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13661. if (ctx.cert) {
  13662. std::string serial = ctx.serial();
  13663. EXPECT_FALSE(serial.empty());
  13664. // Serial should be a hex string
  13665. for (char c : serial) {
  13666. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13667. (c >= 'a' && c <= 'f'));
  13668. }
  13669. serial_checked = true;
  13670. }
  13671. return true;
  13672. });
  13673. auto res = cli.Get("/test");
  13674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13675. EXPECT_TRUE(serial_checked);
  13676. }
  13677. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13678. // Test 1: Valid CA file - no error should be recorded
  13679. {
  13680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13681. CLIENT_CA_CERT_FILE);
  13682. ASSERT_TRUE(svr.is_valid());
  13683. // With valid setup, last_ssl_error should be 0
  13684. EXPECT_EQ(0, svr.ssl_last_error());
  13685. }
  13686. // Test 2: Invalid CA file content
  13687. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13688. {
  13689. // Create a temporary file with completely invalid content
  13690. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13691. {
  13692. std::ofstream ofs(temp_invalid_ca);
  13693. ofs << "This is not a certificate file at all\n";
  13694. ofs << "Just plain text content\n";
  13695. }
  13696. // Create server with invalid CA file
  13697. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13698. // Clean up temporary file
  13699. std::remove(temp_invalid_ca);
  13700. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13701. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13702. // Note: SSL_CTX_load_verify_locations typically fails first,
  13703. // but our error handling code path is still exercised
  13704. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13705. }
  13706. }
  13707. TEST(VerifyCallbackTest, VerifyContextFields) {
  13708. using namespace httplib::tls;
  13709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13710. ASSERT_TRUE(svr.is_valid());
  13711. svr.Get("/test", [](const Request &, Response &res) {
  13712. res.set_content("ok", "text/plain");
  13713. });
  13714. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13715. auto se = detail::scope_exit([&] {
  13716. svr.stop();
  13717. t.join();
  13718. });
  13719. svr.wait_until_ready();
  13720. SSLClient cli(HOST, PORT);
  13721. cli.enable_server_certificate_verification(false);
  13722. cli.set_connection_timeout(30);
  13723. int callback_count = 0;
  13724. bool saw_leaf_cert = false;
  13725. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13726. if (ctx.cert) {
  13727. callback_count++;
  13728. // We should see at least one certificate (the leaf)
  13729. std::string cn = ctx.subject_cn();
  13730. if (!cn.empty()) { saw_leaf_cert = true; }
  13731. // Verify context fields are populated
  13732. EXPECT_NE(ctx.session, nullptr);
  13733. EXPECT_GE(ctx.depth, 0);
  13734. }
  13735. return true;
  13736. });
  13737. auto res = cli.Get("/test");
  13738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13739. EXPECT_GT(callback_count, 0);
  13740. EXPECT_TRUE(saw_leaf_cert);
  13741. }
  13742. // A verifier belongs to the client that set it, not to the thread that set it.
  13743. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13744. using namespace httplib::tls;
  13745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13746. ASSERT_TRUE(svr.is_valid());
  13747. svr.Get("/test", [](const Request &, Response &res) {
  13748. res.set_content("ok", "text/plain");
  13749. });
  13750. auto port = svr.bind_to_any_port(HOST);
  13751. thread t([&]() { svr.listen_after_bind(); });
  13752. auto se = detail::scope_exit([&] {
  13753. svr.stop();
  13754. t.join();
  13755. });
  13756. svr.wait_until_ready();
  13757. auto rejecting_calls = 0;
  13758. SSLClient rejecting(HOST, port);
  13759. rejecting.enable_server_certificate_verification(false);
  13760. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13761. rejecting_calls++;
  13762. return false;
  13763. });
  13764. auto accepting_calls = 0;
  13765. SSLClient accepting(HOST, port);
  13766. accepting.enable_server_certificate_verification(false);
  13767. // Set on another thread than the requests below.
  13768. thread([&]() {
  13769. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13770. accepting_calls++;
  13771. return true;
  13772. });
  13773. }).join();
  13774. // Requested on another thread than the verifier was set on.
  13775. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13776. EXPECT_GT(rejecting_calls, 0);
  13777. auto res = accepting.Get("/test");
  13778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13779. EXPECT_GT(accepting_calls, 0);
  13780. }
  13781. // VerifyContext::session is the same handle the other tls:: functions take.
  13782. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13783. using namespace httplib::tls;
  13784. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13785. ASSERT_TRUE(svr.is_valid());
  13786. svr.Get("/test", [](const Request &, Response &res) {
  13787. res.set_content("ok", "text/plain");
  13788. });
  13789. auto port = svr.bind_to_any_port(HOST);
  13790. thread t([&]() { svr.listen_after_bind(); });
  13791. auto se = detail::scope_exit([&] {
  13792. svr.stop();
  13793. t.join();
  13794. });
  13795. svr.wait_until_ready();
  13796. SSLClient cli(HOST, port);
  13797. cli.enable_server_certificate_verification(false);
  13798. session_t verifier_session = nullptr;
  13799. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13800. verifier_session = ctx.session;
  13801. return true;
  13802. });
  13803. session_t session_verifier_session = nullptr;
  13804. cli.set_session_verifier([&](session_t session) {
  13805. session_verifier_session = session;
  13806. return SSLVerifierResponse::NoDecisionMade;
  13807. });
  13808. auto res = cli.Get("/test");
  13809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13810. EXPECT_NE(nullptr, verifier_session);
  13811. EXPECT_EQ(session_verifier_session, verifier_session);
  13812. }
  13813. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13814. using httplib::tls::TlsError;
  13815. // Test that verify_error_to_string returns empty for success
  13816. std::string success_str = TlsError::verify_error_to_string(0);
  13817. EXPECT_TRUE(success_str.empty());
  13818. // Test that verify_error_to_string returns non-empty for error codes
  13819. // Using a common error code (certificate expired)
  13820. std::string error_str =
  13821. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13822. EXPECT_FALSE(error_str.empty());
  13823. }
  13824. TEST(SessionVerifierTest, CertificateAccepted) {
  13825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13826. ASSERT_TRUE(svr.is_valid());
  13827. svr.Get("/test", [](const Request &, Response &res) {
  13828. res.set_content("ok", "text/plain");
  13829. });
  13830. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13831. auto se = detail::scope_exit([&] {
  13832. svr.stop();
  13833. t.join();
  13834. });
  13835. svr.wait_until_ready();
  13836. SSLClient cli(HOST, PORT);
  13837. cli.enable_server_certificate_verification(false);
  13838. cli.set_connection_timeout(30);
  13839. bool callback_called = false;
  13840. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13841. EXPECT_NE(session, nullptr);
  13842. callback_called = true;
  13843. return SSLVerifierResponse::CertificateAccepted;
  13844. });
  13845. auto res = cli.Get("/test");
  13846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13847. EXPECT_EQ(200, res->status);
  13848. EXPECT_TRUE(callback_called);
  13849. }
  13850. TEST(SessionVerifierTest, CertificateRejected) {
  13851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13852. ASSERT_TRUE(svr.is_valid());
  13853. svr.Get("/test", [](const Request &, Response &res) {
  13854. res.set_content("ok", "text/plain");
  13855. });
  13856. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13857. auto se = detail::scope_exit([&] {
  13858. svr.stop();
  13859. t.join();
  13860. });
  13861. svr.wait_until_ready();
  13862. SSLClient cli(HOST, PORT);
  13863. cli.enable_server_certificate_verification(false);
  13864. cli.set_connection_timeout(30);
  13865. bool callback_called = false;
  13866. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13867. EXPECT_NE(session, nullptr);
  13868. callback_called = true;
  13869. return SSLVerifierResponse::CertificateRejected;
  13870. });
  13871. auto res = cli.Get("/test");
  13872. EXPECT_FALSE(res);
  13873. EXPECT_TRUE(callback_called);
  13874. }
  13875. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13877. ASSERT_TRUE(svr.is_valid());
  13878. svr.Get("/test", [](const Request &, Response &res) {
  13879. res.set_content("ok", "text/plain");
  13880. });
  13881. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13882. auto se = detail::scope_exit([&] {
  13883. svr.stop();
  13884. t.join();
  13885. });
  13886. svr.wait_until_ready();
  13887. // NoDecisionMade with verification disabled should succeed (no default check)
  13888. SSLClient cli(HOST, PORT);
  13889. cli.enable_server_certificate_verification(false);
  13890. cli.set_connection_timeout(30);
  13891. bool callback_called = false;
  13892. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13893. EXPECT_NE(session, nullptr);
  13894. callback_called = true;
  13895. return SSLVerifierResponse::NoDecisionMade;
  13896. });
  13897. auto res = cli.Get("/test");
  13898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13899. EXPECT_EQ(200, res->status);
  13900. EXPECT_TRUE(callback_called);
  13901. }
  13902. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13903. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13904. ASSERT_TRUE(svr.is_valid());
  13905. svr.Get("/test", [](const Request &, Response &res) {
  13906. res.set_content("ok", "text/plain");
  13907. });
  13908. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13909. auto se = detail::scope_exit([&] {
  13910. svr.stop();
  13911. t.join();
  13912. });
  13913. svr.wait_until_ready();
  13914. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13915. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13916. // so we only check that the request fails, not whether the callback was
  13917. // called.
  13918. SSLClient cli(HOST, PORT);
  13919. cli.enable_server_certificate_verification(true);
  13920. cli.set_connection_timeout(30);
  13921. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13922. EXPECT_NE(session, nullptr);
  13923. return SSLVerifierResponse::NoDecisionMade;
  13924. });
  13925. auto res = cli.Get("/test");
  13926. EXPECT_FALSE(res);
  13927. }
  13928. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13929. // Test SSL server using PemMemory constructor with client CA certificates
  13930. // Read PEM files
  13931. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13932. read_file(SERVER_CERT_FILE, server_cert_pem);
  13933. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13934. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13935. // Create SSLServer with PemMemory constructor including client CA
  13936. SSLServer::PemMemory server_pem = {
  13937. server_cert_pem.c_str(),
  13938. server_cert_pem.size(),
  13939. server_key_pem.c_str(),
  13940. server_key_pem.size(),
  13941. client_ca_pem.c_str(),
  13942. client_ca_pem.size(),
  13943. nullptr // no password for server key
  13944. };
  13945. SSLServer svr(server_pem);
  13946. ASSERT_TRUE(svr.is_valid());
  13947. // No SSL error should be recorded for valid setup
  13948. EXPECT_EQ(0, svr.ssl_last_error());
  13949. // Set up server endpoints
  13950. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13951. res.set_content("ok", "text/plain");
  13952. });
  13953. // Start server in a thread
  13954. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13955. svr.wait_until_ready();
  13956. // Connect with client certificate (using constructor with paths)
  13957. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13958. cli.enable_server_certificate_verification(false);
  13959. auto res = cli.Get("/test-pem-ca");
  13960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13961. EXPECT_EQ(200, res->status);
  13962. EXPECT_EQ("ok", res->body);
  13963. svr.stop();
  13964. server_thread.join();
  13965. }
  13966. #endif
  13967. #ifdef _WIN32
  13968. TEST(CleanupTest, WSACleanup) {
  13969. int ret = WSACleanup();
  13970. ASSERT_EQ(0, ret);
  13971. }
  13972. #endif
  13973. #ifndef CPPHTTPLIB_SSL_ENABLED
  13974. TEST(NoSSLSupport, SimpleInterface) {
  13975. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13976. }
  13977. #endif
  13978. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13979. TEST(InvalidScheme, SimpleInterface) {
  13980. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13981. }
  13982. #endif
  13983. TEST(NoScheme, SimpleInterface) {
  13984. Client cli("yahoo.com:80");
  13985. ASSERT_TRUE(cli.is_valid());
  13986. }
  13987. TEST(SendAPI, SimpleInterface_Online) {
  13988. Client cli("http://yahoo.com");
  13989. Request req;
  13990. req.method = "GET";
  13991. req.path = "/";
  13992. auto res = cli.send(req);
  13993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13994. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13995. }
  13996. TEST(SendAPI, WithParamsInRequest) {
  13997. Server svr;
  13998. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13999. EXPECT_TRUE(req.has_param("test"));
  14000. EXPECT_EQ("test_value", req.get_param_value("test"));
  14001. });
  14002. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14003. auto se = detail::scope_exit([&] {
  14004. svr.stop();
  14005. t.join();
  14006. ASSERT_FALSE(svr.is_running());
  14007. });
  14008. svr.wait_until_ready();
  14009. Client cli(HOST, PORT);
  14010. {
  14011. Request req;
  14012. req.method = "GET";
  14013. req.path = "/";
  14014. req.params.emplace("test", "test_value");
  14015. auto res = cli.send(req);
  14016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14017. }
  14018. {
  14019. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14021. }
  14022. }
  14023. TEST(ClientImplMethods, GetSocketTest) {
  14024. httplib::Server svr;
  14025. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14026. res.status = StatusCode::OK_200;
  14027. });
  14028. auto port = svr.bind_to_any_port("127.0.0.1");
  14029. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14030. auto se = detail::scope_exit([&] {
  14031. svr.stop();
  14032. thread.join();
  14033. ASSERT_FALSE(svr.is_running());
  14034. });
  14035. svr.wait_until_ready();
  14036. {
  14037. httplib::Client cli("127.0.0.1", port);
  14038. cli.set_keep_alive(true);
  14039. // Use the behavior of cpp-httplib of opening the connection
  14040. // only when the first request happens. If that changes,
  14041. // this test would be obsolete.
  14042. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14043. // This also implicitly tests the server. But other tests would fail much
  14044. // earlier than this one to be considered.
  14045. auto res = cli.Get("/");
  14046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14047. EXPECT_EQ(StatusCode::OK_200, res->status);
  14048. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14049. }
  14050. }
  14051. #ifdef CPPHTTPLIB_SSL_ENABLED
  14052. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14053. Client cli("http://yahoo.com");
  14054. auto res = cli.Get("/");
  14055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14056. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14057. cli.set_follow_location(true);
  14058. res = cli.Get("/");
  14059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14060. EXPECT_EQ(StatusCode::OK_200, res->status);
  14061. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14062. }
  14063. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14064. Client cli("https://yahoo.com");
  14065. auto res = cli.Get("/");
  14066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14067. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14068. cli.set_follow_location(true);
  14069. res = cli.Get("/");
  14070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14071. EXPECT_EQ(StatusCode::OK_200, res->status);
  14072. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14073. }
  14074. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14075. Client cli("https://yahoo.com");
  14076. auto res = cli.Get("/");
  14077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14078. ASSERT_FALSE(!res);
  14079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14080. ASSERT_FALSE(res == nullptr);
  14081. ASSERT_TRUE(res != nullptr);
  14082. EXPECT_EQ(Error::Success, res.error());
  14083. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14084. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14085. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14086. cli.set_follow_location(true);
  14087. res = cli.Get("/");
  14088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14089. EXPECT_EQ(Error::Success, res.error());
  14090. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14091. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14092. EXPECT_EQ(StatusCode::OK_200, res->status);
  14093. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14094. }
  14095. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14096. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14097. Client cli("https://cdnjs.cloudflare.com");
  14098. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14099. Headers{{"Accept-Encoding", "br"}});
  14100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14101. EXPECT_EQ(StatusCode::OK_200, res->status);
  14102. EXPECT_EQ(287630U, res->body.size());
  14103. EXPECT_EQ("application/javascript; charset=utf-8",
  14104. res->get_header_value("Content-Type"));
  14105. }
  14106. #endif
  14107. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14108. #undef REDIR_HOST // Silence compiler warning
  14109. #define REDIR_HOST "https://httpbingo.org"
  14110. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14111. Client cli(REDIR_HOST);
  14112. cli.set_follow_location(true);
  14113. auto res =
  14114. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14116. EXPECT_EQ(StatusCode::OK_200, res->status);
  14117. }
  14118. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14119. Client cli(REDIR_HOST);
  14120. cli.set_follow_location(true);
  14121. Params params;
  14122. params.emplace("url", "http://example.com");
  14123. params.emplace("status_code", "302");
  14124. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14126. EXPECT_EQ(StatusCode::OK_200, res->status);
  14127. }
  14128. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14129. Client cli(REDIR_HOST);
  14130. cli.set_follow_location(true);
  14131. Params params;
  14132. params.emplace("url", "http://example.com");
  14133. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14135. EXPECT_EQ(StatusCode::OK_200, res->status);
  14136. }
  14137. TEST(HttpToHttpsRedirectTest, CertFile) {
  14138. auto ssl_port = PORT + 1;
  14139. Server svr;
  14140. ASSERT_TRUE(svr.is_valid());
  14141. svr.Get("/index", [&](const Request &, Response &res) {
  14142. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14143. "/index");
  14144. svr.stop();
  14145. });
  14146. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14147. ASSERT_TRUE(ssl_svr.is_valid());
  14148. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14149. res.set_content("test", "text/plain");
  14150. ssl_svr.stop();
  14151. });
  14152. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14153. thread t2 =
  14154. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14155. auto se = detail::scope_exit([&] {
  14156. t2.join();
  14157. t.join();
  14158. ASSERT_FALSE(svr.is_running());
  14159. });
  14160. svr.wait_until_ready();
  14161. ssl_svr.wait_until_ready();
  14162. Client cli("127.0.0.1", PORT);
  14163. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14164. cli.enable_server_certificate_verification(true);
  14165. cli.set_follow_location(true);
  14166. cli.set_connection_timeout(30);
  14167. auto res = cli.Get("/index");
  14168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14169. ASSERT_EQ(StatusCode::OK_200, res->status);
  14170. }
  14171. TEST(SSLClientRedirectTest, CertFile) {
  14172. auto ssl_port = PORT + 1;
  14173. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14174. ASSERT_TRUE(ssl_svr1.is_valid());
  14175. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14176. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14177. "/index");
  14178. ssl_svr1.stop();
  14179. });
  14180. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14181. ASSERT_TRUE(ssl_svr2.is_valid());
  14182. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14183. res.set_content("test", "text/plain");
  14184. ssl_svr2.stop();
  14185. });
  14186. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14187. thread t2 =
  14188. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14189. auto se = detail::scope_exit([&] {
  14190. t2.join();
  14191. t.join();
  14192. ASSERT_FALSE(ssl_svr1.is_running());
  14193. });
  14194. ssl_svr1.wait_until_ready();
  14195. ssl_svr2.wait_until_ready();
  14196. SSLClient cli("127.0.0.1", PORT);
  14197. std::string cert;
  14198. read_file(SERVER_CERT2_FILE, cert);
  14199. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14200. cli.enable_server_certificate_verification(true);
  14201. cli.set_follow_location(true);
  14202. cli.set_connection_timeout(30);
  14203. auto res = cli.Get("/index");
  14204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14205. ASSERT_EQ(StatusCode::OK_200, res->status);
  14206. }
  14207. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14208. // another port, so the client follows it with a new client.
  14209. static Result GetThroughTlsRedirectToDifferentPort(
  14210. const std::function<void(SSLClient &)> &setup,
  14211. const char *target_cert = SERVER_CERT2_FILE) {
  14212. auto ssl_port = PORT + 1;
  14213. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14214. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14215. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14216. "/index");
  14217. });
  14218. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14219. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14220. res.set_content("test", "text/plain");
  14221. });
  14222. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14223. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14224. auto se = detail::scope_exit([&] {
  14225. ssl_svr2.stop();
  14226. ssl_svr1.stop();
  14227. t2.join();
  14228. t.join();
  14229. });
  14230. ssl_svr1.wait_until_ready();
  14231. ssl_svr2.wait_until_ready();
  14232. SSLClient cli("127.0.0.1", PORT);
  14233. cli.set_follow_location(true);
  14234. cli.set_connection_timeout(30);
  14235. setup(cli);
  14236. return cli.Get("/index");
  14237. }
  14238. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14239. auto calls = 0;
  14240. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14241. cli.enable_server_certificate_verification(false);
  14242. // Accept the first server only.
  14243. cli.set_session_verifier([&](tls::session_t) {
  14244. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14245. : SSLVerifierResponse::CertificateRejected;
  14246. });
  14247. });
  14248. EXPECT_FALSE(res);
  14249. EXPECT_EQ(2, calls);
  14250. }
  14251. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14252. std::string pinned;
  14253. auto res = GetThroughTlsRedirectToDifferentPort(
  14254. [&](SSLClient &cli) {
  14255. cli.enable_server_certificate_verification(false);
  14256. // Pin the first certificate seen.
  14257. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14258. if (pinned.empty()) { pinned = ctx.serial(); }
  14259. return ctx.serial() == pinned;
  14260. });
  14261. },
  14262. // A certificate other than the first server's.
  14263. SERVER_CERT_FILE);
  14264. EXPECT_FALSE(res);
  14265. EXPECT_FALSE(pinned.empty());
  14266. }
  14267. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14268. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14269. std::string cert;
  14270. read_file(SERVER_CERT2_FILE, cert);
  14271. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14272. });
  14273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14274. EXPECT_EQ(StatusCode::OK_200, res->status);
  14275. }
  14276. #endif
  14277. #ifdef CPPHTTPLIB_SSL_ENABLED
  14278. // Test that set_ca_cert_store() skips system certs (consistent with
  14279. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14280. // should be trusted - system certs should NOT be loaded.
  14281. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14282. // Load a specific cert that is NOT a system CA cert
  14283. std::string cert;
  14284. read_file(SERVER_CERT2_FILE, cert);
  14285. SSLClient cli("google.com");
  14286. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14287. cli.enable_server_certificate_verification(true);
  14288. // This should FAIL because:
  14289. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14290. // 2. System certs should NOT be loaded when custom store is set
  14291. // If system certs WERE loaded, this would succeed
  14292. auto res = cli.Get("/");
  14293. ASSERT_FALSE(res);
  14294. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14295. }
  14296. // Same as above, but through the native store handle path. Regression test:
  14297. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14298. // merged system certs into the user-provided store.
  14299. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14300. std::string cert;
  14301. read_file(SERVER_CERT2_FILE, cert);
  14302. SSLClient cli("google.com");
  14303. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14304. cli.enable_server_certificate_verification(true);
  14305. auto res = cli.Get("/");
  14306. ASSERT_FALSE(res);
  14307. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14308. }
  14309. // A custom store set via the native handle must still verify a server whose
  14310. // cert it does contain.
  14311. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14312. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14313. ASSERT_TRUE(svr.is_valid());
  14314. svr.Get("/test", [&](const Request &, Response &res) {
  14315. res.set_content("test", "text/plain");
  14316. });
  14317. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14318. auto se = detail::scope_exit([&] {
  14319. svr.stop();
  14320. t.join();
  14321. ASSERT_FALSE(svr.is_running());
  14322. });
  14323. svr.wait_until_ready();
  14324. SSLClient cli("127.0.0.1", PORT);
  14325. std::string cert;
  14326. read_file(SERVER_CERT2_FILE, cert);
  14327. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14328. cli.enable_server_certificate_verification(true);
  14329. cli.set_connection_timeout(30);
  14330. auto res = cli.Get("/test");
  14331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14332. ASSERT_EQ(StatusCode::OK_200, res->status);
  14333. }
  14334. // CA certs loaded through the universal Client must be transferred to the
  14335. // client created internally for following an HTTPS redirect. Regression test:
  14336. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14337. // the CA data for redirect transfer.
  14338. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14339. auto ssl_port = PORT + 1;
  14340. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14341. ASSERT_TRUE(ssl_svr1.is_valid());
  14342. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14343. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14344. "/index");
  14345. });
  14346. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14347. ASSERT_TRUE(ssl_svr2.is_valid());
  14348. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14349. res.set_content("test", "text/plain");
  14350. });
  14351. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14352. thread t2 =
  14353. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14354. auto se = detail::scope_exit([&] {
  14355. ssl_svr2.stop();
  14356. ssl_svr1.stop();
  14357. t2.join();
  14358. t.join();
  14359. ASSERT_FALSE(ssl_svr1.is_running());
  14360. });
  14361. ssl_svr1.wait_until_ready();
  14362. ssl_svr2.wait_until_ready();
  14363. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14364. std::string cert;
  14365. read_file(SERVER_CERT2_FILE, cert);
  14366. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14367. cli.enable_server_certificate_verification(true);
  14368. cli.set_follow_location(true);
  14369. cli.set_connection_timeout(30);
  14370. auto res = cli.Get("/index");
  14371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14372. ASSERT_EQ(StatusCode::OK_200, res->status);
  14373. }
  14374. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14375. // so a host signed by a system CA verifies even though a custom CA is set
  14376. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14377. std::string cert;
  14378. read_file(SERVER_CERT2_FILE, cert);
  14379. SSLClient cli("google.com");
  14380. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14381. cli.enable_system_ca(true);
  14382. cli.enable_server_certificate_verification(true);
  14383. auto res = cli.Get("/");
  14384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14385. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14386. }
  14387. // The custom CA remains effective when combined with the system CA
  14388. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14389. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14390. ASSERT_TRUE(svr.is_valid());
  14391. svr.Get("/test", [&](const Request &, Response &res) {
  14392. res.set_content("test", "text/plain");
  14393. });
  14394. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14395. auto se = detail::scope_exit([&] {
  14396. svr.stop();
  14397. t.join();
  14398. ASSERT_FALSE(svr.is_running());
  14399. });
  14400. svr.wait_until_ready();
  14401. SSLClient cli("127.0.0.1", PORT);
  14402. std::string cert;
  14403. read_file(SERVER_CERT2_FILE, cert);
  14404. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14405. cli.enable_system_ca(true);
  14406. cli.enable_server_certificate_verification(true);
  14407. cli.set_connection_timeout(30);
  14408. auto res = cli.Get("/test");
  14409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14410. ASSERT_EQ(StatusCode::OK_200, res->status);
  14411. }
  14412. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14413. // skip chain verification entirely (only the certificate identity was
  14414. // checked), so a server presenting an untrusted certificate with a matching
  14415. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14416. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14417. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14418. ASSERT_TRUE(svr.is_valid());
  14419. svr.Get("/test", [&](const Request &, Response &res) {
  14420. res.set_content("test", "text/plain");
  14421. });
  14422. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14423. auto se = detail::scope_exit([&] {
  14424. svr.stop();
  14425. t.join();
  14426. ASSERT_FALSE(svr.is_running());
  14427. });
  14428. svr.wait_until_ready();
  14429. SSLClient cli("127.0.0.1", PORT);
  14430. std::string cert;
  14431. // A trusted CA that did not sign the server certificate. The server cert
  14432. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14433. // this connection.
  14434. read_file(CLIENT_CA_CERT_FILE, cert);
  14435. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14436. cli.enable_server_certificate_verification(true);
  14437. cli.set_connection_timeout(30);
  14438. auto res = cli.Get("/test");
  14439. ASSERT_FALSE(res);
  14440. }
  14441. // enable_system_ca(false) prevents system CA loading entirely
  14442. TEST(SSLClientTest, DisableSystemCa_Online) {
  14443. SSLClient cli("google.com");
  14444. cli.enable_system_ca(false);
  14445. cli.enable_server_certificate_verification(true);
  14446. auto res = cli.Get("/");
  14447. ASSERT_FALSE(res);
  14448. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14449. // itself when the CA chain is empty
  14450. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14451. res.error() == Error::SSLConnection);
  14452. }
  14453. // The universal Client forwards enable_system_ca()
  14454. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14455. std::string cert;
  14456. read_file(SERVER_CERT2_FILE, cert);
  14457. Client cli("https://google.com");
  14458. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14459. cli.enable_system_ca(true);
  14460. cli.enable_server_certificate_verification(true);
  14461. auto res = cli.Get("/");
  14462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14463. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14464. }
  14465. // The system CA policy must carry over to the client created internally for
  14466. // following a cross-host HTTPS redirect
  14467. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14468. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14469. ASSERT_TRUE(svr.is_valid());
  14470. svr.Get("/index", [&](const Request &, Response &res) {
  14471. res.set_redirect("https://www.google.com/");
  14472. });
  14473. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", 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. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14481. std::string cert;
  14482. read_file(SERVER_CERT2_FILE, cert);
  14483. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14484. cli.enable_system_ca(true);
  14485. cli.enable_server_certificate_verification(true);
  14486. cli.set_follow_location(true);
  14487. cli.set_connection_timeout(30);
  14488. // Receiving any response proves the redirect client completed the TLS
  14489. // handshake with a system-CA-signed host
  14490. auto res = cli.Get("/index");
  14491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14492. }
  14493. TEST(MultipartFormDataTest, LargeData) {
  14494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14495. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14496. const ContentReader &content_reader) {
  14497. if (req.is_multipart_form_data()) {
  14498. std::vector<FormData> items;
  14499. content_reader(
  14500. [&](const FormData &file) {
  14501. items.push_back(file);
  14502. return true;
  14503. },
  14504. [&](const char *data, size_t data_length) {
  14505. items.back().content.append(data, data_length);
  14506. return true;
  14507. });
  14508. EXPECT_TRUE(std::string(items[0].name) == "document");
  14509. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14510. EXPECT_TRUE(items[0].filename == "2MB_data");
  14511. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14512. EXPECT_TRUE(items[1].name == "hello");
  14513. EXPECT_TRUE(items[1].content == "world");
  14514. EXPECT_TRUE(items[1].filename == "");
  14515. EXPECT_TRUE(items[1].content_type == "");
  14516. } else {
  14517. std::string body;
  14518. content_reader([&](const char *data, size_t data_length) {
  14519. body.append(data, data_length);
  14520. return true;
  14521. });
  14522. }
  14523. });
  14524. auto port = svr.bind_to_any_port(HOST);
  14525. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14526. auto se = detail::scope_exit([&] {
  14527. svr.stop();
  14528. t.join();
  14529. ASSERT_FALSE(svr.is_running());
  14530. });
  14531. svr.wait_until_ready();
  14532. {
  14533. std::string data(1024 * 1024 * 2, '.');
  14534. std::stringstream buffer;
  14535. buffer << data;
  14536. SSLClient cli(HOST, port);
  14537. cli.enable_server_certificate_verification(false);
  14538. UploadFormDataItems items{
  14539. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14540. {"hello", "world", "", ""},
  14541. };
  14542. auto res = cli.Post("/post", items);
  14543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14544. ASSERT_EQ(StatusCode::OK_200, res->status);
  14545. }
  14546. }
  14547. TEST(MultipartFormDataTest, DataProviderItems) {
  14548. std::random_device seed_gen;
  14549. std::mt19937 random(seed_gen());
  14550. std::string rand1;
  14551. rand1.resize(1000);
  14552. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14553. std::string rand2;
  14554. rand2.resize(3000);
  14555. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14556. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14557. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14558. const ContentReader &content_reader) {
  14559. ASSERT_FALSE(req.is_multipart_form_data());
  14560. std::string body;
  14561. content_reader([&](const char *data, size_t data_length) {
  14562. body.append(data, data_length);
  14563. return true;
  14564. });
  14565. EXPECT_EQ(body, "");
  14566. });
  14567. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14568. const ContentReader &content_reader) {
  14569. ASSERT_TRUE(req.is_multipart_form_data());
  14570. std::vector<FormData> items;
  14571. content_reader(
  14572. [&](const FormData &file) {
  14573. items.push_back(file);
  14574. return true;
  14575. },
  14576. [&](const char *data, size_t data_length) {
  14577. items.back().content.append(data, data_length);
  14578. return true;
  14579. });
  14580. ASSERT_TRUE(items.size() == 2);
  14581. EXPECT_EQ(std::string(items[0].name), "name1");
  14582. EXPECT_EQ(items[0].content, "Testing123");
  14583. EXPECT_EQ(items[0].filename, "filename1");
  14584. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14585. EXPECT_EQ(items[1].name, "name2");
  14586. EXPECT_EQ(items[1].content, "Testing456");
  14587. EXPECT_EQ(items[1].filename, "");
  14588. EXPECT_EQ(items[1].content_type, "");
  14589. });
  14590. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14591. const ContentReader &content_reader) {
  14592. ASSERT_TRUE(req.is_multipart_form_data());
  14593. std::vector<FormData> items;
  14594. content_reader(
  14595. [&](const FormData &file) {
  14596. items.push_back(file);
  14597. return true;
  14598. },
  14599. [&](const char *data, size_t data_length) {
  14600. items.back().content.append(data, data_length);
  14601. return true;
  14602. });
  14603. ASSERT_TRUE(items.size() == 2);
  14604. EXPECT_EQ(items[0].name, "name3");
  14605. EXPECT_EQ(items[0].content, rand1);
  14606. EXPECT_EQ(items[0].filename, "filename3");
  14607. EXPECT_EQ(items[0].content_type, "");
  14608. EXPECT_EQ(items[1].name, "name4");
  14609. EXPECT_EQ(items[1].content, rand2);
  14610. EXPECT_EQ(items[1].filename, "filename4");
  14611. EXPECT_EQ(items[1].content_type, "");
  14612. });
  14613. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14614. const ContentReader &content_reader) {
  14615. ASSERT_TRUE(req.is_multipart_form_data());
  14616. std::vector<FormData> items;
  14617. content_reader(
  14618. [&](const FormData &file) {
  14619. items.push_back(file);
  14620. return true;
  14621. },
  14622. [&](const char *data, size_t data_length) {
  14623. items.back().content.append(data, data_length);
  14624. return true;
  14625. });
  14626. ASSERT_TRUE(items.size() == 4);
  14627. EXPECT_EQ(std::string(items[0].name), "name1");
  14628. EXPECT_EQ(items[0].content, "Testing123");
  14629. EXPECT_EQ(items[0].filename, "filename1");
  14630. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14631. EXPECT_EQ(items[1].name, "name2");
  14632. EXPECT_EQ(items[1].content, "Testing456");
  14633. EXPECT_EQ(items[1].filename, "");
  14634. EXPECT_EQ(items[1].content_type, "");
  14635. EXPECT_EQ(items[2].name, "name3");
  14636. EXPECT_EQ(items[2].content, rand1);
  14637. EXPECT_EQ(items[2].filename, "filename3");
  14638. EXPECT_EQ(items[2].content_type, "");
  14639. EXPECT_EQ(items[3].name, "name4");
  14640. EXPECT_EQ(items[3].content, rand2);
  14641. EXPECT_EQ(items[3].filename, "filename4");
  14642. EXPECT_EQ(items[3].content_type, "");
  14643. });
  14644. auto port = svr.bind_to_any_port("localhost");
  14645. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14646. auto se = detail::scope_exit([&] {
  14647. svr.stop();
  14648. t.join();
  14649. ASSERT_FALSE(svr.is_running());
  14650. });
  14651. svr.wait_until_ready();
  14652. {
  14653. SSLClient cli("localhost", port);
  14654. cli.enable_server_certificate_verification(false);
  14655. UploadFormDataItems items{
  14656. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14657. {"name2", "Testing456", "", ""}, // not a file
  14658. };
  14659. {
  14660. auto res = cli.Post("/post-none", {}, {}, {});
  14661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14662. ASSERT_EQ(StatusCode::OK_200, res->status);
  14663. }
  14664. FormDataProviderItems providers;
  14665. {
  14666. auto res =
  14667. cli.Post("/post-items", {}, items, providers); // empty providers
  14668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14669. ASSERT_EQ(StatusCode::OK_200, res->status);
  14670. }
  14671. providers.push_back({"name3",
  14672. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14673. // test the offset is given correctly at each step
  14674. if (!offset)
  14675. sink.os.write(rand1.data(), 30);
  14676. else if (offset == 30)
  14677. sink.os.write(rand1.data() + 30, 300);
  14678. else if (offset == 330)
  14679. sink.os.write(rand1.data() + 330, 670);
  14680. else if (offset == rand1.size())
  14681. sink.done();
  14682. return true;
  14683. },
  14684. "filename3",
  14685. {}});
  14686. providers.push_back({"name4",
  14687. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14688. // test the offset is given correctly at each step
  14689. if (!offset)
  14690. sink.os.write(rand2.data(), 2000);
  14691. else if (offset == 2000)
  14692. sink.os.write(rand2.data() + 2000, 1);
  14693. else if (offset == 2001)
  14694. sink.os.write(rand2.data() + 2001, 999);
  14695. else if (offset == rand2.size())
  14696. sink.done();
  14697. return true;
  14698. },
  14699. "filename4",
  14700. {}});
  14701. {
  14702. auto res = cli.Post("/post-providers", {}, {}, providers);
  14703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14704. ASSERT_EQ(StatusCode::OK_200, res->status);
  14705. }
  14706. {
  14707. auto res = cli.Post("/post-both", {}, items, providers);
  14708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14709. ASSERT_EQ(StatusCode::OK_200, res->status);
  14710. }
  14711. }
  14712. }
  14713. TEST(MultipartFormDataTest, BadHeader) {
  14714. Server svr;
  14715. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14716. res.set_content("ok", "text/plain");
  14717. });
  14718. thread t = thread([&] { svr.listen(HOST, PORT); });
  14719. auto se = detail::scope_exit([&] {
  14720. svr.stop();
  14721. t.join();
  14722. ASSERT_FALSE(svr.is_running());
  14723. });
  14724. svr.wait_until_ready();
  14725. const std::string body =
  14726. "This is the preamble. It is to be ignored, though it\r\n"
  14727. "is a handy place for composition agents to include an\r\n"
  14728. "explanatory note to non-MIME conformant readers.\r\n"
  14729. "\r\n"
  14730. "\r\n"
  14731. "--simple boundary\r\n"
  14732. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14733. ": BAD...\r\n"
  14734. "\r\n"
  14735. "value1\r\n"
  14736. "--simple boundary\r\n"
  14737. "Content-Disposition: form-data; name=\"field2\"; "
  14738. "filename=\"example.txt\"\r\n"
  14739. "\r\n"
  14740. "value2\r\n"
  14741. "--simple boundary--\r\n"
  14742. "This is the epilogue. It is also to be ignored.\r\n";
  14743. std::string content_type =
  14744. R"(multipart/form-data; boundary="simple boundary")";
  14745. Client cli(HOST, PORT);
  14746. auto res = cli.Post("/post", body, content_type.c_str());
  14747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14748. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14749. }
  14750. TEST(MultipartFormDataTest, WithPreamble) {
  14751. Server svr;
  14752. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14753. res.set_content("ok", "text/plain");
  14754. });
  14755. thread t = thread([&] { svr.listen(HOST, PORT); });
  14756. auto se = detail::scope_exit([&] {
  14757. svr.stop();
  14758. t.join();
  14759. ASSERT_FALSE(svr.is_running());
  14760. });
  14761. svr.wait_until_ready();
  14762. const std::string body =
  14763. "This is the preamble. It is to be ignored, though it\r\n"
  14764. "is a handy place for composition agents to include an\r\n"
  14765. "explanatory note to non-MIME conformant readers.\r\n"
  14766. "\r\n"
  14767. "\r\n"
  14768. "--simple boundary\r\n"
  14769. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14770. "\r\n"
  14771. "value1\r\n"
  14772. "--simple boundary\r\n"
  14773. "Content-Disposition: form-data; name=\"field2\"; "
  14774. "filename=\"example.txt\"\r\n"
  14775. "\r\n"
  14776. "value2\r\n"
  14777. "--simple boundary--\r\n"
  14778. "This is the epilogue. It is also to be ignored.\r\n";
  14779. std::string content_type =
  14780. R"(multipart/form-data; boundary="simple boundary")";
  14781. Client cli(HOST, PORT);
  14782. auto res = cli.Post("/post", body, content_type.c_str());
  14783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14784. EXPECT_EQ(StatusCode::OK_200, res->status);
  14785. }
  14786. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14787. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14788. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14789. const ContentReader &content_reader) {
  14790. if (req.is_multipart_form_data()) {
  14791. std::vector<FormData> items;
  14792. content_reader(
  14793. [&](const FormData &file) {
  14794. items.push_back(file);
  14795. return true;
  14796. },
  14797. [&](const char *data, size_t data_length) {
  14798. items.back().content.append(data, data_length);
  14799. return true;
  14800. });
  14801. EXPECT_TRUE(std::string(items[0].name) == "document");
  14802. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14803. EXPECT_TRUE(items[0].filename == "2MB_data");
  14804. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14805. EXPECT_TRUE(items[1].name == "hello");
  14806. EXPECT_TRUE(items[1].content == "world");
  14807. EXPECT_TRUE(items[1].filename == "");
  14808. EXPECT_TRUE(items[1].content_type == "");
  14809. } else {
  14810. std::string body;
  14811. content_reader([&](const char *data, size_t data_length) {
  14812. body.append(data, data_length);
  14813. return true;
  14814. });
  14815. }
  14816. });
  14817. auto port = svr.bind_to_any_port("localhost");
  14818. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14819. auto se = detail::scope_exit([&] {
  14820. svr.stop();
  14821. t.join();
  14822. ASSERT_FALSE(svr.is_running());
  14823. });
  14824. svr.wait_until_ready();
  14825. {
  14826. std::string data(1024 * 1024 * 2, '.');
  14827. std::stringstream buffer;
  14828. buffer << data;
  14829. SSLClient cli("localhost", port);
  14830. cli.enable_server_certificate_verification(false);
  14831. UploadFormDataItems items{
  14832. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14833. {"hello", "world", "", ""},
  14834. };
  14835. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14837. ASSERT_EQ(StatusCode::OK_200, res->status);
  14838. }
  14839. }
  14840. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14841. std::string data(1024 * 1024 * 2, '&');
  14842. std::stringstream buffer;
  14843. buffer << data;
  14844. Client cli("https://localhost:8080");
  14845. UploadFormDataItems items{
  14846. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14847. {"hello", "world", "", ""},
  14848. };
  14849. for (const char &c : " \t\r\n") {
  14850. auto res =
  14851. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14852. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14853. ASSERT_FALSE(res);
  14854. }
  14855. }
  14856. TEST(MultipartFormDataTest, PutFormData) {
  14857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14858. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14859. const ContentReader &content_reader) {
  14860. if (req.is_multipart_form_data()) {
  14861. std::vector<FormData> items;
  14862. content_reader(
  14863. [&](const FormData &file) {
  14864. items.push_back(file);
  14865. return true;
  14866. },
  14867. [&](const char *data, size_t data_length) {
  14868. items.back().content.append(data, data_length);
  14869. return true;
  14870. });
  14871. EXPECT_TRUE(std::string(items[0].name) == "document");
  14872. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14873. EXPECT_TRUE(items[0].filename == "2MB_data");
  14874. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14875. EXPECT_TRUE(items[1].name == "hello");
  14876. EXPECT_TRUE(items[1].content == "world");
  14877. EXPECT_TRUE(items[1].filename == "");
  14878. EXPECT_TRUE(items[1].content_type == "");
  14879. } else {
  14880. std::string body;
  14881. content_reader([&](const char *data, size_t data_length) {
  14882. body.append(data, data_length);
  14883. return true;
  14884. });
  14885. }
  14886. });
  14887. auto port = svr.bind_to_any_port("localhost");
  14888. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14889. auto se = detail::scope_exit([&] {
  14890. svr.stop();
  14891. t.join();
  14892. ASSERT_FALSE(svr.is_running());
  14893. });
  14894. svr.wait_until_ready();
  14895. {
  14896. std::string data(1024 * 1024 * 2, '&');
  14897. std::stringstream buffer;
  14898. buffer << data;
  14899. SSLClient cli("localhost", port);
  14900. cli.enable_server_certificate_verification(false);
  14901. UploadFormDataItems items{
  14902. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14903. {"hello", "world", "", ""},
  14904. };
  14905. auto res = cli.Put("/put", items);
  14906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14907. ASSERT_EQ(StatusCode::OK_200, res->status);
  14908. }
  14909. }
  14910. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14911. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14912. svr.Put("/put_customboundary",
  14913. [&](const Request &req, const Response & /*res*/,
  14914. const ContentReader &content_reader) {
  14915. if (req.is_multipart_form_data()) {
  14916. std::vector<FormData> items;
  14917. content_reader(
  14918. [&](const FormData &file) {
  14919. items.push_back(file);
  14920. return true;
  14921. },
  14922. [&](const char *data, size_t data_length) {
  14923. items.back().content.append(data, data_length);
  14924. return true;
  14925. });
  14926. EXPECT_TRUE(std::string(items[0].name) == "document");
  14927. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14928. EXPECT_TRUE(items[0].filename == "2MB_data");
  14929. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14930. EXPECT_TRUE(items[1].name == "hello");
  14931. EXPECT_TRUE(items[1].content == "world");
  14932. EXPECT_TRUE(items[1].filename == "");
  14933. EXPECT_TRUE(items[1].content_type == "");
  14934. } else {
  14935. std::string body;
  14936. content_reader([&](const char *data, size_t data_length) {
  14937. body.append(data, data_length);
  14938. return true;
  14939. });
  14940. }
  14941. });
  14942. auto port = svr.bind_to_any_port("localhost");
  14943. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14944. auto se = detail::scope_exit([&] {
  14945. svr.stop();
  14946. t.join();
  14947. ASSERT_FALSE(svr.is_running());
  14948. });
  14949. svr.wait_until_ready();
  14950. {
  14951. std::string data(1024 * 1024 * 2, '&');
  14952. std::stringstream buffer;
  14953. buffer << data;
  14954. SSLClient cli("localhost", port);
  14955. cli.enable_server_certificate_verification(false);
  14956. UploadFormDataItems items{
  14957. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14958. {"hello", "world", "", ""},
  14959. };
  14960. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14962. ASSERT_EQ(StatusCode::OK_200, res->status);
  14963. }
  14964. }
  14965. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14966. std::string data(1024 * 1024 * 2, '&');
  14967. std::stringstream buffer;
  14968. buffer << data;
  14969. Client cli("https://localhost:8080");
  14970. cli.enable_server_certificate_verification(false);
  14971. UploadFormDataItems items{
  14972. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14973. {"hello", "world", "", ""},
  14974. };
  14975. for (const char &c : " \t\r\n") {
  14976. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14977. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14978. ASSERT_FALSE(res);
  14979. }
  14980. }
  14981. TEST(MultipartFormDataTest, AlternateFilename) {
  14982. auto handled = false;
  14983. Server svr;
  14984. svr.Post("/test", [&](const Request &req, Response &res) {
  14985. ASSERT_EQ(2u, req.form.files.size());
  14986. ASSERT_EQ(1u, req.form.fields.size());
  14987. // Test files
  14988. const auto &file1 = req.form.get_file("file1");
  14989. ASSERT_EQ("file1", file1.name);
  14990. ASSERT_EQ("A.txt", file1.filename);
  14991. ASSERT_EQ("text/plain", file1.content_type);
  14992. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14993. const auto &file2 = req.form.get_file("file2");
  14994. ASSERT_EQ("file2", file2.name);
  14995. ASSERT_EQ("a.html", file2.filename);
  14996. ASSERT_EQ("text/html", file2.content_type);
  14997. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14998. file2.content);
  14999. // Test text field
  15000. const auto &text = req.form.get_field("text");
  15001. ASSERT_EQ("text default", text);
  15002. res.set_content("ok", "text/plain");
  15003. handled = true;
  15004. });
  15005. thread t = thread([&] { svr.listen(HOST, PORT); });
  15006. auto se = detail::scope_exit([&] {
  15007. svr.stop();
  15008. t.join();
  15009. ASSERT_FALSE(svr.is_running());
  15010. ASSERT_TRUE(handled);
  15011. });
  15012. svr.wait_until_ready();
  15013. auto req = "POST /test HTTP/1.1\r\n"
  15014. "Host: localhost\r\n"
  15015. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15016. "Content-Length: 399\r\n"
  15017. "\r\n"
  15018. "----------\r\n"
  15019. "Content-Disposition: form-data; name=\"text\"\r\n"
  15020. "\r\n"
  15021. "text default\r\n"
  15022. "----------\r\n"
  15023. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15024. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15025. "Content-Type: text/plain\r\n"
  15026. "\r\n"
  15027. "Content of a.txt.\r\n"
  15028. "\r\n"
  15029. "----------\r\n"
  15030. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15031. "\"a.html\"\r\n"
  15032. "Content-Type: text/html\r\n"
  15033. "\r\n"
  15034. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15035. "\r\n"
  15036. "------------\r\n";
  15037. ASSERT_TRUE(send_request(1, req));
  15038. }
  15039. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15040. auto handled = false;
  15041. Server svr;
  15042. svr.Post("/test", [&](const Request &req, Response &res) {
  15043. // Case-insensitive "utf-8''" prefix with a long value
  15044. const auto &file = req.form.get_file("file1");
  15045. ASSERT_EQ("file1", file.name);
  15046. // 8000 chars exercises both the Content-Disposition parser and the
  15047. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15048. // Prior to the fix, std::regex_match on this header would cause O(N)
  15049. // stack recursion in libstdc++, leading to SIGSEGV.
  15050. std::string expected_filename(8000, 'A');
  15051. ASSERT_EQ(expected_filename, file.filename);
  15052. res.set_content("ok", "text/plain");
  15053. handled = true;
  15054. });
  15055. thread t = thread([&] { svr.listen(HOST, PORT); });
  15056. auto se = detail::scope_exit([&] {
  15057. svr.stop();
  15058. t.join();
  15059. ASSERT_FALSE(svr.is_running());
  15060. ASSERT_TRUE(handled);
  15061. });
  15062. svr.wait_until_ready();
  15063. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15064. // Regression test for GHSA-qq6v-r583-3h69
  15065. std::string long_filename(8000, 'A');
  15066. std::string body = "----------\r\n"
  15067. "Content-Disposition: form-data; name=\"file1\"; "
  15068. "filename*=\"Utf-8''" +
  15069. long_filename +
  15070. "\"\r\n"
  15071. "\r\n"
  15072. "hello\r\n"
  15073. "------------\r\n";
  15074. auto req = "POST /test HTTP/1.1\r\n"
  15075. "Host: localhost\r\n"
  15076. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15077. "Content-Length: " +
  15078. std::to_string(body.size()) + "\r\n\r\n" + body;
  15079. ASSERT_TRUE(send_request(1, req));
  15080. }
  15081. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15082. auto handled = false;
  15083. Server svr;
  15084. svr.Post("/test", [&](const Request &req, Response &) {
  15085. ASSERT_EQ(2u, req.form.fields.size());
  15086. const auto &text1 = req.form.get_field("text1");
  15087. ASSERT_EQ("text1", text1);
  15088. const auto &text2 = req.form.get_field("text2");
  15089. ASSERT_EQ("text2", text2);
  15090. handled = true;
  15091. });
  15092. thread t = thread([&] { svr.listen(HOST, PORT); });
  15093. auto se = detail::scope_exit([&] {
  15094. svr.stop();
  15095. t.join();
  15096. ASSERT_FALSE(svr.is_running());
  15097. ASSERT_TRUE(handled);
  15098. });
  15099. svr.wait_until_ready();
  15100. auto req = "POST /test HTTP/1.1\r\n"
  15101. "Host: localhost\r\n"
  15102. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15103. "Content-Length: 146\r\n"
  15104. "\r\n----------\r\n"
  15105. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15106. "\r\n"
  15107. "text1"
  15108. "\r\n----------\r\n"
  15109. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15110. "\r\n"
  15111. "text2"
  15112. "\r\n------------";
  15113. std::string response;
  15114. ASSERT_TRUE(send_request(1, req, &response));
  15115. ASSERT_EQ("200", response.substr(9, 3));
  15116. }
  15117. TEST(MultipartFormDataTest, ContentLength) {
  15118. auto handled = false;
  15119. Server svr;
  15120. svr.Post("/test", [&](const Request &req, Response &) {
  15121. ASSERT_EQ(2u, req.form.fields.size());
  15122. const auto &text1 = req.form.get_field("text1");
  15123. ASSERT_EQ("text1", text1);
  15124. const auto &text2 = req.form.get_field("text2");
  15125. ASSERT_EQ("text2", text2);
  15126. handled = true;
  15127. });
  15128. thread t = thread([&] { svr.listen(HOST, PORT); });
  15129. auto se = detail::scope_exit([&] {
  15130. svr.stop();
  15131. t.join();
  15132. ASSERT_FALSE(svr.is_running());
  15133. ASSERT_TRUE(handled);
  15134. });
  15135. svr.wait_until_ready();
  15136. auto req = "POST /test HTTP/1.1\r\n"
  15137. "Host: localhost\r\n"
  15138. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15139. "Content-Length: 167\r\n"
  15140. "\r\n----------\r\n"
  15141. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15142. "Content-Length: 5\r\n"
  15143. "\r\n"
  15144. "text1"
  15145. "\r\n----------\r\n"
  15146. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15147. "\r\n"
  15148. "text2"
  15149. "\r\n------------\r\n";
  15150. std::string response;
  15151. ASSERT_TRUE(send_request(1, req, &response));
  15152. ASSERT_EQ("200", response.substr(9, 3));
  15153. }
  15154. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15155. auto handled = false;
  15156. Server svr;
  15157. svr.Post("/test", [&](const Request &req, Response &) {
  15158. ASSERT_EQ(2u, req.form.fields.size());
  15159. const auto &text1 = req.form.get_field("text1");
  15160. ASSERT_EQ("text1", text1);
  15161. // TODO: Add header access for text fields if needed
  15162. const auto &text2 = req.form.get_field("text2");
  15163. ASSERT_EQ("text2", text2);
  15164. // TODO: Header access for text fields needs to be implemented
  15165. // auto &headers = it->second.headers;
  15166. // ASSERT_EQ(3U, headers.size());
  15167. // auto custom_header = headers.find("x-whatever");
  15168. // ASSERT_TRUE(custom_header != headers.end());
  15169. // ASSERT_NE("customvalue", custom_header->second);
  15170. // ASSERT_EQ("CustomValue", custom_header->second);
  15171. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15172. handled = true;
  15173. });
  15174. thread t = thread([&] { svr.listen(HOST, PORT); });
  15175. auto se = detail::scope_exit([&] {
  15176. svr.stop();
  15177. t.join();
  15178. ASSERT_FALSE(svr.is_running());
  15179. ASSERT_TRUE(handled);
  15180. });
  15181. svr.wait_until_ready();
  15182. auto req = "POST /test HTTP/1.1\r\n"
  15183. "Host: localhost\r\n"
  15184. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15185. "Content-Length: 232\r\n"
  15186. "\r\n----------\r\n"
  15187. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15188. "Content-Length: 5\r\n"
  15189. "X-Test: 1\r\n"
  15190. "\r\n"
  15191. "text1"
  15192. "\r\n----------\r\n"
  15193. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15194. "Content-Type: text/plain\r\n"
  15195. "X-Whatever: CustomValue\r\n"
  15196. "\r\n"
  15197. "text2"
  15198. "\r\n------------\r\n"
  15199. "That should be disregarded. Not even read";
  15200. std::string response;
  15201. ASSERT_TRUE(send_request(1, req, &response));
  15202. ASSERT_EQ("200", response.substr(9, 3));
  15203. }
  15204. TEST(MultipartFormDataTest, LargeHeader) {
  15205. auto handled = false;
  15206. Server svr;
  15207. svr.Post("/test", [&](const Request &req, Response &) {
  15208. ASSERT_EQ(1u, req.form.fields.size());
  15209. const auto &text = req.form.get_field("name1");
  15210. ASSERT_EQ("text1", text);
  15211. handled = true;
  15212. });
  15213. thread t = thread([&] { svr.listen(HOST, PORT); });
  15214. auto se = detail::scope_exit([&] {
  15215. svr.stop();
  15216. t.join();
  15217. ASSERT_FALSE(svr.is_running());
  15218. ASSERT_TRUE(handled);
  15219. });
  15220. svr.wait_until_ready();
  15221. auto boundary = std::string("cpp-httplib-multipart-data");
  15222. std::string content = "--" + boundary +
  15223. "\r\n"
  15224. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15225. "\r\n"
  15226. "text1\r\n"
  15227. "--" +
  15228. boundary + "--\r\n";
  15229. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15230. "Host: localhost\r\n"
  15231. "Content-Type: multipart/form-data;boundary=" +
  15232. boundary +
  15233. "\r\n"
  15234. "Content-Length: " +
  15235. std::to_string(content.size()) +
  15236. "\r\n"
  15237. "Dummy-Header: ";
  15238. std::string header_suffix = "\r\n"
  15239. "\r\n";
  15240. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15241. size_t header_dummy_size =
  15242. read_buff_size -
  15243. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15244. auto header_dummy = std::string(header_dummy_size, '@');
  15245. auto req = header_prefix + header_dummy + header_suffix + content;
  15246. std::string response;
  15247. ASSERT_TRUE(send_request(1, req, &response));
  15248. ASSERT_EQ("200", response.substr(9, 3));
  15249. }
  15250. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15251. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15252. // (not chunked Transfer-Encoding) after the streaming refactor.
  15253. auto handled = false;
  15254. Server svr;
  15255. svr.Post("/upload", [&](const Request &req, Response &res) {
  15256. auto cl_it = req.headers.find("Content-Length");
  15257. EXPECT_TRUE(cl_it != req.headers.end());
  15258. auto te_it = req.headers.find("Transfer-Encoding");
  15259. EXPECT_TRUE(te_it == req.headers.end());
  15260. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15261. res.set_content("ok", "text/plain");
  15262. handled = true;
  15263. });
  15264. auto port = svr.bind_to_any_port(HOST);
  15265. auto t = thread([&] { svr.listen_after_bind(); });
  15266. auto se = detail::scope_exit([&] {
  15267. svr.stop();
  15268. t.join();
  15269. ASSERT_FALSE(svr.is_running());
  15270. ASSERT_TRUE(handled);
  15271. });
  15272. svr.wait_until_ready();
  15273. UploadFormDataItems items = {
  15274. {"field1", "hello", "", "text/plain"},
  15275. {"file1", "world", "test.txt", "application/octet-stream"},
  15276. };
  15277. Client cli(HOST, port);
  15278. auto res = cli.Post("/upload", {}, items);
  15279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15280. EXPECT_EQ(StatusCode::OK_200, res->status);
  15281. }
  15282. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15283. // Verify that make_multipart_content_provider coalesces many small segments
  15284. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15285. constexpr size_t kItemCount = 1000;
  15286. UploadFormDataItems items;
  15287. items.reserve(kItemCount);
  15288. for (size_t i = 0; i < kItemCount; i++) {
  15289. items.push_back(
  15290. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15291. }
  15292. const std::string boundary = "----test-boundary";
  15293. auto content_length = detail::get_multipart_content_length(items, boundary);
  15294. auto provider = detail::make_multipart_content_provider(items, boundary);
  15295. // Drive the provider the same way write_content_with_progress does
  15296. size_t write_count = 0;
  15297. size_t total_bytes = 0;
  15298. DataSink sink;
  15299. size_t offset = 0;
  15300. sink.write = [&](const char *d, size_t l) -> bool {
  15301. (void)d;
  15302. write_count++;
  15303. total_bytes += l;
  15304. offset += l;
  15305. return true;
  15306. };
  15307. sink.is_writable = []() -> bool { return true; };
  15308. while (offset < content_length) {
  15309. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15310. }
  15311. EXPECT_EQ(content_length, total_bytes);
  15312. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15313. // With buffering into 64KB blocks, write_count should be much smaller.
  15314. auto segment_count = 3 * kItemCount + 1;
  15315. EXPECT_LT(write_count, segment_count / 10);
  15316. }
  15317. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15318. // Integration test: send many UploadFormDataItems and verify the server
  15319. // receives all of them correctly (#2410).
  15320. constexpr size_t kItemCount = 500;
  15321. auto handled = false;
  15322. Server svr;
  15323. svr.Post("/upload", [&](const Request &req, Response &res) {
  15324. EXPECT_EQ(kItemCount, req.form.fields.size());
  15325. for (size_t i = 0; i < kItemCount; i++) {
  15326. auto key = "field" + std::to_string(i);
  15327. auto val = "value" + std::to_string(i);
  15328. auto it = req.form.fields.find(key);
  15329. if (it != req.form.fields.end()) {
  15330. EXPECT_EQ(val, it->second.content);
  15331. } else {
  15332. ADD_FAILURE() << "Missing field: " << key;
  15333. }
  15334. }
  15335. res.set_content("ok", "text/plain");
  15336. handled = true;
  15337. });
  15338. auto port = svr.bind_to_any_port(HOST);
  15339. auto t = thread([&] { svr.listen_after_bind(); });
  15340. auto se = detail::scope_exit([&] {
  15341. svr.stop();
  15342. t.join();
  15343. ASSERT_FALSE(svr.is_running());
  15344. ASSERT_TRUE(handled);
  15345. });
  15346. svr.wait_until_ready();
  15347. UploadFormDataItems items;
  15348. items.reserve(kItemCount);
  15349. for (size_t i = 0; i < kItemCount; i++) {
  15350. items.push_back(
  15351. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15352. }
  15353. Client cli(HOST, port);
  15354. auto res = cli.Post("/upload", items);
  15355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15356. EXPECT_EQ(StatusCode::OK_200, res->status);
  15357. }
  15358. TEST(MultipartFormDataTest, MakeFileProvider) {
  15359. // Verify make_file_provider sends a file's contents correctly.
  15360. const std::string file_content(4096, 'Z');
  15361. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15362. {
  15363. std::ofstream ofs(tmp_path, std::ios::binary);
  15364. ofs.write(file_content.data(),
  15365. static_cast<std::streamsize>(file_content.size()));
  15366. }
  15367. auto handled = false;
  15368. Server svr;
  15369. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15370. const ContentReader &content_reader) {
  15371. ASSERT_TRUE(req.is_multipart_form_data());
  15372. std::vector<FormData> items;
  15373. content_reader(
  15374. [&](const FormData &file) {
  15375. items.push_back(file);
  15376. return true;
  15377. },
  15378. [&](const char *data, size_t data_length) {
  15379. items.back().content.append(data, data_length);
  15380. return true;
  15381. });
  15382. ASSERT_EQ(1u, items.size());
  15383. EXPECT_EQ("myfile", items[0].name);
  15384. EXPECT_EQ("data.bin", items[0].filename);
  15385. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15386. EXPECT_EQ(file_content, items[0].content);
  15387. handled = true;
  15388. });
  15389. auto port = svr.bind_to_any_port(HOST);
  15390. auto t = thread([&] { svr.listen_after_bind(); });
  15391. auto se = detail::scope_exit([&] {
  15392. svr.stop();
  15393. t.join();
  15394. ASSERT_FALSE(svr.is_running());
  15395. ASSERT_TRUE(handled);
  15396. std::remove(tmp_path.c_str());
  15397. });
  15398. svr.wait_until_ready();
  15399. FormDataProviderItems providers;
  15400. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15401. "application/octet-stream"));
  15402. Client cli(HOST, port);
  15403. auto res = cli.Post("/upload", {}, {}, providers);
  15404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15405. EXPECT_EQ(StatusCode::OK_200, res->status);
  15406. }
  15407. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15408. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15409. // (100) headers is rejected with a 400 Bad Request response.
  15410. Server svr;
  15411. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15412. res.set_content("ok", "text/plain");
  15413. });
  15414. thread t = thread([&] { svr.listen(HOST, PORT); });
  15415. auto se = detail::scope_exit([&] {
  15416. svr.stop();
  15417. t.join();
  15418. ASSERT_FALSE(svr.is_running());
  15419. });
  15420. svr.wait_until_ready();
  15421. // Build a multipart part with 101 custom headers (exceeding
  15422. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15423. std::stringstream body;
  15424. body << "--simpleboundary\r\n"
  15425. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15426. for (int i = 0; i < 101; i++) {
  15427. body << "X-Custom-Header-" << i << ": value\r\n";
  15428. }
  15429. body << "\r\n"
  15430. << "value1\r\n"
  15431. << "--simpleboundary--\r\n";
  15432. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15433. Client cli(HOST, PORT);
  15434. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15436. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15437. }
  15438. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15439. // A body that never contains the declared boundary must not be accumulated
  15440. // while the parser waits for it. Buffering it would also make every read
  15441. // rescan everything seen so far, which is quadratic in the body size.
  15442. Server svr;
  15443. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15444. res.set_content("ok", "text/plain");
  15445. });
  15446. auto port = svr.bind_to_any_port(HOST);
  15447. thread t = thread([&] { svr.listen_after_bind(); });
  15448. auto se = detail::scope_exit([&] {
  15449. svr.stop();
  15450. t.join();
  15451. ASSERT_FALSE(svr.is_running());
  15452. });
  15453. svr.wait_until_ready();
  15454. Client cli(HOST, port);
  15455. cli.set_read_timeout(60, 0);
  15456. cli.set_write_timeout(60, 0);
  15457. // '-' is the worst case: it matches the first character of the boundary, so
  15458. // every position has to be checked against it.
  15459. auto post_dashes = [&](size_t size) {
  15460. const std::string body(size, '-');
  15461. auto start = std::chrono::steady_clock::now();
  15462. auto res =
  15463. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15464. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15465. std::chrono::steady_clock::now() - start)
  15466. .count();
  15467. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15468. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15469. return ms;
  15470. };
  15471. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15472. // Windows.
  15473. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15474. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15475. // Comparing the two sizes rather than checking an absolute duration keeps
  15476. // this meaningful across build types and CI load, both of which move the
  15477. // absolute numbers by more than an order of magnitude. Four times the bytes
  15478. // costs about four times the time when parsing is linear, and about sixteen
  15479. // times when the body is buffered and rescanned.
  15480. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15481. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15482. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15483. << "ms, which suggests the body is being buffered and rescanned";
  15484. }
  15485. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15486. // A boundary can only be followed by CRLF or by "--", so anything else is
  15487. // malformed no matter what comes next. The parser must say so right away
  15488. // instead of buffering the rest of the declared body.
  15489. Server svr;
  15490. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15491. res.set_content("ok", "text/plain");
  15492. });
  15493. auto port = svr.bind_to_any_port(HOST);
  15494. thread t = thread([&] { svr.listen_after_bind(); });
  15495. auto se = detail::scope_exit([&] {
  15496. svr.stop();
  15497. t.join();
  15498. ASSERT_FALSE(svr.is_running());
  15499. });
  15500. svr.wait_until_ready();
  15501. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15502. // buffers instead of failing would still be waiting for the remaining bytes.
  15503. const std::string body = "--zzzz\r\n"
  15504. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15505. "\r\n"
  15506. "text1"
  15507. "\r\n--zzzzXX";
  15508. const std::string req = "POST /post HTTP/1.1\r\n"
  15509. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15510. "Content-Length: 1048576\r\n"
  15511. "\r\n" +
  15512. body;
  15513. std::string response;
  15514. ASSERT_TRUE(send_request(3, req, &response, port));
  15515. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15516. EXPECT_EQ("400", response.substr(9, 3));
  15517. }
  15518. // Posts a multipart body split into two writes, so that the server sees the
  15519. // split at whatever offset the caller chose, and expects the single "text1"
  15520. // field to come through.
  15521. static void expect_split_multipart_ok(const std::string &body1,
  15522. const std::string &body2) {
  15523. auto handled = false;
  15524. Server svr;
  15525. svr.Post("/post", [&](const Request &req, Response &) {
  15526. EXPECT_EQ(1u, req.form.fields.size());
  15527. EXPECT_EQ("text1", req.form.get_field("text1"));
  15528. handled = true;
  15529. });
  15530. auto port = svr.bind_to_any_port(HOST);
  15531. thread t = thread([&] { svr.listen_after_bind(); });
  15532. auto se = detail::scope_exit([&] {
  15533. svr.stop();
  15534. t.join();
  15535. ASSERT_FALSE(svr.is_running());
  15536. ASSERT_TRUE(handled);
  15537. });
  15538. svr.wait_until_ready();
  15539. // "Connection: close" makes the server close once it has answered, so the
  15540. // response drain ends immediately instead of idling until the read timeout.
  15541. const std::string head =
  15542. "POST /post HTTP/1.1\r\n"
  15543. "Host: localhost\r\n"
  15544. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15545. "Connection: close\r\n"
  15546. "Content-Length: " +
  15547. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15548. std::string response;
  15549. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15550. ASSERT_GE(response.size(), 12u) << "no response";
  15551. EXPECT_EQ("200", response.substr(9, 3));
  15552. }
  15553. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15554. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15555. // ignored, including when it does not arrive in the same read as the
  15556. // close-delimiter itself.
  15557. expect_split_multipart_ok("--zzzz\r\n"
  15558. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15559. "\r\n"
  15560. "text1"
  15561. "\r\n--zzzz--",
  15562. "\r\nthis epilogue must be ignored\r\n");
  15563. }
  15564. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15565. // The initial boundary may be preceded by a preamble of any length and may
  15566. // straddle a read boundary. Discarding data while waiting for it must not
  15567. // throw away a partial boundary sitting at the end of the buffer.
  15568. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15569. "zz\r\n"
  15570. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15571. "\r\n"
  15572. "text1"
  15573. "\r\n--zzzz--\r\n");
  15574. }
  15575. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15576. // The received boundary was only checked for being non-empty, so it could be
  15577. // as long as a header is allowed to be. The parser scans the body for
  15578. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15579. // costs a nearly full comparison at nearly every position, making the
  15580. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15581. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15582. Server svr;
  15583. svr.Post("/post", [](const Request &req, Response &res) {
  15584. EXPECT_EQ(1u, req.form.fields.size());
  15585. EXPECT_EQ("text1", req.form.get_field("text1"));
  15586. res.set_content("ok", "text/plain");
  15587. });
  15588. auto port = svr.bind_to_any_port(HOST);
  15589. thread t = thread([&] { svr.listen_after_bind(); });
  15590. auto se = detail::scope_exit([&] {
  15591. svr.stop();
  15592. t.join();
  15593. ASSERT_FALSE(svr.is_running());
  15594. });
  15595. svr.wait_until_ready();
  15596. Client cli(HOST, port);
  15597. auto post_with_boundary_of_length = [&](size_t len) {
  15598. const std::string boundary(len, 'a');
  15599. const std::string body =
  15600. "--" + boundary +
  15601. "\r\n"
  15602. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15603. "\r\n"
  15604. "text1"
  15605. "\r\n--" +
  15606. boundary + "--\r\n";
  15607. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15608. };
  15609. auto res = post_with_boundary_of_length(70);
  15610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15611. EXPECT_EQ(StatusCode::OK_200, res->status);
  15612. res = post_with_boundary_of_length(71);
  15613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15614. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15615. }
  15616. TEST(MakeFileBodyTest, Basic) {
  15617. const std::string file_content(4096, 'Z');
  15618. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15619. {
  15620. std::ofstream ofs(tmp_path, std::ios::binary);
  15621. ofs.write(file_content.data(),
  15622. static_cast<std::streamsize>(file_content.size()));
  15623. }
  15624. auto handled = false;
  15625. Server svr;
  15626. svr.Post("/upload", [&](const Request &req, Response &res) {
  15627. EXPECT_EQ(file_content, req.body);
  15628. handled = true;
  15629. res.status = StatusCode::OK_200;
  15630. });
  15631. auto port = svr.bind_to_any_port(HOST);
  15632. auto t = thread([&] { svr.listen_after_bind(); });
  15633. auto se = detail::scope_exit([&] {
  15634. svr.stop();
  15635. t.join();
  15636. ASSERT_FALSE(svr.is_running());
  15637. ASSERT_TRUE(handled);
  15638. std::remove(tmp_path.c_str());
  15639. });
  15640. svr.wait_until_ready();
  15641. auto fb = make_file_body(tmp_path);
  15642. ASSERT_GT(fb.first, 0u);
  15643. Client cli(HOST, port);
  15644. auto res =
  15645. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15647. EXPECT_EQ(StatusCode::OK_200, res->status);
  15648. }
  15649. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15650. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15651. {
  15652. std::ofstream ofs(path, std::ios::binary);
  15653. const std::string content(100, 'A');
  15654. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15655. }
  15656. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15657. auto body = make_file_body(path);
  15658. ASSERT_EQ(100u, body.first);
  15659. ASSERT_TRUE(static_cast<bool>(body.second));
  15660. // Rewritten shorter after its length was measured - and, on a server, after
  15661. // that length has already gone out as Content-Length.
  15662. {
  15663. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15664. const std::string content(10, 'A');
  15665. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15666. }
  15667. std::string written;
  15668. DataSink sink;
  15669. sink.write = [&](const char *d, size_t l) {
  15670. written.append(d, l);
  15671. return true;
  15672. };
  15673. // The provider has to report failure. write_content_with_progress() advances
  15674. // its offset only by what was written, so a provider that returns true
  15675. // without completing the length it promised is called again straight away,
  15676. // and again.
  15677. EXPECT_FALSE(body.second(0, body.first, sink));
  15678. EXPECT_EQ(std::string(10, 'A'), written);
  15679. }
  15680. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15681. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15682. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15683. {
  15684. std::ofstream ofs(path, std::ios::binary);
  15685. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15686. }
  15687. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15688. auto body = make_file_body(path);
  15689. ASSERT_EQ(content.size(), body.first);
  15690. ASSERT_TRUE(static_cast<bool>(body.second));
  15691. std::string written;
  15692. DataSink sink;
  15693. sink.write = [&](const char *d, size_t l) {
  15694. written.append(d, l);
  15695. return true;
  15696. };
  15697. EXPECT_TRUE(body.second(0, body.first, sink));
  15698. EXPECT_EQ(content, written);
  15699. }
  15700. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15701. static constexpr unsigned int number_of_tasks{1000000};
  15702. std::atomic_uint count{0};
  15703. std::unique_ptr<TaskQueue> task_queue{
  15704. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15705. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15706. auto queued = task_queue->enqueue(
  15707. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15708. EXPECT_TRUE(queued);
  15709. }
  15710. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15711. task_queue->shutdown();
  15712. #else
  15713. EXPECT_NO_THROW(task_queue->shutdown());
  15714. #endif
  15715. EXPECT_EQ(number_of_tasks, count.load());
  15716. }
  15717. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15718. static constexpr unsigned int number_of_tasks{1000000};
  15719. static constexpr unsigned int qlimit{2};
  15720. unsigned int queued_count{0};
  15721. std::atomic_uint count{0};
  15722. std::unique_ptr<TaskQueue> task_queue{
  15723. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15724. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15725. if (task_queue->enqueue(
  15726. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15727. queued_count++;
  15728. }
  15729. }
  15730. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15731. task_queue->shutdown();
  15732. #else
  15733. EXPECT_NO_THROW(task_queue->shutdown());
  15734. #endif
  15735. EXPECT_EQ(queued_count, count.load());
  15736. EXPECT_TRUE(queued_count <= number_of_tasks);
  15737. EXPECT_TRUE(queued_count >= qlimit);
  15738. }
  15739. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15740. // Use a short idle timeout so a dynamic thread spawns, times out and
  15741. // exits during the test, and the pool keeps working afterwards.
  15742. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15743. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15744. /*idle_timeout_sec=*/1}};
  15745. std::atomic_uint count{0};
  15746. std::condition_variable cv;
  15747. std::mutex mtx;
  15748. bool release = false;
  15749. // Block the base thread so the second task spawns a dynamic thread.
  15750. EXPECT_TRUE(task_queue->enqueue([&] {
  15751. std::unique_lock<std::mutex> lock(mtx);
  15752. while (!release) {
  15753. cv.wait(lock);
  15754. }
  15755. count++;
  15756. }));
  15757. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15758. // Let the dynamic thread finish its task and exceed the idle timeout.
  15759. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15760. {
  15761. std::unique_lock<std::mutex> lock(mtx);
  15762. release = true;
  15763. }
  15764. cv.notify_all();
  15765. // The pool must still accept and run tasks after the dynamic thread exited.
  15766. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15767. task_queue->shutdown();
  15768. EXPECT_EQ(3u, count.load());
  15769. }
  15770. TEST(TaskQueueTest, MaxQueuedRequests) {
  15771. static constexpr unsigned int qlimit{3};
  15772. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15773. std::condition_variable sem_cv;
  15774. std::mutex sem_mtx;
  15775. int credits = 0;
  15776. bool queued;
  15777. /* Fill up the queue with tasks that will block until we give them credits to
  15778. * complete. */
  15779. for (unsigned int n = 0; n <= qlimit;) {
  15780. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15781. std::unique_lock<std::mutex> lock(sem_mtx);
  15782. while (credits <= 0) {
  15783. sem_cv.wait(lock);
  15784. }
  15785. /* Consume the credit and signal the test code if they are all gone. */
  15786. if (--credits == 0) { sem_cv.notify_one(); }
  15787. });
  15788. if (n < qlimit) {
  15789. /* The first qlimit enqueues must succeed. */
  15790. EXPECT_TRUE(queued);
  15791. } else {
  15792. /* The last one will succeed only when the worker thread
  15793. * starts and dequeues the first blocking task. Although
  15794. * not necessary for the correctness of this test, we sleep for
  15795. * a short while to avoid busy waiting. */
  15796. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15797. }
  15798. if (queued) { n++; }
  15799. }
  15800. /* Further enqueues must fail since the queue is full. */
  15801. for (auto i = 0; i < 4; i++) {
  15802. queued = task_queue->enqueue([] {});
  15803. EXPECT_FALSE(queued);
  15804. }
  15805. /* Give the credits to allow the previous tasks to complete. */
  15806. {
  15807. std::unique_lock<std::mutex> lock(sem_mtx);
  15808. credits += qlimit + 1;
  15809. }
  15810. sem_cv.notify_all();
  15811. /* Wait for all the credits to be consumed. */
  15812. {
  15813. std::unique_lock<std::mutex> lock(sem_mtx);
  15814. while (credits > 0) {
  15815. sem_cv.wait(lock);
  15816. }
  15817. }
  15818. /* Check that we are able again to enqueue at least qlimit tasks. */
  15819. for (unsigned int i = 0; i < qlimit; i++) {
  15820. queued = task_queue->enqueue([] {});
  15821. EXPECT_TRUE(queued);
  15822. }
  15823. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15824. task_queue->shutdown();
  15825. #else
  15826. EXPECT_NO_THROW(task_queue->shutdown());
  15827. #endif
  15828. }
  15829. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15830. Server svr;
  15831. std::string method;
  15832. std::string body;
  15833. auto has_content_length = false;
  15834. auto has_transfer_encoding = false;
  15835. std::atomic<int> bad_requests{0};
  15836. // Leftover body bytes get parsed as a malformed request and answered with
  15837. // 400
  15838. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15839. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15840. });
  15841. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15842. res.set_redirect("/down", StatusCode::SeeOther_303);
  15843. });
  15844. svr.Get("/down", [&](const Request &req, Response &res) {
  15845. method = req.method;
  15846. body = req.body;
  15847. has_content_length = req.has_header("Content-Length");
  15848. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15849. res.set_content("ok", "text/plain");
  15850. });
  15851. auto port = svr.bind_to_any_port(HOST);
  15852. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15853. auto se = detail::scope_exit([&] {
  15854. svr.stop();
  15855. thread.join();
  15856. ASSERT_FALSE(svr.is_running());
  15857. });
  15858. svr.wait_until_ready();
  15859. const std::string payload = "SECRET-BODY";
  15860. auto check = [&](Client &cli, const Result &res) {
  15861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15862. EXPECT_EQ(StatusCode::OK_200, res->status);
  15863. EXPECT_EQ("ok", res->body);
  15864. EXPECT_EQ("GET", method);
  15865. EXPECT_TRUE(body.empty());
  15866. EXPECT_FALSE(has_content_length);
  15867. EXPECT_FALSE(has_transfer_encoding);
  15868. // Nothing of the original body may be left on the connection
  15869. auto res2 = cli.Get("/down");
  15870. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15871. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15872. EXPECT_EQ("ok", res2->body);
  15873. EXPECT_EQ(0, bad_requests);
  15874. };
  15875. // With content length
  15876. {
  15877. Client cli(HOST, port);
  15878. cli.set_keep_alive(true);
  15879. cli.set_follow_location(true);
  15880. auto res = cli.Post(
  15881. "/up", payload.size(),
  15882. [&](size_t offset, size_t length, DataSink &sink) {
  15883. return sink.write(payload.data() + offset, length);
  15884. },
  15885. "text/plain");
  15886. check(cli, res);
  15887. }
  15888. // Without content length (chunked)
  15889. {
  15890. Client cli(HOST, port);
  15891. cli.set_keep_alive(true);
  15892. cli.set_follow_location(true);
  15893. auto res = cli.Post(
  15894. "/up",
  15895. [&](size_t /*offset*/, DataSink &sink) {
  15896. sink.write(payload.data(), payload.size());
  15897. sink.done();
  15898. return true;
  15899. },
  15900. "text/plain");
  15901. check(cli, res);
  15902. }
  15903. }
  15904. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15905. Server svr;
  15906. std::string target;
  15907. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15908. // Echo the still-encoded name back in the Location
  15909. const std::string prefix = "/start/";
  15910. res.status = StatusCode::Found_302;
  15911. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15912. });
  15913. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15914. target = req.target;
  15915. res.set_content("ok", "text/plain");
  15916. });
  15917. auto port = svr.bind_to_any_port(HOST);
  15918. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15919. auto se = detail::scope_exit([&] {
  15920. svr.stop();
  15921. thread.join();
  15922. ASSERT_FALSE(svr.is_running());
  15923. });
  15924. svr.wait_until_ready();
  15925. // Decoding the Location path would turn the first four into a path
  15926. // separator, a query delimiter, a fragment delimiter and a different
  15927. // percent-encoded octet. The rest must keep reaching the server as they are.
  15928. const std::vector<std::string> names = {
  15929. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15930. };
  15931. for (auto path_encode : {true, false}) {
  15932. Client cli(HOST, port);
  15933. cli.set_follow_location(true);
  15934. cli.set_path_encode(path_encode);
  15935. for (const auto &name : names) {
  15936. target.clear();
  15937. auto res = cli.Get("/start/" + name);
  15938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15939. EXPECT_EQ(StatusCode::OK_200, res->status);
  15940. EXPECT_EQ("/dest/" + name, target);
  15941. }
  15942. }
  15943. }
  15944. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15945. Server svr;
  15946. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15947. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15948. });
  15949. svr.Get("/hello", [](const Request &req, Response &res) {
  15950. res.set_content(req.get_param_value("key"), "text/plain");
  15951. });
  15952. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15953. auto se = detail::scope_exit([&] {
  15954. svr.stop();
  15955. thread.join();
  15956. ASSERT_FALSE(svr.is_running());
  15957. });
  15958. svr.wait_until_ready();
  15959. {
  15960. Client cli(HOST, PORT);
  15961. cli.set_follow_location(true);
  15962. auto res = cli.Get("/");
  15963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15964. EXPECT_EQ(StatusCode::OK_200, res->status);
  15965. EXPECT_EQ("val&key2=val2", res->body);
  15966. }
  15967. }
  15968. #endif
  15969. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15970. Server svr;
  15971. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15972. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15973. });
  15974. svr.Get("/hello", [](const Request &req, Response &res) {
  15975. res.set_content(req.get_param_value("key"), "text/plain");
  15976. });
  15977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15978. auto se = detail::scope_exit([&] {
  15979. svr.stop();
  15980. thread.join();
  15981. ASSERT_FALSE(svr.is_running());
  15982. });
  15983. svr.wait_until_ready();
  15984. {
  15985. Client cli(HOST, PORT);
  15986. cli.set_follow_location(true);
  15987. auto res = cli.Get("/");
  15988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15989. EXPECT_EQ(StatusCode::OK_200, res->status);
  15990. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15991. }
  15992. }
  15993. TEST(RedirectTest, RedirectWithPlusInPath) {
  15994. Server svr;
  15995. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15996. res.set_redirect("/a+b");
  15997. });
  15998. // Route pattern uses regex; escape + as \\+
  15999. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16000. res.set_content(req.path, "text/plain");
  16001. });
  16002. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16003. auto se = detail::scope_exit([&] {
  16004. svr.stop();
  16005. thread.join();
  16006. ASSERT_FALSE(svr.is_running());
  16007. });
  16008. svr.wait_until_ready();
  16009. {
  16010. Client cli(HOST, PORT);
  16011. cli.set_follow_location(true);
  16012. auto res = cli.Get("/");
  16013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16014. EXPECT_EQ(StatusCode::OK_200, res->status);
  16015. EXPECT_EQ("/a+b", res->body);
  16016. }
  16017. }
  16018. TEST(RedirectTest, ResolveRelativeLocation) {
  16019. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16020. const std::vector<std::pair<std::string, std::string>> cases = {
  16021. {"g", "/b/c/g"},
  16022. {"./g", "/b/c/g"},
  16023. {"g/", "/b/c/g/"},
  16024. {"?y", "/b/c/d;p?y"},
  16025. {"g?y", "/b/c/g?y"},
  16026. {"#s", "/b/c/d;p?q#s"},
  16027. {"g#s", "/b/c/g#s"},
  16028. {"g?y#s", "/b/c/g?y#s"},
  16029. {";x", "/b/c/;x"},
  16030. {"g;x", "/b/c/g;x"},
  16031. {".", "/b/c/"},
  16032. {"./", "/b/c/"},
  16033. {"..", "/b/"},
  16034. {"../", "/b/"},
  16035. {"../g", "/b/g"},
  16036. {"../..", "/"},
  16037. {"../../", "/"},
  16038. {"../../g", "/g"},
  16039. {"../../../g", "/g"},
  16040. {"g.", "/b/c/g."},
  16041. {".g", "/b/c/.g"},
  16042. {"g..", "/b/c/g.."},
  16043. {"..g", "/b/c/..g"},
  16044. {"./../g", "/b/g"},
  16045. {"./g/.", "/b/c/g/"},
  16046. {"g/./h", "/b/c/g/h"},
  16047. {"g/../h", "/b/c/h"},
  16048. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16049. {"g;x=1/../y", "/b/c/y"},
  16050. {"g?y/./x", "/b/c/g?y/./x"},
  16051. {"g#s/../x", "/b/c/g#s/../x"},
  16052. // Not relative-path references, so left for parse_url.
  16053. {"/g", "/g"},
  16054. {"//g", "//g"},
  16055. {"http://g/x", "http://g/x"},
  16056. {"g:h", "g:h"},
  16057. };
  16058. for (const auto &c : cases) {
  16059. EXPECT_EQ(c.second,
  16060. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16061. << c.first;
  16062. }
  16063. }
  16064. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16065. Server svr;
  16066. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16067. res.set_redirect(req.get_param_value("to"));
  16068. });
  16069. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16070. res.set_content(req.target, "text/plain");
  16071. });
  16072. svr.Get("/other", [](const Request &req, Response &res) {
  16073. res.set_content(req.target, "text/plain");
  16074. });
  16075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16076. auto se = detail::scope_exit([&] {
  16077. svr.stop();
  16078. thread.join();
  16079. ASSERT_FALSE(svr.is_running());
  16080. });
  16081. svr.wait_until_ready();
  16082. const std::vector<std::pair<std::string, std::string>> cases = {
  16083. {"next", "/dir/next"},
  16084. {"./next?x=1", "/dir/next?x=1"},
  16085. {"../other", "/other"},
  16086. };
  16087. for (const auto &c : cases) {
  16088. Client cli(HOST, PORT);
  16089. cli.set_follow_location(true);
  16090. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16091. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16092. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16093. EXPECT_EQ(c.second, res->body) << c.first;
  16094. }
  16095. }
  16096. #ifdef CPPHTTPLIB_SSL_ENABLED
  16097. TEST(RedirectTest, Issue2185_Online) {
  16098. SSLClient client("github.com");
  16099. client.set_follow_location(true);
  16100. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16101. "Coollab-Windows.zip");
  16102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16103. EXPECT_EQ(StatusCode::OK_200, res->status);
  16104. EXPECT_EQ(9920427U, res->body.size());
  16105. }
  16106. #endif
  16107. TEST(VulnerabilityTest, CRLFInjection) {
  16108. Server svr;
  16109. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16110. res.set_content("Hello 1", "text/plain");
  16111. });
  16112. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16113. res.set_content("Hello 2", "text/plain");
  16114. });
  16115. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16116. res.set_content("Hello 3", "text/plain");
  16117. });
  16118. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16119. res.set_content("Hello 4", "text/plain");
  16120. });
  16121. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16122. for (const auto &x : req.headers) {
  16123. auto key = x.first;
  16124. EXPECT_STRNE("evil", key.c_str());
  16125. }
  16126. });
  16127. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16128. auto se = detail::scope_exit([&] {
  16129. svr.stop();
  16130. thread.join();
  16131. ASSERT_FALSE(svr.is_running());
  16132. });
  16133. svr.wait_until_ready();
  16134. {
  16135. Client cli(HOST, PORT);
  16136. cli.Post("/test1", "A=B",
  16137. "application/x-www-form-urlencoded\r\nevil: hello1");
  16138. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16139. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16140. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16141. }
  16142. }
  16143. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16144. auto server_thread = std::thread([] {
  16145. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16146. default_socket_options(srv);
  16147. sockaddr_in addr{};
  16148. addr.sin_family = AF_INET;
  16149. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16150. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16151. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16152. ::listen(srv, 1);
  16153. sockaddr_in cli_addr{};
  16154. socklen_t cli_len = sizeof(cli_addr);
  16155. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16156. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16157. std::string buf_all;
  16158. char buf[2048];
  16159. ssize_t n;
  16160. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16161. buf_all.append(buf, static_cast<size_t>(n));
  16162. size_t pos;
  16163. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16164. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16165. auto e = request_block.find("\r\n");
  16166. if (e != std::string::npos) {
  16167. auto request_line = request_block.substr(0, e);
  16168. std::string msg =
  16169. "CRLF injection detected in request line: '" + request_line + "'";
  16170. EXPECT_FALSE(true) << msg;
  16171. }
  16172. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16173. ::send(cli,
  16174. #ifdef _WIN32
  16175. static_cast<const char *>(resp.c_str()),
  16176. static_cast<int>(resp.size()),
  16177. #else
  16178. resp.c_str(), resp.size(),
  16179. #endif
  16180. 0);
  16181. buf_all.erase(0, pos + 4);
  16182. }
  16183. }
  16184. detail::close_socket(cli);
  16185. detail::close_socket(srv);
  16186. });
  16187. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16188. auto cli = Client("127.0.0.1", PORT + 1);
  16189. auto headers = Headers{
  16190. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16191. {"Connection", "keep-alive"}};
  16192. auto res = cli.Get("/hi", headers);
  16193. EXPECT_FALSE(res);
  16194. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16195. server_thread.join();
  16196. }
  16197. // A request rejected before any byte reaches the socket must fail right away
  16198. // instead of waiting for a response the server will never send.
  16199. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16200. // The kernel completes the TCP handshake from the listen backlog, so the
  16201. // client connects, but nothing ever reads, responds or closes.
  16202. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16203. default_socket_options(srv);
  16204. sockaddr_in addr{};
  16205. addr.sin_family = AF_INET;
  16206. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16207. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16208. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16209. ASSERT_EQ(0, ::listen(srv, 8));
  16210. auto cli = Client("127.0.0.1", PORT + 1);
  16211. cli.set_read_timeout(10, 0);
  16212. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16213. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16214. std::chrono::steady_clock::now() - start)
  16215. .count();
  16216. };
  16217. {
  16218. Request req;
  16219. req.method = "GE T";
  16220. req.path = "/";
  16221. auto start = std::chrono::steady_clock::now();
  16222. auto res = cli.send(req);
  16223. EXPECT_FALSE(res);
  16224. EXPECT_EQ(Error::Write, res.error());
  16225. EXPECT_LT(elapsed_ms(start), 1000);
  16226. }
  16227. {
  16228. auto start = std::chrono::steady_clock::now();
  16229. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16230. EXPECT_FALSE(res);
  16231. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16232. EXPECT_LT(elapsed_ms(start), 1000);
  16233. }
  16234. EXPECT_FALSE(cli.is_socket_open());
  16235. detail::close_socket(srv);
  16236. }
  16237. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16238. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16239. default_socket_options(srv);
  16240. sockaddr_in addr{};
  16241. addr.sin_family = AF_INET;
  16242. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16243. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16244. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16245. ASSERT_EQ(0, ::listen(srv, 1));
  16246. std::string received;
  16247. auto server_thread = std::thread([&] {
  16248. auto sock = ::accept(srv, nullptr, nullptr);
  16249. if (sock == INVALID_SOCKET) { return; }
  16250. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16251. char buf[2048];
  16252. ssize_t n;
  16253. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16254. received.append(buf, static_cast<size_t>(n));
  16255. }
  16256. detail::close_socket(sock);
  16257. });
  16258. {
  16259. auto cli = Client("127.0.0.1", PORT + 1);
  16260. // "Z" sorts after the default headers, so writing straight to the socket
  16261. // would have sent the request line and those headers before the rejection.
  16262. auto handle =
  16263. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16264. EXPECT_FALSE(handle.is_valid());
  16265. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16266. }
  16267. server_thread.join();
  16268. detail::close_socket(srv);
  16269. EXPECT_TRUE(received.empty()) << received;
  16270. }
  16271. TEST(PathParamsTest, StaticMatch) {
  16272. const auto pattern = "/users/all";
  16273. detail::PathParamsMatcher matcher(pattern);
  16274. Request request;
  16275. request.path = "/users/all";
  16276. ASSERT_TRUE(matcher.match(request));
  16277. std::unordered_map<std::string, std::string> expected_params = {};
  16278. EXPECT_EQ(request.path_params, expected_params);
  16279. }
  16280. TEST(PathParamsTest, StaticMismatch) {
  16281. const auto pattern = "/users/all";
  16282. detail::PathParamsMatcher matcher(pattern);
  16283. Request request;
  16284. request.path = "/users/1";
  16285. ASSERT_FALSE(matcher.match(request));
  16286. }
  16287. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16288. const auto pattern = "/users/:id/subscriptions";
  16289. detail::PathParamsMatcher matcher(pattern);
  16290. Request request;
  16291. request.path = "/users/42/subscriptions";
  16292. ASSERT_TRUE(matcher.match(request));
  16293. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16294. EXPECT_EQ(request.path_params, expected_params);
  16295. }
  16296. TEST(PathParamsTest, SingleParamInTheEnd) {
  16297. const auto pattern = "/users/:id";
  16298. detail::PathParamsMatcher matcher(pattern);
  16299. Request request;
  16300. request.path = "/users/24";
  16301. ASSERT_TRUE(matcher.match(request));
  16302. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16303. EXPECT_EQ(request.path_params, expected_params);
  16304. }
  16305. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16306. const auto pattern = "/users/:id/";
  16307. detail::PathParamsMatcher matcher(pattern);
  16308. Request request;
  16309. request.path = "/users/42/";
  16310. ASSERT_TRUE(matcher.match(request));
  16311. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16312. EXPECT_EQ(request.path_params, expected_params);
  16313. }
  16314. TEST(PathParamsTest, EmptyParam) {
  16315. const auto pattern = "/users/:id/";
  16316. detail::PathParamsMatcher matcher(pattern);
  16317. Request request;
  16318. request.path = "/users//";
  16319. ASSERT_TRUE(matcher.match(request));
  16320. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16321. EXPECT_EQ(request.path_params, expected_params);
  16322. }
  16323. TEST(PathParamsTest, FragmentMismatch) {
  16324. const auto pattern = "/users/:id/";
  16325. detail::PathParamsMatcher matcher(pattern);
  16326. Request request;
  16327. request.path = "/admins/24/";
  16328. ASSERT_FALSE(matcher.match(request));
  16329. }
  16330. TEST(PathParamsTest, ExtraFragments) {
  16331. const auto pattern = "/users/:id";
  16332. detail::PathParamsMatcher matcher(pattern);
  16333. Request request;
  16334. request.path = "/users/42/subscriptions";
  16335. ASSERT_FALSE(matcher.match(request));
  16336. }
  16337. TEST(PathParamsTest, MissingTrailingParam) {
  16338. const auto pattern = "/users/:id";
  16339. detail::PathParamsMatcher matcher(pattern);
  16340. Request request;
  16341. request.path = "/users";
  16342. ASSERT_FALSE(matcher.match(request));
  16343. }
  16344. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16345. const auto pattern = "/users/:id/subscriptions";
  16346. detail::PathParamsMatcher matcher(pattern);
  16347. Request request;
  16348. request.path = "/users/subscriptions";
  16349. ASSERT_FALSE(matcher.match(request));
  16350. }
  16351. TEST(PathParamsTest, MultipleParams) {
  16352. const auto pattern = "/users/:userid/subscriptions/:subid";
  16353. detail::PathParamsMatcher matcher(pattern);
  16354. Request request;
  16355. request.path = "/users/42/subscriptions/2";
  16356. ASSERT_TRUE(matcher.match(request));
  16357. std::unordered_map<std::string, std::string> expected_params = {
  16358. {"userid", "42"}, {"subid", "2"}};
  16359. EXPECT_EQ(request.path_params, expected_params);
  16360. }
  16361. TEST(PathParamsTest, SequenceOfParams) {
  16362. const auto pattern = "/values/:x/:y/:z";
  16363. detail::PathParamsMatcher matcher(pattern);
  16364. Request request;
  16365. request.path = "/values/1/2/3";
  16366. ASSERT_TRUE(matcher.match(request));
  16367. std::unordered_map<std::string, std::string> expected_params = {
  16368. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16369. EXPECT_EQ(request.path_params, expected_params);
  16370. }
  16371. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16372. const auto pattern = "/prefix:suffix";
  16373. detail::PathParamsMatcher matcher(pattern);
  16374. Request request;
  16375. request.path = "/prefix:suffix";
  16376. ASSERT_TRUE(matcher.match(request));
  16377. const std::unordered_map<std::string, std::string> expected_params = {};
  16378. EXPECT_EQ(request.path_params, expected_params);
  16379. }
  16380. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16381. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16382. // calling thread's stack on a long enough path for a quantified pattern;
  16383. // RegexMatcher must refuse to run regex matching on paths beyond
  16384. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16385. detail::RegexMatcher matcher("/files/(.*)");
  16386. Request within_limit;
  16387. within_limit.path = "/files/" + std::string(10, 'A');
  16388. EXPECT_TRUE(matcher.match(within_limit));
  16389. Request over_limit;
  16390. over_limit.path =
  16391. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16392. EXPECT_FALSE(matcher.match(over_limit));
  16393. }
  16394. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16395. Server svr;
  16396. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16397. res.set_content("ok", "text/plain");
  16398. });
  16399. auto port = svr.bind_to_any_port(HOST);
  16400. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16401. auto se = detail::scope_exit([&] {
  16402. svr.stop();
  16403. thread.join();
  16404. ASSERT_FALSE(svr.is_running());
  16405. });
  16406. svr.wait_until_ready();
  16407. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16408. // request URI limit; this used to be able to crash the process.
  16409. std::string path =
  16410. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16411. std::string req = "GET " + path +
  16412. " HTTP/1.1\r\n"
  16413. "Host: " +
  16414. std::string(HOST) + ":" + std::to_string(port) +
  16415. "\r\n"
  16416. "Connection: close\r\n"
  16417. "\r\n";
  16418. std::string response;
  16419. ASSERT_TRUE(send_request(5, req, &response, port));
  16420. EXPECT_NE(std::string::npos, response.find("404"));
  16421. }
  16422. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16423. Server svr;
  16424. auto handler = [](const Request & /*req*/, Response &res) {
  16425. res.set_content("hit", "text/plain");
  16426. };
  16427. // No regex metacharacter, so this one is compared literally
  16428. svr.Get("/literal/route", handler);
  16429. // '.' is a regex metacharacter, so this one must keep regex semantics
  16430. svr.Get("/a.c", handler);
  16431. auto port = svr.bind_to_any_port(HOST);
  16432. std::thread t([&]() { svr.listen_after_bind(); });
  16433. auto se = detail::scope_exit([&] {
  16434. svr.stop();
  16435. t.join();
  16436. ASSERT_FALSE(svr.is_running());
  16437. });
  16438. svr.wait_until_ready();
  16439. Client cli(HOST, port);
  16440. struct {
  16441. const char *path;
  16442. int status;
  16443. } cases[] = {
  16444. {"/literal/route", StatusCode::OK_200},
  16445. {"/literal/routes", StatusCode::NotFound_404},
  16446. {"/literal/rout", StatusCode::NotFound_404},
  16447. {"/abc", StatusCode::OK_200},
  16448. {"/a.c", StatusCode::OK_200},
  16449. };
  16450. for (const auto &x : cases) {
  16451. auto res = cli.Get(x.path);
  16452. ASSERT_TRUE(res) << x.path;
  16453. EXPECT_EQ(x.status, res->status) << x.path;
  16454. }
  16455. }
  16456. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16457. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16458. // from exhausting the stack, so it must only constrain routes that actually
  16459. // run a regular expression. A literal route is matched by comparison and
  16460. // stays usable at any length.
  16461. Server svr;
  16462. const std::string pattern =
  16463. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16464. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16465. res.set_content("hit", "text/plain");
  16466. });
  16467. auto port = svr.bind_to_any_port(HOST);
  16468. std::thread t([&]() { svr.listen_after_bind(); });
  16469. auto se = detail::scope_exit([&] {
  16470. svr.stop();
  16471. t.join();
  16472. ASSERT_FALSE(svr.is_running());
  16473. });
  16474. svr.wait_until_ready();
  16475. Client cli(HOST, port);
  16476. auto res = cli.Get(pattern);
  16477. ASSERT_TRUE(res);
  16478. EXPECT_EQ(StatusCode::OK_200, res->status);
  16479. }
  16480. TEST(ParseUrlTest, VariousPatterns) {
  16481. {
  16482. detail::UrlComponents uc;
  16483. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16484. EXPECT_EQ("http", uc.scheme);
  16485. EXPECT_EQ("example.com", uc.host);
  16486. EXPECT_EQ("8080", uc.port);
  16487. EXPECT_EQ("/path", uc.path);
  16488. EXPECT_EQ("?q=1", uc.query);
  16489. }
  16490. {
  16491. detail::UrlComponents uc;
  16492. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16493. EXPECT_EQ("https", uc.scheme);
  16494. EXPECT_EQ("example.com", uc.host);
  16495. EXPECT_TRUE(uc.port.empty());
  16496. EXPECT_EQ("/path", uc.path);
  16497. }
  16498. {
  16499. detail::UrlComponents uc;
  16500. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16501. EXPECT_EQ("::1", uc.host);
  16502. EXPECT_EQ("8080", uc.port);
  16503. EXPECT_EQ("/path", uc.path);
  16504. }
  16505. {
  16506. detail::UrlComponents uc;
  16507. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16508. }
  16509. {
  16510. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16511. // the path while the connection still targets the bracketed host.
  16512. detail::UrlComponents uc;
  16513. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16514. }
  16515. {
  16516. detail::UrlComponents uc;
  16517. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16518. }
  16519. {
  16520. detail::UrlComponents uc;
  16521. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16522. EXPECT_EQ("::1", uc.host);
  16523. EXPECT_TRUE(uc.port.empty());
  16524. EXPECT_EQ("/path", uc.path);
  16525. }
  16526. {
  16527. detail::UrlComponents uc;
  16528. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16529. EXPECT_TRUE(uc.scheme.empty());
  16530. EXPECT_EQ("example.com", uc.host);
  16531. EXPECT_EQ("/path", uc.path);
  16532. EXPECT_EQ("?q=1", uc.query);
  16533. }
  16534. {
  16535. detail::UrlComponents uc;
  16536. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16537. EXPECT_TRUE(uc.host.empty());
  16538. EXPECT_EQ("/path", uc.path);
  16539. EXPECT_EQ("?q=1", uc.query);
  16540. }
  16541. {
  16542. detail::UrlComponents uc;
  16543. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16544. EXPECT_EQ("example.com", uc.host);
  16545. EXPECT_EQ("8080", uc.port);
  16546. }
  16547. {
  16548. // Unix socket path — must not be parsed as host
  16549. detail::UrlComponents uc;
  16550. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16551. EXPECT_TRUE(uc.host.empty());
  16552. }
  16553. {
  16554. detail::UrlComponents uc;
  16555. ASSERT_TRUE(detail::parse_url("", uc));
  16556. EXPECT_TRUE(uc.host.empty());
  16557. EXPECT_TRUE(uc.path.empty());
  16558. }
  16559. {
  16560. detail::UrlComponents uc;
  16561. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16562. }
  16563. {
  16564. detail::UrlComponents uc;
  16565. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16566. }
  16567. {
  16568. // Accepted by parse_url; callers restrict to http/https
  16569. detail::UrlComponents uc;
  16570. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16571. EXPECT_EQ("ftp", uc.scheme);
  16572. }
  16573. {
  16574. detail::UrlComponents uc;
  16575. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16576. }
  16577. {
  16578. detail::UrlComponents uc;
  16579. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16580. }
  16581. }
  16582. TEST(ParseUrlTest, FragmentHandling) {
  16583. {
  16584. detail::UrlComponents uc;
  16585. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16586. EXPECT_EQ("/path", uc.path);
  16587. EXPECT_TRUE(uc.query.empty());
  16588. }
  16589. {
  16590. detail::UrlComponents uc;
  16591. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16592. EXPECT_TRUE(uc.path.empty());
  16593. EXPECT_TRUE(uc.query.empty());
  16594. }
  16595. }
  16596. TEST(ParseUrlTest, UserinfoHandling) {
  16597. // userinfo is not supported. Parsers that honour it, or take a backslash for
  16598. // '/', would see evil.com where the host used to be the whole authority.
  16599. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16600. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16601. for (auto url : urls) {
  16602. detail::UrlComponents uc;
  16603. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16604. }
  16605. }
  16606. TEST(ParseUrlTest, IPv6EdgeCases) {
  16607. {
  16608. detail::UrlComponents uc;
  16609. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16610. EXPECT_TRUE(uc.scheme.empty());
  16611. EXPECT_EQ("::1", uc.host);
  16612. EXPECT_EQ("8080", uc.port);
  16613. }
  16614. {
  16615. // Zone ID '%25' is not in [a-fA-F0-9:]
  16616. detail::UrlComponents uc;
  16617. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16618. }
  16619. }
  16620. TEST(ParseUrlTest, SchemeEdgeCases) {
  16621. {
  16622. detail::UrlComponents uc;
  16623. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16624. }
  16625. {
  16626. detail::UrlComponents uc;
  16627. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16628. }
  16629. {
  16630. detail::UrlComponents uc;
  16631. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16632. }
  16633. }
  16634. TEST(ParseUrlTest, PortEdgeCases) {
  16635. {
  16636. detail::UrlComponents uc;
  16637. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16638. EXPECT_TRUE(uc.port.empty());
  16639. EXPECT_EQ("/path", uc.path);
  16640. }
  16641. {
  16642. // parse_url accepts any port string; validation is done by parse_port
  16643. detail::UrlComponents uc;
  16644. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16645. EXPECT_EQ("abc", uc.port);
  16646. }
  16647. }
  16648. TEST(ParseUrlTest, WebSocketPatterns) {
  16649. {
  16650. detail::UrlComponents uc;
  16651. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16652. EXPECT_EQ("ws", uc.scheme);
  16653. EXPECT_EQ("echo.example.com", uc.host);
  16654. EXPECT_EQ("8080", uc.port);
  16655. EXPECT_EQ("/ws", uc.path);
  16656. }
  16657. {
  16658. detail::UrlComponents uc;
  16659. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16660. EXPECT_EQ("wss", uc.scheme);
  16661. EXPECT_EQ("echo.example.com", uc.host);
  16662. EXPECT_TRUE(uc.port.empty());
  16663. EXPECT_EQ("/ws", uc.path);
  16664. }
  16665. }
  16666. TEST(ParseUrlTest, QueryOnly) {
  16667. detail::UrlComponents uc;
  16668. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16669. EXPECT_TRUE(uc.host.empty());
  16670. EXPECT_TRUE(uc.path.empty());
  16671. EXPECT_EQ("?q=1&r=2", uc.query);
  16672. }
  16673. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16674. detail::UrlComponents uc;
  16675. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16676. EXPECT_TRUE(uc.scheme.empty());
  16677. EXPECT_EQ("example.com", uc.host);
  16678. EXPECT_EQ("443", uc.port);
  16679. EXPECT_EQ("/path", uc.path);
  16680. }
  16681. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16682. // If ipv6 regex working, regex match codepath is taken.
  16683. // else port will default to 80 in Client impl
  16684. int clientImplMagicPort = 80;
  16685. int port = 4321;
  16686. // above ports must be different to avoid false negative
  16687. EXPECT_NE(clientImplMagicPort, port);
  16688. std::string ipV6TestURL = "http://[ff06::c3]";
  16689. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16690. CLIENT_PRIVATE_KEY_FILE);
  16691. EXPECT_EQ(cli.port(), port);
  16692. }
  16693. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16694. auto file_path = "./www/dir/index.html";
  16695. auto dir_path = "./www/dir";
  16696. detail::FileStat stat_file(file_path);
  16697. EXPECT_TRUE(stat_file.is_file());
  16698. EXPECT_FALSE(stat_file.is_dir());
  16699. detail::FileStat stat_dir(dir_path);
  16700. EXPECT_FALSE(stat_dir.is_file());
  16701. EXPECT_TRUE(stat_dir.is_dir());
  16702. }
  16703. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16704. // IPv4 with default HTTP port (80)
  16705. EXPECT_EQ("example.com",
  16706. detail::make_host_and_port_string("example.com", 80, false));
  16707. // IPv4 with default HTTPS port (443)
  16708. EXPECT_EQ("example.com",
  16709. detail::make_host_and_port_string("example.com", 443, true));
  16710. // IPv4 with non-default HTTP port
  16711. EXPECT_EQ("example.com:8080",
  16712. detail::make_host_and_port_string("example.com", 8080, false));
  16713. // IPv4 with non-default HTTPS port
  16714. EXPECT_EQ("example.com:8443",
  16715. detail::make_host_and_port_string("example.com", 8443, true));
  16716. // IPv6 with default HTTP port (80)
  16717. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16718. // IPv6 with default HTTPS port (443)
  16719. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16720. // IPv6 with non-default HTTP port
  16721. EXPECT_EQ("[::1]:8080",
  16722. detail::make_host_and_port_string("::1", 8080, false));
  16723. // IPv6 with non-default HTTPS port
  16724. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16725. // IPv6 full address with default port
  16726. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16727. detail::make_host_and_port_string(
  16728. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16729. // IPv6 full address with non-default port
  16730. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16731. detail::make_host_and_port_string(
  16732. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16733. // IPv6 localhost with non-default port
  16734. EXPECT_EQ("[::1]:3000",
  16735. detail::make_host_and_port_string("::1", 3000, false));
  16736. // IPv6 with zone ID (link-local address) with default port
  16737. EXPECT_EQ("[fe80::1%eth0]",
  16738. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16739. // IPv6 with zone ID (link-local address) with non-default port
  16740. EXPECT_EQ("[fe80::1%eth0]:8080",
  16741. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16742. // Edge case: Port 443 with is_ssl=false (should add port)
  16743. EXPECT_EQ("example.com:443",
  16744. detail::make_host_and_port_string("example.com", 443, false));
  16745. // Edge case: Port 80 with is_ssl=true (should add port)
  16746. EXPECT_EQ("example.com:80",
  16747. detail::make_host_and_port_string("example.com", 80, true));
  16748. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16749. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16750. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16751. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16752. // Security fix: Already bracketed IPv6 should not get double brackets
  16753. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16754. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16755. EXPECT_EQ("[::1]:8080",
  16756. detail::make_host_and_port_string("[::1]", 8080, false));
  16757. EXPECT_EQ("[2001:db8::1]:8080",
  16758. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16759. EXPECT_EQ("[fe80::1%eth0]",
  16760. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16761. EXPECT_EQ("[fe80::1%eth0]:8080",
  16762. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16763. // Edge case: Empty host (should return as-is)
  16764. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16765. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16766. // This is a known limitation but shouldn't crash
  16767. EXPECT_EQ("[host:name]",
  16768. detail::make_host_and_port_string("host:name", 80, false));
  16769. // Port number edge cases (no validation, but should not crash)
  16770. EXPECT_EQ("example.com:0",
  16771. detail::make_host_and_port_string("example.com", 0, false));
  16772. EXPECT_EQ("example.com:-1",
  16773. detail::make_host_and_port_string("example.com", -1, false));
  16774. EXPECT_EQ("example.com:65535",
  16775. detail::make_host_and_port_string("example.com", 65535, false));
  16776. EXPECT_EQ("example.com:65536",
  16777. detail::make_host_and_port_string("example.com", 65536, false));
  16778. }
  16779. #ifdef CPPHTTPLIB_SSL_ENABLED
  16780. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16781. httplib::SSLClient cli("roblox.com", 443);
  16782. cli.set_follow_location(true);
  16783. auto res = cli.Get("/");
  16784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16785. EXPECT_EQ(StatusCode::OK_200, res->status);
  16786. }
  16787. #endif
  16788. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16789. Server svr;
  16790. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16791. EXPECT_EQ(res.status, 400);
  16792. });
  16793. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16794. auto se = detail::scope_exit([&] {
  16795. svr.stop();
  16796. thread.join();
  16797. ASSERT_FALSE(svr.is_running());
  16798. });
  16799. svr.wait_until_ready();
  16800. Client cli(HOST, PORT);
  16801. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16802. }
  16803. TEST(InvalidHeaderCharsTest, is_field_name) {
  16804. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16805. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16806. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16807. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16808. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16809. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16810. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16811. EXPECT_FALSE(detail::fields::is_field_name(""));
  16812. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16813. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16814. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16815. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16816. }
  16817. TEST(InvalidHeaderCharsTest, is_field_value) {
  16818. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16819. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16820. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16821. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16822. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16823. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16824. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16825. EXPECT_TRUE(detail::fields::is_field_value(""));
  16826. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16827. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16828. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16829. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16830. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16831. }
  16832. TEST(InvalidHeaderCharsTest, OnServer) {
  16833. Server svr;
  16834. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16835. std::string header = "Not Set";
  16836. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16837. res.set_header(header, "value");
  16838. res.set_content("Page Content Page Content", "text/plain");
  16839. });
  16840. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16841. std::string header = "Not Set";
  16842. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16843. res.set_header("X-Test", header);
  16844. res.set_content("Page Content Page Content", "text/plain");
  16845. });
  16846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16847. auto se = detail::scope_exit([&] {
  16848. svr.stop();
  16849. thread.join();
  16850. ASSERT_FALSE(svr.is_running());
  16851. });
  16852. svr.wait_until_ready();
  16853. Client cli(HOST, PORT);
  16854. {
  16855. auto res = cli.Get(
  16856. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16858. EXPECT_EQ("Page Content Page Content", res->body);
  16859. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16860. }
  16861. {
  16862. auto res = cli.Get(
  16863. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16865. EXPECT_EQ("Page Content Page Content", res->body);
  16866. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16867. }
  16868. }
  16869. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16870. auto handled = false;
  16871. Server svr;
  16872. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16873. thread t = thread([&] { svr.listen(HOST, PORT); });
  16874. auto se = detail::scope_exit([&] {
  16875. svr.stop();
  16876. t.join();
  16877. ASSERT_FALSE(svr.is_running());
  16878. ASSERT_FALSE(handled);
  16879. });
  16880. svr.wait_until_ready();
  16881. auto req = "POST /test HTTP/1.1\r\n"
  16882. "Content-Length: x\r\n"
  16883. "\r\n";
  16884. std::string response;
  16885. ASSERT_TRUE(send_request(1, req, &response));
  16886. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16887. response.substr(0, response.find("\r\n")));
  16888. }
  16889. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16890. // case-insensitive, and a server that receives a 100-continue expectation in
  16891. // an HTTP/1.0 request MUST ignore it.
  16892. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16893. std::string response;
  16894. ASSERT_TRUE(send_request(1, req, &response, port));
  16895. *got_100 = response.find("100 Continue") != std::string::npos;
  16896. }
  16897. class ExpectTokenTest : public ::testing::Test {
  16898. protected:
  16899. void SetUp() override {
  16900. svr_.Post("/p", [](const Request &, Response &res) {
  16901. res.set_content("ok", "text/plain");
  16902. });
  16903. port_ = svr_.bind_to_any_port(HOST);
  16904. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16905. svr_.wait_until_ready();
  16906. }
  16907. void TearDown() override {
  16908. svr_.stop();
  16909. if (thread_.joinable()) { thread_.join(); }
  16910. }
  16911. std::string request(const char *version, const char *expect_value) const {
  16912. return std::string("POST /p ") + version +
  16913. "\r\n"
  16914. "Host: localhost\r\n"
  16915. "Content-Length: 2\r\n"
  16916. "Connection: close\r\n"
  16917. "Expect: " +
  16918. expect_value +
  16919. "\r\n"
  16920. "\r\n"
  16921. "hi";
  16922. }
  16923. Server svr_;
  16924. int port_ = 0;
  16925. thread thread_;
  16926. };
  16927. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16928. bool got_100 = false;
  16929. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16930. EXPECT_TRUE(got_100);
  16931. }
  16932. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16933. bool got_100 = true;
  16934. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16935. EXPECT_FALSE(got_100);
  16936. }
  16937. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16938. bool got_100 = false;
  16939. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16940. EXPECT_TRUE(got_100);
  16941. }
  16942. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16943. bool got_100 = false;
  16944. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16945. EXPECT_TRUE(got_100);
  16946. }
  16947. // `100 Continue` is sent only when the server starts reading the body, so a
  16948. // request rejected before that never invites the client to send it. The
  16949. // requests below carry the expectation but withhold the body, as a client
  16950. // waiting for `100 Continue` would.
  16951. // A POST that expects `100 Continue` and withholds its two-byte body.
  16952. static std::string expect_headers_only(const std::string &path) {
  16953. return "POST " + path +
  16954. " HTTP/1.1\r\n"
  16955. "Host: localhost\r\n"
  16956. "Content-Length: 2\r\n"
  16957. "Expect: 100-continue\r\n"
  16958. "\r\n";
  16959. }
  16960. class ExpectLazyContinueTest : public ::testing::Test {
  16961. protected:
  16962. void SetUp() override {
  16963. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16964. if (req.path == "/pre-routing") {
  16965. res.status = StatusCode::Unauthorized_401;
  16966. return Server::HandlerResponse::Handled;
  16967. }
  16968. return Server::HandlerResponse::Unhandled;
  16969. });
  16970. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16971. if (req.matched_route == "/pre-request") {
  16972. res.status = StatusCode::Forbidden_403;
  16973. return Server::HandlerResponse::Handled;
  16974. }
  16975. return Server::HandlerResponse::Unhandled;
  16976. });
  16977. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16978. res.set_content("ok", "text/plain");
  16979. });
  16980. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16981. res.set_content("ok", "text/plain");
  16982. });
  16983. svr_.Post("/reader-used", [](const Request &, Response &res,
  16984. const ContentReader &content_reader) {
  16985. std::string body;
  16986. content_reader([&](const char *data, size_t len) {
  16987. body.append(data, len);
  16988. return true;
  16989. });
  16990. res.set_content(body, "text/plain");
  16991. });
  16992. svr_.Post("/reader-unused",
  16993. [](const Request &, Response &res, const ContentReader &) {
  16994. res.set_content("ignored", "text/plain");
  16995. });
  16996. port_ = svr_.bind_to_any_port(HOST);
  16997. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16998. svr_.wait_until_ready();
  16999. }
  17000. void TearDown() override {
  17001. svr_.stop();
  17002. if (thread_.joinable()) { thread_.join(); }
  17003. }
  17004. // Sends `req` and reads until the server closes the connection. Returns
  17005. // false if the read had to wait for the client-side timeout instead.
  17006. bool send_until_closed(const std::string &req, std::string *resp) const {
  17007. auto start = std::chrono::steady_clock::now();
  17008. if (!send_request(3, req, resp, port_)) { return false; }
  17009. auto elapsed = std::chrono::steady_clock::now() - start;
  17010. return elapsed < std::chrono::seconds(2);
  17011. }
  17012. // The final response comes without `100 Continue`, and the server closes
  17013. // the connection since the body may or may not follow.
  17014. void expect_final_without_interim(const std::string &path,
  17015. const char *status_line) const {
  17016. std::string resp;
  17017. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17018. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17019. EXPECT_EQ(0u, resp.find(status_line));
  17020. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17021. }
  17022. Server svr_;
  17023. int port_ = 0;
  17024. thread thread_;
  17025. };
  17026. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17027. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17028. }
  17029. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17030. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17031. }
  17032. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17033. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17034. }
  17035. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17036. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17037. }
  17038. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17039. // The body follows once `100 Continue` has had time to arrive.
  17040. auto req = expect_headers_only("/reader-used");
  17041. req.insert(req.size() - 2, "Connection: close\r\n");
  17042. std::string resp;
  17043. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17044. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17045. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17046. EXPECT_NE(std::string::npos, resp.find("hi"));
  17047. }
  17048. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17049. // Large enough for the client to add `Expect: 100-continue` itself.
  17050. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17051. std::atomic<bool> body_sent{false};
  17052. Client cli(HOST, port_);
  17053. auto res = cli.Post(
  17054. "/pre-request", length,
  17055. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17056. body_sent = true;
  17057. std::string chunk(len, 'x');
  17058. sink.write(chunk.data(), chunk.size());
  17059. return true;
  17060. },
  17061. "application/octet-stream");
  17062. ASSERT_TRUE(res);
  17063. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17064. EXPECT_FALSE(body_sent);
  17065. }
  17066. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17067. Server svr;
  17068. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17069. return StatusCode::ExpectationFailed_417;
  17070. });
  17071. svr.Post("/p", [](const Request &, Response &res) {
  17072. res.set_content("ok", "text/plain");
  17073. });
  17074. auto port = svr.bind_to_any_port(HOST);
  17075. thread t = thread([&] { svr.listen_after_bind(); });
  17076. auto se = detail::scope_exit([&] {
  17077. svr.stop();
  17078. t.join();
  17079. });
  17080. svr.wait_until_ready();
  17081. std::string resp;
  17082. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17083. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17084. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17085. // Exactly one response: the route handler must not run after the 417.
  17086. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17087. }
  17088. #ifndef _WIN32
  17089. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17090. static constexpr char reject[] = "Unauthorized";
  17091. static constexpr char accept[] = "Upload accepted";
  17092. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17093. Server svr;
  17094. svr.set_expect_100_continue_handler(
  17095. [](const Request & /*req*/, Response &res) {
  17096. res.status = StatusCode::Unauthorized_401;
  17097. res.set_content(reject, "text/plain");
  17098. return res.status;
  17099. });
  17100. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17101. res.set_content(accept, "text/plain");
  17102. });
  17103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17104. auto se = detail::scope_exit([&] {
  17105. svr.stop();
  17106. thread.join();
  17107. ASSERT_FALSE(svr.is_running());
  17108. });
  17109. svr.wait_until_ready();
  17110. {
  17111. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17112. curl_easy_init(), &curl_easy_cleanup};
  17113. ASSERT_NE(curl, nullptr);
  17114. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17115. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17116. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17117. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17118. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17119. &curl_slist_free_all};
  17120. ASSERT_NE(list, nullptr);
  17121. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17122. struct read_data {
  17123. size_t read_size;
  17124. size_t total_size;
  17125. } data = {0, total_size};
  17126. using read_callback_t =
  17127. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17128. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17129. void *userdata) -> size_t {
  17130. read_data *d = (read_data *)userdata;
  17131. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17132. std::fill_n(ptr, size * nmemb, 'A');
  17133. d->read_size += size * nmemb;
  17134. return size * nmemb;
  17135. };
  17136. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17137. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17138. std::vector<char> buffer;
  17139. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17140. using write_callback_t =
  17141. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17142. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17143. void *userdata) -> size_t {
  17144. std::vector<char> *buf = (std::vector<char> *)userdata;
  17145. buf->reserve(buf->size() + size * nmemb + 1);
  17146. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17147. return size * nmemb;
  17148. };
  17149. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17150. {
  17151. const auto res = curl_easy_perform(curl.get());
  17152. ASSERT_EQ(res, CURLE_OK);
  17153. }
  17154. {
  17155. auto response_code = long{};
  17156. const auto res =
  17157. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17158. ASSERT_EQ(res, CURLE_OK);
  17159. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17160. }
  17161. {
  17162. auto dl = curl_off_t{};
  17163. const auto res =
  17164. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17165. ASSERT_EQ(res, CURLE_OK);
  17166. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17167. }
  17168. {
  17169. buffer.push_back('\0');
  17170. ASSERT_STRCASEEQ(buffer.data(), reject);
  17171. }
  17172. }
  17173. }
  17174. #endif
  17175. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17176. // Regression test for #2458.
  17177. //
  17178. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17179. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17180. // ticket can make the client socket spuriously readable during the
  17181. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17182. // the client withholds the body and then blocks reading a response that never
  17183. // comes, failing with `Failed to read connection`.
  17184. //
  17185. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17186. // within the timeout. This raw OpenSSL server deliberately never sends
  17187. // `100 Continue`; the client must still deliver the body and receive 200.
  17188. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17189. signal(SIGPIPE, SIG_IGN);
  17190. const auto port = PORT + 4;
  17191. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17192. ASSERT_NE(srv, INVALID_SOCKET);
  17193. int opt = 1;
  17194. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17195. sockaddr_in addr{};
  17196. addr.sin_family = AF_INET;
  17197. addr.sin_port = htons(static_cast<uint16_t>(port));
  17198. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17199. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17200. ASSERT_EQ(0, ::listen(srv, 1));
  17201. std::atomic<size_t> server_body_bytes{0};
  17202. auto server_thread = std::thread([&] {
  17203. sockaddr_in cli_addr{};
  17204. socklen_t cli_len = sizeof(cli_addr);
  17205. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17206. if (cli == INVALID_SOCKET) { return; }
  17207. // Bound the lifetime of the server side so a buggy client (which never
  17208. // sends the body) cannot make this thread block forever on join.
  17209. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17210. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17211. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17212. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17213. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17214. SSL *ssl = SSL_new(ctx);
  17215. SSL_set_fd(ssl, static_cast<int>(cli));
  17216. if (SSL_accept(ssl) > 0) {
  17217. // Read the request headers. Reading here also flushes the TLS 1.3
  17218. // session tickets to the client. Deliberately do NOT send
  17219. // `100 Continue`.
  17220. std::string buf;
  17221. char tmp[1024];
  17222. while (buf.find("\r\n\r\n") == std::string::npos) {
  17223. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17224. if (n <= 0) { break; }
  17225. buf.append(tmp, static_cast<size_t>(n));
  17226. }
  17227. // A correct client sends the body now; count what arrives.
  17228. auto pos = buf.find("\r\n\r\n");
  17229. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17230. while (body < 4096) {
  17231. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17232. if (n <= 0) { break; }
  17233. body += static_cast<size_t>(n);
  17234. }
  17235. server_body_bytes = body;
  17236. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17237. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17238. SSL_shutdown(ssl);
  17239. }
  17240. SSL_free(ssl);
  17241. detail::close_socket(cli);
  17242. SSL_CTX_free(ctx);
  17243. });
  17244. auto se = detail::scope_exit([&] {
  17245. server_thread.join();
  17246. detail::close_socket(srv);
  17247. });
  17248. SSLClient cli("127.0.0.1", port);
  17249. cli.enable_server_certificate_verification(false);
  17250. cli.set_connection_timeout(5, 0);
  17251. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17252. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17253. std::string body(4096, 'A');
  17254. auto res = cli.Put("/api/test", body, "application/json");
  17255. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17256. EXPECT_EQ(StatusCode::OK_200, res->status);
  17257. EXPECT_EQ(body.size(), server_body_bytes.load());
  17258. }
  17259. #endif
  17260. template <typename S, typename C>
  17261. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17262. svr.Get("/stream", [&](const Request &, Response &res) {
  17263. auto data = new std::string("01234567890123456789");
  17264. res.set_content_provider(
  17265. data->size(), "text/plain",
  17266. [&, data](size_t offset, size_t length, DataSink &sink) {
  17267. const size_t DATA_CHUNK_SIZE = 4;
  17268. const auto &d = *data;
  17269. std::this_thread::sleep_for(std::chrono::seconds(1));
  17270. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17271. return true;
  17272. },
  17273. [data](bool success) {
  17274. EXPECT_FALSE(success);
  17275. delete data;
  17276. });
  17277. });
  17278. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17279. auto i = new size_t(0);
  17280. res.set_content_provider(
  17281. "text/plain",
  17282. [i](size_t, DataSink &sink) {
  17283. if (*i < 5) {
  17284. std::this_thread::sleep_for(std::chrono::seconds(1));
  17285. sink.write("abcd", 4);
  17286. (*i)++;
  17287. } else {
  17288. sink.done();
  17289. }
  17290. return true;
  17291. },
  17292. [i](bool success) {
  17293. EXPECT_FALSE(success);
  17294. delete i;
  17295. });
  17296. });
  17297. svr.Get("/chunked", [&](const Request &, Response &res) {
  17298. auto i = new size_t(0);
  17299. res.set_chunked_content_provider(
  17300. "text/plain",
  17301. [i](size_t, DataSink &sink) {
  17302. if (*i < 5) {
  17303. std::this_thread::sleep_for(std::chrono::seconds(1));
  17304. sink.os << "abcd";
  17305. (*i)++;
  17306. } else {
  17307. sink.done();
  17308. }
  17309. return true;
  17310. },
  17311. [i](bool success) {
  17312. EXPECT_FALSE(success);
  17313. delete i;
  17314. });
  17315. });
  17316. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17317. auto se = detail::scope_exit([&] {
  17318. svr.stop();
  17319. listen_thread.join();
  17320. ASSERT_FALSE(svr.is_running());
  17321. });
  17322. svr.wait_until_ready();
  17323. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17324. {
  17325. auto start = std::chrono::steady_clock::now();
  17326. auto res = cli.Get("/stream");
  17327. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17328. std::chrono::steady_clock::now() - start)
  17329. .count();
  17330. ASSERT_FALSE(res);
  17331. EXPECT_EQ(Error::Read, res.error());
  17332. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17333. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17334. }
  17335. {
  17336. auto start = std::chrono::steady_clock::now();
  17337. auto res = cli.Get("/stream_without_length");
  17338. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17339. std::chrono::steady_clock::now() - start)
  17340. .count();
  17341. ASSERT_FALSE(res);
  17342. EXPECT_EQ(Error::Read, res.error());
  17343. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17344. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17345. }
  17346. {
  17347. auto start = std::chrono::steady_clock::now();
  17348. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17349. EXPECT_EQ("abcd", string(data, data_length));
  17350. return true;
  17351. });
  17352. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17353. std::chrono::steady_clock::now() - start)
  17354. .count();
  17355. ASSERT_FALSE(res);
  17356. EXPECT_EQ(Error::Read, res.error());
  17357. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17358. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17359. }
  17360. }
  17361. TEST(MaxTimeoutTest, ContentStream) {
  17362. time_t timeout = 2000;
  17363. time_t threshold = 200;
  17364. Server svr;
  17365. Client cli("localhost", PORT);
  17366. max_timeout_test(svr, cli, timeout, threshold);
  17367. }
  17368. #ifdef CPPHTTPLIB_SSL_ENABLED
  17369. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17370. time_t timeout = 2000;
  17371. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17372. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17373. SSLClient cli("localhost", PORT);
  17374. cli.enable_server_certificate_verification(false);
  17375. max_timeout_test(svr, cli, timeout, threshold);
  17376. }
  17377. #endif
  17378. class EventDispatcher {
  17379. public:
  17380. EventDispatcher() {}
  17381. bool wait_event(DataSink *sink) {
  17382. unique_lock<mutex> lk(m_);
  17383. int id = id_;
  17384. // Wait with timeout to prevent hanging if client disconnects
  17385. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17386. [&] { return cid_ == id; })) {
  17387. return false; // Timeout occurred
  17388. }
  17389. sink->write(message_.data(), message_.size());
  17390. return true;
  17391. }
  17392. void send_event(const string &message) {
  17393. lock_guard<mutex> lk(m_);
  17394. cid_ = id_++;
  17395. message_ = message;
  17396. cv_.notify_all();
  17397. }
  17398. private:
  17399. mutex m_;
  17400. condition_variable cv_;
  17401. atomic_int id_{0};
  17402. atomic_int cid_{-1};
  17403. string message_;
  17404. };
  17405. TEST(ClientInThreadTest, Issue2068) {
  17406. EventDispatcher ed;
  17407. Server svr;
  17408. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17409. res.set_chunked_content_provider("text/event-stream",
  17410. [&](size_t /*offset*/, DataSink &sink) {
  17411. return ed.wait_event(&sink);
  17412. });
  17413. });
  17414. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17415. svr.wait_until_ready();
  17416. thread event_thread([&] {
  17417. int id = 0;
  17418. while (svr.is_running()) {
  17419. this_thread::sleep_for(chrono::milliseconds(500));
  17420. std::stringstream ss;
  17421. ss << "data: " << id << "\n\n";
  17422. ed.send_event(ss.str());
  17423. id++;
  17424. }
  17425. });
  17426. auto se = detail::scope_exit([&] {
  17427. svr.stop();
  17428. listen_thread.join();
  17429. event_thread.join();
  17430. ASSERT_FALSE(svr.is_running());
  17431. });
  17432. {
  17433. auto client = detail::make_unique<Client>(HOST, PORT);
  17434. client->set_read_timeout(std::chrono::minutes(10));
  17435. std::atomic<bool> stop{false};
  17436. std::thread t([&] {
  17437. client->Get("/event1",
  17438. [&](const char *, size_t) -> bool { return !stop; });
  17439. });
  17440. std::this_thread::sleep_for(std::chrono::seconds(2));
  17441. stop = true;
  17442. client->stop();
  17443. t.join();
  17444. // Reset client after thread has finished
  17445. client.reset();
  17446. }
  17447. }
  17448. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17449. auto handled = false;
  17450. Server svr;
  17451. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17452. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17453. auto se = detail::scope_exit([&] {
  17454. svr.stop();
  17455. t.join();
  17456. ASSERT_FALSE(svr.is_running());
  17457. ASSERT_FALSE(handled);
  17458. });
  17459. svr.wait_until_ready();
  17460. // Two Content-Length headers with different values — must be rejected
  17461. auto req = "POST /test HTTP/1.1\r\n"
  17462. "Content-Length: 5\r\n"
  17463. "Content-Length: 10\r\n"
  17464. "\r\n"
  17465. "hello";
  17466. std::string response;
  17467. ASSERT_TRUE(send_request(1, req, &response));
  17468. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17469. response.substr(0, response.find("\r\n")));
  17470. }
  17471. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17472. auto handled = false;
  17473. Server svr;
  17474. svr.Post("/test", [&](const Request &, Response &res) {
  17475. handled = true;
  17476. res.set_content("ok", "text/plain");
  17477. });
  17478. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17479. auto se = detail::scope_exit([&] {
  17480. svr.stop();
  17481. t.join();
  17482. ASSERT_FALSE(svr.is_running());
  17483. ASSERT_TRUE(handled);
  17484. });
  17485. svr.wait_until_ready();
  17486. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17487. auto req = "POST /test HTTP/1.1\r\n"
  17488. "Host: localhost\r\n"
  17489. "Content-Length: 5\r\n"
  17490. "Content-Length: 5\r\n"
  17491. "\r\n"
  17492. "hello";
  17493. std::string response;
  17494. ASSERT_TRUE(send_request(1, req, &response));
  17495. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17496. }
  17497. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17498. Server svr;
  17499. svr.Get("/test", [](const Request &, Response &res) {
  17500. res.set_content("ok", "text/plain");
  17501. });
  17502. auto port = svr.bind_to_any_port(HOST);
  17503. thread t = thread([&] { svr.listen_after_bind(); });
  17504. auto se = detail::scope_exit([&] {
  17505. svr.stop();
  17506. t.join();
  17507. ASSERT_FALSE(svr.is_running());
  17508. });
  17509. svr.wait_until_ready();
  17510. auto status_line = [&](const std::string &host_lines) {
  17511. std::string res;
  17512. send_request(
  17513. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17514. &res, port);
  17515. return res.substr(0, res.find("\r\n"));
  17516. };
  17517. const char *accepted[] = {
  17518. "Host: localhost\r\n",
  17519. "Host: a.example:8080\r\n",
  17520. "Host: my_service\r\n",
  17521. "Host: [::1]:8080\r\n",
  17522. "Host: [fe80::1%25eth0]\r\n",
  17523. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17524. };
  17525. for (auto host_lines : accepted) {
  17526. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17527. }
  17528. const char *rejected[] = {
  17529. "Host: a.example\r\nHost: b.example\r\n",
  17530. "Host: a.example\r\nHost: a.example\r\n",
  17531. "Host: a@b.example\r\n",
  17532. "Host: a.example/b\r\n",
  17533. "Host: a.example\\b\r\n",
  17534. "Host: a.example?b\r\n",
  17535. "Host: a.example#b\r\n",
  17536. "Host: a.example b.example\r\n",
  17537. };
  17538. for (auto host_lines : rejected) {
  17539. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17540. << host_lines;
  17541. }
  17542. }
  17543. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17544. Server svr;
  17545. svr.Get("/", [](const Request &req, Response &res) {
  17546. EXPECT_EQ(2U, req.trailers.size());
  17547. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17548. // Denied
  17549. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17550. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17551. // Accepted
  17552. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17553. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17554. EXPECT_TRUE(req.has_trailer("X-World"));
  17555. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17556. res.set_content("ok", "text/plain");
  17557. });
  17558. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17559. auto se = detail::scope_exit([&] {
  17560. svr.stop();
  17561. t.join();
  17562. ASSERT_FALSE(svr.is_running());
  17563. });
  17564. svr.wait_until_ready();
  17565. const std::string req = "GET / HTTP/1.1\r\n"
  17566. "Transfer-Encoding: chunked\r\n"
  17567. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17568. "\r\n"
  17569. "0\r\n"
  17570. "Content-Length: 10\r\n"
  17571. "Host: internal.local\r\n"
  17572. "Content-Type: malicious/content\r\n"
  17573. "Cookie: any\r\n"
  17574. "Set-Cookie: any\r\n"
  17575. "X-Forwarded-For: attacker.com\r\n"
  17576. "X-Real-Ip: 1.1.1.1\r\n"
  17577. "X-Hello: hello\r\n"
  17578. "X-World: world\r\n"
  17579. "\r\n";
  17580. std::string res;
  17581. ASSERT_TRUE(send_request(1, req, &res));
  17582. }
  17583. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17584. // several field lines, and the combined value is what has to be parsed. A
  17585. // Trailer field split across lines therefore declares every name it lists;
  17586. // reading only the first line silently drops the trailers the later lines
  17587. // declare. The prohibited-trailer filter still applies to every line.
  17588. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17589. Server svr;
  17590. size_t observed_trailer_count = 0;
  17591. std::string observed_hello;
  17592. std::string observed_world;
  17593. bool observed_content_length = true;
  17594. svr.Get("/", [&](const Request &req, Response &res) {
  17595. observed_trailer_count = req.trailers.size();
  17596. observed_hello = req.get_trailer_value("X-Hello");
  17597. observed_world = req.get_trailer_value("X-World");
  17598. observed_content_length = req.has_trailer("Content-Length");
  17599. res.set_content("ok", "text/plain");
  17600. });
  17601. auto port = svr.bind_to_any_port(HOST);
  17602. thread t = thread([&]() { svr.listen_after_bind(); });
  17603. auto se = detail::scope_exit([&] {
  17604. svr.stop();
  17605. t.join();
  17606. ASSERT_FALSE(svr.is_running());
  17607. });
  17608. svr.wait_until_ready();
  17609. const std::string req = "GET / HTTP/1.1\r\n"
  17610. "Host: localhost\r\n"
  17611. "Transfer-Encoding: chunked\r\n"
  17612. "Trailer: X-Hello\r\n"
  17613. "Trailer: X-World, Content-Length\r\n"
  17614. "\r\n"
  17615. "0\r\n"
  17616. "X-Hello: hello\r\n"
  17617. "X-World: world\r\n"
  17618. "Content-Length: 10\r\n"
  17619. "\r\n";
  17620. std::string res;
  17621. ASSERT_TRUE(send_request(1, req, &res, port));
  17622. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17623. // Accepted: both field lines contribute to the declared set
  17624. EXPECT_EQ(2U, observed_trailer_count);
  17625. EXPECT_EQ(observed_hello, "hello");
  17626. EXPECT_EQ(observed_world, "world");
  17627. // Denied: a prohibited name stays prohibited on a later field line
  17628. EXPECT_FALSE(observed_content_length);
  17629. }
  17630. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17631. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17632. // unbounded run of fields that are never declared, because the counter would
  17633. // only advance for declared fields.
  17634. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17635. Server svr;
  17636. bool handler_called = false;
  17637. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17638. handler_called = true;
  17639. res.set_content("ok", "text/plain");
  17640. });
  17641. auto port = svr.bind_to_any_port(HOST);
  17642. thread t = thread([&]() { svr.listen_after_bind(); });
  17643. auto se = detail::scope_exit([&] {
  17644. svr.stop();
  17645. t.join();
  17646. ASSERT_FALSE(svr.is_running());
  17647. });
  17648. svr.wait_until_ready();
  17649. // Declare nothing, then send far more undeclared trailer fields than the
  17650. // header-count limit. Parsing must stop and reject the request rather than
  17651. // read every line.
  17652. std::string req = "GET / HTTP/1.1\r\n"
  17653. "Transfer-Encoding: chunked\r\n"
  17654. "\r\n"
  17655. "0\r\n";
  17656. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17657. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17658. }
  17659. req += "\r\n";
  17660. std::string res;
  17661. ASSERT_TRUE(send_request(1, req, &res, port));
  17662. // The request is rejected before the handler runs.
  17663. EXPECT_FALSE(handler_called);
  17664. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17665. }
  17666. // The set of declared trailer names is capped so a peer cannot grow it without
  17667. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17668. // declared past the cap is not honored, even if the field is actually sent.
  17669. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17670. Server svr;
  17671. // One name inside the cap and one past it, so the test tracks the cap rather
  17672. // than a fixed count.
  17673. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17674. const std::string within_cap_name = "X-T-0";
  17675. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17676. bool observed_within_cap = false;
  17677. bool observed_past_cap = false;
  17678. svr.Get("/", [&](const Request &req, Response &res) {
  17679. observed_within_cap = req.has_trailer(within_cap_name);
  17680. observed_past_cap = req.has_trailer(past_cap_name);
  17681. res.set_content("ok", "text/plain");
  17682. });
  17683. auto port = svr.bind_to_any_port(HOST);
  17684. thread t = thread([&]() { svr.listen_after_bind(); });
  17685. auto se = detail::scope_exit([&] {
  17686. svr.stop();
  17687. t.join();
  17688. ASSERT_FALSE(svr.is_running());
  17689. });
  17690. svr.wait_until_ready();
  17691. // Declare more trailer names than the cap in a single Trailer field, then
  17692. // actually send the first (within the cap) and the last (past it).
  17693. std::string trailer_decl = "Trailer: ";
  17694. for (int i = 0; i < declared_count; i++) {
  17695. if (i != 0) { trailer_decl += ", "; }
  17696. trailer_decl += "X-T-" + std::to_string(i);
  17697. }
  17698. trailer_decl += "\r\n";
  17699. const std::string req = "GET / HTTP/1.1\r\n"
  17700. "Host: localhost\r\n"
  17701. "Transfer-Encoding: chunked\r\n" +
  17702. trailer_decl +
  17703. "\r\n"
  17704. "0\r\n" +
  17705. within_cap_name + ": a\r\n" + past_cap_name +
  17706. ": b\r\n"
  17707. "\r\n";
  17708. std::string res;
  17709. ASSERT_TRUE(send_request(1, req, &res, port));
  17710. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17711. // A name within the cap is honored; one declared past the cap is dropped.
  17712. EXPECT_TRUE(observed_within_cap);
  17713. EXPECT_FALSE(observed_past_cap);
  17714. }
  17715. // A direct client that is not listed in trusted_proxies must not be able to
  17716. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17717. // the peer address on the actual TCP connection determines whether the
  17718. // header is honored.
  17719. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17720. Server svr;
  17721. // Deliberately does NOT include the loopback address the test client
  17722. // actually connects from, so the direct connection is not a trusted proxy.
  17723. svr.set_trusted_proxies({"203.0.113.66"});
  17724. std::string observed_remote_addr;
  17725. svr.Get("/ip", [&](const Request &req, Response &res) {
  17726. observed_remote_addr = req.remote_addr;
  17727. res.set_content("ok", "text/plain");
  17728. });
  17729. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17730. auto se = detail::scope_exit([&] {
  17731. svr.stop();
  17732. t.join();
  17733. ASSERT_FALSE(svr.is_running());
  17734. });
  17735. svr.wait_until_ready();
  17736. Client cli(HOST, PORT);
  17737. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17739. EXPECT_EQ(StatusCode::OK_200, res->status);
  17740. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17741. // ignored entirely and the real connection-level address retained.
  17742. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17743. observed_remote_addr == "127.0.0.1");
  17744. }
  17745. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17746. Server svr;
  17747. std::string observed_remote_addr;
  17748. std::string observed_xff;
  17749. svr.Get("/ip", [&](const Request &req, Response &res) {
  17750. observed_remote_addr = req.remote_addr;
  17751. observed_xff = req.get_header_value("X-Forwarded-For");
  17752. res.set_content("ok", "text/plain");
  17753. });
  17754. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17755. auto se = detail::scope_exit([&] {
  17756. svr.stop();
  17757. t.join();
  17758. ASSERT_FALSE(svr.is_running());
  17759. });
  17760. svr.wait_until_ready();
  17761. Client cli(HOST, PORT);
  17762. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17764. EXPECT_EQ(StatusCode::OK_200, res->status);
  17765. EXPECT_EQ(observed_xff, "203.0.113.66");
  17766. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17767. observed_remote_addr == "127.0.0.1");
  17768. }
  17769. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17770. Server svr;
  17771. svr.set_trusted_proxies({"203.0.113.66"});
  17772. std::string observed_remote_addr;
  17773. std::string observed_xff;
  17774. svr.Get("/ip", [&](const Request &req, Response &res) {
  17775. observed_remote_addr = req.remote_addr;
  17776. observed_xff = req.get_header_value("X-Forwarded-For");
  17777. res.set_content("ok", "text/plain");
  17778. });
  17779. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17780. auto se = detail::scope_exit([&] {
  17781. svr.stop();
  17782. t.join();
  17783. ASSERT_FALSE(svr.is_running());
  17784. });
  17785. svr.wait_until_ready();
  17786. Client cli(HOST, PORT);
  17787. auto res = cli.Get("/ip");
  17788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17789. EXPECT_EQ(StatusCode::OK_200, res->status);
  17790. EXPECT_EQ(observed_xff, "");
  17791. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17792. observed_remote_addr == "127.0.0.1");
  17793. }
  17794. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17795. Server svr;
  17796. // Include the loopback address the test client actually connects from, so
  17797. // the direct connection itself is recognized as the trusted proxy hop.
  17798. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17799. std::string observed_remote_addr;
  17800. std::string observed_xff;
  17801. svr.Get("/ip", [&](const Request &req, Response &res) {
  17802. observed_remote_addr = req.remote_addr;
  17803. observed_xff = req.get_header_value("X-Forwarded-For");
  17804. res.set_content("ok", "text/plain");
  17805. });
  17806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17807. auto se = detail::scope_exit([&] {
  17808. svr.stop();
  17809. t.join();
  17810. ASSERT_FALSE(svr.is_running());
  17811. });
  17812. svr.wait_until_ready();
  17813. Client cli(HOST, PORT);
  17814. auto res = cli.Get(
  17815. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17817. EXPECT_EQ(StatusCode::OK_200, res->status);
  17818. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17819. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17820. }
  17821. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17822. Server svr;
  17823. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17824. std::string observed_remote_addr;
  17825. std::string observed_xff;
  17826. svr.Get("/ip", [&](const Request &req, Response &res) {
  17827. observed_remote_addr = req.remote_addr;
  17828. observed_xff = req.get_header_value("X-Forwarded-For");
  17829. res.set_content("ok", "text/plain");
  17830. });
  17831. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17832. auto se = detail::scope_exit([&] {
  17833. svr.stop();
  17834. t.join();
  17835. ASSERT_FALSE(svr.is_running());
  17836. });
  17837. svr.wait_until_ready();
  17838. Client cli(HOST, PORT);
  17839. auto res = cli.Get(
  17840. "/ip",
  17841. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17843. EXPECT_EQ(StatusCode::OK_200, res->status);
  17844. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17845. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17846. }
  17847. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17848. Server svr;
  17849. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17850. std::string observed_remote_addr;
  17851. std::string observed_xff;
  17852. svr.Get("/ip", [&](const Request &req, Response &res) {
  17853. observed_remote_addr = req.remote_addr;
  17854. observed_xff = req.get_header_value("X-Forwarded-For");
  17855. res.set_content("ok", "text/plain");
  17856. });
  17857. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17858. auto se = detail::scope_exit([&] {
  17859. svr.stop();
  17860. t.join();
  17861. ASSERT_FALSE(svr.is_running());
  17862. });
  17863. svr.wait_until_ready();
  17864. Client cli(HOST, PORT);
  17865. auto res = cli.Get(
  17866. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17868. EXPECT_EQ(StatusCode::OK_200, res->status);
  17869. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17870. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17871. // and must not be selected.
  17872. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17873. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17874. }
  17875. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17876. Server svr;
  17877. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17878. std::string observed_remote_addr;
  17879. svr.Get("/ip", [&](const Request &req, Response &res) {
  17880. observed_remote_addr = req.remote_addr;
  17881. res.set_content("ok", "text/plain");
  17882. });
  17883. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17884. auto se = detail::scope_exit([&] {
  17885. svr.stop();
  17886. t.join();
  17887. ASSERT_FALSE(svr.is_running());
  17888. });
  17889. svr.wait_until_ready();
  17890. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17891. // a forged address and the trusted proxy's own address; the forged value must
  17892. // not win over the address the trusted proxy actually recorded.
  17893. Client cli(HOST, PORT);
  17894. auto res = cli.Get(
  17895. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17897. EXPECT_EQ(StatusCode::OK_200, res->status);
  17898. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17899. }
  17900. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17901. Server svr;
  17902. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17903. std::string observed_remote_addr;
  17904. std::string observed_xff;
  17905. svr.Get("/ip", [&](const Request &req, Response &res) {
  17906. observed_remote_addr = req.remote_addr;
  17907. observed_xff = req.get_header_value("X-Forwarded-For");
  17908. res.set_content("ok", "text/plain");
  17909. });
  17910. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17911. auto se = detail::scope_exit([&] {
  17912. svr.stop();
  17913. t.join();
  17914. ASSERT_FALSE(svr.is_running());
  17915. });
  17916. svr.wait_until_ready();
  17917. Client cli(HOST, PORT);
  17918. auto res = cli.Get(
  17919. "/ip",
  17920. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17922. EXPECT_EQ(StatusCode::OK_200, res->status);
  17923. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17924. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17925. }
  17926. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17927. Server svr;
  17928. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17929. std::string observed_remote_addr;
  17930. std::string observed_xff;
  17931. svr.Get("/ip", [&](const Request &req, Response &res) {
  17932. observed_remote_addr = req.remote_addr;
  17933. observed_xff = req.get_header_value("X-Forwarded-For");
  17934. res.set_content("ok", "text/plain");
  17935. });
  17936. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17937. auto se = detail::scope_exit([&] {
  17938. svr.stop();
  17939. t.join();
  17940. ASSERT_FALSE(svr.is_running());
  17941. });
  17942. svr.wait_until_ready();
  17943. std::string raw_req =
  17944. "GET /ip HTTP/1.1\r\n"
  17945. "Host: localhost\r\n"
  17946. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17947. "Connection: close\r\n"
  17948. "\r\n";
  17949. std::string out;
  17950. ASSERT_TRUE(send_request(5, raw_req, &out));
  17951. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17952. // Header parser trims surrounding whitespace of the header value
  17953. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17954. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17955. }
  17956. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17957. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17958. // their own X-Forwarded-For as a separate field line rather than extending the
  17959. // one the client sent, so every occurrence has to be taken into account.
  17960. // Reading only the first one hands back the address the client chose.
  17961. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17962. Server svr;
  17963. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17964. std::string observed_remote_addr;
  17965. size_t observed_xff_count = 0;
  17966. svr.Get("/ip", [&](const Request &req, Response &res) {
  17967. observed_remote_addr = req.remote_addr;
  17968. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17969. res.set_content("ok", "text/plain");
  17970. });
  17971. auto port = svr.bind_to_any_port(HOST);
  17972. thread t = thread([&]() { svr.listen_after_bind(); });
  17973. auto se = detail::scope_exit([&] {
  17974. svr.stop();
  17975. t.join();
  17976. ASSERT_FALSE(svr.is_running());
  17977. });
  17978. svr.wait_until_ready();
  17979. // The client supplies the first field line; the trusted proxy appends the
  17980. // address it observed as a second one.
  17981. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17982. "Host: localhost\r\n"
  17983. "X-Forwarded-For: 1.2.3.4\r\n"
  17984. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17985. "Connection: close\r\n"
  17986. "\r\n";
  17987. std::string out;
  17988. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17989. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17990. EXPECT_EQ(observed_xff_count, 2U);
  17991. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17992. // The same chain spread over one field line per hop derives the same client
  17993. // address, i.e. the split and the comma-joined representations agree.
  17994. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17995. "Host: localhost\r\n"
  17996. "X-Forwarded-For: 1.2.3.4\r\n"
  17997. "X-Forwarded-For: 198.51.100.23\r\n"
  17998. "X-Forwarded-For: 192.0.2.45\r\n"
  17999. "Connection: close\r\n"
  18000. "\r\n";
  18001. out.clear();
  18002. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18003. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18004. EXPECT_EQ(observed_xff_count, 3U);
  18005. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18006. }
  18007. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18008. // crash the server (it used to call front() on an empty vector inside
  18009. // get_client_ip). The connection-level remote address must be retained instead.
  18010. static void run_malformed_xff_test(const std::string &xff_value) {
  18011. Server svr;
  18012. svr.set_trusted_proxies({"192.0.2.45"});
  18013. std::string observed_remote_addr;
  18014. svr.Get("/ip", [&](const Request &req, Response &res) {
  18015. observed_remote_addr = req.remote_addr;
  18016. res.set_content("ok", "text/plain");
  18017. });
  18018. int port = 0;
  18019. thread t = thread([&]() {
  18020. port = svr.bind_to_any_port(HOST);
  18021. svr.listen_after_bind();
  18022. });
  18023. auto se = detail::scope_exit([&] {
  18024. svr.stop();
  18025. t.join();
  18026. ASSERT_FALSE(svr.is_running());
  18027. });
  18028. svr.wait_until_ready();
  18029. Client cli(HOST, port);
  18030. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18032. EXPECT_EQ(StatusCode::OK_200, res->status);
  18033. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18034. observed_remote_addr == "127.0.0.1");
  18035. }
  18036. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18037. run_malformed_xff_test("");
  18038. }
  18039. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18040. run_malformed_xff_test(",");
  18041. }
  18042. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18043. run_malformed_xff_test(", , ,");
  18044. }
  18045. // The same rule applies to Accept: a request whose acceptable types are spread
  18046. // over several field lines must be negotiated against all of them.
  18047. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18048. // case-insensitive connection options. Comparing the whole field value against
  18049. // one option misses a client that sends several of them, and misses every
  18050. // casing but the one written in the comparison.
  18051. //
  18052. // Sends req, reads the response, then reuses the same socket for a second
  18053. // request to find out whether the server kept the connection.
  18054. static void probe_connection_reuse(int port, const std::string &req,
  18055. bool *announced_close, bool *reusable) {
  18056. auto error = Error::Success;
  18057. auto sock = detail::create_client_socket(
  18058. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18059. /*connection_timeout_sec=*/5, 0,
  18060. /*read_timeout_sec=*/1, 0,
  18061. /*write_timeout_sec=*/5, 0, std::string(), error);
  18062. ASSERT_NE(sock, INVALID_SOCKET);
  18063. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18064. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18065. "Host: localhost\r\n"
  18066. "Connection: close\r\n"
  18067. "\r\n";
  18068. std::string first_response;
  18069. std::string second_response;
  18070. detail::process_client_socket(
  18071. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18072. [&](Stream &strm) {
  18073. if (strm.write(req.data(), req.size()) !=
  18074. static_cast<ssize_t>(req.size())) {
  18075. return false;
  18076. }
  18077. char buf[512];
  18078. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18079. // Headers plus the two-byte body of the handler below
  18080. while (reader.getline()) {
  18081. first_response += reader.ptr();
  18082. if (first_response.find("ok") != std::string::npos) { break; }
  18083. }
  18084. if (strm.write(second.data(), second.size()) !=
  18085. static_cast<ssize_t>(second.size())) {
  18086. return true;
  18087. }
  18088. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18089. while (reader2.getline()) {
  18090. second_response += reader2.ptr();
  18091. if (second_response.find("ok") != std::string::npos) { break; }
  18092. }
  18093. return true;
  18094. });
  18095. *announced_close =
  18096. first_response.find("Connection: close") != std::string::npos;
  18097. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18098. }
  18099. class ConnectionTokenTest : public ::testing::Test {
  18100. protected:
  18101. void SetUp() override {
  18102. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18103. res.set_content("ok", "text/plain");
  18104. });
  18105. port_ = svr_.bind_to_any_port(HOST);
  18106. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18107. svr_.wait_until_ready();
  18108. }
  18109. void TearDown() override {
  18110. svr_.stop();
  18111. if (thread_.joinable()) { thread_.join(); }
  18112. }
  18113. Server svr_;
  18114. int port_ = 0;
  18115. thread thread_;
  18116. };
  18117. // "close" alongside another option still closes the connection, and the
  18118. // response says so rather than leaving the peer to discover it.
  18119. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18120. bool announced_close = false;
  18121. bool reusable = true;
  18122. probe_connection_reuse(port_,
  18123. "GET /keepalive HTTP/1.1\r\n"
  18124. "Host: localhost\r\n"
  18125. "Connection: keep-alive, close\r\n"
  18126. "\r\n",
  18127. &announced_close, &reusable);
  18128. EXPECT_TRUE(announced_close);
  18129. EXPECT_FALSE(reusable);
  18130. }
  18131. // "close" split over two field lines is the same list, so it is honored too.
  18132. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18133. bool announced_close = false;
  18134. bool reusable = true;
  18135. probe_connection_reuse(port_,
  18136. "GET /keepalive HTTP/1.1\r\n"
  18137. "Host: localhost\r\n"
  18138. "Connection: keep-alive\r\n"
  18139. "Connection: close\r\n"
  18140. "\r\n",
  18141. &announced_close, &reusable);
  18142. EXPECT_TRUE(announced_close);
  18143. EXPECT_FALSE(reusable);
  18144. }
  18145. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18146. // keep-alive in the spelling everyone actually sends keeps its connection.
  18147. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18148. bool announced_close = false;
  18149. bool reusable = false;
  18150. probe_connection_reuse(port_,
  18151. "GET /keepalive HTTP/1.0\r\n"
  18152. "Host: localhost\r\n"
  18153. "Connection: keep-alive\r\n"
  18154. "\r\n",
  18155. &announced_close, &reusable);
  18156. EXPECT_FALSE(announced_close);
  18157. EXPECT_TRUE(reusable);
  18158. }
  18159. // A token the value merely contains is not the token itself.
  18160. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18161. bool announced_close = false;
  18162. bool reusable = false;
  18163. probe_connection_reuse(port_,
  18164. "GET /keepalive HTTP/1.1\r\n"
  18165. "Host: localhost\r\n"
  18166. "Connection: notclose\r\n"
  18167. "\r\n",
  18168. &announced_close, &reusable);
  18169. EXPECT_FALSE(announced_close);
  18170. EXPECT_TRUE(reusable);
  18171. }
  18172. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18173. Server svr;
  18174. std::vector<std::string> observed_types;
  18175. svr.Get("/", [&](const Request &req, Response &res) {
  18176. observed_types = req.accept_content_types;
  18177. res.set_content("ok", "text/plain");
  18178. });
  18179. auto port = svr.bind_to_any_port(HOST);
  18180. thread t = thread([&]() { svr.listen_after_bind(); });
  18181. auto se = detail::scope_exit([&] {
  18182. svr.stop();
  18183. t.join();
  18184. ASSERT_FALSE(svr.is_running());
  18185. });
  18186. svr.wait_until_ready();
  18187. Client cli(HOST, port);
  18188. Headers headers;
  18189. headers.emplace("Accept", "text/plain;q=0.5");
  18190. headers.emplace("Accept", "application/json");
  18191. auto res = cli.Get("/", headers);
  18192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18193. EXPECT_EQ(StatusCode::OK_200, res->status);
  18194. // Sorted by q-value, so the second field line's type comes first
  18195. ASSERT_EQ(2U, observed_types.size());
  18196. EXPECT_EQ("application/json", observed_types[0]);
  18197. EXPECT_EQ("text/plain", observed_types[1]);
  18198. }
  18199. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18200. // empty field line must not contribute a bare comma to the combined value.
  18201. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18202. Server svr;
  18203. std::vector<std::string> observed_types;
  18204. svr.Get("/", [&](const Request &req, Response &res) {
  18205. observed_types = req.accept_content_types;
  18206. res.set_content("ok", "text/plain");
  18207. });
  18208. auto port = svr.bind_to_any_port(HOST);
  18209. thread t = thread([&]() { svr.listen_after_bind(); });
  18210. auto se = detail::scope_exit([&] {
  18211. svr.stop();
  18212. t.join();
  18213. ASSERT_FALSE(svr.is_running());
  18214. });
  18215. svr.wait_until_ready();
  18216. // Empty first field line, then a real one
  18217. std::string raw_req = "GET / HTTP/1.1\r\n"
  18218. "Host: localhost\r\n"
  18219. "Accept:\r\n"
  18220. "Accept: application/json\r\n"
  18221. "Connection: close\r\n"
  18222. "\r\n";
  18223. std::string out;
  18224. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18225. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18226. ASSERT_EQ(1U, observed_types.size());
  18227. EXPECT_EQ("application/json", observed_types[0]);
  18228. }
  18229. // The skip in get_combined_header_value() is what keeps an empty field line
  18230. // from contributing a bare comma. Only a trailing empty field line exercises
  18231. // it: a leading one is already covered by the "combined is still empty" check,
  18232. // and parse_accept_header() now ignores the empty element either way, so the
  18233. // request-level test above can no longer tell the two apart.
  18234. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18235. Headers headers;
  18236. headers.emplace("Accept", "text/html");
  18237. headers.emplace("Accept", "");
  18238. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18239. headers.clear();
  18240. headers.emplace("Accept", "");
  18241. headers.emplace("Accept", "application/json");
  18242. EXPECT_EQ("application/json",
  18243. detail::get_combined_header_value(headers, "Accept"));
  18244. }
  18245. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18246. // An encoding offered on a later Accept-Encoding field line is still offered.
  18247. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18248. Server svr;
  18249. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18250. res.set_content(std::string(1024, 'x'), "text/plain");
  18251. });
  18252. auto port = svr.bind_to_any_port(HOST);
  18253. thread t = thread([&]() { svr.listen_after_bind(); });
  18254. auto se = detail::scope_exit([&] {
  18255. svr.stop();
  18256. t.join();
  18257. ASSERT_FALSE(svr.is_running());
  18258. });
  18259. svr.wait_until_ready();
  18260. Client cli(HOST, port);
  18261. cli.set_decompress(false);
  18262. Headers headers;
  18263. headers.emplace("Accept-Encoding", "identity");
  18264. headers.emplace("Accept-Encoding", "gzip");
  18265. auto res = cli.Get("/", headers);
  18266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18267. EXPECT_EQ(StatusCode::OK_200, res->status);
  18268. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18269. }
  18270. #endif
  18271. #ifndef _WIN32
  18272. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18273. Server svr;
  18274. svr.Post("/post", [&](const Request &req, Response &res) {
  18275. res.set_content(req.body, "text/plain");
  18276. });
  18277. svr.Put("/put", [&](const Request &req, Response &res) {
  18278. res.set_content(req.body, "text/plain");
  18279. });
  18280. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18281. res.set_content(req.body, "text/plain");
  18282. });
  18283. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18284. res.set_content(req.body, "text/plain");
  18285. });
  18286. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18287. auto se = detail::scope_exit([&] {
  18288. svr.stop();
  18289. t.join();
  18290. ASSERT_FALSE(svr.is_running());
  18291. });
  18292. svr.wait_until_ready();
  18293. std::string resp;
  18294. // POST without Content-Length
  18295. ASSERT_TRUE(send_request(5,
  18296. "POST /post HTTP/1.1\r\n"
  18297. "Host: localhost\r\n"
  18298. "Connection: close\r\n"
  18299. "\r\n",
  18300. &resp));
  18301. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18302. // PUT without Content-Length
  18303. resp.clear();
  18304. ASSERT_TRUE(send_request(5,
  18305. "PUT /put HTTP/1.1\r\n"
  18306. "Host: localhost\r\n"
  18307. "Connection: close\r\n"
  18308. "\r\n",
  18309. &resp));
  18310. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18311. // PATCH without Content-Length
  18312. resp.clear();
  18313. ASSERT_TRUE(send_request(5,
  18314. "PATCH /patch HTTP/1.1\r\n"
  18315. "Host: localhost\r\n"
  18316. "Connection: close\r\n"
  18317. "\r\n",
  18318. &resp));
  18319. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18320. // DELETE without Content-Length
  18321. resp.clear();
  18322. ASSERT_TRUE(send_request(5,
  18323. "DELETE /delete HTTP/1.1\r\n"
  18324. "Host: localhost\r\n"
  18325. "Connection: close\r\n"
  18326. "\r\n",
  18327. &resp));
  18328. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18329. }
  18330. #endif
  18331. //==============================================================================
  18332. // open_stream() Tests
  18333. //==============================================================================
  18334. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18335. std::string result;
  18336. char buf[8192];
  18337. ssize_t n;
  18338. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18339. result.append(buf, static_cast<size_t>(n));
  18340. }
  18341. return result;
  18342. }
  18343. // Mock stream for unit tests
  18344. class MockStream : public Stream {
  18345. public:
  18346. std::string data;
  18347. size_t pos = 0;
  18348. ssize_t error_after = -1; // -1 = no error
  18349. explicit MockStream(const std::string &d, ssize_t err = -1)
  18350. : data(d), error_after(err) {}
  18351. bool is_readable() const override { return true; }
  18352. bool wait_readable() const override { return true; }
  18353. bool wait_writable() const override { return true; }
  18354. ssize_t read(char *ptr, size_t size) override {
  18355. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18356. if (pos >= data.size()) return 0;
  18357. size_t limit =
  18358. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18359. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18360. std::memcpy(ptr, data.data() + pos, to_read);
  18361. pos += to_read;
  18362. return static_cast<ssize_t>(to_read);
  18363. }
  18364. ssize_t write(const char *, size_t) override { return -1; }
  18365. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18366. ip = "127.0.0.1";
  18367. port = 0;
  18368. }
  18369. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18370. ip = "127.0.0.1";
  18371. port = 0;
  18372. }
  18373. socket_t socket() const override { return INVALID_SOCKET; }
  18374. time_t duration() const override { return 0; }
  18375. };
  18376. TEST(StreamHandleTest, Basic) {
  18377. ClientImpl::StreamHandle handle;
  18378. EXPECT_FALSE(handle.is_valid());
  18379. handle.response = detail::make_unique<Response>();
  18380. handle.error = Error::Connection;
  18381. EXPECT_FALSE(handle.is_valid());
  18382. handle.error = Error::Success;
  18383. EXPECT_TRUE(handle.is_valid());
  18384. }
  18385. TEST(BodyReaderTest, Basic) {
  18386. MockStream stream("Hello, World!");
  18387. detail::BodyReader reader;
  18388. reader.stream = &stream;
  18389. reader.content_length = 13;
  18390. char buf[32];
  18391. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18392. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18393. EXPECT_TRUE(reader.eof);
  18394. }
  18395. TEST(BodyReaderTest, NoStream) {
  18396. detail::BodyReader reader;
  18397. char buf[32];
  18398. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18399. EXPECT_EQ(Error::Connection, reader.last_error);
  18400. }
  18401. TEST(BodyReaderTest, Error) {
  18402. MockStream stream("Hello, World!", 5);
  18403. detail::BodyReader reader;
  18404. reader.stream = &stream;
  18405. reader.content_length = 13;
  18406. char buf[32];
  18407. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18408. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18409. EXPECT_EQ(Error::Read, reader.last_error);
  18410. }
  18411. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18412. // Mock-based StreamHandle tests relying on private internals are removed.
  18413. class OpenStreamTest : public ::testing::Test {
  18414. protected:
  18415. void SetUp() override {
  18416. svr_.Get("/hello", [](const Request &, Response &res) {
  18417. res.set_content("Hello World!", "text/plain");
  18418. });
  18419. svr_.Get("/large", [](const Request &, Response &res) {
  18420. res.set_content(std::string(10000, 'X'), "text/plain");
  18421. });
  18422. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18423. res.set_content("Hello World!", "image/jpeg");
  18424. res.set_header("Content-Encoding", "UTF-8");
  18425. });
  18426. svr_.Get("/chunked", [](const Request &, Response &res) {
  18427. res.set_chunked_content_provider("text/plain",
  18428. [](size_t offset, DataSink &sink) {
  18429. if (offset < 15) {
  18430. sink.write("chunk", 5);
  18431. return true;
  18432. }
  18433. sink.done();
  18434. return true;
  18435. });
  18436. });
  18437. svr_.Get("/compressible", [](const Request &, Response &res) {
  18438. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18439. DataSink &sink) {
  18440. if (offset < 100 * 1024) {
  18441. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18442. sink.write(chunk.data(), chunk.size());
  18443. return true;
  18444. }
  18445. sink.done();
  18446. return true;
  18447. });
  18448. });
  18449. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18450. [](const Request & /*req*/, Response &res) {
  18451. auto i = new int(0);
  18452. res.set_header("Trailer", "Content-Length, X-Allowed");
  18453. res.set_chunked_content_provider(
  18454. "text/plain",
  18455. [i](size_t /*offset*/, DataSink &sink) {
  18456. switch (*i) {
  18457. case 0: sink.os << "123"; break;
  18458. case 1: sink.os << "456"; break;
  18459. case 2: sink.os << "789"; break;
  18460. case 3: {
  18461. sink.done_with_trailer(
  18462. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18463. } break;
  18464. }
  18465. (*i)++;
  18466. return true;
  18467. },
  18468. [i](bool success) {
  18469. EXPECT_TRUE(success);
  18470. delete i;
  18471. });
  18472. });
  18473. // Echo headers endpoint for header-related tests
  18474. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18475. std::string body;
  18476. for (const auto &h : req.headers) {
  18477. body.append(h.first);
  18478. body.push_back(':');
  18479. body.append(h.second);
  18480. body.push_back('\n');
  18481. }
  18482. res.set_content(body, "text/plain");
  18483. });
  18484. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18485. std::string body;
  18486. for (const auto &h : req.headers) {
  18487. body.append(h.first);
  18488. body.push_back(':');
  18489. body.append(h.second);
  18490. body.push_back('\n');
  18491. }
  18492. res.set_content(body, "text/plain");
  18493. });
  18494. port_ = svr_.bind_to_any_port("127.0.0.1");
  18495. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18496. svr_.wait_until_ready();
  18497. }
  18498. void TearDown() override {
  18499. svr_.stop();
  18500. if (thread_.joinable()) thread_.join();
  18501. }
  18502. Server svr_;
  18503. std::thread thread_;
  18504. int port_ = 0;
  18505. };
  18506. TEST_F(OpenStreamTest, Basic) {
  18507. Client cli("127.0.0.1", port_);
  18508. auto handle = cli.open_stream("GET", "/hello");
  18509. EXPECT_TRUE(handle.is_valid());
  18510. EXPECT_EQ("Hello World!", read_all(handle));
  18511. }
  18512. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18513. Client cli("127.0.0.1", port_);
  18514. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18515. ASSERT_TRUE(handle.is_valid());
  18516. EXPECT_EQ("Hello World!", read_all(handle));
  18517. }
  18518. TEST_F(OpenStreamTest, SmallBuffer) {
  18519. Client cli("127.0.0.1", port_);
  18520. auto handle = cli.open_stream("GET", "/hello");
  18521. std::string result;
  18522. char buf[4];
  18523. ssize_t n;
  18524. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18525. result.append(buf, static_cast<size_t>(n));
  18526. EXPECT_EQ("Hello World!", result);
  18527. }
  18528. TEST_F(OpenStreamTest, DefaultHeaders) {
  18529. Client cli("127.0.0.1", port_);
  18530. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18531. {
  18532. auto handle = cli.open_stream("GET", "/echo-headers");
  18533. ASSERT_TRUE(handle.is_valid());
  18534. auto body = read_all(handle);
  18535. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18536. std::string::npos);
  18537. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18538. std::string::npos);
  18539. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18540. }
  18541. // open_stream POST with body and no explicit content_type should NOT add
  18542. // text/plain Content-Type (behavior differs from non-streaming path), but
  18543. // should include Content-Length
  18544. {
  18545. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18546. ASSERT_TRUE(handle.is_valid());
  18547. auto body = read_all(handle);
  18548. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18549. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18550. }
  18551. // open_stream POST with explicit Content-Type should preserve it
  18552. {
  18553. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18554. {{"Content-Type", "application/custom"}},
  18555. "{}", "application/custom");
  18556. ASSERT_TRUE(handle.is_valid());
  18557. auto body = read_all(handle);
  18558. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18559. }
  18560. // User-specified User-Agent must not be overwritten for stream API
  18561. {
  18562. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18563. {{"User-Agent", "MyAgent/1.2"}});
  18564. ASSERT_TRUE(handle.is_valid());
  18565. auto body = read_all(handle);
  18566. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18567. }
  18568. }
  18569. TEST_F(OpenStreamTest, Large) {
  18570. Client cli("127.0.0.1", port_);
  18571. auto handle = cli.open_stream("GET", "/large");
  18572. EXPECT_EQ(10000u, read_all(handle).size());
  18573. }
  18574. TEST_F(OpenStreamTest, ConnectionError) {
  18575. Client cli("127.0.0.1", 9999);
  18576. auto handle = cli.open_stream("GET", "/hello");
  18577. EXPECT_FALSE(handle.is_valid());
  18578. }
  18579. TEST_F(OpenStreamTest, Chunked) {
  18580. Client cli("127.0.0.1", port_);
  18581. auto handle = cli.open_stream("GET", "/chunked");
  18582. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18583. "Transfer-Encoding") == "chunked");
  18584. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18585. }
  18586. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18587. Client cli("127.0.0.1", port_);
  18588. auto handle =
  18589. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18590. ASSERT_TRUE(handle.is_valid());
  18591. // Consume body to allow trailers to be received/parsed
  18592. auto body = read_all(handle);
  18593. // Explicitly parse trailers (ensure trailers are available for assertion)
  18594. handle.parse_trailers_if_needed();
  18595. EXPECT_EQ(std::string("123456789"), body);
  18596. // The response should include a Trailer header declaring both names
  18597. ASSERT_TRUE(handle.response);
  18598. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18599. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18600. handle.response->get_header_value("Trailer"));
  18601. // Prohibited trailer must not be present
  18602. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18603. // Allowed trailer should be present
  18604. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18605. EXPECT_EQ(std::string("yes"),
  18606. handle.response->get_trailer_value("X-Allowed"));
  18607. // Verify trailers are NOT present as regular headers
  18608. EXPECT_EQ(std::string(""),
  18609. handle.response->get_header_value("Content-Length"));
  18610. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18611. }
  18612. static std::thread serve_single_response(std::promise<int> &port_promise,
  18613. const std::string &response) {
  18614. return std::thread([&port_promise, response] {
  18615. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18616. default_socket_options(srv);
  18617. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18618. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18619. sockaddr_in addr{};
  18620. addr.sin_family = AF_INET;
  18621. addr.sin_port = htons(0); // Let OS assign a free port
  18622. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18623. int opt = 1;
  18624. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18625. #ifdef _WIN32
  18626. reinterpret_cast<const char *>(&opt),
  18627. #else
  18628. &opt,
  18629. #endif
  18630. sizeof(opt));
  18631. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18632. ::listen(srv, 1) != 0) {
  18633. port_promise.set_value(-1);
  18634. detail::close_socket(srv);
  18635. return;
  18636. }
  18637. socklen_t addr_len = sizeof(addr);
  18638. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18639. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18640. sockaddr_in cli_addr{};
  18641. socklen_t cli_len = sizeof(cli_addr);
  18642. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18643. if (cli != INVALID_SOCKET) {
  18644. // Read the complete HTTP request (until the blank line that terminates
  18645. // headers) before sending the response. If the server closes the socket
  18646. // while the client's request data is still unread in the kernel receive
  18647. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18648. // connection on both sides: it discards the client's receive buffer
  18649. // (which already holds our response) and causes any in-progress write on
  18650. // the client to fail with ECONNRESET. Reading all request data first
  18651. // ensures close() emits a graceful FIN.
  18652. {
  18653. char rbuf[256];
  18654. std::string req;
  18655. while (req.find("\r\n\r\n") == std::string::npos) {
  18656. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18657. if (n <= 0) { break; }
  18658. req.append(rbuf, static_cast<size_t>(n));
  18659. }
  18660. }
  18661. ::send(cli,
  18662. #ifdef _WIN32
  18663. static_cast<const char *>(response.c_str()),
  18664. static_cast<int>(response.size()),
  18665. #else
  18666. response.c_str(), response.size(),
  18667. #endif
  18668. 0);
  18669. detail::close_socket(cli);
  18670. }
  18671. detail::close_socket(srv);
  18672. });
  18673. }
  18674. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18675. #ifndef _WIN32
  18676. signal(SIGPIPE, SIG_IGN);
  18677. #endif
  18678. std::promise<int> port_promise;
  18679. auto port_future = port_promise.get_future();
  18680. auto server_thread =
  18681. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18682. "Content-Type: text/plain\r\n"
  18683. "Content-Length: not-a-number\r\n"
  18684. "Connection: close\r\n"
  18685. "\r\n"
  18686. "hello");
  18687. auto port = port_future.get();
  18688. ASSERT_GT(port, 0);
  18689. Client cli("127.0.0.1", port);
  18690. auto handle = cli.open_stream("GET", "/");
  18691. EXPECT_FALSE(handle.is_valid());
  18692. server_thread.join();
  18693. }
  18694. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18695. #ifndef _WIN32
  18696. signal(SIGPIPE, SIG_IGN);
  18697. #endif
  18698. std::promise<int> port_promise;
  18699. auto port_future = port_promise.get_future();
  18700. auto server_thread = serve_single_response(
  18701. port_promise, "HTTP/1.1 200 OK\r\n"
  18702. "Content-Type: text/plain\r\n"
  18703. "Content-Length: 99999999999999999999999999\r\n"
  18704. "Connection: close\r\n"
  18705. "\r\n"
  18706. "hello");
  18707. auto port = port_future.get();
  18708. ASSERT_GT(port, 0);
  18709. // Historically std::stoull would throw std::out_of_range here and crash
  18710. // the process, then parsing silently clamped to a bogus framing length and
  18711. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18712. // so the stream fails to open, matching the not-a-number case above. The
  18713. // process still must NOT terminate.
  18714. Client cli("127.0.0.1", port);
  18715. auto handle = cli.open_stream("GET", "/");
  18716. EXPECT_FALSE(handle.is_valid());
  18717. server_thread.join();
  18718. }
  18719. // Serves `response` to the single request `fn` makes with a fresh client.
  18720. template <typename Fn>
  18721. static void with_single_response(const std::string &response, Fn fn) {
  18722. #ifndef _WIN32
  18723. signal(SIGPIPE, SIG_IGN);
  18724. #endif
  18725. std::promise<int> port_promise;
  18726. auto port_future = port_promise.get_future();
  18727. auto server_thread = serve_single_response(port_promise, response);
  18728. auto se = detail::scope_exit([&] { server_thread.join(); });
  18729. auto port = port_future.get();
  18730. ASSERT_GT(port, 0);
  18731. Client cli("127.0.0.1", port);
  18732. fn(cli);
  18733. }
  18734. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18735. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18736. // the chunked coding and drop Content-Length, so a front-end that trusts
  18737. // Content-Length would disagree about where the body ends (response
  18738. // smuggling). The client must reject such a response.
  18739. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18740. for (const char *te : {"chunked", "gzip, chunked"}) {
  18741. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18742. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18743. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18744. "5\r\nhello\r\n0\r\n\r\n";
  18745. with_single_response(response, [&](Client &cli) {
  18746. auto res = cli.Get("/");
  18747. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18748. EXPECT_EQ(Error::Read, res.error()) << te;
  18749. });
  18750. with_single_response(response, [&](Client &cli) {
  18751. auto handle = cli.open_stream("GET", "/");
  18752. EXPECT_FALSE(handle.is_valid()) << te;
  18753. EXPECT_EQ(Error::Read, handle.error) << te;
  18754. });
  18755. }
  18756. }
  18757. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18758. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18759. // closing the connection (unlike a request, which must be rejected).
  18760. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18761. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18762. "Transfer-Encoding: chunked\r\n"
  18763. "Connection: close\r\n"
  18764. "\r\n"
  18765. "5\r\nhello\r\n0\r\n\r\n",
  18766. "HTTP/1.1 200 OK\r\n"
  18767. "Transfer-Encoding: gzip\r\n"
  18768. "Connection: close\r\n"
  18769. "\r\n"
  18770. "hello"}) {
  18771. with_single_response(response, [&](Client &cli) {
  18772. auto res = cli.Get("/");
  18773. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18774. EXPECT_EQ("hello", res->body);
  18775. });
  18776. with_single_response(response, [&](Client &cli) {
  18777. auto handle = cli.open_stream("GET", "/");
  18778. ASSERT_TRUE(handle.is_valid()) << response;
  18779. EXPECT_EQ("hello", read_all(handle));
  18780. });
  18781. }
  18782. }
  18783. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18784. // framing headers describe nothing to read and must not be rejected.
  18785. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18786. const std::string framing = "Content-Length: 5\r\n"
  18787. "Transfer-Encoding: chunked\r\n"
  18788. "Connection: close\r\n"
  18789. "\r\n";
  18790. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18791. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18792. });
  18793. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18794. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18795. });
  18796. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18797. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18798. with_single_response(response, [&](Client &cli) {
  18799. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18800. });
  18801. with_single_response(response, [&](Client &cli) {
  18802. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18803. });
  18804. }
  18805. }
  18806. // A payload max length of 0 means no limit, however the body is framed.
  18807. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18808. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18809. "Transfer-Encoding: chunked\r\n"
  18810. "\r\n"
  18811. "5\r\nhello\r\n0\r\n\r\n",
  18812. "HTTP/1.1 200 OK\r\n"
  18813. "Connection: close\r\n"
  18814. "\r\n"
  18815. "hello"}) {
  18816. with_single_response(response, [&](Client &cli) {
  18817. cli.set_payload_max_length(0);
  18818. auto res = cli.Get("/");
  18819. ASSERT_TRUE(res) << response;
  18820. EXPECT_EQ("hello", res->body) << response;
  18821. });
  18822. }
  18823. }
  18824. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18825. Server svr;
  18826. svr.set_payload_max_length(0);
  18827. svr.Post("/echo", [](const Request &req, Response &res) {
  18828. res.set_content(req.body, "text/plain");
  18829. });
  18830. auto port = svr.bind_to_any_port(HOST);
  18831. thread t = thread([&] { svr.listen_after_bind(); });
  18832. auto se = detail::scope_exit([&] {
  18833. svr.stop();
  18834. t.join();
  18835. ASSERT_FALSE(svr.is_running());
  18836. });
  18837. svr.wait_until_ready();
  18838. Client cli(HOST, port);
  18839. auto res = cli.Post(
  18840. "/echo",
  18841. [](size_t /*offset*/, DataSink &sink) {
  18842. sink.write("hello", 5);
  18843. sink.done();
  18844. return true;
  18845. },
  18846. "text/plain");
  18847. ASSERT_TRUE(res);
  18848. EXPECT_EQ(StatusCode::OK_200, res->status);
  18849. EXPECT_EQ("hello", res->body);
  18850. }
  18851. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18852. TEST_F(OpenStreamTest, Gzip) {
  18853. Client cli("127.0.0.1", port_);
  18854. auto handle = cli.open_stream("GET", "/compressible", {},
  18855. {{"Accept-Encoding", "gzip"}});
  18856. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18857. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18858. }
  18859. #endif
  18860. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18861. TEST_F(OpenStreamTest, Brotli) {
  18862. Client cli("127.0.0.1", port_);
  18863. auto handle =
  18864. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18865. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18866. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18867. }
  18868. #endif
  18869. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18870. TEST_F(OpenStreamTest, Zstd) {
  18871. Client cli("127.0.0.1", port_);
  18872. auto handle = cli.open_stream("GET", "/compressible", {},
  18873. {{"Accept-Encoding", "zstd"}});
  18874. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18875. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18876. }
  18877. #endif
  18878. #ifdef CPPHTTPLIB_SSL_ENABLED
  18879. class SSLOpenStreamTest : public ::testing::Test {
  18880. protected:
  18881. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18882. void SetUp() override {
  18883. svr_.Get("/hello", [](const Request &, Response &res) {
  18884. res.set_content("Hello SSL World!", "text/plain");
  18885. });
  18886. svr_.Get("/chunked", [](const Request &, Response &res) {
  18887. res.set_chunked_content_provider("text/plain",
  18888. [](size_t offset, DataSink &sink) {
  18889. if (offset < 15) {
  18890. sink.write("chunk", 5);
  18891. return true;
  18892. }
  18893. sink.done();
  18894. return true;
  18895. });
  18896. });
  18897. svr_.Post("/echo", [](const Request &req, Response &res) {
  18898. res.set_content(req.body, req.get_header_value("Content-Type"));
  18899. });
  18900. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18901. std::string body = req.body;
  18902. res.set_chunked_content_provider(
  18903. "text/plain", [body](size_t offset, DataSink &sink) {
  18904. if (offset < body.size()) {
  18905. sink.write(body.data() + offset, body.size() - offset);
  18906. }
  18907. sink.done();
  18908. return true;
  18909. });
  18910. });
  18911. port_ = svr_.bind_to_any_port("127.0.0.1");
  18912. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18913. svr_.wait_until_ready();
  18914. }
  18915. void TearDown() override {
  18916. svr_.stop();
  18917. if (thread_.joinable()) thread_.join();
  18918. }
  18919. SSLServer svr_;
  18920. std::thread thread_;
  18921. int port_ = 0;
  18922. };
  18923. TEST_F(SSLOpenStreamTest, Basic) {
  18924. SSLClient cli("127.0.0.1", port_);
  18925. cli.enable_server_certificate_verification(false);
  18926. auto handle = cli.open_stream("GET", "/hello");
  18927. ASSERT_TRUE(handle.is_valid());
  18928. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18929. }
  18930. TEST_F(SSLOpenStreamTest, Chunked) {
  18931. SSLClient cli("127.0.0.1", port_);
  18932. cli.enable_server_certificate_verification(false);
  18933. auto handle = cli.open_stream("GET", "/chunked");
  18934. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18935. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18936. "Transfer-Encoding") == "chunked");
  18937. auto body = read_all(handle);
  18938. EXPECT_EQ("chunkchunkchunk", body);
  18939. }
  18940. TEST_F(SSLOpenStreamTest, Post) {
  18941. SSLClient cli("127.0.0.1", port_);
  18942. cli.enable_server_certificate_verification(false);
  18943. auto handle =
  18944. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18945. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18946. EXPECT_EQ(200, handle.response->status);
  18947. auto body = read_all(handle);
  18948. EXPECT_EQ("Hello SSL POST", body);
  18949. }
  18950. TEST_F(SSLOpenStreamTest, PostChunked) {
  18951. SSLClient cli("127.0.0.1", port_);
  18952. cli.enable_server_certificate_verification(false);
  18953. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18954. "Chunked SSL Data", "text/plain");
  18955. ASSERT_TRUE(handle.is_valid());
  18956. EXPECT_EQ(200, handle.response->status);
  18957. auto body = read_all(handle);
  18958. EXPECT_EQ("Chunked SSL Data", body);
  18959. }
  18960. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18961. // Content-Length is terminated by the server closing the connection. When the
  18962. // SSL peer sends a close_notify after the body, the client must treat it as a
  18963. // clean EOF and return a successful response rather than an error.
  18964. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18965. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18966. ASSERT_TRUE(svr.is_valid());
  18967. svr.set_keep_alive_max_count(1);
  18968. const std::string expected_body = "Hello from connection-close response!";
  18969. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18970. res.set_content_provider("text/plain",
  18971. [&](size_t offset, DataSink &sink) -> bool {
  18972. if (offset < expected_body.size()) {
  18973. sink.write(expected_body.data() + offset,
  18974. expected_body.size() - offset);
  18975. }
  18976. sink.done();
  18977. return true;
  18978. });
  18979. });
  18980. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18981. auto se = detail::scope_exit([&] {
  18982. svr.stop();
  18983. listen_thread.join();
  18984. ASSERT_FALSE(svr.is_running());
  18985. });
  18986. svr.wait_until_ready();
  18987. SSLClient cli(HOST, PORT);
  18988. cli.enable_server_certificate_verification(false);
  18989. auto res = cli.Get("/no-content-length");
  18990. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18991. EXPECT_EQ(StatusCode::OK_200, res->status);
  18992. EXPECT_EQ(expected_body, res->body);
  18993. }
  18994. #endif // CPPHTTPLIB_SSL_ENABLED
  18995. //==============================================================================
  18996. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18997. // results for various scenarios.
  18998. //==============================================================================
  18999. TEST(ParityTest, GetVsOpenStream) {
  19000. Server svr;
  19001. const std::string path = "/parity";
  19002. const std::string content = "Parity test content: hello world";
  19003. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19004. res.set_content(content, "text/plain");
  19005. });
  19006. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19007. auto se = detail::scope_exit([&] {
  19008. svr.stop();
  19009. t.join();
  19010. ASSERT_FALSE(svr.is_running());
  19011. });
  19012. svr.wait_until_ready();
  19013. Client cli(HOST, PORT);
  19014. // Non-stream path
  19015. auto r1 = cli.Get(path);
  19016. ASSERT_TRUE(r1);
  19017. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19018. // Stream path
  19019. auto h = cli.open_stream("GET", path);
  19020. ASSERT_TRUE(h.is_valid());
  19021. EXPECT_EQ(r1->body, read_all(h));
  19022. }
  19023. // Helper to compress data with provided compressor type T
  19024. template <typename Compressor>
  19025. static std::string compress_payload_for_parity(const std::string &in) {
  19026. std::string out;
  19027. Compressor compressor;
  19028. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19029. [&](const char *data, size_t n) {
  19030. out.append(data, n);
  19031. return true;
  19032. });
  19033. EXPECT_TRUE(ok);
  19034. return out;
  19035. }
  19036. // Helper function for compression parity tests
  19037. template <typename Compressor>
  19038. static void test_compression_parity(const std::string &original,
  19039. const std::string &path,
  19040. const std::string &encoding) {
  19041. const std::string compressed =
  19042. compress_payload_for_parity<Compressor>(original);
  19043. Server svr;
  19044. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19045. res.set_content(compressed, "application/octet-stream");
  19046. res.set_header("Content-Encoding", encoding);
  19047. });
  19048. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19049. auto se = detail::scope_exit([&] {
  19050. svr.stop();
  19051. t.join();
  19052. ASSERT_FALSE(svr.is_running());
  19053. });
  19054. svr.wait_until_ready();
  19055. Client cli(HOST, PORT);
  19056. // Non-streaming
  19057. {
  19058. auto res = cli.Get(path);
  19059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19060. EXPECT_EQ(StatusCode::OK_200, res->status);
  19061. EXPECT_EQ(original, res->body);
  19062. }
  19063. // Streaming
  19064. {
  19065. auto h = cli.open_stream("GET", path);
  19066. ASSERT_TRUE(h.is_valid());
  19067. EXPECT_EQ(original, read_all(h));
  19068. }
  19069. }
  19070. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19071. TEST(ParityTest, Gzip) {
  19072. test_compression_parity<detail::gzip_compressor>(
  19073. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19074. }
  19075. #endif
  19076. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19077. TEST(ParityTest, Brotli) {
  19078. test_compression_parity<detail::brotli_compressor>(
  19079. "Hello, brotli parity test payload", "/parity-br", "br");
  19080. }
  19081. #endif
  19082. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19083. TEST(ParityTest, Zstd) {
  19084. test_compression_parity<detail::zstd_compressor>(
  19085. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19086. }
  19087. #endif
  19088. //==============================================================================
  19089. // New Stream API Tests
  19090. //==============================================================================
  19091. inline std::string read_body(httplib::stream::Result &result) {
  19092. std::string body;
  19093. while (result.next()) {
  19094. body.append(result.data(), result.size());
  19095. }
  19096. return body;
  19097. }
  19098. TEST(ClientConnectionTest, Basic) {
  19099. httplib::ClientConnection conn;
  19100. EXPECT_FALSE(conn.is_open());
  19101. conn.sock = 1;
  19102. EXPECT_TRUE(conn.is_open());
  19103. httplib::ClientConnection conn2(std::move(conn));
  19104. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19105. conn2.sock = INVALID_SOCKET;
  19106. }
  19107. // Unified test server for all stream::* tests
  19108. class StreamApiTest : public ::testing::Test {
  19109. protected:
  19110. void SetUp() override {
  19111. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19112. res.set_content("Hello World!", "text/plain");
  19113. });
  19114. svr_.Get("/echo-params",
  19115. [](const httplib::Request &req, httplib::Response &res) {
  19116. std::string r;
  19117. for (const auto &p : req.params) {
  19118. if (!r.empty()) r += "&";
  19119. r += p.first + "=" + p.second;
  19120. }
  19121. res.set_content(r, "text/plain");
  19122. });
  19123. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19124. res.set_content(req.body, req.get_header_value("Content-Type"));
  19125. });
  19126. svr_.Post("/echo-headers",
  19127. [](const httplib::Request &req, httplib::Response &res) {
  19128. std::string r;
  19129. for (const auto &h : req.headers)
  19130. r += h.first + ": " + h.second + "\n";
  19131. res.set_content(r, "text/plain");
  19132. });
  19133. svr_.Post("/echo-params",
  19134. [](const httplib::Request &req, httplib::Response &res) {
  19135. std::string r = "params:";
  19136. for (const auto &p : req.params)
  19137. r += p.first + "=" + p.second + ";";
  19138. res.set_content(r + " body:" + req.body, "text/plain");
  19139. });
  19140. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19141. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19142. });
  19143. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19144. res.set_content("PUT:" + req.body, "text/plain");
  19145. });
  19146. svr_.Patch("/echo",
  19147. [](const httplib::Request &req, httplib::Response &res) {
  19148. res.set_content("PATCH:" + req.body, "text/plain");
  19149. });
  19150. svr_.Delete(
  19151. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19152. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19153. "text/plain");
  19154. });
  19155. svr_.Get("/head-test",
  19156. [](const httplib::Request &, httplib::Response &res) {
  19157. res.set_content("body for HEAD", "text/plain");
  19158. });
  19159. svr_.Options("/options",
  19160. [](const httplib::Request &, httplib::Response &res) {
  19161. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19162. });
  19163. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19164. svr_.wait_until_ready();
  19165. }
  19166. void TearDown() override {
  19167. svr_.stop();
  19168. if (thread_.joinable()) thread_.join();
  19169. }
  19170. httplib::Server svr_;
  19171. std::thread thread_;
  19172. };
  19173. // stream::Get tests
  19174. TEST_F(StreamApiTest, GetBasic) {
  19175. httplib::Client cli(HOST, PORT);
  19176. auto result = httplib::stream::Get(cli, "/hello");
  19177. ASSERT_TRUE(result.is_valid());
  19178. EXPECT_EQ(200, result.status());
  19179. EXPECT_EQ("Hello World!", read_body(result));
  19180. }
  19181. TEST_F(StreamApiTest, GetWithParams) {
  19182. httplib::Client cli(HOST, PORT);
  19183. httplib::Params params{{"foo", "bar"}};
  19184. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19185. ASSERT_TRUE(result.is_valid());
  19186. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19187. }
  19188. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19189. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19190. httplib::Client cli(HOST, PORT);
  19191. cli.set_payload_max_length(0);
  19192. auto result = httplib::stream::Get(cli, "/hello");
  19193. ASSERT_TRUE(result.is_valid());
  19194. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19195. EXPECT_EQ("Hello World!", read_body(result));
  19196. }
  19197. #endif
  19198. TEST_F(StreamApiTest, GetConnectionError) {
  19199. httplib::Client cli(HOST, 9999);
  19200. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19201. }
  19202. TEST_F(StreamApiTest, Get404) {
  19203. httplib::Client cli(HOST, PORT);
  19204. auto result = httplib::stream::Get(cli, "/nonexistent");
  19205. EXPECT_TRUE(result.is_valid());
  19206. EXPECT_EQ(404, result.status());
  19207. }
  19208. // stream::Post tests
  19209. TEST_F(StreamApiTest, PostBasic) {
  19210. httplib::Client cli(HOST, PORT);
  19211. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19212. "application/json");
  19213. ASSERT_TRUE(result.is_valid());
  19214. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19215. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19216. }
  19217. TEST_F(StreamApiTest, PostWithHeaders) {
  19218. httplib::Client cli(HOST, PORT);
  19219. httplib::Headers headers{{"X-Custom", "value"}};
  19220. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19221. "text/plain");
  19222. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19223. }
  19224. TEST_F(StreamApiTest, PostWithParams) {
  19225. httplib::Client cli(HOST, PORT);
  19226. httplib::Params params{{"k", "v"}};
  19227. auto result =
  19228. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19229. auto body = read_body(result);
  19230. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19231. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19232. }
  19233. TEST_F(StreamApiTest, PostLarge) {
  19234. httplib::Client cli(HOST, PORT);
  19235. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19236. size_t total = 0;
  19237. while (result.next()) {
  19238. total += result.size();
  19239. }
  19240. EXPECT_EQ(100u * 1024u, total);
  19241. }
  19242. // stream::Put/Patch tests
  19243. TEST_F(StreamApiTest, PutAndPatch) {
  19244. httplib::Client cli(HOST, PORT);
  19245. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19246. EXPECT_EQ("PUT:test", read_body(put));
  19247. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19248. EXPECT_EQ("PATCH:test", read_body(patch));
  19249. }
  19250. // stream::Delete tests
  19251. TEST_F(StreamApiTest, Delete) {
  19252. httplib::Client cli(HOST, PORT);
  19253. auto del1 = httplib::stream::Delete(cli, "/resource");
  19254. EXPECT_EQ("Deleted", read_body(del1));
  19255. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19256. EXPECT_EQ("Deleted:data", read_body(del2));
  19257. }
  19258. // stream::Head/Options tests
  19259. TEST_F(StreamApiTest, HeadAndOptions) {
  19260. httplib::Client cli(HOST, PORT);
  19261. auto head = httplib::stream::Head(cli, "/head-test");
  19262. EXPECT_TRUE(head.is_valid());
  19263. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19264. auto opts = httplib::stream::Options(cli, "/options");
  19265. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19266. }
  19267. // SSL stream::* tests
  19268. #ifdef CPPHTTPLIB_SSL_ENABLED
  19269. class SSLStreamApiTest : public ::testing::Test {
  19270. protected:
  19271. void SetUp() override {
  19272. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19273. res.set_content("Hello SSL!", "text/plain");
  19274. });
  19275. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19276. res.set_content(req.body, "text/plain");
  19277. });
  19278. port_ = svr_.bind_to_any_port("127.0.0.1");
  19279. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19280. svr_.wait_until_ready();
  19281. }
  19282. void TearDown() override {
  19283. svr_.stop();
  19284. if (thread_.joinable()) thread_.join();
  19285. }
  19286. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19287. std::thread thread_;
  19288. int port_ = 0;
  19289. };
  19290. TEST_F(SSLStreamApiTest, GetAndPost) {
  19291. httplib::SSLClient cli("127.0.0.1", port_);
  19292. cli.enable_server_certificate_verification(false);
  19293. auto get = httplib::stream::Get(cli, "/hello");
  19294. EXPECT_EQ("Hello SSL!", read_body(get));
  19295. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19296. EXPECT_EQ("test", read_body(post));
  19297. }
  19298. #endif
  19299. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19300. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19301. // BodyReader
  19302. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19303. // Test that read timeout during streaming is detected
  19304. // Use a large content-length response where server delays mid-stream
  19305. Server svr;
  19306. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19307. // Send a large response with delay in the middle
  19308. res.set_content_provider(
  19309. 1000, // content_length
  19310. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19311. if (offset < 100) {
  19312. // Send first 100 bytes immediately
  19313. std::string data(100, 'A');
  19314. sink.write(data.c_str(), data.size());
  19315. return true;
  19316. }
  19317. // Then delay longer than client timeout
  19318. std::this_thread::sleep_for(std::chrono::seconds(3));
  19319. std::string data(900, 'B');
  19320. sink.write(data.c_str(), data.size());
  19321. return true;
  19322. });
  19323. });
  19324. auto port = 8091;
  19325. std::thread t([&]() { svr.listen("localhost", port); });
  19326. svr.wait_until_ready();
  19327. Client cli("localhost", port);
  19328. cli.set_read_timeout(1, 0); // 1 second timeout
  19329. auto handle = cli.open_stream("GET", "/slow-stream");
  19330. ASSERT_TRUE(handle.is_valid());
  19331. char buf[256];
  19332. ssize_t total = 0;
  19333. ssize_t n;
  19334. bool got_error = false;
  19335. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19336. total += n;
  19337. }
  19338. if (n < 0) {
  19339. got_error = true;
  19340. // Should be timeout or read error
  19341. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19342. handle.get_read_error() == Error::Read)
  19343. << "Actual error: " << to_string(handle.get_read_error());
  19344. }
  19345. // Either we got an error, or we got less data than expected
  19346. EXPECT_TRUE(got_error || total < 1000)
  19347. << "Expected timeout but got all " << total << " bytes";
  19348. svr.stop();
  19349. t.join();
  19350. }
  19351. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19352. // Test connection closed detection via BodyReader
  19353. Server svr;
  19354. std::atomic<bool> close_now{false};
  19355. svr.Get("/will-close", [&](const Request &, Response &res) {
  19356. res.set_content_provider(
  19357. 10000, // Large content_length that we won't fully send
  19358. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19359. if (offset < 100) {
  19360. std::string data(100, 'X');
  19361. sink.write(data.c_str(), data.size());
  19362. return true;
  19363. }
  19364. // Wait for signal then abort
  19365. while (!close_now) {
  19366. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19367. }
  19368. return false; // Abort - server will close connection
  19369. });
  19370. });
  19371. auto port = 8092;
  19372. std::thread t([&]() { svr.listen("localhost", port); });
  19373. svr.wait_until_ready();
  19374. Client cli("localhost", port);
  19375. auto handle = cli.open_stream("GET", "/will-close");
  19376. ASSERT_TRUE(handle.is_valid());
  19377. char buf[256];
  19378. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19379. EXPECT_GT(n, 0) << "First read should succeed";
  19380. // Signal server to close
  19381. close_now = true;
  19382. // Keep reading until error or EOF
  19383. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19384. // Keep reading
  19385. }
  19386. // Should get an error since content_length wasn't satisfied
  19387. if (n < 0) {
  19388. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19389. handle.get_read_error() == Error::Read)
  19390. << "Actual error: " << to_string(handle.get_read_error());
  19391. }
  19392. svr.stop();
  19393. t.join();
  19394. }
  19395. #ifdef CPPHTTPLIB_SSL_ENABLED
  19396. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19397. // Test that read timeout during SSL streaming is detected
  19398. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19399. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19400. res.set_content_provider(
  19401. 1000, "text/plain",
  19402. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19403. if (offset < 100) {
  19404. std::string data(100, 'A');
  19405. sink.write(data.c_str(), data.size());
  19406. return true;
  19407. }
  19408. std::this_thread::sleep_for(std::chrono::seconds(3));
  19409. std::string data(900, 'B');
  19410. sink.write(data.c_str(), data.size());
  19411. return true;
  19412. });
  19413. });
  19414. auto port = 8093;
  19415. std::thread t([&]() { svr.listen("localhost", port); });
  19416. svr.wait_until_ready();
  19417. SSLClient cli("localhost", port);
  19418. cli.enable_server_certificate_verification(false);
  19419. cli.set_read_timeout(1, 0); // 1 second timeout
  19420. auto handle = cli.open_stream("GET", "/slow-stream");
  19421. ASSERT_TRUE(handle.is_valid());
  19422. char buf[256];
  19423. ssize_t total = 0;
  19424. ssize_t n;
  19425. bool got_error = false;
  19426. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19427. total += n;
  19428. }
  19429. if (n < 0) {
  19430. got_error = true;
  19431. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19432. handle.get_read_error() == Error::Read)
  19433. << "Actual error: " << to_string(handle.get_read_error());
  19434. }
  19435. EXPECT_TRUE(got_error || total < 1000)
  19436. << "Expected timeout but got all " << total << " bytes";
  19437. svr.stop();
  19438. t.join();
  19439. }
  19440. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19441. // Test SSL connection closed detection
  19442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19443. std::atomic<bool> close_now{false};
  19444. svr.Get("/will-close", [&](const Request &, Response &res) {
  19445. res.set_content_provider(
  19446. 10000, "text/plain",
  19447. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19448. if (offset < 100) {
  19449. std::string data(100, 'X');
  19450. sink.write(data.c_str(), data.size());
  19451. return true;
  19452. }
  19453. while (!close_now) {
  19454. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19455. }
  19456. return false;
  19457. });
  19458. });
  19459. auto port = 8094;
  19460. std::thread t([&]() { svr.listen("localhost", port); });
  19461. svr.wait_until_ready();
  19462. SSLClient cli("localhost", port);
  19463. cli.enable_server_certificate_verification(false);
  19464. auto handle = cli.open_stream("GET", "/will-close");
  19465. ASSERT_TRUE(handle.is_valid());
  19466. char buf[256];
  19467. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19468. EXPECT_GT(n, 0);
  19469. // Signal server to close
  19470. close_now = true;
  19471. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19472. // Keep reading
  19473. }
  19474. if (n < 0) {
  19475. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19476. handle.get_read_error() == Error::Read)
  19477. << "Actual error: " << to_string(handle.get_read_error());
  19478. }
  19479. svr.stop();
  19480. t.join();
  19481. }
  19482. #endif
  19483. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19484. using namespace httplib;
  19485. // Create a test file
  19486. const char *fname = "etag_testfile.txt";
  19487. const char *content = "etag-content";
  19488. {
  19489. std::ofstream ofs(fname);
  19490. ofs << content;
  19491. ASSERT_TRUE(ofs.good());
  19492. }
  19493. Server svr;
  19494. svr.set_mount_point("/static", ".");
  19495. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19496. svr.wait_until_ready();
  19497. Client cli(HOST, PORT);
  19498. // First request: should get 200 with ETag header
  19499. auto res1 = cli.Get("/static/etag_testfile.txt");
  19500. ASSERT_TRUE(res1);
  19501. ASSERT_EQ(200, res1->status);
  19502. ASSERT_TRUE(res1->has_header("ETag"));
  19503. std::string etag = res1->get_header_value("ETag");
  19504. EXPECT_FALSE(etag.empty());
  19505. // Verify ETag format: W/"hex-hex"
  19506. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19507. EXPECT_EQ('W', etag[0]);
  19508. EXPECT_EQ('/', etag[1]);
  19509. EXPECT_EQ('"', etag[2]);
  19510. EXPECT_EQ('"', etag.back());
  19511. // Exact match: expect 304 Not Modified
  19512. Headers h2 = {{"If-None-Match", etag}};
  19513. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19514. ASSERT_TRUE(res2);
  19515. EXPECT_EQ(304, res2->status);
  19516. // Wildcard match: expect 304 Not Modified
  19517. Headers h3 = {{"If-None-Match", "*"}};
  19518. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19519. ASSERT_TRUE(res3);
  19520. EXPECT_EQ(304, res3->status);
  19521. // Non-matching ETag: expect 200
  19522. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19523. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19524. ASSERT_TRUE(res4);
  19525. EXPECT_EQ(200, res4->status);
  19526. // Multiple ETags with one matching: expect 304
  19527. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19528. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19529. ASSERT_TRUE(res5);
  19530. EXPECT_EQ(304, res5->status);
  19531. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19532. // that equivalent to the single comma-separated list above, so the match on
  19533. // the second line must still be found.
  19534. Headers h6;
  19535. h6.emplace("If-None-Match", "W/\"other\"");
  19536. h6.emplace("If-None-Match", etag);
  19537. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19538. ASSERT_TRUE(res6);
  19539. EXPECT_EQ(304, res6->status);
  19540. svr.stop();
  19541. t.join();
  19542. std::remove(fname);
  19543. }
  19544. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19545. using namespace httplib;
  19546. Server svr;
  19547. svr.set_mount_point("/static", ".");
  19548. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19549. svr.wait_until_ready();
  19550. Client cli(HOST, PORT);
  19551. // Send If-None-Match: * to a non-existent file
  19552. Headers h = {{"If-None-Match", "*"}};
  19553. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19555. EXPECT_EQ(404, res->status);
  19556. svr.stop();
  19557. t.join();
  19558. }
  19559. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19560. using namespace httplib;
  19561. // Create a test file
  19562. const char *fname = "etag_boundary_testfile.txt";
  19563. const char *content = "boundary-test";
  19564. {
  19565. std::ofstream ofs(fname);
  19566. ofs << content;
  19567. ASSERT_TRUE(ofs.good());
  19568. }
  19569. Server svr;
  19570. svr.set_mount_point("/static", ".");
  19571. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19572. svr.wait_until_ready();
  19573. Client cli(HOST, PORT);
  19574. // Get the actual ETag
  19575. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19576. ASSERT_TRUE(res1);
  19577. ASSERT_EQ(200, res1->status);
  19578. ASSERT_TRUE(res1->has_header("ETag"));
  19579. std::string etag = res1->get_header_value("ETag");
  19580. // Test 1: Very long ETag value (longer than actual ETag)
  19581. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19582. Headers h1 = {{"If-None-Match", "W/"
  19583. "\"very-long-etag-value-that-is-much-longer-"
  19584. "than-the-actual-etag-value\""}};
  19585. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19586. ASSERT_TRUE(res2);
  19587. EXPECT_EQ(200, res2->status); // Should not match
  19588. // Test 2: Long string followed by wildcard
  19589. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19590. // string)
  19591. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19592. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19593. ASSERT_TRUE(res3);
  19594. EXPECT_EQ(304, res3->status); // Should match on "*"
  19595. // Test 3: Wildcard followed by long string
  19596. // Should match on "*" immediately and return 304
  19597. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19598. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19599. ASSERT_TRUE(res4);
  19600. EXPECT_EQ(304, res4->status); // Should match on "*"
  19601. // Test 4: Multiple long non-matching values
  19602. // Should NOT match and return 200 (test that all comparisons are safe)
  19603. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19604. "W/\"second-long-non-matching-value\", "
  19605. "W/\"third-long-non-matching-value\""}};
  19606. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19607. ASSERT_TRUE(res5);
  19608. EXPECT_EQ(200, res5->status); // Should not match
  19609. // Test 5: Single character that is not "*" (edge case)
  19610. Headers h5 = {{"If-None-Match", "X"}};
  19611. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19612. ASSERT_TRUE(res6);
  19613. EXPECT_EQ(200, res6->status); // Should not match
  19614. svr.stop();
  19615. t.join();
  19616. std::remove(fname);
  19617. }
  19618. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19619. using namespace httplib;
  19620. // Create a test file
  19621. const char *fname = "ims_testfile.txt";
  19622. const char *content = "if-modified-since-test";
  19623. {
  19624. std::ofstream ofs(fname);
  19625. ofs << content;
  19626. ASSERT_TRUE(ofs.good());
  19627. }
  19628. Server svr;
  19629. svr.set_mount_point("/static", ".");
  19630. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19631. svr.wait_until_ready();
  19632. Client cli(HOST, PORT);
  19633. // First request: should get 200 with Last-Modified header
  19634. auto res1 = cli.Get("/static/ims_testfile.txt");
  19635. ASSERT_TRUE(res1);
  19636. ASSERT_EQ(200, res1->status);
  19637. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19638. std::string last_modified = res1->get_header_value("Last-Modified");
  19639. EXPECT_FALSE(last_modified.empty());
  19640. // If-Modified-Since with same time: expect 304
  19641. Headers h2 = {{"If-Modified-Since", last_modified}};
  19642. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19643. ASSERT_TRUE(res2);
  19644. EXPECT_EQ(304, res2->status);
  19645. // If-Modified-Since with future time: expect 304
  19646. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19647. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19648. ASSERT_TRUE(res3);
  19649. EXPECT_EQ(304, res3->status);
  19650. // If-Modified-Since with past time: expect 200
  19651. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19652. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19653. ASSERT_TRUE(res4);
  19654. EXPECT_EQ(200, res4->status);
  19655. // If-None-Match takes precedence over If-Modified-Since
  19656. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19657. ASSERT_TRUE(res1->has_header("ETag"));
  19658. std::string etag = res1->get_header_value("ETag");
  19659. Headers h5 = {{"If-None-Match", etag},
  19660. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19661. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19662. ASSERT_TRUE(res5);
  19663. EXPECT_EQ(304, res5->status);
  19664. svr.stop();
  19665. t.join();
  19666. std::remove(fname);
  19667. }
  19668. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19669. using namespace httplib;
  19670. Server svr;
  19671. // Endpoint that returns compressible content
  19672. svr.Get("/compressible", [](const Request &, Response &res) {
  19673. // Return a large enough body to trigger compression
  19674. std::string body(1000, 'a');
  19675. res.set_content(body, "text/plain");
  19676. });
  19677. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19678. svr.wait_until_ready();
  19679. Client cli(HOST, PORT);
  19680. // Request with gzip support: should get Vary header when compressed
  19681. cli.set_compress(true);
  19682. auto res1 = cli.Get("/compressible");
  19683. ASSERT_TRUE(res1);
  19684. EXPECT_EQ(200, res1->status);
  19685. // If Content-Encoding is set, Vary should also be set
  19686. if (res1->has_header("Content-Encoding")) {
  19687. EXPECT_TRUE(res1->has_header("Vary"));
  19688. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19689. }
  19690. // Request without Accept-Encoding header: should not have compression
  19691. Headers h_no_compress;
  19692. auto res2 = cli.Get("/compressible", h_no_compress);
  19693. ASSERT_TRUE(res2);
  19694. EXPECT_EQ(200, res2->status);
  19695. // Verify Vary header is present when compression is applied
  19696. // (the exact behavior depends on server configuration)
  19697. svr.stop();
  19698. t.join();
  19699. }
  19700. TEST(ETagTest, IfRangeWithETag) {
  19701. using namespace httplib;
  19702. // Create a test file with known content
  19703. const char *fname = "if_range_testfile.txt";
  19704. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19705. {
  19706. std::ofstream ofs(fname);
  19707. ofs << content;
  19708. ASSERT_TRUE(ofs.good());
  19709. }
  19710. Server svr;
  19711. svr.set_mount_point("/static", ".");
  19712. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19713. svr.wait_until_ready();
  19714. Client cli(HOST, PORT);
  19715. // First request: get ETag
  19716. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19717. ASSERT_TRUE(res1);
  19718. ASSERT_EQ(200, res1->status);
  19719. ASSERT_TRUE(res1->has_header("ETag"));
  19720. std::string etag = res1->get_header_value("ETag");
  19721. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19722. // Since our server generates weak ETags (W/"..."), If-Range with our
  19723. // ETag should NOT result in partial content - it should return full content.
  19724. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19725. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19726. ASSERT_TRUE(res2);
  19727. // Weak ETag in If-Range -> full content (200), not partial (206)
  19728. EXPECT_EQ(200, res2->status);
  19729. EXPECT_EQ(content, res2->body);
  19730. EXPECT_FALSE(res2->has_header("Content-Range"));
  19731. // Range request with non-matching If-Range (ETag): should get 200 (full
  19732. // content)
  19733. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19734. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19735. ASSERT_TRUE(res3);
  19736. EXPECT_EQ(200, res3->status);
  19737. EXPECT_EQ(content, res3->body);
  19738. EXPECT_FALSE(res3->has_header("Content-Range"));
  19739. // Range request with strong ETag (hypothetical - our server doesn't generate
  19740. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19741. // should return full content)
  19742. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19743. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19744. ASSERT_TRUE(res4);
  19745. EXPECT_EQ(200, res4->status);
  19746. EXPECT_EQ(content, res4->body);
  19747. EXPECT_FALSE(res4->has_header("Content-Range"));
  19748. svr.stop();
  19749. t.join();
  19750. std::remove(fname);
  19751. }
  19752. TEST(ETagTest, IfRangeWithDate) {
  19753. using namespace httplib;
  19754. // Create a test file
  19755. const char *fname = "if_range_date_testfile.txt";
  19756. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19757. {
  19758. std::ofstream ofs(fname);
  19759. ofs << content;
  19760. ASSERT_TRUE(ofs.good());
  19761. }
  19762. Server svr;
  19763. svr.set_mount_point("/static", ".");
  19764. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19765. svr.wait_until_ready();
  19766. Client cli(HOST, PORT);
  19767. // First request: get Last-Modified
  19768. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19769. ASSERT_TRUE(res1);
  19770. ASSERT_EQ(200, res1->status);
  19771. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19772. std::string last_modified = res1->get_header_value("Last-Modified");
  19773. // Range request with matching If-Range (date): should get 206
  19774. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19775. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19776. ASSERT_TRUE(res2);
  19777. EXPECT_EQ(206, res2->status);
  19778. EXPECT_EQ("FGHIJ", res2->body);
  19779. // Range request with old If-Range date: should get 200 (full content)
  19780. Headers h3 = {{"Range", "bytes=5-9"},
  19781. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19782. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19783. ASSERT_TRUE(res3);
  19784. EXPECT_EQ(200, res3->status);
  19785. EXPECT_EQ(content, res3->body);
  19786. // Range request with future If-Range date: should get 206
  19787. Headers h4 = {{"Range", "bytes=0-4"},
  19788. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19789. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19790. ASSERT_TRUE(res4);
  19791. EXPECT_EQ(206, res4->status);
  19792. EXPECT_EQ("ABCDE", res4->body);
  19793. svr.stop();
  19794. t.join();
  19795. std::remove(fname);
  19796. }
  19797. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19798. using namespace httplib;
  19799. const char *fname = "etag_malformed.txt";
  19800. const char *content = "malformed-etag";
  19801. {
  19802. std::ofstream ofs(fname);
  19803. ofs << content;
  19804. ASSERT_TRUE(ofs.good());
  19805. }
  19806. Server svr;
  19807. svr.set_mount_point("/static", ".");
  19808. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19809. svr.wait_until_ready();
  19810. Client cli(HOST, PORT);
  19811. // baseline: should get 200 and an ETag
  19812. auto res1 = cli.Get("/static/etag_malformed.txt");
  19813. ASSERT_TRUE(res1);
  19814. ASSERT_EQ(200, res1->status);
  19815. ASSERT_TRUE(res1->has_header("ETag"));
  19816. // Malformed ETag value (missing quotes) should be treated as non-matching
  19817. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19818. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19819. ASSERT_TRUE(res_bad);
  19820. EXPECT_EQ(200, res_bad->status);
  19821. // Whitespace-only header value should be considered invalid / non-matching
  19822. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19823. "Host: localhost\r\n"
  19824. "If-None-Match: \r\n"
  19825. "Connection: close\r\n"
  19826. "\r\n";
  19827. std::string out;
  19828. ASSERT_TRUE(send_request(5, raw_req, &out));
  19829. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19830. svr.stop();
  19831. t.join();
  19832. std::remove(fname);
  19833. }
  19834. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19835. using namespace httplib;
  19836. const char *fname = "ims_invalid_format.txt";
  19837. const char *content = "ims-bad-format";
  19838. {
  19839. std::ofstream ofs(fname);
  19840. ofs << content;
  19841. ASSERT_TRUE(ofs.good());
  19842. }
  19843. Server svr;
  19844. svr.set_mount_point("/static", ".");
  19845. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19846. svr.wait_until_ready();
  19847. Client cli(HOST, PORT);
  19848. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19849. ASSERT_TRUE(res1);
  19850. ASSERT_EQ(200, res1->status);
  19851. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19852. // If-Modified-Since with invalid format should not result in 304
  19853. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19854. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19855. ASSERT_TRUE(res_bad);
  19856. EXPECT_EQ(200, res_bad->status);
  19857. // If-Range with invalid date format should be treated as mismatch -> full
  19858. // content (200)
  19859. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19860. {"If-Range", "invalid-date"}};
  19861. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19862. ASSERT_TRUE(res_ifrange);
  19863. EXPECT_EQ(200, res_ifrange->status);
  19864. svr.stop();
  19865. t.join();
  19866. std::remove(fname);
  19867. }
  19868. TEST(ETagTest, IfRangeWithMalformedETag) {
  19869. using namespace httplib;
  19870. const char *fname = "ifrange_malformed.txt";
  19871. const std::string content = "0123456789";
  19872. {
  19873. std::ofstream ofs(fname);
  19874. ofs << content;
  19875. ASSERT_TRUE(ofs.good());
  19876. }
  19877. Server svr;
  19878. svr.set_mount_point("/static", ".");
  19879. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19880. svr.wait_until_ready();
  19881. Client cli(HOST, PORT);
  19882. // First request: get ETag
  19883. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19884. ASSERT_TRUE(res1);
  19885. ASSERT_EQ(200, res1->status);
  19886. ASSERT_TRUE(res1->has_header("ETag"));
  19887. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19888. // full content (200)
  19889. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19890. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19891. ASSERT_TRUE(res2);
  19892. EXPECT_EQ(200, res2->status);
  19893. EXPECT_EQ(content, res2->body);
  19894. svr.stop();
  19895. t.join();
  19896. std::remove(fname);
  19897. }
  19898. TEST(ETagTest, ExtremeLargeDateValues) {
  19899. using namespace httplib;
  19900. const char *fname = "ims_extreme_date.txt";
  19901. const char *content = "ims-extreme-date";
  19902. {
  19903. std::ofstream ofs(fname);
  19904. ofs << content;
  19905. ASSERT_TRUE(ofs.good());
  19906. }
  19907. Server svr;
  19908. svr.set_mount_point("/static", ".");
  19909. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19910. svr.wait_until_ready();
  19911. Client cli(HOST, PORT);
  19912. auto res1 = cli.Get(std::string("/static/") + fname);
  19913. ASSERT_TRUE(res1);
  19914. ASSERT_EQ(200, res1->status);
  19915. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19916. // Extremely large year that may overflow date parsing routines.
  19917. Headers h_large_date = {
  19918. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19919. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19920. ASSERT_TRUE(res_bad);
  19921. // Expect server to treat this as invalid/mismatch and return full content
  19922. EXPECT_EQ(200, res_bad->status);
  19923. // If-Range with extremely large date should be treated as mismatch -> full
  19924. // content (200)
  19925. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19926. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19927. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19928. ASSERT_TRUE(res_ifrange);
  19929. EXPECT_EQ(200, res_ifrange->status);
  19930. svr.stop();
  19931. t.join();
  19932. std::remove(fname);
  19933. }
  19934. TEST(ETagTest, NegativeFileModificationTime) {
  19935. using namespace httplib;
  19936. const char *fname = "ims_negative_mtime.txt";
  19937. const std::string content = "negative-mtime";
  19938. {
  19939. std::ofstream ofs(fname);
  19940. ofs << content;
  19941. ASSERT_TRUE(ofs.good());
  19942. }
  19943. // Try to set file mtime to a negative value. This may fail on some
  19944. // platforms/filesystems; if it fails, the test will still verify server
  19945. // behaves safely by performing a regular conditional request.
  19946. #if defined(__APPLE__) || defined(__linux__)
  19947. bool set_negative = false;
  19948. do {
  19949. struct timeval times[2];
  19950. // access time: now
  19951. times[0].tv_sec = time(nullptr);
  19952. times[0].tv_usec = 0;
  19953. // modification time: negative (e.g., -1)
  19954. times[1].tv_sec = -1;
  19955. times[1].tv_usec = 0;
  19956. if (utimes(fname, times) == 0) { set_negative = true; }
  19957. } while (0);
  19958. #else
  19959. bool set_negative = false;
  19960. #endif
  19961. Server svr;
  19962. svr.set_mount_point("/static", ".");
  19963. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19964. svr.wait_until_ready();
  19965. Client cli(HOST, PORT);
  19966. auto res1 = cli.Get(std::string("/static/") + fname);
  19967. ASSERT_TRUE(res1);
  19968. ASSERT_EQ(200, res1->status);
  19969. bool has_last_modified = res1->has_header("Last-Modified");
  19970. std::string last_modified;
  19971. if (has_last_modified) {
  19972. last_modified = res1->get_header_value("Last-Modified");
  19973. }
  19974. if (set_negative) {
  19975. // If we successfully set a negative mtime, ensure server returns a
  19976. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19977. // with an old date and ensure server handles it without crash.
  19978. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19979. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19980. ASSERT_TRUE(res2);
  19981. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19982. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19983. } else {
  19984. // Could not set negative mtime on this platform; fall back to verifying
  19985. // that normal invalid/malformed dates are treated safely (non-304).
  19986. Headers h_bad_date = {
  19987. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19988. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19989. ASSERT_TRUE(res_bad);
  19990. EXPECT_EQ(200, res_bad->status);
  19991. }
  19992. svr.stop();
  19993. t.join();
  19994. std::remove(fname);
  19995. }
  19996. //==============================================================================
  19997. // Integration Tests with Server
  19998. //==============================================================================
  19999. class SSEIntegrationTest : public ::testing::Test {
  20000. protected:
  20001. void SetUp() override {
  20002. stop_server_.store(false);
  20003. events_.clear();
  20004. server_ = httplib::detail::make_unique<Server>();
  20005. setup_server();
  20006. start_server();
  20007. }
  20008. void TearDown() override {
  20009. stop_server_.store(true);
  20010. event_cv_.notify_all();
  20011. server_->stop();
  20012. if (server_thread_.joinable()) { server_thread_.join(); }
  20013. }
  20014. void setup_server() {
  20015. // Simple SSE endpoint
  20016. server_->Get("/events", [this](const Request &req, Response &res) {
  20017. auto last_id = req.get_header_value("Last-Event-ID");
  20018. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20019. res.set_chunked_content_provider(
  20020. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20021. std::unique_lock<std::mutex> lock(event_mutex_);
  20022. if (event_cv_.wait_for(
  20023. lock, std::chrono::milliseconds(200), [this] {
  20024. return !events_.empty() || stop_server_.load();
  20025. })) {
  20026. if (stop_server_.load()) { return false; }
  20027. if (!events_.empty()) {
  20028. std::string event = events_.front();
  20029. events_.erase(events_.begin());
  20030. sink.write(event.data(), event.size());
  20031. return true;
  20032. }
  20033. }
  20034. return !stop_server_.load();
  20035. });
  20036. });
  20037. // Endpoint that returns error
  20038. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20039. res.status = 500;
  20040. res.set_content("Internal Server Error", "text/plain");
  20041. });
  20042. // Endpoint for custom event types
  20043. server_->Get("/custom-events", [](const Request &, Response &res) {
  20044. res.set_chunked_content_provider(
  20045. "text/event-stream", [](size_t offset, DataSink &sink) {
  20046. if (offset == 0) {
  20047. std::string event = "event: update\ndata: updated\n\n"
  20048. "event: delete\ndata: deleted\n\n";
  20049. sink.write(event.data(), event.size());
  20050. }
  20051. return false; // End stream after sending
  20052. });
  20053. });
  20054. }
  20055. void start_server() {
  20056. port_ = server_->bind_to_any_port(HOST);
  20057. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20058. // Wait for server to start
  20059. while (!server_->is_running()) {
  20060. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20061. }
  20062. }
  20063. int get_port() const { return port_; }
  20064. void send_event(const std::string &event) {
  20065. std::lock_guard<std::mutex> lock(event_mutex_);
  20066. events_.push_back(event);
  20067. event_cv_.notify_all();
  20068. }
  20069. std::unique_ptr<Server> server_;
  20070. std::thread server_thread_;
  20071. std::mutex event_mutex_;
  20072. std::condition_variable event_cv_;
  20073. std::vector<std::string> events_;
  20074. std::atomic<bool> stop_server_{false};
  20075. std::string last_received_event_id_;
  20076. int port_ = 0;
  20077. };
  20078. //==============================================================================
  20079. // SSE Parsing Tests
  20080. //==============================================================================
  20081. class SSEParsingTest : public SSEIntegrationTest {
  20082. protected:
  20083. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20084. // A trailing sentinel event tells when the whole stream has been parsed.
  20085. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20086. auto body = stream + "event: end\ndata: end\n\n";
  20087. server_->Get("/parse", [body](const Request &, Response &res) {
  20088. res.set_content(body, "text/event-stream");
  20089. });
  20090. return collect("/parse");
  20091. }
  20092. // Runs SSEClient against path until an "end" event arrives and returns the
  20093. // messages dispatched before it
  20094. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20095. Client client(HOST, get_port());
  20096. sse::SSEClient sse(client, path);
  20097. std::mutex mutex;
  20098. std::condition_variable cv;
  20099. std::vector<sse::SSEMessage> messages;
  20100. auto done = false;
  20101. sse.on_message([&](const sse::SSEMessage &msg) {
  20102. std::lock_guard<std::mutex> lock(mutex);
  20103. // Ignore a replay from a reconnect that races with stop()
  20104. if (!done) { messages.push_back(msg); }
  20105. });
  20106. sse.on_event("end", [&](const sse::SSEMessage &) {
  20107. std::lock_guard<std::mutex> lock(mutex);
  20108. done = true;
  20109. cv.notify_all();
  20110. });
  20111. sse.set_reconnect_interval(100);
  20112. sse.start_async();
  20113. {
  20114. std::unique_lock<std::mutex> lock(mutex);
  20115. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20116. }
  20117. sse.stop();
  20118. EXPECT_TRUE(done);
  20119. return messages;
  20120. }
  20121. };
  20122. TEST_F(SSEParsingTest, SingleLineData) {
  20123. auto msgs = parse("data: hello\n\n");
  20124. ASSERT_EQ(msgs.size(), 1u);
  20125. EXPECT_EQ(msgs[0].data, "hello");
  20126. EXPECT_EQ(msgs[0].event, "message");
  20127. }
  20128. TEST_F(SSEParsingTest, MultiLineData) {
  20129. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20130. ASSERT_EQ(msgs.size(), 1u);
  20131. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20132. }
  20133. TEST_F(SSEParsingTest, CustomEventType) {
  20134. auto msgs = parse("event: update\ndata: payload\n\n");
  20135. ASSERT_EQ(msgs.size(), 1u);
  20136. EXPECT_EQ(msgs[0].event, "update");
  20137. EXPECT_EQ(msgs[0].data, "payload");
  20138. }
  20139. TEST_F(SSEParsingTest, EventIdHandling) {
  20140. auto msgs = parse("id: 12345\ndata: test\n\n");
  20141. ASSERT_EQ(msgs.size(), 1u);
  20142. EXPECT_EQ(msgs[0].id, "12345");
  20143. }
  20144. TEST_F(SSEParsingTest, EmptyEventId) {
  20145. auto msgs = parse("id:\ndata: test\n\n");
  20146. ASSERT_EQ(msgs.size(), 1u);
  20147. EXPECT_EQ(msgs[0].id, "");
  20148. }
  20149. TEST_F(SSEParsingTest, CommentsIgnored) {
  20150. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20151. ASSERT_EQ(msgs.size(), 1u);
  20152. EXPECT_EQ(msgs[0].data, "hello");
  20153. EXPECT_EQ(msgs[0].event, "message");
  20154. }
  20155. TEST_F(SSEParsingTest, ColonInValue) {
  20156. auto msgs = parse("data: hello:world:test\n\n");
  20157. ASSERT_EQ(msgs.size(), 1u);
  20158. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20159. }
  20160. TEST_F(SSEParsingTest, FieldNameOnly) {
  20161. // A line without a colon is a field name with an empty value
  20162. auto msgs = parse("data\n\n");
  20163. ASSERT_EQ(msgs.size(), 1u);
  20164. EXPECT_EQ(msgs[0].data, "");
  20165. }
  20166. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20167. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20168. ASSERT_EQ(msgs.size(), 1u);
  20169. EXPECT_EQ(msgs[0].event, "update");
  20170. EXPECT_EQ(msgs[0].data, "hello");
  20171. }
  20172. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20173. auto msgs = parse("data\r\n\r\n");
  20174. ASSERT_EQ(msgs.size(), 1u);
  20175. EXPECT_EQ(msgs[0].data, "");
  20176. }
  20177. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20178. auto msgs = parse("event: update\rdata: hello\r\r");
  20179. ASSERT_EQ(msgs.size(), 1u);
  20180. EXPECT_EQ(msgs[0].event, "update");
  20181. EXPECT_EQ(msgs[0].data, "hello");
  20182. }
  20183. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20184. // Chunk boundaries fall inside every \r\n and right before the first one
  20185. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20186. "\n\r", "\nevent: end\ndata: end\n\n"};
  20187. server_->Get("/split", [chunks](const Request &, Response &res) {
  20188. auto i = std::make_shared<size_t>(0);
  20189. res.set_chunked_content_provider(
  20190. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20191. if (*i == chunks.size()) {
  20192. sink.done();
  20193. } else {
  20194. sink.write(chunks[*i].data(), chunks[*i].size());
  20195. (*i)++;
  20196. }
  20197. return true;
  20198. });
  20199. });
  20200. auto msgs = collect("/split");
  20201. ASSERT_EQ(msgs.size(), 1u);
  20202. EXPECT_EQ(msgs[0].event, "update");
  20203. EXPECT_EQ(msgs[0].data, "hello");
  20204. }
  20205. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20206. // Only a BOM at the start of the stream is ignored
  20207. auto msgs = parse("\xEF\xBB\xBF"
  20208. "data: first\n\n"
  20209. "\xEF\xBB\xBF"
  20210. "data: second\n\n");
  20211. ASSERT_EQ(msgs.size(), 1u);
  20212. EXPECT_EQ(msgs[0].data, "first");
  20213. }
  20214. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20215. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20216. ASSERT_EQ(msgs.size(), 1u);
  20217. EXPECT_EQ(msgs[0].data, "hello");
  20218. EXPECT_EQ(msgs[0].event, "message");
  20219. }
  20220. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20221. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20222. ASSERT_EQ(msgs.size(), 2u);
  20223. EXPECT_EQ(msgs[0].data, "hello");
  20224. EXPECT_EQ(msgs[1].data, "hello");
  20225. }
  20226. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20227. // An event without data is not dispatched, and its type must not leak
  20228. // into the next event
  20229. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20230. ASSERT_EQ(msgs.size(), 1u);
  20231. EXPECT_EQ(msgs[0].event, "message");
  20232. EXPECT_EQ(msgs[0].data, "hello");
  20233. }
  20234. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20235. // The first connection sends only an id; the second echoes back the
  20236. // Last-Event-ID it was reconnected with
  20237. std::atomic<int> connection_count{0};
  20238. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20239. if (connection_count++ == 0) {
  20240. res.set_content("id: 42\n\n", "text/event-stream");
  20241. } else {
  20242. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20243. "\n\nevent: end\ndata: end\n\n",
  20244. "text/event-stream");
  20245. }
  20246. });
  20247. auto msgs = collect("/id-only");
  20248. ASSERT_EQ(msgs.size(), 1u);
  20249. EXPECT_EQ(msgs[0].data, "42");
  20250. }
  20251. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20252. // The first connection sets an id and then clears it with an empty one; the
  20253. // second reports whether it was reconnected with a Last-Event-ID
  20254. std::atomic<int> connection_count{0};
  20255. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20256. if (connection_count++ == 0) {
  20257. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20258. "text/event-stream");
  20259. } else {
  20260. res.set_content(
  20261. std::string("data: ") +
  20262. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20263. "\n\nevent: end\ndata: end\n\n",
  20264. "text/event-stream");
  20265. }
  20266. });
  20267. auto msgs = collect("/id-clear");
  20268. ASSERT_EQ(msgs.size(), 3u);
  20269. EXPECT_EQ(msgs[0].id, "1");
  20270. EXPECT_EQ(msgs[1].id, "");
  20271. EXPECT_EQ(msgs[2].data, "not sent");
  20272. }
  20273. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20274. // The first connection sets an id and then sends ids that cannot be carried
  20275. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20276. // with
  20277. std::atomic<int> connection_count{0};
  20278. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20279. if (connection_count++ == 0) {
  20280. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20281. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20282. "text/event-stream");
  20283. } else {
  20284. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20285. "\n\nevent: end\ndata: end\n\n",
  20286. "text/event-stream");
  20287. }
  20288. });
  20289. auto msgs = collect("/id-unsendable");
  20290. ASSERT_EQ(msgs.size(), 1u);
  20291. EXPECT_EQ(msgs[0].data, "42");
  20292. }
  20293. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20294. auto msgs = parse("event: notification\nid: evt-42\n"
  20295. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20296. ASSERT_EQ(msgs.size(), 1u);
  20297. EXPECT_EQ(msgs[0].event, "notification");
  20298. EXPECT_EQ(msgs[0].id, "evt-42");
  20299. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20300. }
  20301. TEST(SSEMessageTest, Clear) {
  20302. sse::SSEMessage msg;
  20303. msg.event = "custom";
  20304. msg.data = "some data";
  20305. msg.id = "123";
  20306. msg.clear();
  20307. EXPECT_EQ(msg.event, "message");
  20308. EXPECT_EQ(msg.data, "");
  20309. EXPECT_EQ(msg.id, "");
  20310. }
  20311. //==============================================================================
  20312. // SSE Integration Tests
  20313. //==============================================================================
  20314. // Test: Successful connection and on_open callback
  20315. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20316. // Add a simple endpoint that sends one event and closes
  20317. server_->Get("/simple-event", [](const Request &, Response &res) {
  20318. res.set_chunked_content_provider(
  20319. "text/event-stream", [](size_t offset, DataSink &sink) {
  20320. if (offset == 0) {
  20321. std::string event = "data: hello\n\n";
  20322. sink.write(event.data(), event.size());
  20323. }
  20324. return false; // Close stream after sending
  20325. });
  20326. });
  20327. Client client("localhost", get_port());
  20328. sse::SSEClient sse(client, "/simple-event");
  20329. std::atomic<bool> open_called{false};
  20330. std::atomic<bool> message_received{false};
  20331. sse.on_open([&open_called]() { open_called.store(true); });
  20332. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20333. if (msg.data == "hello") { message_received.store(true); }
  20334. });
  20335. sse.set_reconnect_interval(100);
  20336. sse.set_max_reconnect_attempts(1);
  20337. // Start async
  20338. sse.start_async();
  20339. // Wait for message to be processed
  20340. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20341. sse.stop();
  20342. EXPECT_TRUE(open_called.load());
  20343. EXPECT_TRUE(message_received.load());
  20344. }
  20345. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20346. // A data line that never ends.
  20347. server_->Get("/endless-line", [](const Request &, Response &res) {
  20348. res.set_chunked_content_provider(
  20349. "text/event-stream", [](size_t offset, DataSink &sink) {
  20350. if (offset == 0) { sink.write("data: ", 6); }
  20351. std::string chunk(64 * 1024, 'A');
  20352. return sink.write(chunk.data(), chunk.size());
  20353. });
  20354. });
  20355. Client client("localhost", get_port());
  20356. // A stream that may run forever, so that only the event is bounded.
  20357. client.set_payload_max_length(0);
  20358. sse::SSEClient sse(client, "/endless-line");
  20359. std::atomic<bool> too_long{false};
  20360. sse.on_error([&](Error err) {
  20361. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20362. });
  20363. sse.set_max_reconnect_attempts(1);
  20364. sse.start_async();
  20365. for (int i = 0; i < 500 && !too_long; i++) {
  20366. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20367. }
  20368. sse.stop();
  20369. EXPECT_TRUE(too_long);
  20370. }
  20371. // Test: on_message callback
  20372. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20373. // Endpoint that sends multiple events then closes
  20374. server_->Get("/multi-event", [](const Request &, Response &res) {
  20375. res.set_chunked_content_provider(
  20376. "text/event-stream", [](size_t offset, DataSink &sink) {
  20377. if (offset == 0) {
  20378. std::string events = "data: message1\n\ndata: message2\n\n";
  20379. sink.write(events.data(), events.size());
  20380. }
  20381. return false;
  20382. });
  20383. });
  20384. Client client("localhost", get_port());
  20385. sse::SSEClient sse(client, "/multi-event");
  20386. std::vector<std::string> received_messages;
  20387. std::mutex messages_mutex;
  20388. sse.on_message([&](const sse::SSEMessage &msg) {
  20389. std::lock_guard<std::mutex> lock(messages_mutex);
  20390. received_messages.push_back(msg.data);
  20391. });
  20392. sse.set_reconnect_interval(100);
  20393. sse.set_max_reconnect_attempts(1);
  20394. sse.start_async();
  20395. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20396. sse.stop();
  20397. std::lock_guard<std::mutex> lock(messages_mutex);
  20398. EXPECT_GE(received_messages.size(), 2u);
  20399. if (received_messages.size() >= 2) {
  20400. EXPECT_EQ(received_messages[0], "message1");
  20401. EXPECT_EQ(received_messages[1], "message2");
  20402. }
  20403. }
  20404. // Test: on_event for specific types
  20405. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20406. Client client("localhost", get_port());
  20407. sse::SSEClient sse(client, "/custom-events");
  20408. std::atomic<bool> update_received{false};
  20409. std::atomic<bool> delete_received{false};
  20410. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20411. if (msg.data == "updated") { update_received.store(true); }
  20412. });
  20413. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20414. if (msg.data == "deleted") { delete_received.store(true); }
  20415. });
  20416. sse.set_max_reconnect_attempts(1);
  20417. sse.start_async();
  20418. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20419. sse.stop();
  20420. EXPECT_TRUE(update_received.load());
  20421. EXPECT_TRUE(delete_received.load());
  20422. }
  20423. // Test: on_error callback on connection failure
  20424. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20425. // Connect to a non-existent port
  20426. Client client("localhost", 59999);
  20427. sse::SSEClient sse(client, "/events");
  20428. std::atomic<bool> error_called{false};
  20429. Error received_error = Error::Success;
  20430. sse.on_error([&](Error err) {
  20431. error_called.store(true);
  20432. received_error = err;
  20433. });
  20434. sse.set_reconnect_interval(50);
  20435. sse.set_max_reconnect_attempts(1);
  20436. sse.start_async();
  20437. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20438. sse.stop();
  20439. EXPECT_TRUE(error_called.load());
  20440. EXPECT_NE(received_error, Error::Success);
  20441. }
  20442. // Test: Last-Event-ID header sent on reconnect
  20443. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20444. // Endpoint that sends event with ID
  20445. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20446. res.set_chunked_content_provider(
  20447. "text/event-stream", [](size_t offset, DataSink &sink) {
  20448. if (offset == 0) {
  20449. std::string event = "id: evt-123\ndata: test\n\n";
  20450. sink.write(event.data(), event.size());
  20451. }
  20452. return false;
  20453. });
  20454. });
  20455. Client client("localhost", get_port());
  20456. sse::SSEClient sse(client, "/event-with-id");
  20457. std::atomic<bool> id_received{false};
  20458. sse.on_message([&](const sse::SSEMessage &msg) {
  20459. if (!msg.id.empty()) { id_received.store(true); }
  20460. });
  20461. sse.set_reconnect_interval(100);
  20462. sse.set_max_reconnect_attempts(1);
  20463. sse.start_async();
  20464. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20465. sse.stop();
  20466. EXPECT_TRUE(id_received.load());
  20467. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20468. }
  20469. // Test: Manual stop
  20470. TEST_F(SSEIntegrationTest, ManualStop) {
  20471. // Endpoint that sends one event and stays open briefly
  20472. std::atomic<bool> handler_running{true};
  20473. server_->Get("/stay-open", [&handler_running](const Request &,
  20474. Response &res) {
  20475. res.set_chunked_content_provider(
  20476. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20477. if (offset == 0) {
  20478. std::string event = "data: connected\n\n";
  20479. sink.write(event.data(), event.size());
  20480. }
  20481. // Keep connection open while handler_running is true
  20482. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20483. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20484. }
  20485. return false;
  20486. });
  20487. });
  20488. Client client("localhost", get_port());
  20489. sse::SSEClient sse(client, "/stay-open");
  20490. std::atomic<bool> connected{false};
  20491. sse.on_open([&connected]() { connected.store(true); });
  20492. sse.set_reconnect_interval(100);
  20493. sse.set_max_reconnect_attempts(1);
  20494. sse.start_async();
  20495. // Wait for connection to establish
  20496. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20497. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20498. }
  20499. EXPECT_TRUE(connected.load());
  20500. EXPECT_TRUE(sse.is_connected());
  20501. // Signal handler to stop
  20502. handler_running.store(false);
  20503. // Stop SSE client
  20504. sse.stop();
  20505. EXPECT_FALSE(sse.is_connected());
  20506. }
  20507. // Test: SSEClient with custom headers
  20508. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20509. // Setup a server endpoint that checks for custom header
  20510. std::atomic<bool> header_received{false};
  20511. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20512. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20513. header_received.store(true);
  20514. }
  20515. res.set_chunked_content_provider("text/event-stream",
  20516. [](size_t, DataSink &) { return false; });
  20517. });
  20518. Client client("localhost", get_port());
  20519. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20520. sse::SSEClient sse(client, "/header-check", headers);
  20521. sse.set_max_reconnect_attempts(1);
  20522. sse.start_async();
  20523. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20524. sse.stop();
  20525. EXPECT_TRUE(header_received.load());
  20526. }
  20527. // Test: Reconnect interval configuration
  20528. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20529. Client client("localhost", get_port());
  20530. sse::SSEClient sse(client, "/events");
  20531. auto &result = sse.set_reconnect_interval(500);
  20532. // Builder pattern should return reference to self
  20533. EXPECT_EQ(&result, &sse);
  20534. }
  20535. // Test: Max reconnect attempts
  20536. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20537. // Connect to non-existent port to force reconnects
  20538. Client client("localhost", 59998);
  20539. sse::SSEClient sse(client, "/events");
  20540. std::atomic<int> error_count{0};
  20541. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20542. sse.set_reconnect_interval(50);
  20543. sse.set_max_reconnect_attempts(2);
  20544. auto start = std::chrono::steady_clock::now();
  20545. sse.start(); // Blocking call
  20546. auto end = std::chrono::steady_clock::now();
  20547. // Should have stopped after 2 failed attempts
  20548. EXPECT_GE(error_count.load(), 2);
  20549. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20550. auto duration =
  20551. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20552. #ifdef _WIN32
  20553. // Windows is much slower for socket connection failures
  20554. EXPECT_LT(duration.count(), 7000);
  20555. #else
  20556. EXPECT_LT(duration.count(), 1000);
  20557. #endif
  20558. }
  20559. // Test: Multi-line data in integration
  20560. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20561. // Endpoint with multi-line data
  20562. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20563. res.set_chunked_content_provider(
  20564. "text/event-stream", [](size_t offset, DataSink &sink) {
  20565. if (offset == 0) {
  20566. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20567. sink.write(event.data(), event.size());
  20568. }
  20569. return false;
  20570. });
  20571. });
  20572. Client client("localhost", get_port());
  20573. sse::SSEClient sse(client, "/multiline-data");
  20574. std::string received_data;
  20575. std::mutex data_mutex;
  20576. sse.on_message([&](const sse::SSEMessage &msg) {
  20577. std::lock_guard<std::mutex> lock(data_mutex);
  20578. received_data = msg.data;
  20579. });
  20580. sse.set_reconnect_interval(100);
  20581. sse.set_max_reconnect_attempts(1);
  20582. sse.start_async();
  20583. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20584. sse.stop();
  20585. std::lock_guard<std::mutex> lock(data_mutex);
  20586. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20587. }
  20588. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20589. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20590. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20591. DataSink &sink) {
  20592. if (offset == 0) {
  20593. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20594. sink.write(events.data(), events.size());
  20595. }
  20596. return false;
  20597. });
  20598. });
  20599. Client client("localhost", get_port());
  20600. sse::SSEClient sse(client, "/empty-data-lines");
  20601. std::mutex mutex;
  20602. std::condition_variable cv;
  20603. std::vector<std::string> received;
  20604. sse.on_message([&](const sse::SSEMessage &msg) {
  20605. std::lock_guard<std::mutex> lock(mutex);
  20606. received.push_back(msg.data);
  20607. cv.notify_all();
  20608. });
  20609. sse.set_max_reconnect_attempts(1);
  20610. sse.start_async();
  20611. {
  20612. std::unique_lock<std::mutex> lock(mutex);
  20613. cv.wait_for(lock, std::chrono::seconds(2),
  20614. [&] { return received.size() >= 3; });
  20615. }
  20616. sse.stop();
  20617. ASSERT_GE(received.size(), 3u);
  20618. EXPECT_EQ(received[0], "");
  20619. EXPECT_EQ(received[1], "\nhello");
  20620. EXPECT_EQ(received[2], "");
  20621. }
  20622. // Test: Auto-reconnect after server disconnection
  20623. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20624. std::atomic<int> connection_count{0};
  20625. std::atomic<int> message_count{0};
  20626. // Endpoint that sends one event and closes, forcing reconnect
  20627. server_->Get("/reconnect-test",
  20628. [&connection_count](const Request &, Response &res) {
  20629. connection_count.fetch_add(1);
  20630. res.set_chunked_content_provider(
  20631. "text/event-stream", [](size_t offset, DataSink &sink) {
  20632. if (offset == 0) {
  20633. std::string event = "data: hello\n\n";
  20634. sink.write(event.data(), event.size());
  20635. }
  20636. return false; // Close connection after sending
  20637. });
  20638. });
  20639. Client client("localhost", get_port());
  20640. sse::SSEClient sse(client, "/reconnect-test");
  20641. sse.on_message([&message_count](const sse::SSEMessage &) {
  20642. message_count.fetch_add(1);
  20643. });
  20644. sse.set_reconnect_interval(100);
  20645. sse.set_max_reconnect_attempts(3);
  20646. sse.start_async();
  20647. // Wait long enough for multiple reconnects
  20648. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20649. sse.stop();
  20650. // Should have connected multiple times (initial + reconnects)
  20651. EXPECT_GE(connection_count.load(), 2);
  20652. // Should have received messages from multiple connections
  20653. EXPECT_GE(message_count.load(), 2);
  20654. }
  20655. // Test: A retry field that is not all ASCII digits is ignored
  20656. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20657. std::atomic<int> connection_count{0};
  20658. server_->Get("/bad-retry",
  20659. [&connection_count](const Request &, Response &res) {
  20660. connection_count.fetch_add(1);
  20661. res.set_chunked_content_provider(
  20662. "text/event-stream", [](size_t offset, DataSink &sink) {
  20663. if (offset == 0) {
  20664. std::string event = "retry: -1\ndata: hello\n\n";
  20665. sink.write(event.data(), event.size());
  20666. }
  20667. return false;
  20668. });
  20669. });
  20670. Client client("localhost", get_port());
  20671. sse::SSEClient sse(client, "/bad-retry");
  20672. sse.set_reconnect_interval(10000);
  20673. sse.start_async();
  20674. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20675. sse.stop();
  20676. EXPECT_EQ(connection_count.load(), 1);
  20677. }
  20678. // Test: A retry field of all ASCII digits sets the reconnection time
  20679. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20680. std::mutex mutex;
  20681. std::condition_variable cv;
  20682. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20683. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20684. {
  20685. std::lock_guard<std::mutex> lock(mutex);
  20686. connected_at.push_back(std::chrono::steady_clock::now());
  20687. cv.notify_all();
  20688. }
  20689. res.set_chunked_content_provider(
  20690. "text/event-stream", [](size_t offset, DataSink &sink) {
  20691. if (offset == 0) {
  20692. std::string event = "retry: 0\ndata: hello\n\n";
  20693. sink.write(event.data(), event.size());
  20694. }
  20695. return false;
  20696. });
  20697. });
  20698. Client client("localhost", get_port());
  20699. sse::SSEClient sse(client, "/zero-retry");
  20700. sse.set_reconnect_interval(10000);
  20701. sse.start_async();
  20702. {
  20703. std::unique_lock<std::mutex> lock(mutex);
  20704. cv.wait_for(lock, std::chrono::seconds(5),
  20705. [&] { return connected_at.size() >= 2; });
  20706. }
  20707. sse.stop();
  20708. // The server-supplied interval is applied, but never below 100ms, so
  20709. // "retry: 0" does not cause a busy reconnect loop
  20710. std::lock_guard<std::mutex> lock(mutex);
  20711. ASSERT_GE(connected_at.size(), 2u);
  20712. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20713. connected_at[1] - connected_at[0])
  20714. .count();
  20715. EXPECT_GE(interval_ms, 100);
  20716. }
  20717. // Test: Last-Event-ID sent on reconnect
  20718. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20719. std::atomic<int> connection_count{0};
  20720. std::vector<std::string> received_last_event_ids;
  20721. std::mutex id_mutex;
  20722. // Endpoint that checks Last-Event-ID header and sends event with ID
  20723. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20724. int conn = connection_count.fetch_add(1);
  20725. // Capture the Last-Event-ID header from each connection
  20726. {
  20727. std::lock_guard<std::mutex> lock(id_mutex);
  20728. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20729. }
  20730. res.set_chunked_content_provider(
  20731. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20732. if (offset == 0) {
  20733. std::string event =
  20734. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20735. sink.write(event.data(), event.size());
  20736. }
  20737. return false;
  20738. });
  20739. });
  20740. Client client("localhost", get_port());
  20741. sse::SSEClient sse(client, "/reconnect-with-id");
  20742. sse.set_reconnect_interval(100);
  20743. sse.set_max_reconnect_attempts(3);
  20744. sse.start_async();
  20745. // Wait for at least 2 connections
  20746. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20747. sse.stop();
  20748. // Verify behavior
  20749. std::lock_guard<std::mutex> lock(id_mutex);
  20750. EXPECT_GE(received_last_event_ids.size(), 2u);
  20751. // First connection should have no Last-Event-ID
  20752. if (!received_last_event_ids.empty()) {
  20753. EXPECT_EQ(received_last_event_ids[0], "");
  20754. }
  20755. // Second connection should have Last-Event-ID from first connection
  20756. if (received_last_event_ids.size() >= 2) {
  20757. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20758. }
  20759. }
  20760. // Test: set_headers updates headers used on reconnect
  20761. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20762. std::vector<std::string> received_tokens;
  20763. std::mutex token_mutex;
  20764. // Endpoint that captures Authorization header
  20765. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20766. {
  20767. std::lock_guard<std::mutex> lock(token_mutex);
  20768. received_tokens.push_back(req.get_header_value("Authorization"));
  20769. }
  20770. res.set_chunked_content_provider(
  20771. "text/event-stream", [](size_t offset, DataSink &sink) {
  20772. if (offset == 0) {
  20773. std::string event = "data: hello\n\n";
  20774. sink.write(event.data(), event.size());
  20775. }
  20776. return false; // Close connection to trigger reconnect
  20777. });
  20778. });
  20779. Client client("localhost", get_port());
  20780. Headers headers = {{"Authorization", "Bearer old-token"}};
  20781. sse::SSEClient sse(client, "/auth-check", headers);
  20782. // Update headers on each successful connection
  20783. sse.on_open(
  20784. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20785. sse.set_reconnect_interval(100);
  20786. sse.set_max_reconnect_attempts(3);
  20787. sse.start_async();
  20788. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20789. sse.stop();
  20790. std::lock_guard<std::mutex> lock(token_mutex);
  20791. ASSERT_GE(received_tokens.size(), 2u);
  20792. // First connection uses original header
  20793. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20794. // Second connection uses updated header from set_headers
  20795. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20796. }
  20797. // Test: 401 allows reconnection (so on_error can refresh headers)
  20798. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20799. std::atomic<int> connection_count{0};
  20800. // Endpoint: returns 401 on first attempt, 200 on second
  20801. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20802. int conn = connection_count.fetch_add(1);
  20803. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20804. res.status = StatusCode::Unauthorized_401;
  20805. res.set_content("Unauthorized", "text/plain");
  20806. return;
  20807. }
  20808. res.set_chunked_content_provider(
  20809. "text/event-stream", [](size_t offset, DataSink &sink) {
  20810. if (offset == 0) {
  20811. std::string event = "data: authenticated\n\n";
  20812. sink.write(event.data(), event.size());
  20813. }
  20814. return false;
  20815. });
  20816. });
  20817. Client client("localhost", get_port());
  20818. Headers headers = {{"Authorization", "Bearer expired"}};
  20819. sse::SSEClient sse(client, "/auth-retry", headers);
  20820. std::atomic<bool> message_received{false};
  20821. // Refresh token on error
  20822. sse.on_error(
  20823. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20824. sse.on_message([&](const sse::SSEMessage &msg) {
  20825. if (msg.data == "authenticated") { message_received.store(true); }
  20826. });
  20827. sse.set_reconnect_interval(100);
  20828. sse.set_max_reconnect_attempts(3);
  20829. sse.start_async();
  20830. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20831. sse.stop();
  20832. // Should have reconnected after 401 and succeeded with new token
  20833. EXPECT_GE(connection_count.load(), 2);
  20834. EXPECT_TRUE(message_received.load());
  20835. }
  20836. TEST(Issue2318Test, EmptyHostString) {
  20837. {
  20838. httplib::Client cli_empty("", PORT);
  20839. auto res = cli_empty.Get("/");
  20840. ASSERT_FALSE(res);
  20841. EXPECT_EQ(httplib::Error::Connection, res.error());
  20842. }
  20843. {
  20844. httplib::Client cli(" ", PORT);
  20845. auto res = cli.Get("/");
  20846. ASSERT_FALSE(res);
  20847. EXPECT_EQ(httplib::Error::Connection, res.error());
  20848. }
  20849. }
  20850. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20851. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20852. Server svr;
  20853. // Set a small payload limit (1KB)
  20854. svr.set_payload_max_length(1024);
  20855. svr.Post("/test", [&](const Request &req, Response &res) {
  20856. res.set_content("Body size: " + std::to_string(req.body.size()),
  20857. "text/plain");
  20858. });
  20859. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20860. auto se = detail::scope_exit([&] {
  20861. svr.stop();
  20862. listen_thread.join();
  20863. });
  20864. svr.wait_until_ready();
  20865. // Create data that compresses well but exceeds limit when decompressed
  20866. // 8KB of repeated null bytes compresses to a very small size
  20867. std::string original_data(8 * 1024, '\0');
  20868. // Compress the data using gzip
  20869. std::string compressed_data;
  20870. detail::gzip_compressor compressor;
  20871. compressor.compress(original_data.data(), original_data.size(), true,
  20872. [&](const char *data, size_t size) {
  20873. compressed_data.append(data, size);
  20874. return true;
  20875. });
  20876. // Verify compression worked (compressed should be much smaller)
  20877. ASSERT_LT(compressed_data.size(), original_data.size());
  20878. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20879. // Send compressed data with Content-Encoding: gzip
  20880. Client cli(HOST, PORT);
  20881. Headers headers = {{"Content-Encoding", "gzip"}};
  20882. auto res =
  20883. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20884. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20886. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20887. }
  20888. #endif
  20889. // ============================================================================
  20890. // OpenSSL-Specific Tests
  20891. // ============================================================================
  20892. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20893. X509 *readCertificate(const std::string &strFileName) {
  20894. std::ifstream inStream(strFileName);
  20895. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20896. std::istreambuf_iterator<char>());
  20897. if (strCertPEM.empty()) return (nullptr);
  20898. BIO *pbCert = BIO_new(BIO_s_mem());
  20899. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20900. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20901. BIO_free(pbCert);
  20902. return (pCert);
  20903. }
  20904. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20905. std::ifstream inStream(strFileName);
  20906. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20907. std::istreambuf_iterator<char>());
  20908. if (strPrivateKeyPEM.empty()) return (nullptr);
  20909. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20910. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20911. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20912. BIO_free(pbPrivKey);
  20913. return (pPrivateKey);
  20914. }
  20915. TEST(BindServerTest, UpdateCerts) {
  20916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20917. int port = svr.bind_to_any_port("0.0.0.0");
  20918. ASSERT_TRUE(svr.is_valid());
  20919. ASSERT_TRUE(port > 0);
  20920. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20921. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20922. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20923. ASSERT_TRUE(cert != nullptr);
  20924. ASSERT_TRUE(ca_cert != nullptr);
  20925. ASSERT_TRUE(key != nullptr);
  20926. X509_STORE *cert_store = X509_STORE_new();
  20927. X509_STORE_add_cert(cert_store, ca_cert);
  20928. // svr.update_certs(cert, key, cert_store); // deprecated
  20929. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20930. CLIENT_CA_CERT_FILE);
  20931. ASSERT_TRUE(svr.is_valid());
  20932. svr.stop();
  20933. X509_STORE_free(cert_store);
  20934. X509_free(cert);
  20935. X509_free(ca_cert);
  20936. EVP_PKEY_free(key);
  20937. }
  20938. // Test that update_certs() updates client CA list correctly
  20939. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20940. // Start with file-based constructor
  20941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20942. ASSERT_TRUE(svr.is_valid());
  20943. // Initially no client CA list should be set
  20944. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20945. ASSERT_TRUE(ssl_ctx != nullptr);
  20946. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20947. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20948. EXPECT_EQ(0, count_before);
  20949. // Now update with client CA (PEM string)
  20950. std::string cert_pem, key_pem, ca_pem;
  20951. read_file(SERVER_CERT_FILE, cert_pem);
  20952. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20953. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20954. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20955. ASSERT_TRUE(svr.is_valid());
  20956. // Now client CA list should be set
  20957. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20958. ASSERT_TRUE(ca_list_after != nullptr);
  20959. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20960. }
  20961. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20962. // Test that the file-path SSLServer constructor properly sets the client CA
  20963. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20964. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20965. ASSERT_TRUE(svr.is_valid());
  20966. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20967. ASSERT_TRUE(ssl_ctx != nullptr);
  20968. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20969. ASSERT_TRUE(ca_list != nullptr);
  20970. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20971. }
  20972. #endif
  20973. // ============================================================================
  20974. // MbedTLS-Specific Tests
  20975. // ============================================================================
  20976. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20977. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20978. using namespace httplib::tls;
  20979. // Track if callback was invoked
  20980. bool callback_invoked = false;
  20981. // The callback receives void* ctx which is actually MbedTlsContext*
  20982. // We can access the mbedtls_ssl_config via the context
  20983. auto setup_callback = [&callback_invoked](void *ctx) {
  20984. callback_invoked = true;
  20985. // Cast to MbedTlsContext* to access the ssl config
  20986. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20987. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20988. // Use static variables to hold certificate data (simplified for test)
  20989. static mbedtls_x509_crt own_cert;
  20990. static mbedtls_pk_context own_key;
  20991. static mbedtls_x509_crt ca_chain;
  20992. static bool initialized = false;
  20993. if (!initialized) {
  20994. mbedtls_x509_crt_init(&own_cert);
  20995. mbedtls_pk_init(&own_key);
  20996. mbedtls_x509_crt_init(&ca_chain);
  20997. // Load server certificate
  20998. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20999. return false;
  21000. }
  21001. // Load server private key.
  21002. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21003. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21004. #if MBEDTLS_VERSION_MAJOR == 3
  21005. ,
  21006. mbedtls_ctr_drbg_random, nullptr
  21007. #endif
  21008. ) != 0) {
  21009. return false;
  21010. }
  21011. // Load CA chain for client verification
  21012. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21013. return false;
  21014. }
  21015. initialized = true;
  21016. }
  21017. // Configure the SSL config
  21018. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21019. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21020. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21021. // Set minimum TLS version using mbedTLS native API
  21022. #if MBEDTLS_VERSION_MAJOR >= 3
  21023. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21024. #else
  21025. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21026. MBEDTLS_SSL_MINOR_VERSION_3);
  21027. #endif
  21028. return true;
  21029. };
  21030. SSLServer svr(setup_callback);
  21031. ASSERT_TRUE(svr.is_valid());
  21032. ASSERT_TRUE(callback_invoked);
  21033. svr.Get("/test", [&](const Request &req, Response &res) {
  21034. res.set_content("test", "text/plain");
  21035. auto cert = req.peer_cert();
  21036. ASSERT_TRUE(static_cast<bool>(cert));
  21037. auto common_name = cert.subject_cn();
  21038. EXPECT_EQ("Common Name", common_name);
  21039. });
  21040. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21041. auto se = detail::scope_exit([&] {
  21042. svr.stop();
  21043. t.join();
  21044. ASSERT_FALSE(svr.is_running());
  21045. });
  21046. svr.wait_until_ready();
  21047. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21048. cli.enable_server_certificate_verification(false);
  21049. cli.set_connection_timeout(30);
  21050. auto res = cli.Get("/test");
  21051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21052. ASSERT_EQ(StatusCode::OK_200, res->status);
  21053. }
  21054. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21055. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21056. // keep-alive SSL session, which reads through that config in
  21057. // mbedtls_ssl_close_notify.
  21058. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21060. ASSERT_TRUE(svr.is_valid());
  21061. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21062. res.set_content("test", "text/plain");
  21063. });
  21064. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21065. auto se = detail::scope_exit([&] {
  21066. svr.stop();
  21067. t.join();
  21068. ASSERT_FALSE(svr.is_running());
  21069. });
  21070. svr.wait_until_ready();
  21071. {
  21072. SSLClient cli(HOST, PORT);
  21073. cli.enable_server_certificate_verification(false);
  21074. cli.set_keep_alive(true);
  21075. auto res = cli.Get("/test");
  21076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21077. ASSERT_EQ(StatusCode::OK_200, res->status);
  21078. // cli is destructed here with the keep-alive SSL session still open.
  21079. }
  21080. }
  21081. #endif
  21082. // WebSocket Tests
  21083. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21084. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21085. // defining the meaning of these bits has been negotiated.
  21086. auto make_frame = [](uint8_t first_byte) {
  21087. std::string frame;
  21088. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21089. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21090. frame += "Hello";
  21091. return frame;
  21092. };
  21093. // RSV1 set (0x40)
  21094. {
  21095. detail::BufferStream strm;
  21096. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21097. ws::Opcode opcode;
  21098. std::string payload;
  21099. bool fin;
  21100. EXPECT_EQ(
  21101. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21102. ws::impl::FrameRead::Fail);
  21103. }
  21104. // RSV2 set (0x20)
  21105. {
  21106. detail::BufferStream strm;
  21107. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21108. ws::Opcode opcode;
  21109. std::string payload;
  21110. bool fin;
  21111. EXPECT_EQ(
  21112. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21113. ws::impl::FrameRead::Fail);
  21114. }
  21115. // RSV3 set (0x10)
  21116. {
  21117. detail::BufferStream strm;
  21118. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21119. ws::Opcode opcode;
  21120. std::string payload;
  21121. bool fin;
  21122. EXPECT_EQ(
  21123. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21124. ws::impl::FrameRead::Fail);
  21125. }
  21126. // No RSV bits set - should succeed
  21127. {
  21128. detail::BufferStream strm;
  21129. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21130. ws::Opcode opcode;
  21131. std::string payload;
  21132. bool fin;
  21133. EXPECT_EQ(
  21134. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21135. ws::impl::FrameRead::Ok);
  21136. EXPECT_EQ(ws::Opcode::Text, opcode);
  21137. EXPECT_EQ("Hello", payload);
  21138. EXPECT_TRUE(fin);
  21139. }
  21140. }
  21141. TEST(WebSocketTest, ControlFrameValidation) {
  21142. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21143. // payload length <= 125.
  21144. // Ping with FIN=0 - must be rejected
  21145. {
  21146. detail::BufferStream strm;
  21147. std::string frame;
  21148. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21149. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21150. strm.write(frame.data(), frame.size());
  21151. ws::Opcode opcode;
  21152. std::string payload;
  21153. bool fin;
  21154. EXPECT_EQ(
  21155. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21156. ws::impl::FrameRead::Fail);
  21157. }
  21158. // Close with FIN=0 - must be rejected
  21159. {
  21160. detail::BufferStream strm;
  21161. std::string frame;
  21162. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21163. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21164. strm.write(frame.data(), frame.size());
  21165. ws::Opcode opcode;
  21166. std::string payload;
  21167. bool fin;
  21168. EXPECT_EQ(
  21169. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21170. ws::impl::FrameRead::Fail);
  21171. }
  21172. // Ping with payload_len=126 (extended length) - must be rejected
  21173. {
  21174. detail::BufferStream strm;
  21175. std::string frame;
  21176. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21177. frame += static_cast<char>(126); // payload_len=126 (>125)
  21178. frame += static_cast<char>(0x00); // extended length high byte
  21179. frame += static_cast<char>(126); // extended length low byte
  21180. frame += std::string(126, 'x');
  21181. strm.write(frame.data(), frame.size());
  21182. ws::Opcode opcode;
  21183. std::string payload;
  21184. bool fin;
  21185. EXPECT_EQ(
  21186. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21187. ws::impl::FrameRead::Fail);
  21188. }
  21189. // Ping with FIN=1 and payload_len=125 - should succeed
  21190. {
  21191. detail::BufferStream strm;
  21192. std::string frame;
  21193. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21194. frame += static_cast<char>(125); // payload_len=125
  21195. frame += std::string(125, 'x');
  21196. strm.write(frame.data(), frame.size());
  21197. ws::Opcode opcode;
  21198. std::string payload;
  21199. bool fin;
  21200. EXPECT_EQ(
  21201. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21202. ws::impl::FrameRead::Ok);
  21203. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21204. EXPECT_EQ(125u, payload.size());
  21205. EXPECT_TRUE(fin);
  21206. }
  21207. }
  21208. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21209. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21210. // length MUST be 0.
  21211. // MSB set - must be rejected
  21212. {
  21213. detail::BufferStream strm;
  21214. std::string frame;
  21215. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21216. frame += static_cast<char>(127); // 64-bit extended length
  21217. frame += static_cast<char>(0x80); // MSB set (invalid)
  21218. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21219. strm.write(frame.data(), frame.size());
  21220. ws::Opcode opcode;
  21221. std::string payload;
  21222. bool fin;
  21223. EXPECT_EQ(
  21224. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21225. ws::impl::FrameRead::Fail);
  21226. }
  21227. // MSB clear - should pass length parsing (will be rejected by max_len,
  21228. // but that's a different check; use a small length to verify)
  21229. {
  21230. detail::BufferStream strm;
  21231. std::string frame;
  21232. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21233. frame += static_cast<char>(127); // 64-bit extended length
  21234. frame += std::string(7, '\0'); // high bytes = 0
  21235. frame += static_cast<char>(0x03); // length = 3
  21236. frame += "abc";
  21237. strm.write(frame.data(), frame.size());
  21238. ws::Opcode opcode;
  21239. std::string payload;
  21240. bool fin;
  21241. EXPECT_EQ(
  21242. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21243. ws::impl::FrameRead::Ok);
  21244. EXPECT_EQ(ws::Opcode::Text, opcode);
  21245. EXPECT_EQ("abc", payload);
  21246. }
  21247. }
  21248. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21249. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21250. // Valid UTF-8
  21251. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21252. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21253. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21254. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21255. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21256. // Invalid UTF-8
  21257. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21258. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21259. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21260. EXPECT_FALSE(
  21261. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21262. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21263. }
  21264. TEST(WebSocketTest, ConnectAndDisconnect) {
  21265. Server svr;
  21266. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21267. std::string msg;
  21268. while (ws.read(msg)) {}
  21269. });
  21270. auto port = svr.bind_to_any_port(HOST);
  21271. std::thread t([&]() { svr.listen_after_bind(); });
  21272. svr.wait_until_ready();
  21273. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21274. auto res = client.connect();
  21275. ASSERT_TRUE(res);
  21276. EXPECT_EQ(Error::Success, res.error());
  21277. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21278. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21279. EXPECT_TRUE(client.is_open());
  21280. client.close();
  21281. EXPECT_FALSE(client.is_open());
  21282. svr.stop();
  21283. t.join();
  21284. }
  21285. TEST(WebSocketTest, ValidURL) {
  21286. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21287. EXPECT_TRUE(ws1.is_valid());
  21288. ws::WebSocketClient ws2("ws://example.com/path");
  21289. EXPECT_TRUE(ws2.is_valid());
  21290. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21291. EXPECT_TRUE(ws3.is_valid());
  21292. #ifdef CPPHTTPLIB_SSL_ENABLED
  21293. ws::WebSocketClient wss1("wss://example.com/path");
  21294. EXPECT_TRUE(wss1.is_valid());
  21295. ws::WebSocketClient wss2("wss://example.com:443/path");
  21296. EXPECT_TRUE(wss2.is_valid());
  21297. #endif
  21298. }
  21299. TEST(WebSocketTest, InvalidURL) {
  21300. // No scheme
  21301. ws::WebSocketClient ws1("localhost:8080/path");
  21302. EXPECT_FALSE(ws1.is_valid());
  21303. // No path
  21304. ws::WebSocketClient ws2("ws://localhost:8080");
  21305. EXPECT_FALSE(ws2.is_valid());
  21306. // Empty string
  21307. ws::WebSocketClient ws3("");
  21308. EXPECT_FALSE(ws3.is_valid());
  21309. // Missing host
  21310. ws::WebSocketClient ws4("ws://:8080/path");
  21311. EXPECT_FALSE(ws4.is_valid());
  21312. // Port number overflow — should not crash
  21313. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21314. EXPECT_FALSE(ws5.is_valid());
  21315. // Port out of range
  21316. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21317. EXPECT_FALSE(ws6.is_valid());
  21318. }
  21319. TEST(WebSocketTest, UnsupportedScheme) {
  21320. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21321. ws::WebSocketClient ws1("http://localhost:8080/path");
  21322. EXPECT_FALSE(ws1.is_valid());
  21323. ws::WebSocketClient ws2("https://localhost:8080/path");
  21324. EXPECT_FALSE(ws2.is_valid());
  21325. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21326. EXPECT_FALSE(ws3.is_valid());
  21327. #else
  21328. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21329. std::invalid_argument);
  21330. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21331. std::invalid_argument);
  21332. #endif
  21333. }
  21334. TEST(WebSocketTest, ConnectWhenInvalid) {
  21335. ws::WebSocketClient ws("not a valid url");
  21336. EXPECT_FALSE(ws.is_valid());
  21337. auto res = ws.connect();
  21338. EXPECT_FALSE(res);
  21339. EXPECT_EQ(Error::Connection, res.error());
  21340. EXPECT_EQ(-1, res.status());
  21341. }
  21342. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21343. // Grab a port that is free, then close it again so nothing listens there
  21344. Server svr;
  21345. auto port = svr.bind_to_any_port(HOST);
  21346. svr.stop();
  21347. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21348. auto res = client.connect();
  21349. ASSERT_FALSE(res);
  21350. EXPECT_EQ(Error::Connection, res.error());
  21351. EXPECT_EQ(-1, res.status());
  21352. }
  21353. TEST(WebSocketTest, DefaultPort) {
  21354. ws::WebSocketClient ws1("ws://example.com/path");
  21355. EXPECT_TRUE(ws1.is_valid());
  21356. // ws:// defaults to port 80 (verified by successful parse)
  21357. #ifdef CPPHTTPLIB_SSL_ENABLED
  21358. ws::WebSocketClient ws2("wss://example.com/path");
  21359. EXPECT_TRUE(ws2.is_valid());
  21360. // wss:// defaults to port 443 (verified by successful parse)
  21361. #endif
  21362. }
  21363. TEST(WebSocketTest, IPv6LiteralAddress) {
  21364. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21365. EXPECT_TRUE(ws1.is_valid());
  21366. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21367. EXPECT_TRUE(ws2.is_valid());
  21368. }
  21369. TEST(WebSocketTest, ComplexPath) {
  21370. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21371. EXPECT_TRUE(ws1.is_valid());
  21372. ws::WebSocketClient ws2("ws://localhost:8080/");
  21373. EXPECT_TRUE(ws2.is_valid());
  21374. }
  21375. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21376. Server svr;
  21377. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21378. std::string msg;
  21379. while (ws.read(msg)) {}
  21380. });
  21381. auto port = svr.bind_to_any_port(HOST);
  21382. std::thread t([&]() { svr.listen_after_bind(); });
  21383. svr.wait_until_ready();
  21384. auto another_host = "example.com";
  21385. auto wrong_ip = "192.0.2.1";
  21386. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21387. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21388. ASSERT_TRUE(client.connect());
  21389. EXPECT_TRUE(client.is_open());
  21390. client.close();
  21391. svr.stop();
  21392. t.join();
  21393. }
  21394. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21395. Server svr;
  21396. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21397. std::string msg;
  21398. while (ws.read(msg)) {}
  21399. });
  21400. auto port = svr.bind_to_any_port(HOST);
  21401. std::thread t([&]() { svr.listen_after_bind(); });
  21402. svr.wait_until_ready();
  21403. auto wrong_ip = "192.0.2.1";
  21404. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21405. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21406. client.set_connection_timeout(1);
  21407. client.set_read_timeout(1);
  21408. client.set_write_timeout(1);
  21409. EXPECT_FALSE(client.connect());
  21410. EXPECT_FALSE(client.is_open());
  21411. svr.stop();
  21412. t.join();
  21413. }
  21414. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21415. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21416. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21417. // (RFC 6761) is only a map key and the Host header value.
  21418. auto host = "target.invalid";
  21419. Server svr;
  21420. std::string received_host;
  21421. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21422. received_host = req.get_header_value("Host");
  21423. std::string msg;
  21424. while (ws.read(msg)) {}
  21425. });
  21426. auto port = svr.bind_to_any_port(HOST);
  21427. std::thread t([&]() { svr.listen_after_bind(); });
  21428. // ASSERT_* below returns from the test body, which would leave t joinable
  21429. // and make ~thread call std::terminate.
  21430. auto se = detail::scope_exit([&] {
  21431. svr.stop();
  21432. if (t.joinable()) { t.join(); }
  21433. });
  21434. svr.wait_until_ready();
  21435. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21436. std::to_string(port) + "/ws");
  21437. client.set_hostname_addr_map({{host, HOST}});
  21438. ASSERT_TRUE(client.connect());
  21439. EXPECT_TRUE(client.is_open());
  21440. client.close();
  21441. svr.stop();
  21442. t.join();
  21443. // The mapping only redirects the connection; the identity stays host_.
  21444. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21445. }
  21446. class WebSocketIntegrationTest : public ::testing::Test {
  21447. protected:
  21448. void SetUp() override {
  21449. server_ = httplib::detail::make_unique<Server>();
  21450. setup_server();
  21451. start_server();
  21452. }
  21453. void TearDown() override {
  21454. server_->stop();
  21455. if (server_thread_.joinable()) { server_thread_.join(); }
  21456. }
  21457. void setup_server() {
  21458. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21459. std::string msg;
  21460. ws::ReadResult ret;
  21461. while ((ret = ws.read(msg))) {
  21462. if (ret == ws::Binary) {
  21463. ws.send(msg.data(), msg.size());
  21464. } else {
  21465. ws.send(msg);
  21466. }
  21467. }
  21468. });
  21469. server_->WebSocket("/ws-echo-string",
  21470. [](const Request &, ws::WebSocket &ws) {
  21471. std::string msg;
  21472. while (ws.read(msg)) {
  21473. ws.send("echo: " + msg);
  21474. }
  21475. });
  21476. server_->WebSocket(
  21477. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21478. // Echo back request metadata
  21479. ws.send("path:" + req.path);
  21480. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21481. std::string msg;
  21482. while (ws.read(msg)) {}
  21483. });
  21484. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21485. std::string msg;
  21486. ws.read(msg); // wait for a message
  21487. ws.close();
  21488. });
  21489. server_->WebSocket("/ws-close-status",
  21490. [](const Request &, ws::WebSocket &ws) {
  21491. std::string msg;
  21492. ws.read(msg); // wait for a message
  21493. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21494. });
  21495. server_->WebSocket(
  21496. "/ws-subprotocol",
  21497. [](const Request &, ws::WebSocket &ws) {
  21498. std::string msg;
  21499. while (ws.read(msg)) {
  21500. ws.send(msg);
  21501. }
  21502. },
  21503. [](const std::vector<std::string> &protocols) -> std::string {
  21504. for (const auto &p : protocols) {
  21505. if (p == "graphql-ws") { return p; }
  21506. }
  21507. return "";
  21508. });
  21509. server_->WebSocket(
  21510. "/ws-subprotocol-unoffered",
  21511. [](const Request &, ws::WebSocket &ws) {
  21512. std::string msg;
  21513. while (ws.read(msg)) {
  21514. ws.send(msg);
  21515. }
  21516. },
  21517. [](const std::vector<std::string> &) -> std::string {
  21518. return "admin";
  21519. });
  21520. }
  21521. void start_server() {
  21522. port_ = server_->bind_to_any_port(HOST);
  21523. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21524. server_->wait_until_ready();
  21525. }
  21526. std::unique_ptr<Server> server_;
  21527. std::thread server_thread_;
  21528. int port_ = 0;
  21529. };
  21530. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21531. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21532. "/ws-echo");
  21533. ASSERT_TRUE(client.connect());
  21534. ASSERT_TRUE(client.is_open());
  21535. ASSERT_TRUE(client.send("Hello WebSocket"));
  21536. std::string msg;
  21537. EXPECT_EQ(ws::Text, client.read(msg));
  21538. EXPECT_EQ("Hello WebSocket", msg);
  21539. client.close();
  21540. }
  21541. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21542. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21543. "/ws-echo");
  21544. ASSERT_TRUE(client.connect());
  21545. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21546. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21547. std::string msg;
  21548. EXPECT_EQ(ws::Binary, client.read(msg));
  21549. EXPECT_EQ(binary_data, msg);
  21550. client.close();
  21551. }
  21552. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21553. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21554. "/ws-echo");
  21555. ASSERT_TRUE(client.connect());
  21556. for (int i = 0; i < 10; i++) {
  21557. auto text = "message " + std::to_string(i);
  21558. ASSERT_TRUE(client.send(text));
  21559. std::string msg;
  21560. ASSERT_TRUE(client.read(msg));
  21561. EXPECT_EQ(text, msg);
  21562. }
  21563. client.close();
  21564. }
  21565. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21566. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21567. "/ws-close");
  21568. ASSERT_TRUE(client.connect());
  21569. // Send a message to trigger the server to close
  21570. ASSERT_TRUE(client.send("trigger close"));
  21571. // The server will close, so read should return false
  21572. std::string msg;
  21573. EXPECT_FALSE(client.read(msg));
  21574. EXPECT_FALSE(client.is_open());
  21575. }
  21576. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21577. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21578. "/ws-echo");
  21579. ASSERT_TRUE(client.connect());
  21580. // 128KB message
  21581. std::string large_data(128 * 1024, 'X');
  21582. ASSERT_TRUE(client.send(large_data));
  21583. std::string msg;
  21584. ASSERT_TRUE(client.read(msg));
  21585. EXPECT_EQ(large_data, msg);
  21586. client.close();
  21587. }
  21588. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21589. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21590. "/ws-echo");
  21591. ASSERT_TRUE(client.connect());
  21592. const int num_threads = 4;
  21593. std::vector<std::thread> threads;
  21594. std::atomic<int> send_count{0};
  21595. for (int t = 0; t < num_threads; t++) {
  21596. threads.emplace_back([&client, &send_count, t]() {
  21597. for (int i = 0; i < 5; i++) {
  21598. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21599. if (client.send(text)) { send_count++; }
  21600. }
  21601. });
  21602. }
  21603. for (auto &th : threads) {
  21604. th.join();
  21605. }
  21606. int received = 0;
  21607. std::string msg;
  21608. while (received < send_count.load()) {
  21609. if (!client.read(msg)) { break; }
  21610. received++;
  21611. }
  21612. EXPECT_EQ(send_count.load(), received);
  21613. client.close();
  21614. }
  21615. TEST_F(WebSocketIntegrationTest, ReadString) {
  21616. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21617. "/ws-echo-string");
  21618. ASSERT_TRUE(client.connect());
  21619. ASSERT_TRUE(client.send("hello"));
  21620. std::string msg;
  21621. ASSERT_TRUE(client.read(msg));
  21622. EXPECT_EQ("echo: hello", msg);
  21623. ASSERT_TRUE(client.send("world"));
  21624. ASSERT_TRUE(client.read(msg));
  21625. EXPECT_EQ("echo: world", msg);
  21626. client.close();
  21627. }
  21628. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21629. Headers headers = {{"X-Test-Header", "test-value"}};
  21630. ws::WebSocketClient client(
  21631. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21632. ASSERT_TRUE(client.connect());
  21633. std::string msg;
  21634. ASSERT_TRUE(client.read(msg));
  21635. EXPECT_EQ("path:/ws-request-info", msg);
  21636. ASSERT_TRUE(client.read(msg));
  21637. EXPECT_EQ("header:test-value", msg);
  21638. client.close();
  21639. }
  21640. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21641. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21642. "/ws-echo");
  21643. client.set_read_timeout(1, 0); // 1 second
  21644. ASSERT_TRUE(client.connect());
  21645. // Don't send anything — server echo handler waits for a message, so read()
  21646. // should time out. The connection survives it: nothing was consumed.
  21647. std::string msg;
  21648. EXPECT_EQ(client.read(msg), ws::Timeout);
  21649. EXPECT_TRUE(client.is_open());
  21650. // And it is still usable afterwards.
  21651. EXPECT_TRUE(client.send("after timeout"));
  21652. EXPECT_EQ(client.read(msg), ws::Text);
  21653. EXPECT_EQ(msg, "after timeout");
  21654. }
  21655. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21656. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21657. "/ws-echo");
  21658. client.set_read_timeout(1, 0);
  21659. ASSERT_TRUE(client.connect());
  21660. ASSERT_TRUE(client.send("first"));
  21661. std::string msg;
  21662. ASSERT_EQ(client.read(msg), ws::Text);
  21663. ASSERT_EQ(msg, "first");
  21664. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21665. // not be used with a read timeout: it would reprocess the previous message.
  21666. EXPECT_EQ(client.read(msg), ws::Timeout);
  21667. EXPECT_EQ(msg, "first");
  21668. }
  21669. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21670. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21671. "/ws-echo");
  21672. ASSERT_TRUE(client.connect());
  21673. // Setting it once the connection is open reaches the live stream, not just
  21674. // the seed for the next connect().
  21675. client.set_read_timeout(1, 0);
  21676. std::string msg;
  21677. EXPECT_EQ(client.read(msg), ws::Timeout);
  21678. EXPECT_TRUE(client.is_open());
  21679. }
  21680. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21681. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21682. "/ws-echo");
  21683. client.set_read_timeout(5, 0);
  21684. ASSERT_TRUE(client.connect());
  21685. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21686. // The server should reject it and close the connection.
  21687. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21688. client.send(oversized);
  21689. // The server's read() should have failed due to payload limit,
  21690. // so our read() should return false (connection closed).
  21691. std::string msg;
  21692. EXPECT_FALSE(client.read(msg));
  21693. }
  21694. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21695. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21696. "/ws-echo");
  21697. client.set_read_timeout(10, 0);
  21698. ASSERT_TRUE(client.connect());
  21699. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21700. // This should succeed.
  21701. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21702. ASSERT_TRUE(client.send(at_limit));
  21703. std::string msg;
  21704. ASSERT_TRUE(client.read(msg));
  21705. EXPECT_EQ(at_limit.size(), msg.size());
  21706. client.close();
  21707. }
  21708. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21709. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21710. "/nonexistent");
  21711. auto res = client.connect();
  21712. EXPECT_FALSE(res);
  21713. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21714. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21715. EXPECT_FALSE(client.is_open());
  21716. }
  21717. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21718. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21719. "/ws-echo");
  21720. ASSERT_TRUE(client.connect());
  21721. ASSERT_TRUE(client.send(""));
  21722. std::string msg;
  21723. EXPECT_EQ(ws::Text, client.read(msg));
  21724. EXPECT_EQ("", msg);
  21725. client.close();
  21726. }
  21727. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21728. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21729. "/ws-echo");
  21730. // First connection
  21731. ASSERT_TRUE(client.connect());
  21732. ASSERT_TRUE(client.send("first"));
  21733. std::string msg;
  21734. ASSERT_TRUE(client.read(msg));
  21735. EXPECT_EQ("first", msg);
  21736. client.close();
  21737. EXPECT_FALSE(client.is_open());
  21738. // Reconnect using the same client object
  21739. ASSERT_TRUE(client.connect());
  21740. ASSERT_TRUE(client.is_open());
  21741. ASSERT_TRUE(client.send("second"));
  21742. ASSERT_TRUE(client.read(msg));
  21743. EXPECT_EQ("second", msg);
  21744. client.close();
  21745. }
  21746. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21747. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21748. "/ws-close-status");
  21749. ASSERT_TRUE(client.connect());
  21750. // Trigger the server to close with GoingAway status
  21751. ASSERT_TRUE(client.send("trigger"));
  21752. // read() should return false after receiving the close frame
  21753. std::string msg;
  21754. EXPECT_FALSE(client.read(msg));
  21755. EXPECT_FALSE(client.is_open());
  21756. }
  21757. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21758. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21759. "/ws-echo");
  21760. ASSERT_TRUE(client.connect());
  21761. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21762. EXPECT_FALSE(client.is_open());
  21763. }
  21764. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21765. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21766. ws::WebSocketClient client(
  21767. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21768. ASSERT_TRUE(client.connect());
  21769. // Server should have selected graphql-ws
  21770. EXPECT_EQ("graphql-ws", client.subprotocol());
  21771. client.close();
  21772. }
  21773. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21774. Headers headers;
  21775. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21776. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21777. ws::WebSocketClient client(
  21778. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21779. ASSERT_TRUE(client.connect());
  21780. // The offer on the second field line counts too, so graphql-ws is selected
  21781. EXPECT_EQ("graphql-ws", client.subprotocol());
  21782. client.close();
  21783. }
  21784. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21785. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21786. ws::WebSocketClient client(
  21787. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21788. ASSERT_TRUE(client.connect());
  21789. // Server should not have selected any subprotocol
  21790. EXPECT_TRUE(client.subprotocol().empty());
  21791. client.close();
  21792. }
  21793. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21794. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21795. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21796. "/ws-subprotocol-unoffered",
  21797. headers);
  21798. ASSERT_TRUE(client.connect());
  21799. EXPECT_TRUE(client.subprotocol().empty());
  21800. client.close();
  21801. }
  21802. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21803. // Connect without requesting any subprotocol
  21804. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21805. "/ws-subprotocol");
  21806. ASSERT_TRUE(client.connect());
  21807. EXPECT_TRUE(client.subprotocol().empty());
  21808. client.close();
  21809. }
  21810. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21811. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21812. "/ws-echo");
  21813. client.set_tcp_nodelay(true);
  21814. client.set_connection_timeout(3, 0);
  21815. bool socket_options_called = false;
  21816. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21817. ASSERT_TRUE(client.connect());
  21818. ASSERT_TRUE(client.is_open());
  21819. EXPECT_TRUE(socket_options_called);
  21820. ASSERT_TRUE(client.send("hello"));
  21821. std::string msg;
  21822. auto result = client.read(msg);
  21823. EXPECT_EQ(result, ws::ReadResult::Text);
  21824. EXPECT_EQ(msg, "hello");
  21825. client.close();
  21826. }
  21827. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21828. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21829. "/ws-echo");
  21830. client.set_connection_timeout(std::chrono::seconds(3));
  21831. client.set_write_timeout(std::chrono::seconds(3));
  21832. // A sub-second remainder exercises the seconds/microseconds split.
  21833. client.set_read_timeout(std::chrono::milliseconds(1500));
  21834. ASSERT_TRUE(client.connect());
  21835. auto start = std::chrono::steady_clock::now();
  21836. std::string msg;
  21837. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21838. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21839. std::chrono::steady_clock::now() - start)
  21840. .count();
  21841. // Above 1s so that dropping the microseconds half of the split fails here.
  21842. // Ignoring the setter altogether would not reach this line at all: a client
  21843. // waits forever by default.
  21844. EXPECT_GE(elapsed, 1400);
  21845. EXPECT_LT(elapsed, 30000);
  21846. }
  21847. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21848. Server svr;
  21849. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21850. if (!req.has_header("Authorization")) {
  21851. res.status = StatusCode::Unauthorized_401;
  21852. res.set_content("Unauthorized", "text/plain");
  21853. return Server::HandlerResponse::Handled;
  21854. }
  21855. return Server::HandlerResponse::Unhandled;
  21856. });
  21857. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21858. std::string msg;
  21859. while (ws.read(msg)) {
  21860. ws.send(msg);
  21861. }
  21862. });
  21863. auto port = svr.bind_to_any_port("localhost");
  21864. std::thread t([&]() { svr.listen_after_bind(); });
  21865. svr.wait_until_ready();
  21866. // Without Authorization header - should be rejected before upgrade
  21867. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21868. EXPECT_FALSE(client1.connect());
  21869. // The rejection is framed like any other HTTP response
  21870. {
  21871. Client cli("localhost", port);
  21872. Headers headers = {{"Upgrade", "websocket"},
  21873. {"Connection", "Upgrade"},
  21874. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21875. {"Sec-WebSocket-Version", "13"}};
  21876. auto res = cli.Get("/ws", headers);
  21877. ASSERT_TRUE(res);
  21878. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21879. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21880. EXPECT_EQ("Unauthorized", res->body);
  21881. }
  21882. // With Authorization header - should succeed
  21883. Headers headers = {{"Authorization", "Bearer token123"}};
  21884. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21885. headers);
  21886. ASSERT_TRUE(client2.connect());
  21887. ASSERT_TRUE(client2.send("hello"));
  21888. std::string msg;
  21889. ASSERT_TRUE(client2.read(msg));
  21890. EXPECT_EQ("hello", msg);
  21891. client2.close();
  21892. svr.stop();
  21893. t.join();
  21894. }
  21895. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21896. Server svr;
  21897. std::atomic<int> pre_request_calls{0};
  21898. std::atomic<bool> route_matched{false};
  21899. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21900. pre_request_calls++;
  21901. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21902. if (req.get_header_value("Authorization") != "Bearer token123") {
  21903. res.status = StatusCode::Unauthorized_401;
  21904. res.set_content("Unauthorized", "text/plain");
  21905. return Server::HandlerResponse::Handled;
  21906. }
  21907. return Server::HandlerResponse::Unhandled;
  21908. });
  21909. std::atomic<bool> handler_called{false};
  21910. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21911. handler_called = true;
  21912. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21913. });
  21914. auto port = svr.bind_to_any_port("localhost");
  21915. std::thread t([&]() { svr.listen_after_bind(); });
  21916. svr.wait_until_ready();
  21917. // Without Authorization header - should be rejected before upgrade
  21918. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21919. "/ws/1");
  21920. EXPECT_FALSE(client1.connect());
  21921. EXPECT_FALSE(handler_called);
  21922. EXPECT_EQ(1, pre_request_calls);
  21923. EXPECT_TRUE(route_matched);
  21924. // The rejection is an ordinary HTTP response, not a protocol switch
  21925. {
  21926. Client cli("localhost", port);
  21927. Headers headers = {{"Upgrade", "websocket"},
  21928. {"Connection", "Upgrade"},
  21929. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21930. {"Sec-WebSocket-Version", "13"}};
  21931. auto res = cli.Get("/ws/1", headers);
  21932. ASSERT_TRUE(res);
  21933. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21934. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21935. EXPECT_EQ("Unauthorized", res->body);
  21936. }
  21937. EXPECT_FALSE(handler_called);
  21938. // With Authorization header - should succeed
  21939. Headers headers = {{"Authorization", "Bearer token123"}};
  21940. ws::WebSocketClient client2(
  21941. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21942. ASSERT_TRUE(client2.connect());
  21943. std::string msg;
  21944. ASSERT_TRUE(client2.read(msg));
  21945. EXPECT_EQ("/ws/:id 2", msg);
  21946. EXPECT_TRUE(handler_called);
  21947. client2.close();
  21948. svr.stop();
  21949. t.join();
  21950. }
  21951. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21952. Server svr;
  21953. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21954. // A read timeout is how a handler gets control back. Without it, a handler
  21955. // parked in read() can never write on the connection it is reading.
  21956. ws.set_read_timeout(std::chrono::milliseconds(100));
  21957. std::string msg;
  21958. while (ws.is_open()) {
  21959. auto r = ws.read(msg);
  21960. if (r == httplib::ws::Timeout) {
  21961. ws.send("tick");
  21962. continue;
  21963. }
  21964. if (r == httplib::ws::Fail) { break; }
  21965. ws.send(msg);
  21966. }
  21967. });
  21968. auto port = svr.bind_to_any_port("localhost");
  21969. std::thread t([&]() { svr.listen_after_bind(); });
  21970. svr.wait_until_ready();
  21971. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21972. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21973. ASSERT_TRUE(client.connect());
  21974. // The client sends nothing, so anything it receives came out of the
  21975. // handler's timeout path.
  21976. std::string msg;
  21977. ASSERT_EQ(client.read(msg), ws::Text);
  21978. EXPECT_EQ("tick", msg);
  21979. client.close();
  21980. svr.stop();
  21981. t.join();
  21982. }
  21983. // Stream::read may return fewer bytes than asked for. This is that contract at
  21984. // its worst -- one byte per call -- which is what a frame header straddling a
  21985. // read buffer's boundary looks like to the frame parser.
  21986. class WsByteAtATimeStream : public Stream {
  21987. public:
  21988. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21989. bool is_readable() const override { return true; }
  21990. bool wait_readable() const override { return true; }
  21991. bool wait_writable() const override { return true; }
  21992. ssize_t read(char *ptr, size_t size) override {
  21993. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21994. *ptr = data_[pos_++];
  21995. return 1;
  21996. }
  21997. ssize_t write(const char *, size_t size) override {
  21998. return static_cast<ssize_t>(size);
  21999. }
  22000. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22001. ip = "127.0.0.1";
  22002. port = 0;
  22003. }
  22004. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22005. ip = "127.0.0.1";
  22006. port = 0;
  22007. }
  22008. socket_t socket() const override { return INVALID_SOCKET; }
  22009. time_t duration() const override { return 0; }
  22010. private:
  22011. std::string data_;
  22012. size_t pos_ = 0;
  22013. };
  22014. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22015. // The payload uses the 16-bit extended length, so the header, the length
  22016. // and the mask key are all multi-byte fields here. Each used to be read
  22017. // with a single read() call, which fails as soon as one is split. The
  22018. // payload is also a little over one read chunk, so it is read in two.
  22019. std::string body;
  22020. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22021. body += static_cast<char>(i % 251);
  22022. }
  22023. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22024. std::string frame;
  22025. frame += static_cast<char>(0x81); // FIN + Text
  22026. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22027. frame += static_cast<char>(body.size() >> 8);
  22028. frame += static_cast<char>(body.size() & 0xff);
  22029. for (size_t i = 0; i < 4; i++) {
  22030. frame += static_cast<char>(mask[i]);
  22031. }
  22032. for (size_t i = 0; i < body.size(); i++) {
  22033. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22034. }
  22035. WsByteAtATimeStream strm(frame);
  22036. ws::Opcode opcode;
  22037. std::string payload;
  22038. bool fin = false;
  22039. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22040. /*expect_masked=*/true, body.size()),
  22041. ws::impl::FrameRead::Ok);
  22042. EXPECT_TRUE(fin);
  22043. EXPECT_EQ(opcode, ws::Opcode::Text);
  22044. EXPECT_EQ(payload, body);
  22045. }
  22046. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22047. std::string body(2000, 'x');
  22048. std::string frame;
  22049. frame += static_cast<char>(0x82); // FIN + Binary
  22050. frame += static_cast<char>(126); // 16-bit length follows
  22051. frame += static_cast<char>(body.size() >> 8);
  22052. frame += static_cast<char>(body.size() & 0xff);
  22053. frame += body;
  22054. detail::BufferStream strm;
  22055. strm.write(frame.data(), frame.size());
  22056. ws::Opcode opcode;
  22057. std::string payload;
  22058. bool fin;
  22059. EXPECT_EQ(
  22060. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22061. ws::impl::FrameRead::Ok);
  22062. EXPECT_EQ(body, payload);
  22063. }
  22064. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22065. // The header announces the largest payload allowed, and only 3 bytes of it
  22066. // ever arrive.
  22067. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22068. std::string frame;
  22069. frame += static_cast<char>(0x82); // FIN + Binary
  22070. frame += static_cast<char>(127); // 64-bit length follows
  22071. for (int shift = 56; shift >= 0; shift -= 8) {
  22072. frame += static_cast<char>((len >> shift) & 0xff);
  22073. }
  22074. frame += "abc";
  22075. detail::BufferStream strm;
  22076. strm.write(frame.data(), frame.size());
  22077. ws::Opcode opcode;
  22078. std::string payload;
  22079. bool fin;
  22080. EXPECT_EQ(
  22081. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22082. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22083. ws::impl::FrameRead::Fail);
  22084. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22085. }
  22086. TEST(WebSocketTest, QueryStringInHandshake) {
  22087. Server svr;
  22088. std::mutex mtx;
  22089. std::string received_target;
  22090. std::string received_token;
  22091. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22092. {
  22093. std::lock_guard<std::mutex> lock(mtx);
  22094. received_target = req.target;
  22095. if (req.has_param("token")) {
  22096. received_token = req.get_param_value("token");
  22097. }
  22098. }
  22099. std::string msg;
  22100. while (ws.read(msg)) {
  22101. ws.send(msg);
  22102. }
  22103. });
  22104. auto port = svr.bind_to_any_port("localhost");
  22105. std::thread t([&]() { svr.listen_after_bind(); });
  22106. svr.wait_until_ready();
  22107. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22108. "/ws?token=ABC&session=123");
  22109. ASSERT_TRUE(client.connect());
  22110. // Round-trip ensures the handler has run and captured the request.
  22111. ASSERT_TRUE(client.send("hello"));
  22112. std::string msg;
  22113. ASSERT_TRUE(client.read(msg));
  22114. EXPECT_EQ("hello", msg);
  22115. client.close();
  22116. {
  22117. std::lock_guard<std::mutex> lock(mtx);
  22118. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22119. EXPECT_EQ("ABC", received_token);
  22120. }
  22121. svr.stop();
  22122. t.join();
  22123. }
  22124. // Run a handshake against a throwaway server and hand the request the server
  22125. // received back to the caller, so tests can assert on the headers the client
  22126. // actually put on the wire.
  22127. static void capture_websocket_handshake_request(
  22128. const Headers &client_headers,
  22129. std::function<void(const Request &, int port)> verify) {
  22130. Server svr;
  22131. std::mutex mtx;
  22132. Request received;
  22133. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22134. {
  22135. std::lock_guard<std::mutex> lock(mtx);
  22136. received = req;
  22137. }
  22138. std::string msg;
  22139. while (ws.read(msg)) {
  22140. ws.send(msg);
  22141. }
  22142. });
  22143. auto port = svr.bind_to_any_port("localhost");
  22144. std::thread t([&]() { svr.listen_after_bind(); });
  22145. auto se = detail::scope_exit([&] {
  22146. svr.stop();
  22147. t.join();
  22148. });
  22149. svr.wait_until_ready();
  22150. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22151. client_headers);
  22152. ASSERT_TRUE(client.connect());
  22153. ASSERT_TRUE(client.send("hello"));
  22154. std::string msg;
  22155. ASSERT_TRUE(client.read(msg));
  22156. client.close();
  22157. {
  22158. std::lock_guard<std::mutex> lock(mtx);
  22159. verify(received, port);
  22160. }
  22161. }
  22162. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22163. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22164. // Non-default port must be present in the Host header. Default ports
  22165. // (80/443) are omitted; that logic is covered by
  22166. // MakeHostAndPortStringTest.
  22167. EXPECT_EQ("localhost:" + std::to_string(port),
  22168. req.get_header_value("Host"));
  22169. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22170. req.get_header_value("User-Agent"));
  22171. EXPECT_FALSE(req.has_header("Accept"));
  22172. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22173. EXPECT_FALSE(req.has_header("Content-Length"));
  22174. });
  22175. }
  22176. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22177. capture_websocket_handshake_request(
  22178. {{"Host", "example.com"},
  22179. {"User-Agent", "custom-agent"},
  22180. {"X-Custom", "value"}},
  22181. [](const Request &req, int) {
  22182. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22183. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22184. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22185. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22186. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22187. });
  22188. }
  22189. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22190. capture_websocket_handshake_request(
  22191. {{"Upgrade", "bogus"},
  22192. {"Connection", "close"},
  22193. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22194. {"Sec-WebSocket-Version", "8"}},
  22195. [](const Request &req, int) {
  22196. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22197. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22198. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22199. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22200. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22201. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22202. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22203. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22204. req.get_header_value("Sec-WebSocket-Key"));
  22205. });
  22206. }
  22207. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22208. // A header the client refuses to send must abort the handshake before any
  22209. // part of it reaches the wire; a lone request line would otherwise sit in
  22210. // the peer's buffer as a truncated request.
  22211. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22212. ASSERT_NE(INVALID_SOCKET, srv);
  22213. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22214. sockaddr_in addr{};
  22215. addr.sin_family = AF_INET;
  22216. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22217. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22218. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22219. ASSERT_EQ(0, ::listen(srv, 1));
  22220. sockaddr_in bound{};
  22221. socklen_t bound_len = sizeof(bound);
  22222. ASSERT_EQ(
  22223. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22224. auto port = ntohs(bound.sin_port);
  22225. ssize_t received = -1;
  22226. std::thread t([&] {
  22227. // Bound every blocking call so a regression fails the test with a bad
  22228. // value instead of hanging the suite.
  22229. fd_set rfds;
  22230. FD_ZERO(&rfds);
  22231. FD_SET(srv, &rfds);
  22232. timeval tv{5, 0};
  22233. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22234. 0) {
  22235. return;
  22236. }
  22237. sockaddr_in cli_addr{};
  22238. socklen_t cli_len = sizeof(cli_addr);
  22239. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22240. if (cli == INVALID_SOCKET) { return; }
  22241. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22242. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22243. char buf[4096];
  22244. received = ::recv(cli, buf, sizeof(buf), 0);
  22245. });
  22246. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22247. // connect() has already shut the socket down by the time it returns false,
  22248. // so the peer sees EOF without waiting for the client to be destroyed.
  22249. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22250. {{"X-Bad", "a\r\nInjected: 1"}});
  22251. EXPECT_FALSE(client.connect());
  22252. t.join();
  22253. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22254. EXPECT_EQ(0, received);
  22255. }
  22256. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22257. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22258. // contains "upgrade" as a substring is a different token and must not
  22259. // start a WebSocket handshake.
  22260. auto make_request = [](const std::vector<std::string> &connection_values) {
  22261. Request req;
  22262. req.method = "GET";
  22263. req.headers.emplace("Upgrade", "websocket");
  22264. for (const auto &value : connection_values) {
  22265. req.headers.emplace("Connection", value);
  22266. }
  22267. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22268. req.headers.emplace("Sec-WebSocket-Version", "13");
  22269. return req;
  22270. };
  22271. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22272. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22273. EXPECT_TRUE(
  22274. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22275. EXPECT_TRUE(
  22276. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22277. EXPECT_TRUE(
  22278. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22279. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22280. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22281. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22282. EXPECT_FALSE(
  22283. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22284. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22285. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22286. }
  22287. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22288. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22289. // asks recipients to match each protocol-name case-insensitively, and RFC
  22290. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22291. // client naming websocket alongside another protocol, or on a second field
  22292. // line, is offering websocket; a value that merely contains "websocket" as a
  22293. // substring is a different protocol name and is not.
  22294. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22295. Request req;
  22296. req.method = "GET";
  22297. for (const auto &value : upgrade_values) {
  22298. req.headers.emplace("Upgrade", value);
  22299. }
  22300. req.headers.emplace("Connection", "Upgrade");
  22301. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22302. req.headers.emplace("Sec-WebSocket-Version", "13");
  22303. return req;
  22304. };
  22305. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22306. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22307. EXPECT_TRUE(
  22308. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22309. EXPECT_TRUE(
  22310. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22311. EXPECT_TRUE(
  22312. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22313. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22314. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22315. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22316. EXPECT_FALSE(
  22317. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22318. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22319. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22320. }
  22321. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22322. Server svr;
  22323. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22324. auto port = svr.bind_to_any_port("localhost");
  22325. std::thread t([&]() { svr.listen_after_bind(); });
  22326. auto se = detail::scope_exit([&] {
  22327. svr.stop();
  22328. t.join();
  22329. });
  22330. svr.wait_until_ready();
  22331. Headers headers = {{"Upgrade", "websocket"},
  22332. {"Connection", "notupgrade"},
  22333. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22334. {"Sec-WebSocket-Version", "13"}};
  22335. Client cli("localhost", port);
  22336. auto res = cli.Get("/ws", headers);
  22337. // The route exists only as a WebSocket route, so a request that fails the
  22338. // handshake check falls through to ordinary routing.
  22339. ASSERT_TRUE(res);
  22340. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22341. }
  22342. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22343. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22344. // Connection value is the only thing left for the client to reject.
  22345. Server svr;
  22346. svr.Get("/ws", [](const Request &req, Response &res) {
  22347. res.status = StatusCode::SwitchingProtocol_101;
  22348. res.set_header("Upgrade", "websocket");
  22349. res.set_header("Connection", "notupgrade");
  22350. res.set_header("Sec-WebSocket-Accept",
  22351. detail::websocket_accept_key(
  22352. req.get_header_value("Sec-WebSocket-Key")));
  22353. });
  22354. auto port = svr.bind_to_any_port("localhost");
  22355. std::thread t([&]() { svr.listen_after_bind(); });
  22356. auto se = detail::scope_exit([&] {
  22357. svr.stop();
  22358. t.join();
  22359. });
  22360. svr.wait_until_ready();
  22361. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22362. auto res = client.connect();
  22363. EXPECT_FALSE(res);
  22364. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22365. EXPECT_FALSE(client.is_open());
  22366. }
  22367. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22368. Server svr;
  22369. svr.Get("/ws", [](const Request &req, Response &res) {
  22370. res.status = StatusCode::SwitchingProtocol_101;
  22371. res.set_header("Upgrade", "websocket");
  22372. res.set_header("Connection", "Upgrade");
  22373. res.set_header("Sec-WebSocket-Accept",
  22374. detail::websocket_accept_key(
  22375. req.get_header_value("Sec-WebSocket-Key")));
  22376. res.set_header("Sec-WebSocket-Protocol", "admin");
  22377. });
  22378. auto port = svr.bind_to_any_port("localhost");
  22379. std::thread t([&]() { svr.listen_after_bind(); });
  22380. auto se = detail::scope_exit([&] {
  22381. svr.stop();
  22382. t.join();
  22383. });
  22384. svr.wait_until_ready();
  22385. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22386. // Server selects a subprotocol the client never offered
  22387. {
  22388. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22389. ws::WebSocketClient client(url, headers);
  22390. auto res = client.connect();
  22391. EXPECT_FALSE(res);
  22392. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22393. EXPECT_FALSE(client.is_open());
  22394. EXPECT_TRUE(client.subprotocol().empty());
  22395. }
  22396. // Client offered none but the server named one anyway
  22397. {
  22398. ws::WebSocketClient client(url);
  22399. auto res = client.connect();
  22400. EXPECT_FALSE(res);
  22401. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22402. EXPECT_FALSE(client.is_open());
  22403. EXPECT_TRUE(client.subprotocol().empty());
  22404. }
  22405. }
  22406. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22407. // The socket path doubles as the URL host, so it must not contain '/'.
  22408. const char *shard = getenv("GTEST_SHARD_INDEX");
  22409. const std::string sock_path =
  22410. shard ? std::string("httplib-ws-") + shard + ".sock"
  22411. : std::string("httplib-ws.sock");
  22412. std::remove(sock_path.c_str());
  22413. Server svr;
  22414. std::mutex mtx;
  22415. std::string received_host;
  22416. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22417. {
  22418. std::lock_guard<std::mutex> lock(mtx);
  22419. received_host = req.get_header_value("Host");
  22420. }
  22421. std::string msg;
  22422. while (ws.read(msg)) {
  22423. ws.send(msg);
  22424. }
  22425. });
  22426. svr.set_address_family(AF_UNIX);
  22427. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22428. auto se = detail::scope_exit([&] {
  22429. svr.stop();
  22430. t.join();
  22431. std::remove(sock_path.c_str());
  22432. });
  22433. svr.wait_until_ready();
  22434. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22435. client.set_address_family(AF_UNIX);
  22436. ASSERT_TRUE(client.connect());
  22437. ASSERT_TRUE(client.send("hello"));
  22438. std::string msg;
  22439. ASSERT_TRUE(client.read(msg));
  22440. client.close();
  22441. {
  22442. std::lock_guard<std::mutex> lock(mtx);
  22443. // There is no host:port for a Unix socket, so the same "localhost"
  22444. // placeholder the HTTP client uses is expected.
  22445. EXPECT_EQ("localhost", received_host);
  22446. }
  22447. }
  22448. // Two threads must never parse WebSocket frames from the same stream.
  22449. // close() used to read the peer's Close reply with its own frame read, so it
  22450. // raced a reader thread that was in the middle of a payload: the payload loop
  22451. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22452. // so bytes taken by close() were replaced with bytes from further along the
  22453. // stream. The message kept its length and silently changed content.
  22454. //
  22455. // The raw peer below sends a frame header plus part of the payload, waits for
  22456. // the handler to call close(), and only then sends the rest. Whichever thread
  22457. // would win the race for those bytes, the message must arrive intact, because
  22458. // close() must not touch the stream while read() owns it.
  22459. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22460. #ifndef _WIN32
  22461. signal(SIGPIPE, SIG_IGN);
  22462. #endif
  22463. const size_t payload_len = 120; // fits the 7-bit length field
  22464. const size_t prefix_len = 8;
  22465. const int attempts = 8;
  22466. std::string expected(payload_len, '\0');
  22467. for (size_t i = 0; i < payload_len; i++) {
  22468. expected[i] = static_cast<char>('a' + i % 26);
  22469. }
  22470. std::atomic<bool> peer_stalled{false};
  22471. std::atomic<bool> handler_done{false};
  22472. std::mutex received_mutex;
  22473. std::vector<std::string> received;
  22474. // Bound every wait, so a regression fails the test instead of hanging the
  22475. // suite.
  22476. auto wait_for = [](const std::atomic<bool> &flag) {
  22477. for (int i = 0; i < 500 && !flag; i++) {
  22478. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22479. }
  22480. };
  22481. Server svr;
  22482. svr.set_websocket_ping_interval(0);
  22483. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22484. std::thread reader([&]() {
  22485. std::string msg;
  22486. while (ws.read(msg)) {
  22487. std::lock_guard<std::mutex> guard(received_mutex);
  22488. received.push_back(msg);
  22489. }
  22490. });
  22491. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22492. // inside read_websocket_frame() when close() runs.
  22493. wait_for(peer_stalled);
  22494. ws.close();
  22495. reader.join();
  22496. handler_done = true;
  22497. });
  22498. auto port = svr.bind_to_any_port("127.0.0.1");
  22499. std::thread t([&]() { svr.listen_after_bind(); });
  22500. auto se = detail::scope_exit([&] {
  22501. svr.stop();
  22502. t.join();
  22503. });
  22504. svr.wait_until_ready();
  22505. auto send_bytes = [](socket_t s, const std::string &data) {
  22506. #ifdef _WIN32
  22507. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22508. #else
  22509. auto n = ::send(s, data.data(), data.size(), 0);
  22510. #endif
  22511. return n == static_cast<decltype(n)>(data.size());
  22512. };
  22513. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22514. // Every length used here fits the 7-bit length field.
  22515. auto masked_header = [](uint8_t first_byte, size_t len) {
  22516. std::string h;
  22517. h += static_cast<char>(first_byte);
  22518. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22519. h.append(4, '\0'); // mask key
  22520. return h;
  22521. };
  22522. for (int attempt = 0; attempt < attempts; attempt++) {
  22523. peer_stalled = false;
  22524. handler_done = false;
  22525. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22526. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22527. auto se_sock = detail::scope_exit([&] {
  22528. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22529. });
  22530. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22531. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22532. sockaddr_in addr{};
  22533. addr.sin_family = AF_INET;
  22534. addr.sin_port = htons(static_cast<uint16_t>(port));
  22535. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22536. ASSERT_EQ(
  22537. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22538. << "attempt " << attempt;
  22539. ASSERT_TRUE(send_bytes(sock,
  22540. "GET /ws HTTP/1.1\r\n"
  22541. "Host: 127.0.0.1\r\n"
  22542. "Upgrade: websocket\r\n"
  22543. "Connection: Upgrade\r\n"
  22544. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22545. "Sec-WebSocket-Version: 13\r\n"
  22546. "\r\n"))
  22547. << "attempt " << attempt;
  22548. std::string response;
  22549. while (response.find("\r\n\r\n") == std::string::npos) {
  22550. char buf[512];
  22551. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22552. if (n <= 0) { break; }
  22553. response.append(buf, static_cast<size_t>(n));
  22554. }
  22555. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22556. << "attempt " << attempt;
  22557. // Send the header of a Binary message but only the first prefix_len bytes
  22558. // of its payload, leaving the reader thread stalled inside the payload.
  22559. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22560. expected.substr(0, prefix_len)))
  22561. << "attempt " << attempt;
  22562. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22563. peer_stalled = true;
  22564. // Let close() send its Close frame and park in its own read before the
  22565. // rest of the payload arrives, so both threads are waiting for it.
  22566. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22567. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22568. close_frame += static_cast<char>(0x03); // status 1000
  22569. close_frame += static_cast<char>(0xE8);
  22570. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22571. << "attempt " << attempt;
  22572. // Closing the peer releases the reader thread even on the buggy path,
  22573. // where it waits for bytes another thread already consumed.
  22574. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22575. detail::close_socket(sock);
  22576. sock = INVALID_SOCKET;
  22577. wait_for(handler_done);
  22578. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22579. }
  22580. std::lock_guard<std::mutex> guard(received_mutex);
  22581. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22582. << "a message in flight when close() ran was dropped";
  22583. for (size_t i = 0; i < received.size(); i++) {
  22584. EXPECT_EQ(expected, received[i]) << "message " << i;
  22585. }
  22586. }
  22587. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22588. // returning the socket, or INVALID_SOCKET.
  22589. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22590. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22591. if (sock == INVALID_SOCKET) { return sock; }
  22592. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22593. sockaddr_in addr{};
  22594. addr.sin_family = AF_INET;
  22595. addr.sin_port = htons(static_cast<uint16_t>(port));
  22596. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22597. std::string req = "GET " + path +
  22598. " HTTP/1.1\r\n"
  22599. "Host: 127.0.0.1\r\n"
  22600. "Upgrade: websocket\r\n"
  22601. "Connection: Upgrade\r\n"
  22602. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22603. "Sec-WebSocket-Version: 13\r\n"
  22604. "\r\n";
  22605. std::string res;
  22606. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22607. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22608. static_cast<int>(req.size())) {
  22609. char c;
  22610. while (res.find("\r\n\r\n") == std::string::npos &&
  22611. ::recv(sock, &c, 1, 0) == 1) {
  22612. res += c;
  22613. }
  22614. }
  22615. if (res.find(" 101 ") == std::string::npos) {
  22616. detail::close_socket(sock);
  22617. return INVALID_SOCKET;
  22618. }
  22619. return sock;
  22620. }
  22621. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22622. // The payload must fit the 7-bit length field.
  22623. static std::string masked_frame(uint8_t first_byte,
  22624. const std::string &payload) {
  22625. std::string f;
  22626. f += static_cast<char>(first_byte);
  22627. f += static_cast<char>(0x80 | payload.size());
  22628. f.append(4, '\0');
  22629. return f + payload;
  22630. }
  22631. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22632. std::atomic<bool> done{false};
  22633. std::string received;
  22634. Server svr;
  22635. svr.set_websocket_ping_interval(0);
  22636. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22637. std::string msg;
  22638. if (ws.read(msg) == ws::Binary) { received = msg; }
  22639. done = true;
  22640. });
  22641. auto port = svr.bind_to_any_port("127.0.0.1");
  22642. std::thread t([&]() { svr.listen_after_bind(); });
  22643. auto se = detail::scope_exit([&] {
  22644. svr.stop();
  22645. t.join();
  22646. });
  22647. svr.wait_until_ready();
  22648. auto sock = connect_raw_websocket(port, "/ws");
  22649. ASSERT_NE(INVALID_SOCKET, sock);
  22650. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22651. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22652. masked_frame(0x89, "p") + // FIN + Ping
  22653. masked_frame(0x80, "lo"); // FIN + Continuation
  22654. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22655. for (int i = 0; i < 500 && !done; i++) {
  22656. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22657. }
  22658. ASSERT_TRUE(done);
  22659. EXPECT_EQ("Hello", received);
  22660. }
  22661. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22662. Server svr;
  22663. svr.set_websocket_ping_interval(0);
  22664. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22665. std::string msg;
  22666. while (ws.read(msg)) {}
  22667. });
  22668. auto port = svr.bind_to_any_port("127.0.0.1");
  22669. std::thread t([&]() { svr.listen_after_bind(); });
  22670. auto se = detail::scope_exit([&] {
  22671. svr.stop();
  22672. t.join();
  22673. });
  22674. svr.wait_until_ready();
  22675. // The Close each payload is answered with: an echo when it is valid, and
  22676. // 1002 otherwise.
  22677. std::vector<std::pair<std::string, std::string>> cases = {
  22678. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22679. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22680. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22681. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22682. };
  22683. for (const auto &c : cases) {
  22684. auto sock = connect_raw_websocket(port, "/ws");
  22685. ASSERT_NE(INVALID_SOCKET, sock);
  22686. auto close_frame = masked_frame(0x88, c.first);
  22687. ::send(sock, close_frame.data(), static_cast<int>(close_frame.size()), 0);
  22688. std::string reply;
  22689. char buf[256];
  22690. while (reply.size() < 2 + c.second.size()) {
  22691. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22692. if (n <= 0) { break; }
  22693. reply.append(buf, static_cast<size_t>(n));
  22694. }
  22695. detail::close_socket(sock);
  22696. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22697. c.second,
  22698. reply);
  22699. }
  22700. }
  22701. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22702. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22703. protected:
  22704. void SetUp() override {
  22705. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22706. SERVER_PRIVATE_KEY_FILE);
  22707. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22708. std::string msg;
  22709. ws::ReadResult ret;
  22710. while ((ret = ws.read(msg))) {
  22711. if (ret == ws::Binary) {
  22712. ws.send(msg.data(), msg.size());
  22713. } else {
  22714. ws.send(msg);
  22715. }
  22716. }
  22717. });
  22718. port_ = server_->bind_to_any_port(HOST);
  22719. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22720. server_->wait_until_ready();
  22721. }
  22722. void TearDown() override {
  22723. server_->stop();
  22724. if (server_thread_.joinable()) { server_thread_.join(); }
  22725. }
  22726. std::unique_ptr<SSLServer> server_;
  22727. std::thread server_thread_;
  22728. int port_ = 0;
  22729. };
  22730. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  22731. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22732. {
  22733. ws::WebSocketClient client(url);
  22734. client.enable_server_certificate_verification(false);
  22735. auto calls = 0;
  22736. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  22737. calls++;
  22738. return false;
  22739. });
  22740. EXPECT_FALSE(client.connect());
  22741. EXPECT_GT(calls, 0);
  22742. }
  22743. {
  22744. ws::WebSocketClient client(url);
  22745. client.enable_server_certificate_verification(false);
  22746. client.set_session_verifier([](tls::session_t) {
  22747. return SSLVerifierResponse::CertificateRejected;
  22748. });
  22749. EXPECT_FALSE(client.connect());
  22750. }
  22751. {
  22752. ws::WebSocketClient client(url);
  22753. client.enable_server_certificate_verification(false);
  22754. client.set_session_verifier([](tls::session_t) {
  22755. return SSLVerifierResponse::CertificateAccepted;
  22756. });
  22757. EXPECT_TRUE(client.connect());
  22758. }
  22759. }
  22760. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22761. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22762. "/ws-echo");
  22763. client.enable_server_certificate_verification(false);
  22764. ASSERT_TRUE(client.connect());
  22765. ASSERT_TRUE(client.is_open());
  22766. ASSERT_TRUE(client.send("Hello WSS"));
  22767. std::string msg;
  22768. EXPECT_EQ(ws::Text, client.read(msg));
  22769. EXPECT_EQ("Hello WSS", msg);
  22770. client.close();
  22771. }
  22772. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22773. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22774. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22775. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22776. // client (without calling close() first) is the only path that runs
  22777. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22778. // bug exactly.
  22779. //
  22780. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22781. // when linked against an instrumented libssl; run under Valgrind to catch it
  22782. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22783. // suite (the freed session otherwise stalls on the close handshake) — this test
  22784. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22785. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22786. {
  22787. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22788. "/ws-echo");
  22789. client.enable_server_certificate_verification(false);
  22790. client.set_read_timeout(2, 0);
  22791. client.set_write_timeout(2, 0);
  22792. ASSERT_TRUE(client.connect());
  22793. ASSERT_TRUE(client.is_open());
  22794. ASSERT_TRUE(client.send("still open"));
  22795. // Intentionally do NOT call client.close(): leaving scope runs
  22796. // shutdown_and_close() with the WebSocket still open, which must send the
  22797. // close frame while the TLS session is still alive.
  22798. }
  22799. }
  22800. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22801. // shutdown_and_close() at the start of connect(), reproducing the same
  22802. // use-after-free within the test body rather than at scope exit. The second
  22803. // connect must succeed and echo, proving the close handshake ran over a live
  22804. // session. See the note above about memory-tool requirements.
  22805. TEST_F(WebSocketSSLIntegrationTest,
  22806. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22807. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22808. "/ws-echo");
  22809. client.enable_server_certificate_verification(false);
  22810. client.set_read_timeout(2, 0);
  22811. client.set_write_timeout(2, 0);
  22812. ASSERT_TRUE(client.connect());
  22813. ASSERT_TRUE(client.is_open());
  22814. ASSERT_TRUE(client.send("still open"));
  22815. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22816. // the still-open connection, which must not touch a freed TLS session.
  22817. ASSERT_TRUE(client.connect());
  22818. ASSERT_TRUE(client.is_open());
  22819. ASSERT_TRUE(client.send("after reconnect"));
  22820. std::string msg;
  22821. EXPECT_EQ(ws::Text, client.read(msg));
  22822. EXPECT_EQ("after reconnect", msg);
  22823. client.close();
  22824. }
  22825. #endif
  22826. #ifdef CPPHTTPLIB_SSL_ENABLED
  22827. class WebSocketSSLCATest : public ::testing::Test {
  22828. protected:
  22829. void SetUp() override {
  22830. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22831. SERVER_PRIVATE_KEY_FILE);
  22832. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22833. std::string msg;
  22834. while (ws.read(msg)) {
  22835. ws.send(msg);
  22836. }
  22837. });
  22838. port_ = server_->bind_to_any_port("127.0.0.1");
  22839. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22840. server_->wait_until_ready();
  22841. }
  22842. void TearDown() override {
  22843. server_->stop();
  22844. if (server_thread_.joinable()) { server_thread_.join(); }
  22845. }
  22846. std::string url() const {
  22847. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22848. }
  22849. std::unique_ptr<SSLServer> server_;
  22850. std::thread server_thread_;
  22851. int port_ = 0;
  22852. };
  22853. // A custom CA loaded as PEM verifies the server with full certificate
  22854. // verification enabled
  22855. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22856. ws::WebSocketClient client(url());
  22857. std::string cert;
  22858. read_file(SERVER_CERT2_FILE, cert);
  22859. client.load_ca_cert_store(cert.c_str(), cert.size());
  22860. ASSERT_TRUE(client.connect());
  22861. ASSERT_TRUE(client.send("hello"));
  22862. std::string msg;
  22863. EXPECT_EQ(ws::Text, client.read(msg));
  22864. EXPECT_EQ("hello", msg);
  22865. client.close();
  22866. }
  22867. // A custom CA that does not cover the server must fail verification (the
  22868. // custom CA is exclusive; system certs are not loaded alongside it)
  22869. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22870. ws::WebSocketClient client(url());
  22871. std::string cert;
  22872. read_file(CLIENT_CA_CERT_FILE, cert);
  22873. client.load_ca_cert_store(cert.c_str(), cert.size());
  22874. auto res = client.connect();
  22875. ASSERT_FALSE(res);
  22876. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22877. EXPECT_EQ(-1, res.status());
  22878. EXPECT_NE(0u, res.ssl_backend_error());
  22879. }
  22880. // The same CA as a file path rather than PEM in memory
  22881. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22882. ws::WebSocketClient client(url());
  22883. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22884. ASSERT_TRUE(client.connect());
  22885. ASSERT_TRUE(client.send("hello"));
  22886. std::string msg;
  22887. EXPECT_EQ(ws::Text, client.read(msg));
  22888. EXPECT_EQ("hello", msg);
  22889. client.close();
  22890. }
  22891. // ...and a CA file that does not cover the server still fails, so it is the
  22892. // path above that decides the outcome
  22893. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22894. ws::WebSocketClient client(url());
  22895. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22896. ASSERT_FALSE(client.connect());
  22897. }
  22898. // Regression test: reconnecting with a native custom CA store used to reuse
  22899. // a store handle the previous TLS context had already freed (use-after-free
  22900. // under the OpenSSL backend). The context now lives as long as the client.
  22901. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22902. ws::WebSocketClient client(url());
  22903. std::string cert;
  22904. read_file(SERVER_CERT2_FILE, cert);
  22905. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22906. ASSERT_TRUE(client.connect());
  22907. client.close();
  22908. ASSERT_TRUE(client.connect());
  22909. ASSERT_TRUE(client.send("again"));
  22910. std::string msg;
  22911. EXPECT_EQ(ws::Text, client.read(msg));
  22912. EXPECT_EQ("again", msg);
  22913. client.close();
  22914. }
  22915. // Regression test: a certificate with a trusted chain but no identity match
  22916. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22917. // verification entirely for IP hosts, so this connection succeeded there.
  22918. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22919. // chain verification while the identity check must still fail.
  22920. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22922. ASSERT_TRUE(svr.is_valid());
  22923. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22924. std::string msg;
  22925. while (ws.read(msg)) {
  22926. ws.send(msg);
  22927. }
  22928. });
  22929. auto port = svr.bind_to_any_port("127.0.0.1");
  22930. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22931. auto se = detail::scope_exit([&] {
  22932. svr.stop();
  22933. t.join();
  22934. });
  22935. svr.wait_until_ready();
  22936. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22937. "/echo");
  22938. std::string cert;
  22939. read_file(SERVER_CERT_FILE, cert);
  22940. client.load_ca_cert_store(cert.c_str(), cert.size());
  22941. ASSERT_FALSE(client.connect());
  22942. }
  22943. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22944. // SNI, so nothing binds the host name to the TLS session. These bind the
  22945. // server to "localhost" instead, the only shape that exercises the SNI and
  22946. // hostname-verification path with certificate verification left enabled.
  22947. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22948. protected:
  22949. void Start(const char *cert_file) {
  22950. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22951. SERVER_PRIVATE_KEY_FILE);
  22952. ASSERT_TRUE(server_->is_valid());
  22953. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22954. std::string msg;
  22955. while (ws.read(msg)) {
  22956. ws.send(msg);
  22957. }
  22958. });
  22959. port_ = server_->bind_to_any_port("localhost");
  22960. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22961. server_->wait_until_ready();
  22962. }
  22963. void TearDown() override {
  22964. if (server_) { server_->stop(); }
  22965. if (server_thread_.joinable()) { server_thread_.join(); }
  22966. }
  22967. std::string url() const {
  22968. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22969. }
  22970. std::unique_ptr<SSLServer> server_;
  22971. std::thread server_thread_;
  22972. int port_ = 0;
  22973. };
  22974. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22975. // out and the connection is usable
  22976. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22977. Start(SERVER_CERT2_FILE);
  22978. ws::WebSocketClient client(url());
  22979. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22980. ASSERT_TRUE(client.connect());
  22981. ASSERT_TRUE(client.send("hello"));
  22982. std::string msg;
  22983. EXPECT_EQ(ws::Text, client.read(msg));
  22984. EXPECT_EQ("hello", msg);
  22985. client.close();
  22986. }
  22987. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22988. // while the identity check must still reject "localhost"
  22989. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22990. Start(SERVER_CERT_FILE);
  22991. ws::WebSocketClient client(url());
  22992. client.set_ca_cert_path(SERVER_CERT_FILE);
  22993. auto res = client.connect();
  22994. ASSERT_FALSE(res);
  22995. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22996. EXPECT_EQ(-1, res.status());
  22997. }
  22998. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22999. // disabled: the chain is still checked, only the identity check is skipped
  23000. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23001. Start(SERVER_CERT_FILE);
  23002. ws::WebSocketClient client(url());
  23003. client.set_ca_cert_path(SERVER_CERT_FILE);
  23004. client.enable_server_hostname_verification(false);
  23005. ASSERT_TRUE(client.connect());
  23006. ASSERT_TRUE(client.send("hello"));
  23007. std::string msg;
  23008. EXPECT_EQ(ws::Text, client.read(msg));
  23009. EXPECT_EQ("hello", msg);
  23010. client.close();
  23011. }
  23012. // A CA that did not sign the server certificate fails the chain, even though
  23013. // the name would match
  23014. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23015. Start(SERVER_CERT2_FILE);
  23016. ws::WebSocketClient client(url());
  23017. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23018. ASSERT_FALSE(client.connect());
  23019. }
  23020. // With verification disabled, neither the chain nor the name is checked
  23021. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23022. Start(SERVER_CERT_FILE);
  23023. ws::WebSocketClient client(url());
  23024. client.enable_server_certificate_verification(false);
  23025. ASSERT_TRUE(client.connect());
  23026. ASSERT_TRUE(client.send("hello"));
  23027. std::string msg;
  23028. EXPECT_EQ(ws::Text, client.read(msg));
  23029. EXPECT_EQ("hello", msg);
  23030. client.close();
  23031. }
  23032. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23033. protected:
  23034. void SetUp() override {
  23035. server_ = httplib::detail::make_unique<SSLServer>(
  23036. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23037. ASSERT_TRUE(server_->is_valid());
  23038. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23039. std::string msg;
  23040. while (ws.read(msg)) {
  23041. ws.send(msg);
  23042. }
  23043. });
  23044. port_ = server_->bind_to_any_port("localhost");
  23045. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23046. server_->wait_until_ready();
  23047. }
  23048. void TearDown() override {
  23049. server_->stop();
  23050. if (server_thread_.joinable()) { server_thread_.join(); }
  23051. }
  23052. std::string url() const {
  23053. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23054. }
  23055. void ConnectWithClientCert(const std::string &client_cert_file,
  23056. const std::string &client_private_key_file,
  23057. const char *private_key_password) {
  23058. std::string cert_pem, key_pem;
  23059. read_file(client_cert_file, cert_pem);
  23060. read_file(client_private_key_file, key_pem);
  23061. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23062. key_pem.c_str(), key_pem.size(),
  23063. private_key_password};
  23064. ws::WebSocketClient client(url(), pem);
  23065. ASSERT_TRUE(client.is_valid());
  23066. client.enable_server_certificate_verification(false);
  23067. ASSERT_TRUE(client.connect());
  23068. ASSERT_TRUE(client.send("hello"));
  23069. std::string msg;
  23070. EXPECT_EQ(ws::Text, client.read(msg));
  23071. EXPECT_EQ("hello", msg);
  23072. client.close();
  23073. }
  23074. std::unique_ptr<SSLServer> server_;
  23075. std::thread server_thread_;
  23076. int port_ = 0;
  23077. };
  23078. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23079. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23080. }
  23081. // Control for the tests above: the fixture's server really does require a
  23082. // client certificate, so it is the PEM the constructor installed that decides
  23083. // the outcome.
  23084. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23085. ws::WebSocketClient client(url());
  23086. ASSERT_TRUE(client.is_valid());
  23087. client.enable_server_certificate_verification(false);
  23088. EXPECT_FALSE(client.connect());
  23089. }
  23090. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23091. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23092. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23093. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23094. }
  23095. #endif
  23096. #if !defined(_WIN32)
  23097. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23098. auto secret_dir = std::string("./symlink_test_secret");
  23099. auto served_dir = std::string("./symlink_test_served");
  23100. auto secret_file = secret_dir + "/secret.txt";
  23101. auto symlink_path = served_dir + "/escape";
  23102. // Setup: create directories and files
  23103. mkdir(secret_dir.c_str(), 0755);
  23104. mkdir(served_dir.c_str(), 0755);
  23105. {
  23106. std::ofstream ofs(secret_file);
  23107. ofs << "SECRET_DATA";
  23108. }
  23109. // Create symlink using absolute path so it resolves correctly
  23110. #ifdef PATH_MAX
  23111. char abs_secret[PATH_MAX];
  23112. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23113. #else
  23114. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23115. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23116. ASSERT_NE(nullptr, abs_secret);
  23117. #endif
  23118. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23119. auto se = detail::scope_exit([&] {
  23120. unlink(symlink_path.c_str());
  23121. unlink(secret_file.c_str());
  23122. rmdir(served_dir.c_str());
  23123. rmdir(secret_dir.c_str());
  23124. });
  23125. Server svr;
  23126. svr.set_mount_point("/", served_dir);
  23127. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23128. auto se2 = detail::scope_exit([&] {
  23129. svr.stop();
  23130. listen_thread.join();
  23131. });
  23132. svr.wait_until_ready();
  23133. Client cli("localhost", PORT);
  23134. // Symlink pointing outside base dir should be blocked
  23135. auto res = cli.Get("/escape/secret.txt");
  23136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23137. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23138. }
  23139. #endif
  23140. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23141. // "GET /smuggled" request), reads the first response, and only then sends the
  23142. // embedded request as the body. Returns how many times /smuggled ran.
  23143. //
  23144. // The body is sent AFTER receiving the first response (as in the original
  23145. // PoC) so that the stream_line_reader cannot buffer it together with the
  23146. // headers of the first request.
  23147. static int count_smuggled_requests(const std::string &outer_head,
  23148. std::string &first_response) {
  23149. Server svr;
  23150. svr.set_mount_point("/", "./www");
  23151. std::atomic<int> smuggled_count(0);
  23152. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23153. smuggled_count++;
  23154. res.set_content("oops", "text/plain");
  23155. });
  23156. svr.Post("/post", [&](const Request &req, Response &res) {
  23157. res.set_content(req.body, "text/plain");
  23158. });
  23159. auto port = svr.bind_to_any_port("localhost");
  23160. thread t = thread([&] { svr.listen_after_bind(); });
  23161. auto se = detail::scope_exit([&] {
  23162. svr.stop();
  23163. t.join();
  23164. });
  23165. svr.wait_until_ready();
  23166. auto error = Error::Success;
  23167. auto sock = detail::create_client_socket(
  23168. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23169. /*connection_timeout_sec=*/2, 0,
  23170. /*read_timeout_sec=*/2, 0,
  23171. /*write_timeout_sec=*/2, 0, std::string(), error);
  23172. EXPECT_NE(INVALID_SOCKET, sock);
  23173. if (sock == INVALID_SOCKET) { return -1; }
  23174. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23175. // The "smuggled" request will be sent as the body of the outer request
  23176. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23177. "Host: localhost\r\n"
  23178. "Connection: close\r\n"
  23179. "\r\n";
  23180. auto head = outer_head;
  23181. auto len = std::to_string(smuggled.size());
  23182. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23183. pos = head.find("{len}", pos + len.size())) {
  23184. head.replace(pos, 5, len);
  23185. }
  23186. // Step 1: Send only the outer request headers (no body yet)
  23187. auto sent = send(sock, head.data(), head.size(), 0);
  23188. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23189. // Step 2: Read the first response
  23190. char buf[4096];
  23191. for (;;) {
  23192. auto n = recv(sock, buf, sizeof(buf), 0);
  23193. if (n <= 0) break;
  23194. first_response.append(buf, static_cast<size_t>(n));
  23195. // Stop once we have a complete response (headers + body)
  23196. auto hdr_end = first_response.find("\r\n\r\n");
  23197. if (hdr_end != std::string::npos) {
  23198. // Check for Content-Length to know when the body is complete
  23199. auto cl_pos = first_response.find("Content-Length:");
  23200. if (cl_pos != std::string::npos) {
  23201. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23202. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23203. auto cl = std::stoul(
  23204. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23205. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23206. } else {
  23207. break; // No Content-Length, assume headers-only response
  23208. }
  23209. }
  23210. }
  23211. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23212. // vulnerable server the keep-alive loop reads this as a second request. The
  23213. // server may already have closed the connection, so the result is ignored.
  23214. send(sock, smuggled.data(), smuggled.size(), 0);
  23215. // Half-close so that a server which drained the body sees EOF and closes,
  23216. // instead of the read below waiting for the read timeout.
  23217. #ifdef _WIN32
  23218. ::shutdown(sock, SD_SEND);
  23219. #else
  23220. ::shutdown(sock, SHUT_WR);
  23221. #endif
  23222. // Step 4: Read until the server closes the connection
  23223. for (;;) {
  23224. auto n = recv(sock, buf, sizeof(buf), 0);
  23225. if (n <= 0) break;
  23226. }
  23227. return smuggled_count.load();
  23228. }
  23229. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23230. // A GET request with Content-Length to a static file handler must have its
  23231. // body drained before the keep-alive connection is reused. Otherwise the
  23232. // unread body bytes are interpreted as the next HTTP request.
  23233. std::string first_response;
  23234. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23235. "Host: localhost\r\n"
  23236. "Content-Length: {len}\r\n"
  23237. "\r\n",
  23238. first_response));
  23239. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23240. }
  23241. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23242. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23243. // be answered with 400 and the connection closed. Treating it as "no body"
  23244. // leaves the body to be parsed as the next request.
  23245. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23246. const char *targets[] = {
  23247. "GET /file", // handler that never reads the body
  23248. "GET /not-found", // no handler matches (404)
  23249. "POST /post", // handler that reads the body
  23250. };
  23251. for (auto target : targets) {
  23252. for (auto value : values) {
  23253. std::string first_response;
  23254. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23255. " HTTP/1.1\r\n"
  23256. "Host: localhost\r\n"
  23257. "Content-Length: " +
  23258. value + "\r\n\r\n",
  23259. first_response))
  23260. << target << " with Content-Length: " << value;
  23261. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23262. << target << " with Content-Length: " << value;
  23263. }
  23264. }
  23265. }
  23266. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23267. // A 400 for an unparseable request line leaves the rest of the message
  23268. // unread, so the connection must be closed rather than reused.
  23269. std::string first_response;
  23270. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23271. "Host: localhost\r\n"
  23272. "Content-Length: {len}\r\n"
  23273. "\r\n",
  23274. first_response));
  23275. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23276. }
  23277. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23278. // Same as above for a header block that fails to parse.
  23279. std::string first_response;
  23280. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23281. "Host: localhost\r\n"
  23282. "Bad Header\r\n"
  23283. "Content-Length: {len}\r\n"
  23284. "\r\n",
  23285. first_response));
  23286. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23287. }
  23288. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23289. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23290. // server must not read another request on that connection, even when the
  23291. // request had no body to drain.
  23292. std::string first_response;
  23293. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23294. "Host: localhost\r\n"
  23295. "\r\n",
  23296. first_response));
  23297. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23298. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23299. }
  23300. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23301. // A content reader that stops early leaves the stream inside the body.
  23302. // Draining the whole Content-Length from there, or reading the body again,
  23303. // reads into the next request, and whatever follows is parsed as a request
  23304. // of its own.
  23305. Server svr;
  23306. std::atomic<int> smuggled_count(0);
  23307. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23308. svr.Post("/upload", [](const Request &req, Response &res,
  23309. const ContentReader &content_reader) {
  23310. // Stop at the last chunk, so the whole body has been read however it
  23311. // arrives.
  23312. auto length = req.get_header_value_u64("Content-Length");
  23313. size_t total = 0;
  23314. auto consumed = content_reader([&](const char *, size_t n) {
  23315. total += n;
  23316. return total < length;
  23317. });
  23318. EXPECT_FALSE(consumed);
  23319. if (req.has_param("retry")) {
  23320. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23321. }
  23322. // Replace the 400 the aborted read set, which would close the connection.
  23323. res.set_redirect("/done");
  23324. });
  23325. auto port = svr.bind_to_any_port(HOST);
  23326. thread t = thread([&] { svr.listen_after_bind(); });
  23327. auto se = detail::scope_exit([&] {
  23328. svr.stop();
  23329. t.join();
  23330. });
  23331. svr.wait_until_ready();
  23332. // A front end sees the second request as a POST whose body is the GET. The
  23333. // first body is as long as the POST's headers, so draining it again reads
  23334. // exactly those and leaves the GET to be parsed next.
  23335. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23336. "Host: localhost\r\n"
  23337. "\r\n";
  23338. std::string second_head = "POST /post HTTP/1.1\r\n"
  23339. "Host: localhost\r\n"
  23340. "Content-Length: " +
  23341. std::to_string(inner.size()) +
  23342. "\r\n"
  23343. "\r\n";
  23344. for (auto target : {"/upload", "/upload?retry"}) {
  23345. smuggled_count = 0;
  23346. std::string request = "POST " + std::string(target) +
  23347. " HTTP/1.1\r\n"
  23348. "Host: localhost\r\n"
  23349. "Content-Length: " +
  23350. std::to_string(second_head.size()) +
  23351. "\r\n"
  23352. "\r\n" +
  23353. std::string(second_head.size(), 'A') + second_head +
  23354. inner;
  23355. std::string response;
  23356. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23357. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23358. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23359. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23360. EXPECT_EQ(0, smuggled_count.load()) << target;
  23361. }
  23362. }
  23363. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23364. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23365. // must be rejected with 400 Bad Request.
  23366. Server svr;
  23367. svr.Post("/test", [&](const Request &, Response &res) {
  23368. res.set_content("ok", "text/plain");
  23369. });
  23370. thread t = thread([&] { svr.listen(HOST, PORT); });
  23371. auto se = detail::scope_exit([&] {
  23372. svr.stop();
  23373. t.join();
  23374. ASSERT_FALSE(svr.is_running());
  23375. });
  23376. svr.wait_until_ready();
  23377. // Exact "chunked"
  23378. {
  23379. auto req = "POST /test HTTP/1.1\r\n"
  23380. "Host: localhost\r\n"
  23381. "Content-Length: 5\r\n"
  23382. "Transfer-Encoding: chunked\r\n"
  23383. "Connection: close\r\n"
  23384. "\r\n"
  23385. "hello";
  23386. std::string response;
  23387. ASSERT_TRUE(send_request(1, req, &response));
  23388. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23389. response.substr(0, response.find("\r\n")));
  23390. }
  23391. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23392. {
  23393. auto req = "POST /test HTTP/1.1\r\n"
  23394. "Host: localhost\r\n"
  23395. "Content-Length: 5\r\n"
  23396. "Transfer-Encoding: gzip, chunked\r\n"
  23397. "Connection: close\r\n"
  23398. "\r\n"
  23399. "hello";
  23400. std::string response;
  23401. ASSERT_TRUE(send_request(1, req, &response));
  23402. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23403. response.substr(0, response.find("\r\n")));
  23404. }
  23405. }
  23406. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23407. Server svr;
  23408. svr.Post("/test", [&](const Request &, Response &res) {
  23409. res.set_content("ok", "text/plain");
  23410. });
  23411. thread t = thread([&] { svr.listen(HOST, PORT); });
  23412. auto se = detail::scope_exit([&] {
  23413. svr.stop();
  23414. t.join();
  23415. ASSERT_FALSE(svr.is_running());
  23416. });
  23417. svr.wait_until_ready();
  23418. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23419. // length cannot be determined, so the server must answer 400 and close
  23420. // rather than treat the request as bodyless and leave the body in the
  23421. // socket for the next request to pick up.
  23422. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23423. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23424. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23425. std::string response;
  23426. ASSERT_TRUE(send_request(1, req, &response));
  23427. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23428. response.substr(0, response.find("\r\n")))
  23429. << transfer_encoding;
  23430. }
  23431. // RFC 9110 5.3: the codings may also be split across several
  23432. // Transfer-Encoding lines, which combine in the order they were received.
  23433. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23434. // just like the single-line "chunked, gzip" above.
  23435. {
  23436. auto req = "POST /test HTTP/1.1\r\n"
  23437. "Host: localhost\r\n"
  23438. "Transfer-Encoding: chunked\r\n"
  23439. "Transfer-Encoding: gzip\r\n"
  23440. "\r\n"
  23441. "0\r\n\r\n";
  23442. std::string response;
  23443. ASSERT_TRUE(send_request(1, req, &response));
  23444. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23445. response.substr(0, response.find("\r\n")));
  23446. }
  23447. // A sequence ending in chunked stays valid.
  23448. auto req = "POST /test HTTP/1.1\r\n"
  23449. "Host: localhost\r\n"
  23450. "Transfer-Encoding: gzip, chunked\r\n"
  23451. "Connection: close\r\n"
  23452. "\r\n"
  23453. "0\r\n\r\n";
  23454. std::string response;
  23455. ASSERT_TRUE(send_request(1, req, &response));
  23456. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23457. // ...including when it is spread over several lines.
  23458. auto split_req = "POST /test HTTP/1.1\r\n"
  23459. "Host: localhost\r\n"
  23460. "Transfer-Encoding: gzip\r\n"
  23461. "Transfer-Encoding: chunked\r\n"
  23462. "Connection: close\r\n"
  23463. "\r\n"
  23464. "0\r\n\r\n";
  23465. std::string split_response;
  23466. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23467. EXPECT_EQ("HTTP/1.1 200 OK",
  23468. split_response.substr(0, split_response.find("\r\n")));
  23469. }
  23470. // Regression for issue #2450: a DELETE without Content-Length on a
  23471. // keep-alive connection must not let the post-response drain consume the
  23472. // next request's bytes.
  23473. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23474. Server svr;
  23475. std::atomic<int> delete_count(0);
  23476. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23477. delete_count++;
  23478. res.status = StatusCode::NoContent_204;
  23479. });
  23480. auto port = svr.bind_to_any_port(HOST);
  23481. thread t = thread([&] { svr.listen_after_bind(); });
  23482. auto se = detail::scope_exit([&] {
  23483. svr.stop();
  23484. t.join();
  23485. });
  23486. svr.wait_until_ready();
  23487. auto error = Error::Success;
  23488. auto sock = detail::create_client_socket(
  23489. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23490. /*connection_timeout_sec=*/2, 0,
  23491. /*read_timeout_sec=*/2, 0,
  23492. /*write_timeout_sec=*/2, 0, std::string(), error);
  23493. ASSERT_NE(INVALID_SOCKET, sock);
  23494. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23495. auto send_request_and_read_response = [&](const std::string &req,
  23496. std::string &out) -> bool {
  23497. auto sent = send(sock, req.data(), req.size(), 0);
  23498. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23499. char buf[4096];
  23500. for (;;) {
  23501. auto n = recv(sock, buf, sizeof(buf), 0);
  23502. if (n <= 0) { return !out.empty(); }
  23503. out.append(buf, static_cast<size_t>(n));
  23504. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23505. }
  23506. };
  23507. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23508. "Host: localhost\r\n"
  23509. "\r\n";
  23510. std::string resp1;
  23511. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23512. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23513. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23514. "Host: localhost\r\n"
  23515. "Connection: close\r\n"
  23516. "\r\n";
  23517. std::string resp2;
  23518. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23519. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23520. EXPECT_EQ(2, delete_count.load());
  23521. }
  23522. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23523. Server svr;
  23524. svr.Post("/ingest", [&](const Request &, Response &res,
  23525. const ContentReader &content_reader) {
  23526. auto consumed = content_reader([](const char *, size_t) { return false; });
  23527. EXPECT_FALSE(consumed);
  23528. res.status = StatusCode::Conflict_409;
  23529. res.set_header("Connection", "close");
  23530. });
  23531. auto port = svr.bind_to_any_port(HOST);
  23532. thread t = thread([&] { svr.listen_after_bind(); });
  23533. auto se = detail::scope_exit([&] {
  23534. svr.stop();
  23535. t.join();
  23536. });
  23537. svr.wait_until_ready();
  23538. auto error = Error::Success;
  23539. auto sock = detail::create_client_socket(
  23540. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23541. /*connection_timeout_sec=*/2, 0,
  23542. /*read_timeout_sec=*/1, 0,
  23543. /*write_timeout_sec=*/2, 0, std::string(), error);
  23544. ASSERT_NE(INVALID_SOCKET, sock);
  23545. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23546. std::string request = "POST /ingest HTTP/1.1\r\n"
  23547. "Host: localhost\r\n"
  23548. "Transfer-Encoding: chunked\r\n"
  23549. "\r\n"
  23550. "4\r\n"
  23551. "data\r\n";
  23552. auto sent = send(sock, request.data(), request.size(), 0);
  23553. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23554. std::string response;
  23555. ssize_t received = 0;
  23556. do {
  23557. char buf[4096];
  23558. received = recv(sock, buf, sizeof(buf), 0);
  23559. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23560. } while (received > 0);
  23561. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23562. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23563. EXPECT_EQ(0, received);
  23564. }
  23565. namespace no_proxy_test {
  23566. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23567. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23568. // calling listen().
  23569. class ScopedServer {
  23570. public:
  23571. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23572. ~ScopedServer() {
  23573. svr_.stop();
  23574. if (th_.joinable()) { th_.join(); }
  23575. }
  23576. Server &svr() { return svr_; }
  23577. int port() const { return port_; }
  23578. void listen() {
  23579. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23580. svr_.wait_until_ready();
  23581. }
  23582. private:
  23583. Server svr_;
  23584. std::thread th_;
  23585. int port_ = 0;
  23586. };
  23587. class ProxyAndTargetServers {
  23588. public:
  23589. ProxyAndTargetServers() {
  23590. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23591. proxy_hits_++;
  23592. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23593. res.set_content("via-proxy", "text/plain");
  23594. });
  23595. target_.Get(".*", [this](const Request &req, Response &res) {
  23596. target_hits_++;
  23597. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23598. res.set_content("direct", "text/plain");
  23599. });
  23600. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23601. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23602. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23603. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23604. proxy_mock_.wait_until_ready();
  23605. target_.wait_until_ready();
  23606. }
  23607. ~ProxyAndTargetServers() {
  23608. proxy_mock_.stop();
  23609. target_.stop();
  23610. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23611. if (target_thread_.joinable()) { target_thread_.join(); }
  23612. }
  23613. Server &proxy_mock() { return proxy_mock_; }
  23614. Server &target() { return target_; }
  23615. int proxy_port() const { return proxy_port_; }
  23616. int target_port() const { return target_port_; }
  23617. int proxy_hits() const { return proxy_hits_.load(); }
  23618. int target_hits() const { return target_hits_.load(); }
  23619. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23620. void reset_counters() {
  23621. proxy_hits_ = 0;
  23622. target_hits_ = 0;
  23623. last_had_proxy_authz_ = false;
  23624. }
  23625. private:
  23626. Server proxy_mock_;
  23627. Server target_;
  23628. std::thread proxy_thread_;
  23629. std::thread target_thread_;
  23630. int proxy_port_ = 0;
  23631. int target_port_ = 0;
  23632. std::atomic<int> proxy_hits_{0};
  23633. std::atomic<int> target_hits_{0};
  23634. std::atomic<bool> last_had_proxy_authz_{false};
  23635. };
  23636. inline std::unique_ptr<Client> make_client(const std::string &host,
  23637. ProxyAndTargetServers &s) {
  23638. auto cli = detail::make_unique<Client>(host, s.target_port());
  23639. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23640. cli->set_proxy("127.0.0.1", s.proxy_port());
  23641. return cli;
  23642. }
  23643. } // namespace no_proxy_test
  23644. using no_proxy_test::make_client;
  23645. using no_proxy_test::ProxyAndTargetServers;
  23646. TEST(NoProxyTest, ExactHostnameBypasses) {
  23647. ProxyAndTargetServers s;
  23648. auto cli = make_client("example.com", s);
  23649. cli->set_no_proxy({"example.com"});
  23650. auto res = cli->Get("/");
  23651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23652. EXPECT_EQ(0, s.proxy_hits());
  23653. EXPECT_EQ(1, s.target_hits());
  23654. }
  23655. TEST(NoProxyTest, SubdomainBypasses) {
  23656. ProxyAndTargetServers s;
  23657. auto cli = make_client("foo.example.com", s);
  23658. cli->set_no_proxy({"example.com"});
  23659. auto res = cli->Get("/");
  23660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23661. EXPECT_EQ(0, s.proxy_hits());
  23662. EXPECT_EQ(1, s.target_hits());
  23663. }
  23664. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23665. // Regression guard: "evilexample.com" must not be considered a subdomain
  23666. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23667. // check would let traffic bypass the proxy and leak credentials direct
  23668. // to the attacker host.
  23669. ProxyAndTargetServers s;
  23670. auto cli = make_client("evilexample.com", s);
  23671. cli->set_no_proxy({"example.com"});
  23672. auto res = cli->Get("/");
  23673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23674. EXPECT_GE(s.proxy_hits(), 1);
  23675. EXPECT_EQ(0, s.target_hits());
  23676. }
  23677. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23678. ProxyAndTargetServers s;
  23679. auto cli = make_client("example.com.evil.com", s);
  23680. cli->set_no_proxy({"example.com"});
  23681. auto res = cli->Get("/");
  23682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23683. EXPECT_GE(s.proxy_hits(), 1);
  23684. EXPECT_EQ(0, s.target_hits());
  23685. }
  23686. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23687. ProxyAndTargetServers s;
  23688. auto cli = make_client("example.com", s);
  23689. cli->set_no_proxy({".example.com"});
  23690. auto res = cli->Get("/");
  23691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23692. EXPECT_EQ(0, s.proxy_hits());
  23693. EXPECT_EQ(1, s.target_hits());
  23694. }
  23695. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23696. ProxyAndTargetServers s;
  23697. auto cli = make_client("Example.COM", s);
  23698. cli->set_no_proxy({"EXAMPLE.com"});
  23699. auto res = cli->Get("/");
  23700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23701. EXPECT_EQ(0, s.proxy_hits());
  23702. EXPECT_EQ(1, s.target_hits());
  23703. }
  23704. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23705. ProxyAndTargetServers s;
  23706. auto cli = make_client("example.com.", s);
  23707. cli->set_no_proxy({"example.com"});
  23708. auto res = cli->Get("/");
  23709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23710. EXPECT_EQ(0, s.proxy_hits());
  23711. EXPECT_EQ(1, s.target_hits());
  23712. }
  23713. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23714. // Trailing dots must be normalized on BOTH sides — host and entry.
  23715. // An implementation that only strips the host-side trailing dot would
  23716. // fail to match host "example.com" against entry "example.com." because
  23717. // a literal substring search would compare 11 chars against 12.
  23718. ProxyAndTargetServers s;
  23719. auto cli = make_client("example.com", s);
  23720. cli->set_no_proxy({"example.com."});
  23721. auto res = cli->Get("/");
  23722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23723. EXPECT_EQ(0, s.proxy_hits());
  23724. EXPECT_EQ(1, s.target_hits());
  23725. }
  23726. TEST(NoProxyTest, WildcardBypassesEverything) {
  23727. ProxyAndTargetServers s;
  23728. auto cli = make_client("anything.invalid.test", s);
  23729. cli->set_no_proxy({"*"});
  23730. auto res = cli->Get("/");
  23731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23732. EXPECT_EQ(0, s.proxy_hits());
  23733. EXPECT_EQ(1, s.target_hits());
  23734. }
  23735. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23736. ProxyAndTargetServers s;
  23737. Client cli("127.0.0.1", s.target_port());
  23738. cli.set_proxy("127.0.0.1", s.proxy_port());
  23739. cli.set_no_proxy({"127.0.0.1"});
  23740. auto res = cli.Get("/");
  23741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23742. EXPECT_EQ(0, s.proxy_hits());
  23743. EXPECT_EQ(1, s.target_hits());
  23744. }
  23745. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23746. ProxyAndTargetServers s;
  23747. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23748. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23749. cli.set_proxy("127.0.0.1", s.proxy_port());
  23750. cli.set_no_proxy({"::1"});
  23751. auto res = cli.Get("/");
  23752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23753. EXPECT_EQ(0, s.proxy_hits());
  23754. EXPECT_EQ(1, s.target_hits());
  23755. }
  23756. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23757. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23758. // must still be recognized as IPv6 for CIDR matching. Implementations
  23759. // that detect IPv6 only when the host begins with '[' would parse the
  23760. // host as a hostname and miss the match.
  23761. ProxyAndTargetServers s;
  23762. Client cli("fe80::1", s.target_port());
  23763. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23764. cli.set_proxy("127.0.0.1", s.proxy_port());
  23765. cli.set_no_proxy({"fe80::/10"});
  23766. auto res = cli.Get("/");
  23767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23768. EXPECT_EQ(0, s.proxy_hits());
  23769. EXPECT_EQ(1, s.target_hits());
  23770. }
  23771. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23772. ProxyAndTargetServers s;
  23773. Client cli("::1", s.target_port());
  23774. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23775. cli.set_proxy("127.0.0.1", s.proxy_port());
  23776. cli.set_no_proxy({"[::1]"});
  23777. auto res = cli.Get("/");
  23778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23779. EXPECT_EQ(0, s.proxy_hits());
  23780. EXPECT_EQ(1, s.target_hits());
  23781. }
  23782. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23783. ProxyAndTargetServers s;
  23784. Client cli("fe80::1", s.target_port());
  23785. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23786. cli.set_proxy("127.0.0.1", s.proxy_port());
  23787. cli.set_no_proxy({"[fe80::]/10"});
  23788. auto res = cli.Get("/");
  23789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23790. EXPECT_EQ(0, s.proxy_hits());
  23791. EXPECT_EQ(1, s.target_hits());
  23792. }
  23793. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23794. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23795. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23796. // tricks via address-family conversion.
  23797. ProxyAndTargetServers s;
  23798. Client cli("::ffff:127.0.0.1", s.target_port());
  23799. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23800. cli.set_proxy("127.0.0.1", s.proxy_port());
  23801. cli.set_no_proxy({"127.0.0.1"});
  23802. auto res = cli.Get("/");
  23803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23804. EXPECT_GE(s.proxy_hits(), 1);
  23805. EXPECT_EQ(0, s.target_hits());
  23806. }
  23807. TEST(NoProxyTest, IPv4CidrMatch) {
  23808. ProxyAndTargetServers s;
  23809. Client cli("127.0.0.1", s.target_port());
  23810. cli.set_proxy("127.0.0.1", s.proxy_port());
  23811. cli.set_no_proxy({"127.0.0.0/8"});
  23812. auto res = cli.Get("/");
  23813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23814. EXPECT_EQ(0, s.proxy_hits());
  23815. EXPECT_EQ(1, s.target_hits());
  23816. }
  23817. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23818. ProxyAndTargetServers s;
  23819. Client cli("127.0.0.1", s.target_port());
  23820. cli.set_proxy("127.0.0.1", s.proxy_port());
  23821. cli.set_no_proxy({"10.0.0.0/8"});
  23822. auto res = cli.Get("/");
  23823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23824. EXPECT_GE(s.proxy_hits(), 1);
  23825. EXPECT_EQ(0, s.target_hits());
  23826. }
  23827. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23828. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23829. // IPv4 target matches.
  23830. ProxyAndTargetServers s;
  23831. Client cli("127.0.0.1", s.target_port());
  23832. cli.set_proxy("127.0.0.1", s.proxy_port());
  23833. cli.set_no_proxy({"0.0.0.0/0"});
  23834. auto res = cli.Get("/");
  23835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23836. EXPECT_EQ(0, s.proxy_hits());
  23837. EXPECT_EQ(1, s.target_hits());
  23838. }
  23839. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23840. ProxyAndTargetServers s;
  23841. Client cli("127.0.0.1", s.target_port());
  23842. cli.set_proxy("127.0.0.1", s.proxy_port());
  23843. cli.set_no_proxy({"127.0.0.1"});
  23844. auto res = cli.Get("/");
  23845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23846. EXPECT_EQ(0, s.proxy_hits());
  23847. EXPECT_EQ(1, s.target_hits());
  23848. }
  23849. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23850. ProxyAndTargetServers s;
  23851. Client cli("127.0.0.1", s.target_port());
  23852. cli.set_proxy("127.0.0.1", s.proxy_port());
  23853. cli.set_no_proxy({"127.0.0.0/33"});
  23854. auto res = cli.Get("/");
  23855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23856. EXPECT_GE(s.proxy_hits(), 1);
  23857. EXPECT_EQ(0, s.target_hits());
  23858. }
  23859. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23860. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23861. ProxyAndTargetServers s;
  23862. Client cli("127.0.0.1", s.target_port());
  23863. cli.set_proxy("127.0.0.1", s.proxy_port());
  23864. cli.set_no_proxy({"127.0.0.1/"});
  23865. auto res = cli.Get("/");
  23866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23867. EXPECT_GE(s.proxy_hits(), 1);
  23868. EXPECT_EQ(0, s.target_hits());
  23869. }
  23870. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23871. ProxyAndTargetServers s;
  23872. auto cli = make_client("internal.corp", s);
  23873. cli->set_proxy_basic_auth("u", "p");
  23874. cli->set_no_proxy({"internal.corp"});
  23875. auto res = cli->Get("/");
  23876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23877. EXPECT_EQ(1, s.target_hits());
  23878. EXPECT_EQ(0, s.proxy_hits());
  23879. EXPECT_FALSE(s.last_had_proxy_authz())
  23880. << "Proxy-Authorization must not be sent direct to the target";
  23881. }
  23882. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23883. ProxyAndTargetServers s;
  23884. auto cli = make_client("public.example", s);
  23885. cli->set_proxy_basic_auth("u", "p");
  23886. cli->set_no_proxy({"internal.corp"}); // does not match
  23887. auto res = cli->Get("/");
  23888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23889. EXPECT_GE(s.proxy_hits(), 1);
  23890. EXPECT_TRUE(s.last_had_proxy_authz());
  23891. }
  23892. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23893. std::atomic<int> hits{0};
  23894. std::atomic<int> hits_with_authz{0};
  23895. no_proxy_test::ScopedServer proxy_mock;
  23896. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23897. hits++;
  23898. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23899. if (req.target.find("/redir") != std::string::npos) {
  23900. res.set_redirect("http://other.example/landed");
  23901. } else {
  23902. res.set_content("via-proxy", "text/plain");
  23903. }
  23904. });
  23905. proxy_mock.listen();
  23906. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23907. hits = 0;
  23908. hits_with_authz = 0;
  23909. Client cli("public.example", 80);
  23910. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23911. cli.set_proxy_basic_auth(c.first, c.second);
  23912. cli.set_follow_location(true);
  23913. // The redirect to another host goes through the proxy as well
  23914. auto res = cli.Get("/redir");
  23915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23916. EXPECT_EQ(2, hits.load());
  23917. EXPECT_EQ(2, hits_with_authz.load());
  23918. }
  23919. }
  23920. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23921. ProxyAndTargetServers s;
  23922. auto cli = make_client("anything.test", s);
  23923. auto res = cli->Get("/");
  23924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23925. EXPECT_GE(s.proxy_hits(), 1);
  23926. EXPECT_EQ(0, s.target_hits());
  23927. }
  23928. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23929. ProxyAndTargetServers s;
  23930. auto cli = make_client("example.com", s);
  23931. cli->set_no_proxy({"example.com:8080"});
  23932. auto res = cli->Get("/");
  23933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23934. EXPECT_GE(s.proxy_hits(), 1);
  23935. EXPECT_EQ(0, s.target_hits());
  23936. }
  23937. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23938. ProxyAndTargetServers s;
  23939. auto cli = make_client("anything.test", s);
  23940. cli->set_no_proxy({"", " ", "\t"});
  23941. auto res = cli->Get("/");
  23942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23943. EXPECT_GE(s.proxy_hits(), 1);
  23944. EXPECT_EQ(0, s.target_hits());
  23945. }
  23946. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23947. // An entry with leading/trailing whitespace must still match — env-style
  23948. // values are commonly pasted with stray spaces and an implementation
  23949. // that feeds the raw token directly to inet_pton would fail to match
  23950. // valid CIDRs because of the spaces.
  23951. ProxyAndTargetServers s;
  23952. Client cli("127.0.0.1", s.target_port());
  23953. cli.set_proxy("127.0.0.1", s.proxy_port());
  23954. cli.set_no_proxy({" 127.0.0.0/8 "});
  23955. auto res = cli.Get("/");
  23956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23957. EXPECT_EQ(0, s.proxy_hits());
  23958. EXPECT_EQ(1, s.target_hits());
  23959. }
  23960. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23961. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23962. // go direct and must NOT carry Proxy-Authorization.
  23963. std::atomic<int> proxy_hits{0};
  23964. std::atomic<int> target_hits{0};
  23965. std::atomic<bool> target_saw_authz{false};
  23966. no_proxy_test::ScopedServer proxy_mock, target;
  23967. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23968. proxy_hits++;
  23969. res.status = 302;
  23970. res.set_header("Location", "http://127.0.0.1:" +
  23971. std::to_string(target.port()) + "/landed");
  23972. });
  23973. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23974. target_hits++;
  23975. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23976. res.set_content("direct", "text/plain");
  23977. });
  23978. proxy_mock.listen();
  23979. target.listen();
  23980. Client cli("public.example", target.port());
  23981. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23982. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23983. cli.set_proxy_basic_auth("u", "p");
  23984. cli.set_no_proxy({"127.0.0.1"});
  23985. cli.set_follow_location(true);
  23986. auto res = cli.Get("/redir");
  23987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23988. EXPECT_GE(proxy_hits.load(), 1);
  23989. EXPECT_GE(target_hits.load(), 1);
  23990. EXPECT_FALSE(target_saw_authz.load());
  23991. }
  23992. #ifdef CPPHTTPLIB_SSL_ENABLED
  23993. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23994. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23995. // proxy creds would be sent to the (possibly hostile) origin.
  23996. std::atomic<int> target_hits{0};
  23997. std::atomic<bool> target_saw_proxy_authz{false};
  23998. no_proxy_test::ScopedServer target;
  23999. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24000. target_hits++;
  24001. if (req.has_header("Proxy-Authorization")) {
  24002. target_saw_proxy_authz = true;
  24003. }
  24004. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24005. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24006. "nonce=\"abc\", algorithm=MD5");
  24007. });
  24008. target.listen();
  24009. // The proxy address is set to the target's port: the bypass MUST kick in;
  24010. // if it doesn't, the test still routes "via proxy" to the same server and
  24011. // the Proxy-Authorization assertion below catches the leak.
  24012. Client cli("evil.example", target.port());
  24013. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24014. cli.set_proxy("127.0.0.1", target.port());
  24015. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24016. cli.set_no_proxy({"evil.example"});
  24017. auto res = cli.Get("/x");
  24018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24019. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24020. EXPECT_EQ(1, target_hits.load());
  24021. EXPECT_FALSE(target_saw_proxy_authz.load());
  24022. }
  24023. #endif
  24024. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24025. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24026. std::atomic<int> proxy_hits{0};
  24027. std::atomic<int> bypass_hits{0};
  24028. std::atomic<bool> proxy_saw_c_url{false};
  24029. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24030. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24031. proxy_hits++;
  24032. if (req.path.find("/start") != std::string::npos) {
  24033. res.status = 302;
  24034. res.set_header("Location", "http://127.0.0.1:" +
  24035. std::to_string(bypass_server.port()) +
  24036. "/middle");
  24037. return;
  24038. }
  24039. if (req.path.find("/end") != std::string::npos) {
  24040. proxy_saw_c_url = true;
  24041. res.set_content("c-via-proxy", "text/plain");
  24042. return;
  24043. }
  24044. res.set_content("unexpected", "text/plain");
  24045. });
  24046. // public.example's "advertised" port is arbitrary (the request never lands
  24047. // there — it goes through the proxy), but use a dynamic value to stay
  24048. // friendly with sharded parallel runs.
  24049. int public_port = bypass_server.port();
  24050. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24051. bypass_hits++;
  24052. res.status = 302;
  24053. res.set_header("Location", "http://public.example:" +
  24054. std::to_string(public_port) + "/end");
  24055. });
  24056. proxy_mock.listen();
  24057. bypass_server.listen();
  24058. Client cli("public.example", public_port);
  24059. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24060. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24061. cli.set_no_proxy({"127.0.0.1"});
  24062. cli.set_follow_location(true);
  24063. auto res = cli.Get("/start");
  24064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24065. EXPECT_EQ(StatusCode::OK_200, res->status);
  24066. EXPECT_EQ("c-via-proxy", res->body);
  24067. EXPECT_GE(proxy_hits.load(), 2);
  24068. EXPECT_GE(bypass_hits.load(), 1);
  24069. EXPECT_TRUE(proxy_saw_c_url.load());
  24070. }
  24071. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24072. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24073. // request reconnects to the correct endpoint.
  24074. std::atomic<int> proxy_hits{0};
  24075. std::atomic<int> target_hits{0};
  24076. no_proxy_test::ScopedServer proxy_mock, target;
  24077. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24078. proxy_hits++;
  24079. res.set_content("via-proxy", "text/plain");
  24080. });
  24081. target.svr().Get(".*", [&](const Request &, Response &res) {
  24082. target_hits++;
  24083. res.set_content("direct", "text/plain");
  24084. });
  24085. proxy_mock.listen();
  24086. target.listen();
  24087. Client cli("public.example", target.port());
  24088. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24089. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24090. cli.set_keep_alive(true);
  24091. auto res1 = cli.Get("/a");
  24092. ASSERT_TRUE(res1);
  24093. EXPECT_EQ("via-proxy", res1->body);
  24094. EXPECT_EQ(1, proxy_hits.load());
  24095. EXPECT_EQ(0, target_hits.load());
  24096. cli.set_no_proxy({"public.example"});
  24097. auto res2 = cli.Get("/b");
  24098. ASSERT_TRUE(res2);
  24099. EXPECT_EQ("direct", res2->body);
  24100. EXPECT_EQ(1, proxy_hits.load());
  24101. EXPECT_EQ(1, target_hits.load());
  24102. }
  24103. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24104. namespace proxy_tunnel_test {
  24105. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24106. class ScopedSSLServer {
  24107. public:
  24108. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24109. port_ = svr_.bind_to_any_port("127.0.0.1");
  24110. }
  24111. ~ScopedSSLServer() {
  24112. svr_.stop();
  24113. if (th_.joinable()) { th_.join(); }
  24114. }
  24115. SSLServer &svr() { return svr_; }
  24116. int port() const { return port_; }
  24117. void listen() {
  24118. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24119. svr_.wait_until_ready();
  24120. }
  24121. private:
  24122. SSLServer svr_;
  24123. std::thread th_;
  24124. int port_ = 0;
  24125. };
  24126. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24127. class ScopedConnectProxy {
  24128. public:
  24129. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24130. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24131. if (listen_fd_ < 0) { return; }
  24132. int yes = 1;
  24133. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24134. sockaddr_in a{};
  24135. a.sin_family = AF_INET;
  24136. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24137. a.sin_port = 0;
  24138. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24139. return;
  24140. }
  24141. socklen_t alen = sizeof(a);
  24142. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24143. 0) {
  24144. return;
  24145. }
  24146. port_ = ntohs(a.sin_port);
  24147. if (::listen(listen_fd_, 1) != 0) { return; }
  24148. th_ = std::thread([this] { run(); });
  24149. }
  24150. ~ScopedConnectProxy() {
  24151. stop_ = true;
  24152. if (listen_fd_ >= 0) {
  24153. ::shutdown(listen_fd_, SHUT_RDWR);
  24154. ::close(listen_fd_);
  24155. }
  24156. if (th_.joinable()) { th_.join(); }
  24157. }
  24158. int port() const { return port_; }
  24159. int connect_hits() const { return connect_hits_.load(); }
  24160. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24161. std::string connect_request() const {
  24162. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24163. return connect_request_;
  24164. }
  24165. private:
  24166. void run() {
  24167. while (!stop_.load()) {
  24168. fd_set rfds;
  24169. FD_ZERO(&rfds);
  24170. FD_SET(listen_fd_, &rfds);
  24171. timeval tv{0, 100 * 1000};
  24172. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24173. if (sel <= 0) { continue; }
  24174. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24175. if (client_fd < 0) { continue; }
  24176. std::string req;
  24177. char buf[2048];
  24178. while (req.find("\r\n\r\n") == std::string::npos) {
  24179. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24180. if (n <= 0) { break; }
  24181. req.append(buf, static_cast<size_t>(n));
  24182. }
  24183. if (req.compare(0, 7, "CONNECT") != 0) {
  24184. ::close(client_fd);
  24185. continue;
  24186. }
  24187. connect_hits_++;
  24188. {
  24189. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24190. connect_request_ = req;
  24191. }
  24192. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24193. ::send(client_fd, ok, std::strlen(ok), 0);
  24194. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24195. sockaddr_in o{};
  24196. o.sin_family = AF_INET;
  24197. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24198. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24199. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24200. 0) {
  24201. ::close(client_fd);
  24202. ::close(origin_fd);
  24203. continue;
  24204. }
  24205. auto forward = [](int from, int to) {
  24206. char b[8192];
  24207. for (;;) {
  24208. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24209. if (n <= 0) { break; }
  24210. ssize_t off = 0;
  24211. while (off < n) {
  24212. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24213. if (s <= 0) {
  24214. off = n;
  24215. break;
  24216. }
  24217. off += s;
  24218. }
  24219. }
  24220. ::shutdown(to, SHUT_WR);
  24221. };
  24222. std::thread t1([&] { forward(client_fd, origin_fd); });
  24223. std::thread t2([&] { forward(origin_fd, client_fd); });
  24224. t1.join();
  24225. t2.join();
  24226. ::close(client_fd);
  24227. ::close(origin_fd);
  24228. }
  24229. }
  24230. int forward_port_ = -1;
  24231. int listen_fd_ = -1;
  24232. int port_ = 0;
  24233. std::thread th_;
  24234. std::atomic<bool> stop_{false};
  24235. std::atomic<int> connect_hits_{0};
  24236. mutable std::mutex connect_request_mutex_;
  24237. std::string connect_request_;
  24238. };
  24239. // Sends one request through the CONNECT proxy to the TLS origin with a
  24240. // credential configured for each hop, and checks that each credential reaches
  24241. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24242. // origin's (every header in origin_headers) on the tunnelled request.
  24243. void CredentialsStayWithTheirHop(
  24244. const std::function<void(SSLClient &)> &set_credentials,
  24245. const std::string &scheme,
  24246. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24247. std::atomic<int> origin_hits{0};
  24248. std::atomic<bool> origin_saw_proxy_authz{false};
  24249. std::atomic<bool> origin_saw_headers{false};
  24250. ScopedSSLServer origin;
  24251. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24252. origin_hits++;
  24253. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24254. origin_saw_headers =
  24255. std::all_of(origin_headers.begin(), origin_headers.end(),
  24256. [&](const std::string &h) { return req.has_header(h); });
  24257. res.set_content("ok", "text/plain");
  24258. });
  24259. origin.listen();
  24260. ScopedConnectProxy proxy(origin.port());
  24261. ASSERT_NE(0, proxy.port());
  24262. // Pinned to 127.0.0.1 for the same reason as the test below.
  24263. SSLClient cli("127.0.0.1", origin.port());
  24264. cli.enable_server_certificate_verification(false);
  24265. cli.set_proxy("127.0.0.1", proxy.port());
  24266. set_credentials(cli);
  24267. auto res = cli.Get("/x");
  24268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24269. EXPECT_EQ(StatusCode::OK_200, res->status);
  24270. EXPECT_EQ(1, origin_hits.load());
  24271. EXPECT_EQ(1, proxy.connect_hits());
  24272. EXPECT_TRUE(origin_saw_headers.load());
  24273. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24274. << "Proxy-Authorization must not be sent inside the tunnel";
  24275. auto connect_req = proxy.connect_request();
  24276. EXPECT_NE(std::string::npos,
  24277. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24278. for (const auto &h : origin_headers) {
  24279. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24280. << h << " must not be sent to the proxy on CONNECT";
  24281. }
  24282. }
  24283. } // namespace proxy_tunnel_test
  24284. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24285. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24286. [](SSLClient &cli) {
  24287. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24288. cli.set_basic_auth("origin-user", "origin-pass");
  24289. },
  24290. "Basic");
  24291. }
  24292. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24293. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24294. [](SSLClient &cli) {
  24295. cli.set_proxy_bearer_token_auth("proxy-token");
  24296. cli.set_bearer_token_auth("origin-token");
  24297. },
  24298. "Bearer");
  24299. }
  24300. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24301. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24302. [](SSLClient &cli) {
  24303. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24304. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24305. {"Cookie", "sid=origin-session"},
  24306. {"X-Api-Key", "origin-key"}});
  24307. },
  24308. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24309. }
  24310. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24311. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24312. // retry; otherwise proxy creds would be sent to the origin.
  24313. std::atomic<int> origin_hits{0};
  24314. std::atomic<bool> origin_saw_proxy_authz{false};
  24315. proxy_tunnel_test::ScopedSSLServer origin;
  24316. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24317. origin_hits++;
  24318. if (req.has_header("Proxy-Authorization")) {
  24319. origin_saw_proxy_authz = true;
  24320. }
  24321. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24322. res.set_header("Proxy-Authenticate",
  24323. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24324. "algorithm=MD5");
  24325. });
  24326. origin.listen();
  24327. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24328. ASSERT_NE(0, proxy.port());
  24329. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24330. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24331. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24332. // and answer with its own status, making this test flaky.
  24333. SSLClient cli("127.0.0.1", origin.port());
  24334. cli.enable_server_certificate_verification(false);
  24335. cli.set_proxy("127.0.0.1", proxy.port());
  24336. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24337. auto res = cli.Get("/x");
  24338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24339. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24340. EXPECT_EQ(1, origin_hits.load());
  24341. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24342. EXPECT_EQ(1, proxy.connect_hits());
  24343. }
  24344. #endif