test.cc 954 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401
  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. std::string boundary;
  613. EXPECT_TRUE(detail::parse_multipart_boundary(
  614. req.get_header_value("Content-Type"), boundary));
  615. EXPECT_EQ("x", boundary);
  616. }
  617. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  618. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  619. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  620. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  621. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  622. // Same 26-bit hash as REMOTE_ADDR.
  623. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  624. }
  625. // Forward declaration: in split builds split.py strips `inline` and moves the
  626. // definition into httplib.cc, so detail::base64_encode is not visible from the
  627. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  628. // in both header-only and split builds.
  629. namespace httplib {
  630. namespace detail {
  631. std::string base64_encode(const std::string &in);
  632. } // namespace detail
  633. } // namespace httplib
  634. TEST(Base64EncodeTest, KnownAnswers) {
  635. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  636. // where the accumulator's top bit is already set before the next shift.
  637. EXPECT_EQ("", detail::base64_encode(""));
  638. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  639. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  640. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  641. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  642. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  643. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  644. // High bytes keep the top bit set across several rounds.
  645. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  646. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  647. }
  648. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  649. string unescapedCharacters = "-_.!~*'()";
  650. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  651. }
  652. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  653. string reservedCharacters = ";,/?:@&=+$";
  654. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  655. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  656. }
  657. TEST(ClientQueryOrder, PreserveOrder) {
  658. // This test reproduces Issue #2259: client may reorder query parameters
  659. // when sending a GET request. The expected behavior is that the client
  660. // preserves the original query string order when the caller supplied it
  661. // as part of the path.
  662. Server svr;
  663. svr.Get("/", [&](const Request &req, Response &res) {
  664. // Echo back the raw target so the test can assert ordering
  665. res.set_content(req.target, "text/plain");
  666. });
  667. std::thread t{[&] { svr.listen(HOST, PORT); }};
  668. auto se = detail::scope_exit([&] {
  669. svr.stop();
  670. t.join();
  671. ASSERT_FALSE(svr.is_running());
  672. });
  673. svr.wait_until_ready();
  674. Client cli(HOST, PORT);
  675. ASSERT_TRUE(cli.is_valid());
  676. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  677. auto res = cli.Get(original);
  678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  679. // Expect the echoed target to exactly match the original path (order
  680. // preserved)
  681. EXPECT_EQ(res->body, original);
  682. }
  683. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  684. string chineseCharacters = U8("中国語");
  685. string russianCharacters = U8("дом");
  686. string brazilianCharacters = U8("óculos");
  687. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  688. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  689. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  690. "%D0%B4%D0%BE%D0%BC");
  691. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  692. }
  693. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  694. string unescapedCharacters = "-_.!~*'()";
  695. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  696. }
  697. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  698. string reservedCharacters = ";,/?:@&=+$";
  699. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  700. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  701. }
  702. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  703. string chineseCharacters = U8("中国語");
  704. string russianCharacters = U8("дом");
  705. string brazilianCharacters = U8("óculos");
  706. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  707. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  708. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  709. "%D0%B4%D0%BE%D0%BC");
  710. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  711. }
  712. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  713. // Issue #2082 use case: encoding path component with ampersand
  714. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  715. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  716. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  717. }
  718. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  723. string reservedCharacters = ";,/?:@&=+$#";
  724. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  725. }
  726. TEST(EncodeUriTest, TestUTF8Characters) {
  727. string chineseCharacters = U8("中国語");
  728. string russianCharacters = U8("дом");
  729. string brazilianCharacters = U8("óculos");
  730. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  731. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  732. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  733. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  734. }
  735. TEST(EncodeUriTest, TestCompleteUri) {
  736. string uri =
  737. "https://example.com/path/to/resource?query=value&param=test#fragment";
  738. EXPECT_EQ(
  739. httplib::encode_uri(uri),
  740. "https://example.com/path/to/resource?query=value&param=test#fragment");
  741. }
  742. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  743. string uri =
  744. "https://example.com/path with spaces/file name.html?q=hello world";
  745. EXPECT_EQ(httplib::encode_uri(uri),
  746. "https://example.com/path%20with%20spaces/"
  747. "file%20name.html?q=hello%20world");
  748. }
  749. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  750. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  751. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  752. }
  753. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  754. string unescapedCharacters = "-_.!~*'()";
  755. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  756. }
  757. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  758. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  759. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  760. string encodedBrazilian = "%C3%B3culos";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  762. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  764. }
  765. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  766. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  767. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  768. "Piri Tommy Villiers - on & on");
  769. }
  770. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  771. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  772. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  773. }
  774. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  775. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  776. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  777. }
  778. TEST(DecodeUriTest, TestUTF8Characters) {
  779. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  780. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  781. string encodedBrazilian = "%C3%B3culos";
  782. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  783. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  784. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  785. }
  786. TEST(DecodeUriTest, TestCompleteUri) {
  787. string encodedUri = "https://example.com/path%20with%20spaces/"
  788. "file%20name.html?q=hello%20world";
  789. EXPECT_EQ(
  790. httplib::decode_uri(encodedUri),
  791. "https://example.com/path with spaces/file name.html?q=hello world");
  792. }
  793. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  794. string original =
  795. "https://example.com/path with spaces/file name.html?q=hello world";
  796. string encoded = httplib::encode_uri(original);
  797. string decoded = httplib::decode_uri(encoded);
  798. EXPECT_EQ(decoded, original);
  799. }
  800. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  801. // decode_uri is the inverse of encode_uri: an escaped reserved character
  802. // stays encoded so it is not promoted into a real delimiter, while
  803. // non-reserved escapes still decode (like JS decodeURI).
  804. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  805. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  806. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  807. "%3F%3A%40%26%3D%2B%24%2C%3B");
  808. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  809. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  810. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  811. "http://example.com/a%2Fb");
  812. // decode_uri_component still decodes the reserved character.
  813. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  814. }
  815. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  816. string original = "Piri Tommy Villiers - on & on";
  817. string encoded = httplib::encode_uri_component(original);
  818. string decoded = httplib::decode_uri_component(encoded);
  819. EXPECT_EQ(decoded, original);
  820. }
  821. TEST(TrimTests, TrimStringTests) {
  822. EXPECT_EQ("abc", detail::trim_copy("abc"));
  823. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  824. EXPECT_TRUE(detail::trim_copy("").empty());
  825. }
  826. TEST(AsciiTest, LocaleIndependentClassification) {
  827. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  828. // which consult the global C locale: std::isalnum(0xC5) can return true
  829. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  830. // helpers must classify every byte by the ASCII grammar alone.
  831. for (int i = 0; i < 256; i++) {
  832. auto c = static_cast<char>(i);
  833. auto is_digit = i >= '0' && i <= '9';
  834. auto is_upper = i >= 'A' && i <= 'Z';
  835. auto is_lower = i >= 'a' && i <= 'z';
  836. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  837. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  838. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  839. << "byte " << i;
  840. }
  841. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  842. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  843. // Non-ASCII bytes must be percent-encoded, never passed through as
  844. // alphanumeric.
  845. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  846. }
  847. TEST(FromCharsTest, Double) {
  848. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  849. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  850. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  851. auto parse = [](const std::string &s, double &v) {
  852. return detail::from_chars(s.data(), s.data() + s.size(), v);
  853. };
  854. double v = -1.0;
  855. // Representative quality values.
  856. EXPECT_EQ(parse("0", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.0);
  858. EXPECT_EQ(parse("1", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 1.0);
  860. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.8);
  862. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 0.001);
  864. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 1.0);
  866. // A missing integer or fractional part is tolerated.
  867. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.5);
  869. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 5.0);
  871. // Values outside [0, 1] still parse; the caller range-checks them.
  872. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 123.456);
  874. // Stops at the first byte that is not part of the number and reports where.
  875. std::string trailing = "0.9, text/html";
  876. auto r = parse(trailing, v);
  877. EXPECT_EQ(r.ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.9);
  879. EXPECT_EQ(*r.ptr, ',');
  880. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  881. // outright, and an 'e'/'E' simply ends the number.
  882. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  883. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  884. std::string exp_input = "1.5e3";
  885. r = parse(exp_input, v);
  886. EXPECT_EQ(r.ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 1.5);
  888. EXPECT_EQ(*r.ptr, 'e');
  889. // Invalid inputs.
  890. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  891. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  895. // Pathological but well-formed inputs must stay bounded (no overflow, no
  896. // out-of-bounds table access) and stay within [0, 1] for the caller.
  897. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  898. std::errc{});
  899. EXPECT_DOUBLE_EQ(v, 0.0);
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  901. std::errc{});
  902. EXPECT_GE(v, 0.0);
  903. EXPECT_LE(v, 1.0);
  904. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  905. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  906. }
  907. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  908. // Simple case without quality values
  909. std::vector<std::string> result1;
  910. EXPECT_TRUE(detail::parse_accept_header(
  911. "text/html,application/json,text/plain", result1));
  912. EXPECT_EQ(result1.size(), 3U);
  913. EXPECT_EQ(result1[0], "text/html");
  914. EXPECT_EQ(result1[1], "application/json");
  915. EXPECT_EQ(result1[2], "text/plain");
  916. // With quality values
  917. std::vector<std::string> result2;
  918. EXPECT_TRUE(detail::parse_accept_header(
  919. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  920. EXPECT_EQ(result2.size(), 3U);
  921. EXPECT_EQ(result2[0], "application/json"); // highest q value
  922. EXPECT_EQ(result2[1], "text/html");
  923. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  924. }
  925. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  926. // Mixed with and without quality values
  927. std::vector<std::string> result;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  930. EXPECT_EQ(result.size(), 3U);
  931. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  932. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  933. EXPECT_EQ(result[2], "application/json"); // q=0.5
  934. }
  935. TEST(ParseAcceptHeaderTest, EdgeCases) {
  936. // Empty header
  937. std::vector<std::string> empty_result;
  938. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  939. EXPECT_TRUE(empty_result.empty());
  940. // Single type
  941. std::vector<std::string> single_result;
  942. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  943. EXPECT_EQ(single_result.size(), 1U);
  944. EXPECT_EQ(single_result[0], "application/json");
  945. // Wildcard types
  946. std::vector<std::string> wildcard_result;
  947. EXPECT_TRUE(detail::parse_accept_header(
  948. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  949. EXPECT_EQ(wildcard_result.size(), 3U);
  950. EXPECT_EQ(wildcard_result[0], "application/json");
  951. EXPECT_EQ(wildcard_result[1], "text/*");
  952. EXPECT_EQ(wildcard_result[2], "*/*");
  953. }
  954. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  955. // Common browser Accept header
  956. std::vector<std::string> browser_result;
  957. EXPECT_TRUE(
  958. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  959. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  960. browser_result));
  961. EXPECT_EQ(browser_result.size(), 6U);
  962. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  963. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  967. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  968. // API client header
  969. std::vector<std::string> api_result;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  972. api_result));
  973. EXPECT_EQ(api_result.size(), 3U);
  974. EXPECT_EQ(api_result[0], "application/json");
  975. EXPECT_EQ(api_result[1], "application/xml");
  976. EXPECT_EQ(api_result[2], "text/plain");
  977. }
  978. TEST(ParseAcceptHeaderTest, SpecialCases) {
  979. // Quality value with 3 decimal places
  980. std::vector<std::string> decimal_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  983. EXPECT_EQ(decimal_result.size(), 2U);
  984. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  985. EXPECT_EQ(decimal_result[1], "text/html");
  986. // Zero quality (should still be included but with lowest priority)
  987. std::vector<std::string> zero_q_result;
  988. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  989. zero_q_result));
  990. EXPECT_EQ(zero_q_result.size(), 2U);
  991. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  992. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  993. // No spaces around commas
  994. std::vector<std::string> no_space_result;
  995. EXPECT_TRUE(detail::parse_accept_header(
  996. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  997. no_space_result));
  998. EXPECT_EQ(no_space_result.size(), 3U);
  999. EXPECT_EQ(no_space_result[0], "text/html");
  1000. EXPECT_EQ(no_space_result[1], "application/json");
  1001. EXPECT_EQ(no_space_result[2], "text/plain");
  1002. }
  1003. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1004. // Quality values always use '.' as the decimal separator, so parsing must
  1005. // not depend on the process locale. An embedding application may have
  1006. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1007. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1008. std::string saved = cur ? cur : "C";
  1009. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1010. "fr_FR.UTF-8"};
  1011. bool switched = false;
  1012. for (const auto loc : comma_locales) {
  1013. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1014. std::localeconv()->decimal_point[0] == ',') {
  1015. switched = true;
  1016. break;
  1017. }
  1018. }
  1019. if (!switched) {
  1020. std::setlocale(LC_NUMERIC, saved.c_str());
  1021. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1022. }
  1023. // The higher-weighted type appears later in the list, so a correct parse
  1024. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1025. // sensitive parse reads both weights as 0 and leaves the original order.
  1026. std::vector<std::string> result;
  1027. EXPECT_TRUE(detail::parse_accept_header(
  1028. "application/json;q=0.1,text/html;q=0.9", result));
  1029. ASSERT_EQ(result.size(), 2U);
  1030. EXPECT_EQ(result[0], "text/html");
  1031. EXPECT_EQ(result[1], "application/json");
  1032. std::setlocale(LC_NUMERIC, saved.c_str());
  1033. }
  1034. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1035. std::vector<std::string> result;
  1036. // Invalid quality value (> 1.0)
  1037. EXPECT_FALSE(
  1038. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1039. // Invalid quality value (< 0.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1042. // Invalid quality value (not a number)
  1043. EXPECT_FALSE(detail::parse_accept_header(
  1044. "text/html;q=invalid,application/json", result));
  1045. // A valid numeric prefix does not make the entire quality value valid.
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=0.5junk,application/json", result));
  1048. // Empty quality value
  1049. EXPECT_FALSE(
  1050. detail::parse_accept_header("text/html;q=,application/json", result));
  1051. // Invalid media type format (no slash and not wildcard)
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("invalidtype,application/json", result));
  1054. // Valid cases should still work
  1055. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1056. EXPECT_EQ(result.size(), 1U);
  1057. EXPECT_EQ(result[0], "*/*");
  1058. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*");
  1061. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "text/*");
  1064. }
  1065. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1066. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1067. // and must not be answered with 400 Bad Request.
  1068. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1069. struct {
  1070. const char *value;
  1071. std::vector<std::string> expected;
  1072. } cases[] = {
  1073. {",application/json", {"application/json"}},
  1074. {"text/html,", {"text/html"}},
  1075. {"text/html,,*/*", {"text/html", "*/*"}},
  1076. // An empty element may be spelled with whitespace in it
  1077. {"text/html, , application/json", {"text/html", "application/json"}},
  1078. // Nothing but empty elements is an empty list, which means the same
  1079. // thing as no Accept header at all
  1080. {",,,", {}},
  1081. // Quality values still apply across ignored empty elements
  1082. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1083. };
  1084. for (const auto &c : cases) {
  1085. std::vector<std::string> result;
  1086. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1087. << "value: " << c.value;
  1088. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1089. }
  1090. // An invalid entry is still rejected when empty elements surround it
  1091. std::vector<std::string> result;
  1092. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1093. }
  1094. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1095. // or ';' inside one does not end the list element or the parameter. Section
  1096. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1097. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1098. struct {
  1099. const char *value;
  1100. std::vector<std::string> expected;
  1101. } cases[] = {
  1102. {"text/html;profile=\"a,b\",application/json",
  1103. {"text/html", "application/json"}},
  1104. // A "q=" inside a quoted value is not the weight
  1105. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1106. {"text/html", "application/json"}},
  1107. // The weight after a quoted value still applies
  1108. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1109. {"application/json", "text/html"}},
  1110. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1111. {"application/json", "text/html"}},
  1112. {"text/html;profile=\"a\\\"b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // An escaped backslash does not escape the '"' after it
  1115. {"text/html;profile=\"a\\\\\",application/json",
  1116. {"text/html", "application/json"}},
  1117. };
  1118. for (const auto &c : cases) {
  1119. std::vector<std::string> result;
  1120. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1121. << "value: " << c.value;
  1122. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1123. }
  1124. }
  1125. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1126. Server svr;
  1127. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1128. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1129. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1130. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1131. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1132. res.set_content("ok", "text/plain");
  1133. });
  1134. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1135. EXPECT_TRUE(false);
  1136. res.set_content("bad request", "text/plain");
  1137. });
  1138. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1139. auto se = detail::scope_exit([&] {
  1140. svr.stop();
  1141. listen_thread.join();
  1142. ASSERT_FALSE(svr.is_running());
  1143. });
  1144. svr.wait_until_ready();
  1145. Client cli("localhost", PORT);
  1146. {
  1147. auto res = cli.Get(
  1148. "/accept_ok",
  1149. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1151. EXPECT_EQ(StatusCode::OK_200, res->status);
  1152. }
  1153. {
  1154. auto res = cli.Get("/accept_bad_request",
  1155. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1157. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1158. }
  1159. }
  1160. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1161. Server svr;
  1162. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1163. res.set_content("ok", "text/plain");
  1164. });
  1165. std::atomic<int> start_count{0};
  1166. std::atomic<bool> running_when_called{false};
  1167. svr.set_start_handler([&]() {
  1168. running_when_called = svr.is_running();
  1169. start_count++;
  1170. });
  1171. auto port = svr.bind_to_any_port(HOST);
  1172. std::thread t([&]() { svr.listen_after_bind(); });
  1173. auto se = detail::scope_exit([&] {
  1174. svr.stop();
  1175. t.join();
  1176. ASSERT_FALSE(svr.is_running());
  1177. });
  1178. svr.wait_until_ready();
  1179. // A successful request proves the accept loop is running, which the start
  1180. // handler precedes; so by now the handler must have run exactly once.
  1181. Client cli(HOST, port);
  1182. cli.set_connection_timeout(std::chrono::seconds(5));
  1183. auto res = cli.Get("/");
  1184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1185. EXPECT_EQ(StatusCode::OK_200, res->status);
  1186. EXPECT_EQ(1, start_count.load());
  1187. EXPECT_TRUE(running_when_called.load());
  1188. }
  1189. TEST(DivideTest, DivideStringTests) {
  1190. auto divide = [](const std::string &str, char d) {
  1191. std::string lhs;
  1192. std::string rhs;
  1193. detail::divide(str, d,
  1194. [&](const char *lhs_data, std::size_t lhs_size,
  1195. const char *rhs_data, std::size_t rhs_size) {
  1196. lhs.assign(lhs_data, lhs_size);
  1197. rhs.assign(rhs_data, rhs_size);
  1198. });
  1199. return std::make_pair(std::move(lhs), std::move(rhs));
  1200. };
  1201. {
  1202. const auto res = divide("", '=');
  1203. EXPECT_EQ(res.first, "");
  1204. EXPECT_EQ(res.second, "");
  1205. }
  1206. {
  1207. const auto res = divide("=", '=');
  1208. EXPECT_EQ(res.first, "");
  1209. EXPECT_EQ(res.second, "");
  1210. }
  1211. {
  1212. const auto res = divide(" ", '=');
  1213. EXPECT_EQ(res.first, " ");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("a", '=');
  1218. EXPECT_EQ(res.first, "a");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide("a=", '=');
  1223. EXPECT_EQ(res.first, "a");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("=b", '=');
  1228. EXPECT_EQ(res.first, "");
  1229. EXPECT_EQ(res.second, "b");
  1230. }
  1231. {
  1232. const auto res = divide("a=b", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "b");
  1235. }
  1236. {
  1237. const auto res = divide("a=b=", '=');
  1238. EXPECT_EQ(res.first, "a");
  1239. EXPECT_EQ(res.second, "b=");
  1240. }
  1241. {
  1242. const auto res = divide("a=b=c", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b=c");
  1245. }
  1246. }
  1247. TEST(SplitTest, ParseQueryString) {
  1248. string s = "key1=val1&key2=val2&key3=val3";
  1249. Params dic;
  1250. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1251. [&](const char *b, const char *e) {
  1252. string key, val;
  1253. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1254. if (key.empty()) {
  1255. key.assign(b2, e2);
  1256. } else {
  1257. val.assign(b2, e2);
  1258. }
  1259. });
  1260. dic.emplace(key, val);
  1261. });
  1262. EXPECT_EQ("val1", dic.find("key1")->second);
  1263. EXPECT_EQ("val2", dic.find("key2")->second);
  1264. EXPECT_EQ("val3", dic.find("key3")->second);
  1265. }
  1266. TEST(SplitTest, ParseInvalidQueryTests) {
  1267. {
  1268. string s = " ";
  1269. Params dict;
  1270. detail::parse_query_text(s, dict);
  1271. EXPECT_TRUE(dict.empty());
  1272. }
  1273. {
  1274. string s = " = =";
  1275. Params dict;
  1276. detail::parse_query_text(s, dict);
  1277. EXPECT_TRUE(dict.empty());
  1278. }
  1279. }
  1280. TEST(ParseQueryTest, ParseQueryString) {
  1281. {
  1282. std::string s = "key1=val1&key2=val2&key3=val3";
  1283. Params dic;
  1284. detail::parse_query_text(s, dic);
  1285. EXPECT_EQ("val1", dic.find("key1")->second);
  1286. EXPECT_EQ("val2", dic.find("key2")->second);
  1287. EXPECT_EQ("val3", dic.find("key3")->second);
  1288. }
  1289. {
  1290. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1291. Params dic;
  1292. detail::parse_query_text(s, dic);
  1293. EXPECT_EQ("", dic.find("key1")->second);
  1294. EXPECT_EQ("val1", dic.find("key2")->second);
  1295. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1296. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1297. }
  1298. }
  1299. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1300. Params dic;
  1301. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1302. dic.emplace("key1", "val1");
  1303. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1304. dic.emplace("key2", "val2");
  1305. dic.emplace("key3", "val3");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1307. }
  1308. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1309. Params params;
  1310. params.emplace("a", "1");
  1311. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1312. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1313. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1314. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1315. // Long enough to overflow the stack when matched with std::regex.
  1316. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1317. EXPECT_EQ("/p?" + long_query + "&a=1",
  1318. append_query_params("/p?" + long_query, params));
  1319. }
  1320. // Joins every entry of a Headers or Params into "key=value " so a whole
  1321. // traversal can be compared in one assertion. Both are instantiations of the
  1322. // same insertion-ordered container, so one helper serves both.
  1323. template <typename Map> static std::string entries_to_string(const Map &m) {
  1324. std::string s;
  1325. for (const auto &entry : m) {
  1326. s += entry.first + "=" + entry.second + " ";
  1327. }
  1328. return s;
  1329. }
  1330. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1331. // Params used to be a std::multimap, which sorted by name and handed the
  1332. // caller's query back alphabetised. A client signing its query string could
  1333. // not reproduce the order it asked for.
  1334. Params dic;
  1335. dic.emplace("zulu", "1");
  1336. dic.emplace("alpha", "2");
  1337. dic.emplace("mike", "3");
  1338. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1339. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1340. }
  1341. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1342. Params dic;
  1343. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1344. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1345. }
  1346. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1347. Request req;
  1348. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1349. req.params);
  1350. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1351. EXPECT_EQ("first", req.get_param_value("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1353. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1354. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1355. EXPECT_EQ("", req.get_param_value("tag", 3));
  1356. }
  1357. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1358. // Params shares its container with Headers, which matches field names
  1359. // case-insensitively. Parameter names must not pick that up.
  1360. Params dic;
  1361. dic.emplace("Key", "upper");
  1362. dic.emplace("key", "lower");
  1363. EXPECT_EQ(2U, dic.size());
  1364. EXPECT_EQ(1U, dic.count("Key"));
  1365. EXPECT_EQ(1U, dic.count("key"));
  1366. EXPECT_EQ("upper", dic.find("Key")->second);
  1367. EXPECT_EQ("lower", dic.find("key")->second);
  1368. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1369. }
  1370. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1371. Server svr;
  1372. std::string order;
  1373. svr.Get("/order", [&](const Request &req, Response &res) {
  1374. order = entries_to_string(req.params);
  1375. res.set_content("ok", "text/plain");
  1376. });
  1377. auto port = svr.bind_to_any_port(HOST);
  1378. thread t = thread([&] { svr.listen_after_bind(); });
  1379. auto se = detail::scope_exit([&] {
  1380. svr.stop();
  1381. t.join();
  1382. ASSERT_FALSE(svr.is_running());
  1383. });
  1384. svr.wait_until_ready();
  1385. Client cli(HOST, port);
  1386. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1387. ASSERT_TRUE(res);
  1388. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1389. }
  1390. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1391. Server svr;
  1392. std::string field_order, file_order;
  1393. svr.Post("/order", [&](const Request &req, Response &res) {
  1394. for (const auto &field : req.form.fields) {
  1395. field_order += field.first + "=" + field.second.content + " ";
  1396. }
  1397. for (const auto &file : req.form.files) {
  1398. file_order += file.first + "=" + file.second.filename + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. UploadFormDataItems items = {
  1411. {"zulu", "1", "", ""},
  1412. {"alpha", "2", "", ""},
  1413. {"mike", "3", "", ""},
  1414. {"zebra", "z", "z.txt", "text/plain"},
  1415. {"apple", "a", "a.txt", "text/plain"},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/order", items);
  1419. ASSERT_TRUE(res);
  1420. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1421. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1422. }
  1423. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1424. Server svr;
  1425. std::vector<std::string> values;
  1426. std::string first, second, out_of_range, order;
  1427. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1428. values = req.form.get_fields("tag");
  1429. first = req.form.get_field("tag", 0);
  1430. second = req.form.get_field("tag", 1);
  1431. out_of_range = req.form.get_field("tag", 2);
  1432. for (const auto &field : req.form.fields) {
  1433. order += field.first + "=" + field.second.content + " ";
  1434. }
  1435. res.set_content("ok", "text/plain");
  1436. });
  1437. auto port = svr.bind_to_any_port(HOST);
  1438. thread t = thread([&] { svr.listen_after_bind(); });
  1439. auto se = detail::scope_exit([&] {
  1440. svr.stop();
  1441. t.join();
  1442. ASSERT_FALSE(svr.is_running());
  1443. });
  1444. svr.wait_until_ready();
  1445. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1446. // not adjacent in the container.
  1447. UploadFormDataItems items = {
  1448. {"tag", "first", "", ""},
  1449. {"other", "x", "", ""},
  1450. {"tag", "second", "", ""},
  1451. };
  1452. Client cli(HOST, port);
  1453. auto res = cli.Post("/repeated", items);
  1454. ASSERT_TRUE(res);
  1455. ASSERT_EQ(2U, values.size());
  1456. EXPECT_EQ("first", values[0]);
  1457. EXPECT_EQ("second", values[1]);
  1458. EXPECT_EQ("first", first);
  1459. EXPECT_EQ("second", second);
  1460. // std::multimap already kept entries sharing a name in insertion order, so
  1461. // everything above passes without this change too. The whole traversal is
  1462. // what tells the two apart: sorting by name would hoist "other" to the front
  1463. // and the two "tag" parts would end up adjacent.
  1464. EXPECT_EQ("tag=first other=x tag=second ", order);
  1465. // Advancing past the last entry of a name used to run off the container;
  1466. // the container's saturating increment makes it return the default instead.
  1467. EXPECT_EQ("", out_of_range);
  1468. }
  1469. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1470. Server svr;
  1471. std::string file_names;
  1472. svr.Post("/upload", [&](const Request &req, Response &res) {
  1473. for (const auto &file : req.form.files) {
  1474. file_names += file.first + "|" + file.second.filename + " ";
  1475. }
  1476. res.set_content("ok", "text/plain");
  1477. });
  1478. auto port = svr.bind_to_any_port(HOST);
  1479. thread t = thread([&] { svr.listen_after_bind(); });
  1480. auto se = detail::scope_exit([&] {
  1481. svr.stop();
  1482. t.join();
  1483. ASSERT_FALSE(svr.is_running());
  1484. });
  1485. svr.wait_until_ready();
  1486. // A trailing backslash would otherwise escape the closing quote.
  1487. UploadFormDataItems items = {
  1488. {"dir\\", "x", "a.txt", "text/plain"},
  1489. {"b", "y", "a\\\\b.txt", "text/plain"},
  1490. };
  1491. Client cli(HOST, port);
  1492. auto res = cli.Post("/upload", items);
  1493. ASSERT_TRUE(res);
  1494. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1495. }
  1496. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1497. // Server::read_content() keeps a FormFields::iterator alive across the
  1498. // content callbacks that fill the part it points at. The container is
  1499. // vector-backed, so a later emplace can reallocate and invalidate an older
  1500. // iterator; 64 parts grow the vector through seven reallocations, which
  1501. // checks that every part's content still lands in its own entry.
  1502. const size_t part_count = 64;
  1503. // One formula for both the parts sent and the values expected back, so the
  1504. // two cannot drift apart.
  1505. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1506. auto content_of = [](size_t i) {
  1507. return std::string(64, static_cast<char>('a' + (i % 26)));
  1508. };
  1509. Server svr;
  1510. std::vector<std::pair<std::string, std::string>> received;
  1511. svr.Post("/many", [&](const Request &req, Response &res) {
  1512. for (const auto &field : req.form.fields) {
  1513. received.emplace_back(field.first, field.second.content);
  1514. }
  1515. res.set_content("ok", "text/plain");
  1516. });
  1517. auto port = svr.bind_to_any_port(HOST);
  1518. thread t = thread([&] { svr.listen_after_bind(); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. t.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. UploadFormDataItems items;
  1526. for (size_t i = 0; i < part_count; i++) {
  1527. items.push_back({name_of(i), content_of(i), "", ""});
  1528. }
  1529. Client cli(HOST, port);
  1530. auto res = cli.Post("/many", items);
  1531. ASSERT_TRUE(res);
  1532. ASSERT_EQ(part_count, received.size());
  1533. for (size_t i = 0; i < part_count; i++) {
  1534. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1535. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1536. }
  1537. }
  1538. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1539. string content_type = "multipart/form-data; boundary=something";
  1540. string boundary;
  1541. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1542. EXPECT_TRUE(ret);
  1543. EXPECT_EQ(boundary, "something");
  1544. }
  1545. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1546. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1547. string boundary;
  1548. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1549. EXPECT_TRUE(ret);
  1550. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1551. }
  1552. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1553. string content_type =
  1554. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1555. string boundary;
  1556. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1557. EXPECT_TRUE(ret);
  1558. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1559. }
  1560. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1561. string content_type =
  1562. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1563. string boundary;
  1564. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1565. EXPECT_TRUE(ret);
  1566. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1567. }
  1568. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1569. const string boundary(70, 'a');
  1570. string content_type = "multipart/form-data; boundary=" + boundary;
  1571. string parsed;
  1572. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1573. EXPECT_TRUE(ret);
  1574. EXPECT_EQ(parsed, boundary);
  1575. }
  1576. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1577. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1578. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1579. string parsed;
  1580. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1581. EXPECT_FALSE(ret);
  1582. }
  1583. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1584. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1585. // is 72 characters on the wire and still valid.
  1586. const string boundary(70, 'a');
  1587. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1588. string parsed;
  1589. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1590. EXPECT_EQ(parsed, boundary);
  1591. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1592. parsed.clear();
  1593. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1594. }
  1595. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1596. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1597. // The parameter parser must not treat that '=' as the key/value separator.
  1598. string content_type =
  1599. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1600. "charset=UTF-8";
  1601. string parsed;
  1602. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1603. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1604. }
  1605. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1606. // A ';' inside the quoted-string is part of the value, not a parameter
  1607. // separator, so it must not truncate the boundary.
  1608. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1609. string parsed;
  1610. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1611. EXPECT_EQ(parsed, "a;b");
  1612. }
  1613. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1614. string parsed;
  1615. EXPECT_TRUE(detail::parse_multipart_boundary(
  1616. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1617. EXPECT_EQ("a\\b", parsed);
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1620. EXPECT_EQ("a\"b", parsed);
  1621. }
  1622. TEST(ParseDispositionParamsTest, QuotedValues) {
  1623. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1624. // ';' and '=' are ordinary characters inside one.
  1625. struct {
  1626. const char *value;
  1627. std::vector<std::pair<const char *, const char *>> expected;
  1628. } cases[] = {
  1629. {"name=\"file1\"; filename=\"a.txt\"",
  1630. {{"name", "file1"}, {"filename", "a.txt"}}},
  1631. // Whitespace around '=' and ';' is still trimmed
  1632. {"name=\"file2\" ;filename = \"a.html\"",
  1633. {{"name", "file2"}, {"filename", "a.html"}}},
  1634. // '=' inside the value used to leave only the text after the last one
  1635. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1636. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1637. {"name=\"x=y\"", {{"name", "x=y"}}},
  1638. // ';' inside the value used to truncate the pair and leave a bogus one
  1639. {"name=\"file3\"; filename=\"a;b.txt\"",
  1640. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1641. // An unquoted value keeps working, and so does filename*
  1642. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1643. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1644. // A parameter with no key is dropped rather than turned into one whose
  1645. // key is the value
  1646. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1647. // An escaped quote does not end the value
  1648. {"name=\"a\\\"; filename=evil.php\"",
  1649. {{"name", "a\"; filename=evil.php"}}},
  1650. // Other backslashes, as in a Windows path, are kept
  1651. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1652. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1653. };
  1654. for (const auto &c : cases) {
  1655. Params params;
  1656. detail::parse_disposition_params(c.value, params);
  1657. for (const auto &kv : c.expected) {
  1658. auto it = params.find(kv.first);
  1659. ASSERT_NE(it, params.end())
  1660. << "value: " << c.value << ", key: " << kv.first;
  1661. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1662. }
  1663. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1664. }
  1665. }
  1666. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1667. Server svr;
  1668. std::string filename;
  1669. std::string content;
  1670. svr.Post("/upload", [&](const Request &req, Response &) {
  1671. const auto &file = req.form.get_file("file");
  1672. filename = file.filename;
  1673. content = file.content;
  1674. });
  1675. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1676. auto se = detail::scope_exit([&] {
  1677. svr.stop();
  1678. thread.join();
  1679. ASSERT_FALSE(svr.is_running());
  1680. });
  1681. svr.wait_until_ready();
  1682. std::string body = "--B\r\n"
  1683. "Content-Disposition: form-data; name=\"file\"; "
  1684. "filename=\"a.txt\"\r\n"
  1685. "Content-Type: text/plain\r\n"
  1686. "\r\n"
  1687. "hello\r\n"
  1688. "--B--\r\n";
  1689. Client cli(HOST, PORT);
  1690. auto res = cli.Post(
  1691. "/upload",
  1692. [&](size_t offset, DataSink &sink) {
  1693. if (offset < body.size()) {
  1694. sink.write(&body[offset], 1);
  1695. } else {
  1696. sink.done();
  1697. }
  1698. return true;
  1699. },
  1700. "multipart/form-data; boundary=B");
  1701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1702. EXPECT_EQ(StatusCode::OK_200, res->status);
  1703. EXPECT_EQ("a.txt", filename);
  1704. EXPECT_EQ("hello", content);
  1705. }
  1706. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1707. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1708. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1709. Server svr;
  1710. std::string field_value, file_name, file_filename;
  1711. bool has_field = false, has_file = false;
  1712. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1713. has_field = req.form.has_field("x=y");
  1714. field_value = req.form.get_field("x=y");
  1715. has_file = req.form.has_file("file1");
  1716. const auto &file = req.form.get_file("file1");
  1717. file_name = file.name;
  1718. file_filename = file.filename;
  1719. res.set_content("ok", "text/plain");
  1720. });
  1721. auto port = svr.bind_to_any_port(HOST);
  1722. thread t = thread([&] { svr.listen_after_bind(); });
  1723. auto se = detail::scope_exit([&] {
  1724. svr.stop();
  1725. t.join();
  1726. ASSERT_FALSE(svr.is_running());
  1727. });
  1728. svr.wait_until_ready();
  1729. UploadFormDataItems items = {
  1730. {"x=y", "field-value", "", ""},
  1731. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1732. };
  1733. Client cli(HOST, port);
  1734. auto res = cli.Post("/quoted", items);
  1735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1736. ASSERT_EQ(StatusCode::OK_200, res->status);
  1737. EXPECT_TRUE(has_field);
  1738. EXPECT_EQ("field-value", field_value);
  1739. EXPECT_TRUE(has_file);
  1740. EXPECT_EQ("file1", file_name);
  1741. EXPECT_EQ("a;b=report.pdf", file_filename);
  1742. }
  1743. TEST(GetHeaderValueTest, DefaultValue) {
  1744. Headers headers = {{"Dummy", "Dummy"}};
  1745. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1746. EXPECT_STREQ("text/plain", val);
  1747. }
  1748. TEST(GetHeaderValueTest, DefaultValueInt) {
  1749. Headers headers = {{"Dummy", "Dummy"}};
  1750. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1751. EXPECT_EQ(100ull, val);
  1752. }
  1753. TEST(GetHeaderValueTest, RegularValue) {
  1754. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1755. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1756. EXPECT_STREQ("text/html", val);
  1757. }
  1758. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1759. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1760. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1761. EXPECT_STREQ("text/html", val);
  1762. }
  1763. TEST(GetHeaderValueTest, SetContent) {
  1764. Response res;
  1765. res.set_content("html", "text/html");
  1766. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1767. res.set_content("text", "text/plain");
  1768. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1769. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1770. }
  1771. TEST(GetHeaderValueTest, RegularValueInt) {
  1772. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1773. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1774. EXPECT_EQ(100ull, val);
  1775. }
  1776. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1777. Headers headers = {{"Content-Length", "x"}};
  1778. auto is_invalid_value = false;
  1779. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1780. is_invalid_value);
  1781. EXPECT_EQ(0ull, val);
  1782. EXPECT_TRUE(is_invalid_value);
  1783. }
  1784. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1785. // An all-digit value that overflows size_t must be reported as invalid, not
  1786. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1787. // a large length to a small one on 32-bit builds, leaving the framing length
  1788. // wrong while is_invalid_value stayed false.
  1789. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1790. auto is_invalid_value = false;
  1791. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1792. is_invalid_value);
  1793. EXPECT_TRUE(is_invalid_value);
  1794. // A well-formed length is unaffected.
  1795. Headers ok = {{"Content-Length", "1234"}};
  1796. is_invalid_value = false;
  1797. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1798. is_invalid_value);
  1799. EXPECT_EQ(1234ull, val);
  1800. EXPECT_FALSE(is_invalid_value);
  1801. }
  1802. TEST(GetHeaderValueTest, Range) {
  1803. {
  1804. Headers headers = {make_range_header({{1, -1}})};
  1805. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1806. EXPECT_STREQ("bytes=1-", val);
  1807. }
  1808. {
  1809. Headers headers = {make_range_header({{-1, 1}})};
  1810. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1811. EXPECT_STREQ("bytes=-1", val);
  1812. }
  1813. {
  1814. Headers headers = {make_range_header({{1, 10}})};
  1815. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1816. EXPECT_STREQ("bytes=1-10", val);
  1817. }
  1818. {
  1819. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1820. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1821. EXPECT_STREQ("bytes=1-10, 100-", val);
  1822. }
  1823. {
  1824. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1825. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1826. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1827. }
  1828. {
  1829. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1830. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1831. EXPECT_STREQ("bytes=0-0, -1", val);
  1832. }
  1833. }
  1834. TEST(BearerTokenAuthTest, SchemeValidation) {
  1835. // A value shorter than "Bearer " must not throw from the fixed-length
  1836. // substr, and a non-Bearer scheme must not be reported as a token.
  1837. struct {
  1838. const char *value;
  1839. const char *expected;
  1840. } cases[] = {
  1841. {"x", ""},
  1842. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1843. {"Bearer abc123", "abc123"},
  1844. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1845. };
  1846. for (const auto &c : cases) {
  1847. Request req;
  1848. req.set_header("Authorization", c.value);
  1849. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1850. }
  1851. }
  1852. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1853. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1854. // to depend on the standard library (libstdc++ handed back duplicates in
  1855. // reverse insertion order, libc++ in insertion order).
  1856. Request req;
  1857. req.set_header("Accept-Encoding", "gzip");
  1858. req.set_header("Accept-Encoding", "deflate");
  1859. req.set_header("Accept-Encoding", "br");
  1860. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1861. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1862. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1863. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1864. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1865. }
  1866. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1867. Request req;
  1868. req.set_header("X-Test", "only");
  1869. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1870. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1871. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1872. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1873. }
  1874. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1875. Request req;
  1876. req.set_header("X-First", "1");
  1877. req.set_header("X-Test", "2");
  1878. req.params.emplace("first", "1");
  1879. req.params.emplace("test", "2");
  1880. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1881. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1882. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1883. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1884. // The second one is negative when read as a signed value
  1885. const auto max_id = (std::numeric_limits<size_t>::max)();
  1886. for (auto id : {max_id / 2, max_id}) {
  1887. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1888. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1889. EXPECT_EQ("", req.get_param_value("test", id));
  1890. EXPECT_EQ("", req.form.get_field("test", id));
  1891. EXPECT_EQ("", req.form.get_file("test", id).content);
  1892. }
  1893. }
  1894. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1895. Headers headers;
  1896. headers.emplace("Host", "example.com");
  1897. headers.emplace("Accept-Encoding", "gzip");
  1898. headers.emplace("User-Agent", "test");
  1899. headers.emplace("Accept-Encoding", "deflate");
  1900. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1901. "Accept-Encoding=deflate ",
  1902. entries_to_string(headers));
  1903. }
  1904. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1905. Headers headers = {{"Content-Type", "text/html"},
  1906. {"CONTENT-TYPE", "text/xml"}};
  1907. EXPECT_EQ(2U, headers.count("content-type"));
  1908. auto it = headers.find("content-type");
  1909. ASSERT_TRUE(it != headers.end());
  1910. EXPECT_EQ("text/html", it->second);
  1911. }
  1912. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1913. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1914. // drop only those fields and leave everything positioned between them.
  1915. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1916. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1917. auto rng = headers.equal_range("a");
  1918. headers.erase(rng.first, rng.second);
  1919. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1920. }
  1921. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1922. Headers headers = {
  1923. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1924. EXPECT_EQ(3U, headers.erase("A"));
  1925. EXPECT_EQ(0U, headers.count("A"));
  1926. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1927. }
  1928. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1929. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1930. headers.emplace_front("Host", "example.com");
  1931. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1932. entries_to_string(headers));
  1933. }
  1934. TEST(ParseHeaderValueTest, Range) {
  1935. {
  1936. Ranges ranges;
  1937. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1938. EXPECT_TRUE(ret);
  1939. EXPECT_EQ(1u, ranges.size());
  1940. EXPECT_EQ(1u, ranges[0].first);
  1941. EXPECT_EQ(-1, ranges[0].second);
  1942. }
  1943. {
  1944. Ranges ranges;
  1945. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1946. EXPECT_TRUE(ret);
  1947. EXPECT_EQ(1u, ranges.size());
  1948. EXPECT_EQ(-1, ranges[0].first);
  1949. EXPECT_EQ(1u, ranges[0].second);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ(1u, ranges.size());
  1956. EXPECT_EQ(1u, ranges[0].first);
  1957. EXPECT_EQ(10u, ranges[0].second);
  1958. }
  1959. {
  1960. Ranges ranges;
  1961. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1962. EXPECT_FALSE(ret);
  1963. }
  1964. {
  1965. Ranges ranges;
  1966. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1967. EXPECT_TRUE(ret);
  1968. EXPECT_EQ(2u, ranges.size());
  1969. EXPECT_EQ(1u, ranges[0].first);
  1970. EXPECT_EQ(10u, ranges[0].second);
  1971. EXPECT_EQ(100u, ranges[1].first);
  1972. EXPECT_EQ(-1, ranges[1].second);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. auto ret =
  1977. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ(3u, ranges.size());
  1980. EXPECT_EQ(1u, ranges[0].first);
  1981. EXPECT_EQ(10u, ranges[0].second);
  1982. EXPECT_EQ(100u, ranges[1].first);
  1983. EXPECT_EQ(200u, ranges[1].second);
  1984. EXPECT_EQ(300u, ranges[2].first);
  1985. EXPECT_EQ(400u, ranges[2].second);
  1986. }
  1987. {
  1988. Ranges ranges;
  1989. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1990. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2002. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2003. EXPECT_FALSE(
  2004. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2005. EXPECT_TRUE(ranges.empty());
  2006. }
  2007. {
  2008. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2009. // remainder of the representation, so it stays accepted.
  2010. Ranges ranges;
  2011. auto ret =
  2012. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2013. EXPECT_TRUE(ret);
  2014. ASSERT_EQ(1u, ranges.size());
  2015. EXPECT_EQ(0, ranges[0].first);
  2016. EXPECT_EQ(-1, ranges[0].second);
  2017. }
  2018. // RFC 9110 14.1: range unit names are case-insensitive.
  2019. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2020. Ranges ranges;
  2021. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2022. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2023. }
  2024. }
  2025. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2033. #else
  2034. EXPECT_TRUE(ret == detail::EncodingType::None);
  2035. #endif
  2036. }
  2037. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2038. Request req;
  2039. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2040. Response res;
  2041. res.set_header("Content-Type", "text/plain");
  2042. auto ret = detail::encoding_type(req, res);
  2043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2044. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2045. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2049. #else
  2050. EXPECT_TRUE(ret == detail::EncodingType::None);
  2051. #endif
  2052. }
  2053. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2054. Request req;
  2055. req.set_header("Accept-Encoding",
  2056. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2057. Response res;
  2058. res.set_header("Content-Type", "text/plain");
  2059. auto ret = detail::encoding_type(req, res);
  2060. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2062. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2063. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2064. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2065. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2066. #else
  2067. EXPECT_TRUE(ret == detail::EncodingType::None);
  2068. #endif
  2069. }
  2070. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2071. // All supported encodings rejected with q=0 should return None
  2072. Request req;
  2073. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2074. Response res;
  2075. res.set_header("Content-Type", "text/plain");
  2076. auto ret = detail::encoding_type(req, res);
  2077. EXPECT_TRUE(ret == detail::EncodingType::None);
  2078. }
  2079. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2080. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2081. Request req;
  2082. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2083. Response res;
  2084. res.set_header("Content-Type", "text/plain");
  2085. auto ret = detail::encoding_type(req, res);
  2086. EXPECT_TRUE(ret == detail::EncodingType::None);
  2087. }
  2088. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2089. Request req;
  2090. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2091. Response res;
  2092. res.set_header("Content-Type", "text/plain");
  2093. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2094. }
  2095. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2096. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2097. Request req;
  2098. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2099. Response res;
  2100. res.set_header("Content-Type", "text/plain");
  2101. auto ret = detail::encoding_type(req, res);
  2102. EXPECT_TRUE(ret == detail::EncodingType::None);
  2103. }
  2104. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2105. // RFC 7231: Accept-Encoding values are case-insensitive
  2106. Request req;
  2107. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2108. Response res;
  2109. res.set_header("Content-Type", "text/plain");
  2110. auto ret = detail::encoding_type(req, res);
  2111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2112. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2113. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2114. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2115. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2116. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2117. #else
  2118. EXPECT_TRUE(ret == detail::EncodingType::None);
  2119. #endif
  2120. }
  2121. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2122. // q value should determine priority, not hardcoded order
  2123. Request req;
  2124. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2125. Response res;
  2126. res.set_header("Content-Type", "text/plain");
  2127. auto ret = detail::encoding_type(req, res);
  2128. // gzip has highest q=1.0, so it should be selected even though
  2129. // br and zstd are also supported
  2130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2131. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2132. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2133. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2134. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2135. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2136. #else
  2137. EXPECT_TRUE(ret == detail::EncodingType::None);
  2138. #endif
  2139. }
  2140. TEST(BufferStreamTest, read) {
  2141. detail::BufferStream strm1;
  2142. Stream &strm = strm1;
  2143. EXPECT_EQ(5, strm.write("hello"));
  2144. char buf[512];
  2145. EXPECT_EQ(2, strm.read(buf, 2));
  2146. EXPECT_EQ('h', buf[0]);
  2147. EXPECT_EQ('e', buf[1]);
  2148. EXPECT_EQ(2, strm.read(buf, 2));
  2149. EXPECT_EQ('l', buf[0]);
  2150. EXPECT_EQ('l', buf[1]);
  2151. EXPECT_EQ(1, strm.read(buf, 1));
  2152. EXPECT_EQ('o', buf[0]);
  2153. EXPECT_EQ(0, strm.read(buf, 1));
  2154. }
  2155. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2156. auto host = "www.httpwatch.com";
  2157. auto ip = hosted_at(host);
  2158. EXPECT_EQ("23.96.13.243", ip);
  2159. std::vector<std::string> addrs;
  2160. hosted_at(host, addrs);
  2161. EXPECT_EQ(1u, addrs.size());
  2162. }
  2163. #if 0 // It depends on each test environment...
  2164. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2165. auto host = "www.youtube.com";
  2166. std::vector<std::string> addrs;
  2167. hosted_at(host, addrs);
  2168. EXPECT_EQ(20u, addrs.size());
  2169. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2170. EXPECT_TRUE(it != addrs.end());
  2171. }
  2172. #endif
  2173. class ChunkedEncodingTest : public ::testing::Test {
  2174. protected:
  2175. ChunkedEncodingTest()
  2176. : cli_(HOST, PORT)
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. ,
  2179. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2180. #endif
  2181. {
  2182. cli_.set_connection_timeout(2);
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. cli_.enable_server_certificate_verification(false);
  2185. #endif
  2186. }
  2187. virtual void SetUp() {
  2188. read_file("./image.jpg", image_data_);
  2189. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2190. res.set_content("Hello World!", "text/plain");
  2191. });
  2192. svr_.Get(
  2193. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2194. res.set_chunked_content_provider(
  2195. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2196. size_t remaining = image_data_.size() - offset;
  2197. if (remaining == 0) {
  2198. sink.done();
  2199. } else {
  2200. constexpr size_t CHUNK_SIZE = 1024;
  2201. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2202. sink.write(&image_data_[offset], send_size);
  2203. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2204. }
  2205. return true;
  2206. });
  2207. });
  2208. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2209. svr_.wait_until_ready();
  2210. }
  2211. virtual void TearDown() {
  2212. svr_.stop();
  2213. if (!request_threads_.empty()) {
  2214. std::this_thread::sleep_for(std::chrono::seconds(1));
  2215. for (auto &t : request_threads_) {
  2216. t.join();
  2217. }
  2218. }
  2219. t_.join();
  2220. }
  2221. #ifdef CPPHTTPLIB_SSL_ENABLED
  2222. SSLClient cli_;
  2223. SSLServer svr_;
  2224. #else
  2225. Client cli_;
  2226. Server svr_;
  2227. #endif
  2228. thread t_;
  2229. std::vector<thread> request_threads_;
  2230. std::string image_data_;
  2231. };
  2232. TEST_F(ChunkedEncodingTest, NormalGet) {
  2233. auto res = cli_.Get("/chunked");
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, res->body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2243. body.append(data, data_length);
  2244. return true;
  2245. });
  2246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2247. std::string out;
  2248. read_file("./image.jpg", out);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. EXPECT_EQ(out, body);
  2251. }
  2252. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2253. std::string body;
  2254. auto res = cli_.Get(
  2255. "/chunked",
  2256. [&](const Response &response) {
  2257. EXPECT_EQ(StatusCode::OK_200, response.status);
  2258. return true;
  2259. },
  2260. [&](const char *data, size_t data_length) {
  2261. body.append(data, data_length);
  2262. return true;
  2263. });
  2264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2265. std::string out;
  2266. read_file("./image.jpg", out);
  2267. EXPECT_EQ(StatusCode::OK_200, res->status);
  2268. EXPECT_EQ(out, body);
  2269. }
  2270. TEST(RangeTest, FromHTTPBin_Online) {
  2271. auto host = "httpbingo.org";
  2272. auto path = std::string{"/range/32"};
  2273. #ifdef CPPHTTPLIB_SSL_ENABLED
  2274. auto port = 443;
  2275. SSLClient cli(host, port);
  2276. #else
  2277. auto port = 80;
  2278. Client cli(host, port);
  2279. #endif
  2280. cli.set_connection_timeout(5);
  2281. {
  2282. auto res = cli.Get(path);
  2283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2284. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. }
  2287. {
  2288. Headers headers = {make_range_header({{1, -1}})};
  2289. auto res = cli.Get(path, headers);
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2293. }
  2294. {
  2295. Headers headers = {make_range_header({{1, 10}})};
  2296. auto res = cli.Get(path, headers);
  2297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2298. EXPECT_EQ("bcdefghijk", res->body);
  2299. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2300. }
  2301. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2302. // entire resource, while the original httpbin returned 200. Both are
  2303. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2304. {
  2305. Headers headers = {make_range_header({{0, 31}})};
  2306. auto res = cli.Get(path, headers);
  2307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2308. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2309. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2310. res->status == StatusCode::PartialContent_206);
  2311. }
  2312. {
  2313. Headers headers = {make_range_header({{0, -1}})};
  2314. auto res = cli.Get(path, headers);
  2315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2316. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2317. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2318. res->status == StatusCode::PartialContent_206);
  2319. }
  2320. // go-httpbin returns 206 with clamped range for over-range requests,
  2321. // while the original httpbin returned 416. Both behaviors are observed
  2322. // in real servers, so we only verify the request succeeds.
  2323. {
  2324. Headers headers = {make_range_header({{0, 32}})};
  2325. auto res = cli.Get(path, headers);
  2326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2327. }
  2328. }
  2329. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2330. auto host = "unresolvableaddress.local";
  2331. auto path = std::string{"/"};
  2332. #ifdef CPPHTTPLIB_SSL_ENABLED
  2333. auto port = 443;
  2334. SSLClient cli(host, port);
  2335. #else
  2336. auto port = 80;
  2337. Client cli(host, port);
  2338. #endif
  2339. cli.set_connection_timeout(1);
  2340. {
  2341. auto res = cli.Get(path);
  2342. ASSERT_FALSE(res);
  2343. }
  2344. std::this_thread::sleep_for(std::chrono::seconds(8));
  2345. }
  2346. #if defined(__linux__) && defined(__GLIBC__) && \
  2347. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2348. // Forward declaration: in split builds split.py strips `inline` and moves the
  2349. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2350. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2351. // against the symbol in both header-only and split builds.
  2352. namespace httplib {
  2353. namespace detail {
  2354. int getaddrinfo_with_timeout(const char *node, const char *service,
  2355. const struct addrinfo *hints,
  2356. struct addrinfo **res, time_t timeout_sec);
  2357. } // namespace detail
  2358. } // namespace httplib
  2359. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2360. //
  2361. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2362. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2363. // gai_suspend() call hits the connection timeout the function calls
  2364. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2365. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2366. // still alive and still references the now-destroyed stack frame.
  2367. //
  2368. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2369. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2370. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2371. // and runs them in a container.
  2372. namespace {
  2373. bool should_run_issue_2431_tests() {
  2374. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2375. return v && *v && std::string(v) != "0";
  2376. }
  2377. std::string unique_unresolvable_host(int n) {
  2378. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2379. // glibc still asks the configured nameserver — which is exactly the path
  2380. // we want to exercise. A unique label per call avoids the resolver cache.
  2381. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2382. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2383. std::to_string(n) + ".invalid";
  2384. }
  2385. } // namespace
  2386. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2387. if (!should_run_issue_2431_tests()) {
  2388. GTEST_SKIP()
  2389. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2390. }
  2391. for (int i = 0; i < 8; ++i) {
  2392. struct addrinfo hints;
  2393. memset(&hints, 0, sizeof(hints));
  2394. hints.ai_family = AF_UNSPEC;
  2395. hints.ai_socktype = SOCK_STREAM;
  2396. auto host = unique_unresolvable_host(i);
  2397. struct addrinfo *result = nullptr;
  2398. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2399. &result, /*timeout_sec=*/1);
  2400. if (rc == 0 && result) { freeaddrinfo(result); }
  2401. }
  2402. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2403. // stack region they still believe holds their gaicb.
  2404. std::this_thread::sleep_for(std::chrono::seconds(3));
  2405. }
  2406. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2407. if (!should_run_issue_2431_tests()) {
  2408. GTEST_SKIP()
  2409. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2410. }
  2411. std::atomic<bool> stop{false};
  2412. std::vector<std::thread> threads;
  2413. for (int t = 0; t < 8; ++t) {
  2414. threads.emplace_back([t, &stop] {
  2415. int i = 0;
  2416. while (!stop.load(std::memory_order_relaxed)) {
  2417. struct addrinfo hints;
  2418. memset(&hints, 0, sizeof(hints));
  2419. hints.ai_family = AF_UNSPEC;
  2420. hints.ai_socktype = SOCK_STREAM;
  2421. auto host = unique_unresolvable_host(t * 100000 + i++);
  2422. struct addrinfo *result = nullptr;
  2423. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2424. &result, /*timeout_sec=*/1);
  2425. if (rc == 0 && result) { freeaddrinfo(result); }
  2426. }
  2427. });
  2428. }
  2429. std::this_thread::sleep_for(std::chrono::seconds(8));
  2430. stop.store(true, std::memory_order_relaxed);
  2431. for (auto &th : threads) {
  2432. th.join();
  2433. }
  2434. std::this_thread::sleep_for(std::chrono::seconds(3));
  2435. }
  2436. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2437. if (!should_run_issue_2431_tests()) {
  2438. GTEST_SKIP()
  2439. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2440. }
  2441. std::atomic<bool> stop{false};
  2442. std::vector<std::thread> threads;
  2443. for (int t = 0; t < 8; ++t) {
  2444. threads.emplace_back([t, &stop] {
  2445. int i = 0;
  2446. while (!stop.load(std::memory_order_relaxed)) {
  2447. auto host = unique_unresolvable_host(t * 100000 + i++);
  2448. Client cli(host, 80);
  2449. cli.set_connection_timeout(1, 0);
  2450. cli.set_read_timeout(1, 0);
  2451. cli.set_write_timeout(1, 0);
  2452. (void)cli.Get("/");
  2453. }
  2454. });
  2455. }
  2456. std::this_thread::sleep_for(std::chrono::seconds(8));
  2457. stop.store(true, std::memory_order_relaxed);
  2458. for (auto &th : threads) {
  2459. th.join();
  2460. }
  2461. std::this_thread::sleep_for(std::chrono::seconds(3));
  2462. }
  2463. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2464. TEST(ConnectionErrorTest, InvalidHost) {
  2465. auto host = "-abcde.com";
  2466. #ifdef CPPHTTPLIB_SSL_ENABLED
  2467. auto port = 443;
  2468. SSLClient cli(host, port);
  2469. #else
  2470. auto port = 80;
  2471. Client cli(host, port);
  2472. #endif
  2473. cli.set_connection_timeout(std::chrono::seconds(2));
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(!res);
  2476. EXPECT_EQ(Error::Connection, res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, InvalidHost2) {
  2479. auto host = "httpcan.org/";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. SSLClient cli(host);
  2482. #else
  2483. Client cli(host);
  2484. #endif
  2485. cli.set_connection_timeout(std::chrono::seconds(2));
  2486. auto res = cli.Get("/");
  2487. ASSERT_TRUE(!res);
  2488. EXPECT_EQ(Error::Connection, res.error());
  2489. }
  2490. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2491. auto host = "httpcan.org/";
  2492. #ifdef CPPHTTPLIB_SSL_ENABLED
  2493. SSLClient cli(host);
  2494. #else
  2495. Client cli(host);
  2496. #endif
  2497. cli.set_connection_timeout(std::chrono::seconds(2));
  2498. auto res = cli.Get("/");
  2499. ASSERT_TRUE(!res);
  2500. stringstream s;
  2501. s << "error code: " << res.error();
  2502. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2503. }
  2504. TEST(ConnectionErrorTest, InvalidPort) {
  2505. auto host = "localhost";
  2506. auto port = 44380;
  2507. #ifdef CPPHTTPLIB_SSL_ENABLED
  2508. SSLClient cli(host, port);
  2509. #else
  2510. Client cli(host, port);
  2511. #endif
  2512. cli.set_connection_timeout(std::chrono::seconds(2));
  2513. auto res = cli.Get("/");
  2514. ASSERT_TRUE(!res);
  2515. EXPECT_TRUE(Error::Connection == res.error() ||
  2516. Error::ConnectionTimeout == res.error());
  2517. }
  2518. TEST(ConnectionErrorTest, Timeout_Online) {
  2519. auto host = "google.com";
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 44380;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 8080;
  2525. Client cli(host, port);
  2526. #endif
  2527. cli.set_connection_timeout(std::chrono::seconds(2));
  2528. // only probe one address type so that the error reason
  2529. // correlates to the timed-out IPv4, not the unsupported
  2530. // IPv6 connection attempt
  2531. cli.set_address_family(AF_INET);
  2532. auto res = cli.Get("/");
  2533. ASSERT_TRUE(!res);
  2534. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2535. }
  2536. TEST(CancelTest, NoCancel_Online) {
  2537. auto host = "httpbingo.org";
  2538. auto path = std::string{"/range/32"};
  2539. #ifdef CPPHTTPLIB_SSL_ENABLED
  2540. auto port = 443;
  2541. SSLClient cli(host, port);
  2542. #else
  2543. auto port = 80;
  2544. Client cli(host, port);
  2545. #endif
  2546. cli.set_connection_timeout(std::chrono::seconds(5));
  2547. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2549. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. }
  2552. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2553. // Use /bytes with a large payload so that the DownloadProgress callback
  2554. // (which only fires for Content-Length responses) is invoked before the
  2555. // entire body is received, giving cancellation a chance to fire.
  2556. auto host = "httpbingo.org";
  2557. auto path = std::string{"/bytes/524288"};
  2558. #ifdef CPPHTTPLIB_SSL_ENABLED
  2559. auto port = 443;
  2560. SSLClient cli(host, port);
  2561. #else
  2562. auto port = 80;
  2563. Client cli(host, port);
  2564. #endif
  2565. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2566. cli.set_connection_timeout(std::chrono::seconds(5));
  2567. ASSERT_TRUE(!res);
  2568. EXPECT_EQ(Error::Canceled, res.error());
  2569. }
  2570. TEST(CancelTest, WithCancelLargePayload_Online) {
  2571. auto host = "httpbingo.org";
  2572. auto path = std::string{"/bytes/524288"};
  2573. #ifdef CPPHTTPLIB_SSL_ENABLED
  2574. auto port = 443;
  2575. SSLClient cli(host, port);
  2576. #else
  2577. auto port = 80;
  2578. Client cli(host, port);
  2579. #endif
  2580. cli.set_connection_timeout(std::chrono::seconds(5));
  2581. uint32_t count = 0;
  2582. auto res =
  2583. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2584. ASSERT_TRUE(!res);
  2585. EXPECT_EQ(Error::Canceled, res.error());
  2586. }
  2587. TEST(CancelTest, NoCancelPost) {
  2588. Server svr;
  2589. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2590. res.set_content("Hello World!", "text/plain");
  2591. });
  2592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2593. auto se = detail::scope_exit([&] {
  2594. svr.stop();
  2595. thread.join();
  2596. ASSERT_FALSE(svr.is_running());
  2597. });
  2598. svr.wait_until_ready();
  2599. Client cli(HOST, PORT);
  2600. cli.set_connection_timeout(std::chrono::seconds(5));
  2601. auto res =
  2602. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2603. "application/json", [](uint64_t, uint64_t) { return true; });
  2604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2605. EXPECT_EQ("Hello World!", res->body);
  2606. EXPECT_EQ(StatusCode::OK_200, res->status);
  2607. }
  2608. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2609. Server svr;
  2610. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2611. res.set_content("Hello World!", "text/plain");
  2612. });
  2613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2614. auto se = detail::scope_exit([&] {
  2615. svr.stop();
  2616. thread.join();
  2617. ASSERT_FALSE(svr.is_running());
  2618. });
  2619. svr.wait_until_ready();
  2620. Client cli(HOST, PORT);
  2621. cli.set_connection_timeout(std::chrono::seconds(5));
  2622. auto res =
  2623. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2624. "application/json", [](uint64_t, uint64_t) { return false; });
  2625. ASSERT_TRUE(!res);
  2626. EXPECT_EQ(Error::Canceled, res.error());
  2627. }
  2628. TEST(CancelTest, WithCancelLargePayloadPost) {
  2629. Server svr;
  2630. svr.set_payload_max_length(200 * 1024 * 1024);
  2631. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2632. res.set_content(LARGE_DATA, "text/plain");
  2633. });
  2634. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2635. auto se = detail::scope_exit([&] {
  2636. svr.stop();
  2637. thread.join();
  2638. ASSERT_FALSE(svr.is_running());
  2639. });
  2640. svr.wait_until_ready();
  2641. Client cli(HOST, PORT);
  2642. cli.set_payload_max_length(200 * 1024 * 1024);
  2643. cli.set_connection_timeout(std::chrono::seconds(5));
  2644. auto res =
  2645. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2646. "application/json", [](uint64_t, uint64_t) { return false; });
  2647. ASSERT_TRUE(!res);
  2648. EXPECT_EQ(Error::Canceled, res.error());
  2649. }
  2650. TEST(CancelTest, NoCancelPut) {
  2651. Server svr;
  2652. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2653. res.set_content("Hello World!", "text/plain");
  2654. });
  2655. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2656. auto se = detail::scope_exit([&] {
  2657. svr.stop();
  2658. thread.join();
  2659. ASSERT_FALSE(svr.is_running());
  2660. });
  2661. svr.wait_until_ready();
  2662. Client cli(HOST, PORT);
  2663. cli.set_connection_timeout(std::chrono::seconds(5));
  2664. auto res =
  2665. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2666. "application/json", [](uint64_t, uint64_t) { return true; });
  2667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2668. EXPECT_EQ("Hello World!", res->body);
  2669. EXPECT_EQ(StatusCode::OK_200, res->status);
  2670. }
  2671. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2672. Server svr;
  2673. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2674. res.set_content("Hello World!", "text/plain");
  2675. });
  2676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2677. auto se = detail::scope_exit([&] {
  2678. svr.stop();
  2679. thread.join();
  2680. ASSERT_FALSE(svr.is_running());
  2681. });
  2682. svr.wait_until_ready();
  2683. Client cli(HOST, PORT);
  2684. cli.set_connection_timeout(std::chrono::seconds(5));
  2685. auto res =
  2686. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2687. "application/json", [](uint64_t, uint64_t) { return false; });
  2688. ASSERT_TRUE(!res);
  2689. EXPECT_EQ(Error::Canceled, res.error());
  2690. }
  2691. TEST(CancelTest, WithCancelLargePayloadPut) {
  2692. Server svr;
  2693. svr.set_payload_max_length(200 * 1024 * 1024);
  2694. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2695. res.set_content(LARGE_DATA, "text/plain");
  2696. });
  2697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2698. auto se = detail::scope_exit([&] {
  2699. svr.stop();
  2700. thread.join();
  2701. ASSERT_FALSE(svr.is_running());
  2702. });
  2703. svr.wait_until_ready();
  2704. Client cli(HOST, PORT);
  2705. cli.set_payload_max_length(200 * 1024 * 1024);
  2706. cli.set_connection_timeout(std::chrono::seconds(5));
  2707. auto res =
  2708. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2709. "application/json", [](uint64_t, uint64_t) { return false; });
  2710. ASSERT_TRUE(!res);
  2711. EXPECT_EQ(Error::Canceled, res.error());
  2712. }
  2713. TEST(CancelTest, NoCancelPatch) {
  2714. Server svr;
  2715. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2716. res.set_content("Hello World!", "text/plain");
  2717. });
  2718. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2719. auto se = detail::scope_exit([&] {
  2720. svr.stop();
  2721. thread.join();
  2722. ASSERT_FALSE(svr.is_running());
  2723. });
  2724. svr.wait_until_ready();
  2725. Client cli(HOST, PORT);
  2726. cli.set_connection_timeout(std::chrono::seconds(5));
  2727. auto res =
  2728. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2729. "application/json", [](uint64_t, uint64_t) { return true; });
  2730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2731. EXPECT_EQ("Hello World!", res->body);
  2732. EXPECT_EQ(StatusCode::OK_200, res->status);
  2733. }
  2734. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2735. Server svr;
  2736. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2737. res.set_content("Hello World!", "text/plain");
  2738. });
  2739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2740. auto se = detail::scope_exit([&] {
  2741. svr.stop();
  2742. thread.join();
  2743. ASSERT_FALSE(svr.is_running());
  2744. });
  2745. svr.wait_until_ready();
  2746. Client cli(HOST, PORT);
  2747. cli.set_connection_timeout(std::chrono::seconds(5));
  2748. auto res =
  2749. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2750. "application/json", [](uint64_t, uint64_t) { return false; });
  2751. ASSERT_TRUE(!res);
  2752. EXPECT_EQ(Error::Canceled, res.error());
  2753. }
  2754. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2755. Server svr;
  2756. svr.set_payload_max_length(200 * 1024 * 1024);
  2757. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2758. res.set_content(LARGE_DATA, "text/plain");
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. Client cli(HOST, PORT);
  2768. cli.set_payload_max_length(200 * 1024 * 1024);
  2769. cli.set_connection_timeout(std::chrono::seconds(5));
  2770. auto res =
  2771. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2772. "application/json", [](uint64_t, uint64_t) { return false; });
  2773. ASSERT_TRUE(!res);
  2774. EXPECT_EQ(Error::Canceled, res.error());
  2775. }
  2776. TEST(CancelTest, NoCancelDelete) {
  2777. Server svr;
  2778. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2779. res.set_content("Hello World!", "text/plain");
  2780. });
  2781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2782. auto se = detail::scope_exit([&] {
  2783. svr.stop();
  2784. thread.join();
  2785. ASSERT_FALSE(svr.is_running());
  2786. });
  2787. svr.wait_until_ready();
  2788. Client cli(HOST, PORT);
  2789. cli.set_connection_timeout(std::chrono::seconds(5));
  2790. auto res =
  2791. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2792. "application/json", [](uint64_t, uint64_t) { return true; });
  2793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2794. EXPECT_EQ("Hello World!", res->body);
  2795. EXPECT_EQ(StatusCode::OK_200, res->status);
  2796. }
  2797. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2798. Server svr;
  2799. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. });
  2802. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2803. auto se = detail::scope_exit([&] {
  2804. svr.stop();
  2805. thread.join();
  2806. ASSERT_FALSE(svr.is_running());
  2807. });
  2808. svr.wait_until_ready();
  2809. Client cli(HOST, PORT);
  2810. cli.set_connection_timeout(std::chrono::seconds(5));
  2811. auto res =
  2812. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2813. "application/json", [](uint64_t, uint64_t) { return false; });
  2814. ASSERT_TRUE(!res);
  2815. EXPECT_EQ(Error::Canceled, res.error());
  2816. }
  2817. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2818. Server svr;
  2819. svr.set_payload_max_length(200 * 1024 * 1024);
  2820. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2821. res.set_content(LARGE_DATA, "text/plain");
  2822. });
  2823. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2824. auto se = detail::scope_exit([&] {
  2825. svr.stop();
  2826. thread.join();
  2827. ASSERT_FALSE(svr.is_running());
  2828. });
  2829. svr.wait_until_ready();
  2830. Client cli(HOST, PORT);
  2831. cli.set_payload_max_length(200 * 1024 * 1024);
  2832. cli.set_connection_timeout(std::chrono::seconds(5));
  2833. auto res =
  2834. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2835. "application/json", [](uint64_t, uint64_t) { return false; });
  2836. ASSERT_TRUE(!res);
  2837. EXPECT_EQ(Error::Canceled, res.error());
  2838. }
  2839. static std::string remove_whitespace(const std::string &input) {
  2840. std::string output;
  2841. output.reserve(input.size());
  2842. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2843. [](unsigned char c) { return !std::isspace(c); });
  2844. return output;
  2845. }
  2846. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2847. auto host = "httpbingo.org";
  2848. auto path = std::string{"/basic-auth/hello/world"};
  2849. #ifdef CPPHTTPLIB_SSL_ENABLED
  2850. auto port = 443;
  2851. SSLClient cli(host, port);
  2852. #else
  2853. auto port = 80;
  2854. Client cli(host, port);
  2855. #endif
  2856. {
  2857. auto res = cli.Get(path);
  2858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2859. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2860. }
  2861. {
  2862. auto res = cli.Get(
  2863. path, Headers{make_basic_authentication_header("hello", "world")});
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. auto body = remove_whitespace(res->body);
  2866. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2867. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2868. EXPECT_EQ(StatusCode::OK_200, res->status);
  2869. }
  2870. {
  2871. cli.set_basic_auth("hello", "world");
  2872. auto res = cli.Get(path);
  2873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2874. auto body = remove_whitespace(res->body);
  2875. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2876. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. }
  2879. {
  2880. cli.set_basic_auth("hello", "bad");
  2881. auto res = cli.Get(path);
  2882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2883. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2884. }
  2885. {
  2886. cli.set_basic_auth("bad", "world");
  2887. auto res = cli.Get(path);
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2890. }
  2891. }
  2892. #ifdef CPPHTTPLIB_SSL_ENABLED
  2893. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2894. auto host = "httpbingo.org";
  2895. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2896. auto paths = std::vector<std::string>{
  2897. "/digest-auth/auth/hello/world/MD5",
  2898. "/digest-auth/auth/hello/world/SHA-256",
  2899. };
  2900. auto port = 443;
  2901. SSLClient cli(host, port);
  2902. {
  2903. auto res = cli.Get(unauth_path);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2906. }
  2907. {
  2908. cli.set_digest_auth("hello", "world");
  2909. for (const auto &path : paths) {
  2910. auto res = cli.Get(path.c_str());
  2911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2912. auto body = remove_whitespace(res->body);
  2913. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2914. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. }
  2917. cli.set_digest_auth("hello", "bad");
  2918. for (const auto &path : paths) {
  2919. auto res = cli.Get(path.c_str());
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2922. }
  2923. }
  2924. }
  2925. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2926. // comma-separated list of challenges, and each challenge may itself carry a
  2927. // comma-separated auth-param list, so a server can legally offer Basic
  2928. // before Digest, either as two field lines or packed into one. Runs one 401
  2929. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2930. // value() joins them in receipt order) and checks that the retry carries a
  2931. // well-formed Digest Authorization header naming expected_realm.
  2932. static void
  2933. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2934. const std::string &expected_realm) {
  2935. std::atomic<int> hits{0};
  2936. Server svr;
  2937. svr.Get("/x", [&](const Request &req, Response &res) {
  2938. if (++hits == 1) {
  2939. res.status = StatusCode::Unauthorized_401;
  2940. for (const auto &challenge : challenges) {
  2941. res.set_header("WWW-Authenticate", challenge);
  2942. }
  2943. } else {
  2944. auto authorization = req.get_header_value("Authorization");
  2945. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2946. EXPECT_NE(std::string::npos,
  2947. authorization.find("realm=\"" + expected_realm + "\""));
  2948. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2949. res.set_content("ok", "text/plain");
  2950. }
  2951. });
  2952. auto port = svr.bind_to_any_port(HOST);
  2953. std::thread t([&]() { svr.listen_after_bind(); });
  2954. auto se = detail::scope_exit([&] {
  2955. svr.stop();
  2956. t.join();
  2957. });
  2958. svr.wait_until_ready();
  2959. Client cli(HOST, port);
  2960. cli.set_digest_auth("hello", "world");
  2961. auto res = cli.Get("/x");
  2962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2963. EXPECT_EQ(2, hits.load());
  2964. }
  2965. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2966. static const char *kDigestChallenge =
  2967. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2968. "algorithm=MD5";
  2969. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2970. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2971. "testrealm");
  2972. }
  2973. // Same challenge list with the schemes in the opposite order, to make sure
  2974. // the fix above didn't just special-case "Basic first".
  2975. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2976. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2977. "testrealm");
  2978. }
  2979. // A comma inside a quoted auth-param value must not be mistaken for the
  2980. // separator between two challenges (or two auth-params).
  2981. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2982. run_digest_challenge_list_test(
  2983. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2984. "algorithm=MD5"},
  2985. "test,realm");
  2986. }
  2987. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2988. // make_digest_authentication_header() dereferences both unconditionally, so
  2989. // a server sending a challenge missing either one must not be treated as
  2990. // usable -- doing so used to crash the client with std::out_of_range.
  2991. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2992. Server svr;
  2993. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2994. res.status = StatusCode::Unauthorized_401;
  2995. res.set_header("WWW-Authenticate", challenge);
  2996. });
  2997. auto port = svr.bind_to_any_port(HOST);
  2998. std::thread t([&]() { svr.listen_after_bind(); });
  2999. auto se = detail::scope_exit([&] {
  3000. svr.stop();
  3001. t.join();
  3002. });
  3003. svr.wait_until_ready();
  3004. Client cli(HOST, port);
  3005. cli.set_digest_auth("hello", "world");
  3006. auto res = cli.Get("/x");
  3007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3008. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3009. }
  3010. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3011. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3012. }
  3013. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3014. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3015. }
  3016. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3017. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3018. }
  3019. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3020. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3021. // when storing the values, so the header builder has to re-escape them (and
  3022. // keep algorithm a bare token); otherwise the value breaks out of its
  3023. // quoted-string and injects extra auth-params into the client's Authorization.
  3024. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3025. std::atomic<int> hits{0};
  3026. std::string authorization;
  3027. Server svr;
  3028. svr.Get("/x", [&](const Request &req, Response &res) {
  3029. if (++hits == 1) {
  3030. res.status = StatusCode::Unauthorized_401;
  3031. // On the wire the quotes embedded in the values are backslash-escaped.
  3032. res.set_header("WWW-Authenticate",
  3033. "Digest realm=\"testrealm\", "
  3034. "nonce=\"n\\\"; injected=\\\"x\", "
  3035. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3036. } else {
  3037. authorization = req.get_header_value("Authorization");
  3038. res.set_content("ok", "text/plain");
  3039. }
  3040. });
  3041. auto port = svr.bind_to_any_port(HOST);
  3042. std::thread t([&]() { svr.listen_after_bind(); });
  3043. auto se = detail::scope_exit([&] {
  3044. svr.stop();
  3045. t.join();
  3046. });
  3047. svr.wait_until_ready();
  3048. Client cli(HOST, port);
  3049. cli.set_digest_auth("hello", "world");
  3050. auto res = cli.Get("/x");
  3051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3052. EXPECT_EQ(2, hits.load());
  3053. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3054. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3055. // inside its quoted-string rather than starting an "injected" auth-param.
  3056. EXPECT_NE(std::string::npos,
  3057. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3058. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3059. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3060. }
  3061. #endif
  3062. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3063. auto host = "google.com";
  3064. auto another_host = "example.com";
  3065. auto wrong_ip = "0.0.0.0";
  3066. #ifdef CPPHTTPLIB_SSL_ENABLED
  3067. SSLClient cli(host);
  3068. #else
  3069. Client cli(host);
  3070. #endif
  3071. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3072. auto res = cli.Get("/");
  3073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3074. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3075. }
  3076. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3077. auto host = "google.com";
  3078. auto wrong_ip = "0.0.0.0";
  3079. #ifdef CPPHTTPLIB_SSL_ENABLED
  3080. SSLClient cli(host);
  3081. #else
  3082. Client cli(host);
  3083. #endif
  3084. cli.set_hostname_addr_map({{host, wrong_ip}});
  3085. auto res = cli.Get("/");
  3086. ASSERT_TRUE(!res);
  3087. EXPECT_EQ(Error::Connection, res.error());
  3088. }
  3089. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3090. // A mapped value that is not an IP literal must be resolved. "localhost"
  3091. // resolves from the hosts file, so this test needs no external DNS.
  3092. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3093. auto host = "target.invalid";
  3094. Server svr;
  3095. std::string received_host;
  3096. svr.Get("/hi", [&](const Request &req, Response &res) {
  3097. received_host = req.get_header_value("Host");
  3098. res.set_content("Hello World!", "text/plain");
  3099. });
  3100. auto port = svr.bind_to_any_port(HOST);
  3101. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3102. auto se = detail::scope_exit([&] {
  3103. svr.stop();
  3104. thread.join();
  3105. ASSERT_FALSE(svr.is_running());
  3106. });
  3107. svr.wait_until_ready();
  3108. Client cli(host, port);
  3109. cli.set_hostname_addr_map({{host, HOST}});
  3110. auto res = cli.Get("/hi");
  3111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. // The mapping only redirects the connection; the identity stays host_.
  3114. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3115. }
  3116. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3117. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3118. auto host = "target.invalid";
  3119. Server svr;
  3120. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3121. res.set_content("Hello World!", "text/plain");
  3122. });
  3123. auto port = svr.bind_to_any_port("127.0.0.1");
  3124. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3125. auto se = detail::scope_exit([&] {
  3126. svr.stop();
  3127. thread.join();
  3128. ASSERT_FALSE(svr.is_running());
  3129. });
  3130. svr.wait_until_ready();
  3131. Client cli(host, port);
  3132. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3133. auto res = cli.Get("/hi");
  3134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3135. EXPECT_EQ(StatusCode::OK_200, res->status);
  3136. }
  3137. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3138. // An empty mapped value must leave host_ as the connection target. Without
  3139. // that guard the empty value would become the host argument, getaddrinfo
  3140. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3141. // loopback - silently connecting somewhere the caller never asked for.
  3142. // The server listens on loopback, so such a fallback would succeed and is
  3143. // therefore observable as a failure of this test.
  3144. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3145. Server svr;
  3146. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3147. res.set_content("Hello World!", "text/plain");
  3148. });
  3149. auto port = svr.bind_to_any_port(HOST);
  3150. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3151. auto se = detail::scope_exit([&] {
  3152. svr.stop();
  3153. thread.join();
  3154. ASSERT_FALSE(svr.is_running());
  3155. });
  3156. svr.wait_until_ready();
  3157. Client cli(blackhole, port);
  3158. cli.set_hostname_addr_map({{blackhole, ""}});
  3159. cli.set_connection_timeout(1);
  3160. auto res = cli.Get("/hi");
  3161. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3162. }
  3163. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3164. auto host = "httpbingo.org";
  3165. auto path = std::string{"/absolute-redirect/3"};
  3166. #ifdef CPPHTTPLIB_SSL_ENABLED
  3167. SSLClient cli(host);
  3168. #else
  3169. Client cli(host);
  3170. #endif
  3171. cli.set_follow_location(true);
  3172. auto res = cli.Get(path);
  3173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3174. EXPECT_EQ(StatusCode::OK_200, res->status);
  3175. }
  3176. TEST(RedirectTest, Redirect_Online) {
  3177. auto host = "httpbingo.org";
  3178. auto path = std::string{"/redirect/3"};
  3179. #ifdef CPPHTTPLIB_SSL_ENABLED
  3180. SSLClient cli(host);
  3181. #else
  3182. Client cli(host);
  3183. #endif
  3184. cli.set_follow_location(true);
  3185. auto res = cli.Get(path);
  3186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3187. EXPECT_EQ(StatusCode::OK_200, res->status);
  3188. }
  3189. TEST(RelativeRedirectTest, Redirect_Online) {
  3190. auto host = "httpbingo.org";
  3191. auto path = std::string{"/relative-redirect/3"};
  3192. #ifdef CPPHTTPLIB_SSL_ENABLED
  3193. SSLClient cli(host);
  3194. #else
  3195. Client cli(host);
  3196. #endif
  3197. cli.set_follow_location(true);
  3198. auto res = cli.Get(path);
  3199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3200. EXPECT_EQ(StatusCode::OK_200, res->status);
  3201. }
  3202. TEST(TooManyRedirectTest, Redirect_Online) {
  3203. auto host = "httpbingo.org";
  3204. auto path = std::string{"/redirect/21"};
  3205. #ifdef CPPHTTPLIB_SSL_ENABLED
  3206. SSLClient cli(host);
  3207. #else
  3208. Client cli(host);
  3209. #endif
  3210. cli.set_follow_location(true);
  3211. auto res = cli.Get(path);
  3212. ASSERT_TRUE(!res);
  3213. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3214. }
  3215. #ifdef CPPHTTPLIB_SSL_ENABLED
  3216. TEST(YahooRedirectTest, Redirect_Online) {
  3217. Client cli("yahoo.com");
  3218. auto res = cli.Get("/");
  3219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3220. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3221. cli.set_follow_location(true);
  3222. res = cli.Get("/");
  3223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3224. EXPECT_EQ(StatusCode::OK_200, res->status);
  3225. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3226. }
  3227. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3228. #define REDIR_HOST "httpbingo.org"
  3229. #define REDIR_PATH "/redirect-to"
  3230. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3231. SSLClient cli(REDIR_HOST);
  3232. cli.set_follow_location(true);
  3233. auto res =
  3234. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3236. EXPECT_EQ(StatusCode::OK_200, res->status);
  3237. }
  3238. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3239. SSLClient cli(REDIR_HOST);
  3240. cli.set_follow_location(true);
  3241. Params params;
  3242. params.emplace("url", "http://example.com");
  3243. params.emplace("status_code", "302");
  3244. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3246. EXPECT_EQ(StatusCode::OK_200, res->status);
  3247. }
  3248. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3249. SSLClient cli(REDIR_HOST);
  3250. cli.set_follow_location(true);
  3251. Params params;
  3252. params.emplace("url", "http://example.com");
  3253. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. }
  3257. TEST(UrlWithSpace, Redirect_Online) {
  3258. SSLClient cli("edge.forgecdn.net");
  3259. cli.set_follow_location(true);
  3260. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3262. EXPECT_EQ(StatusCode::OK_200, res->status);
  3263. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3264. }
  3265. #endif
  3266. #if !defined(_WIN32) && !defined(_WIN64)
  3267. TEST(ReceiveSignals, Signal) {
  3268. auto setupSignalHandlers = []() {
  3269. struct sigaction act;
  3270. sigemptyset(&act.sa_mask);
  3271. act.sa_flags = SA_SIGINFO;
  3272. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3273. switch (sig) {
  3274. case SIGINT:
  3275. default: break;
  3276. }
  3277. };
  3278. ::sigaction(SIGINT, &act, nullptr);
  3279. };
  3280. Server svr;
  3281. int port = 0;
  3282. auto thread = std::thread([&]() {
  3283. setupSignalHandlers();
  3284. port = svr.bind_to_any_port(HOST);
  3285. svr.listen_after_bind();
  3286. });
  3287. auto se = detail::scope_exit([&] {
  3288. svr.stop();
  3289. thread.join();
  3290. ASSERT_FALSE(svr.is_running());
  3291. });
  3292. svr.wait_until_ready();
  3293. ASSERT_TRUE(svr.is_running());
  3294. pthread_kill(thread.native_handle(), SIGINT);
  3295. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3296. ASSERT_TRUE(svr.is_running());
  3297. }
  3298. #endif
  3299. TEST(RedirectToDifferentPort, Redirect) {
  3300. Server svr1;
  3301. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3302. res.set_content("Hello World!", "text/plain");
  3303. });
  3304. int svr1_port = 0;
  3305. auto thread1 = std::thread([&]() {
  3306. svr1_port = svr1.bind_to_any_port(HOST);
  3307. svr1.listen_after_bind();
  3308. });
  3309. Server svr2;
  3310. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3311. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3312. });
  3313. int svr2_port = 0;
  3314. auto thread2 = std::thread([&]() {
  3315. svr2_port = svr2.bind_to_any_port(HOST);
  3316. svr2.listen_after_bind();
  3317. });
  3318. auto se = detail::scope_exit([&] {
  3319. svr2.stop();
  3320. thread2.join();
  3321. svr1.stop();
  3322. thread1.join();
  3323. ASSERT_FALSE(svr2.is_running());
  3324. ASSERT_FALSE(svr1.is_running());
  3325. });
  3326. svr1.wait_until_ready();
  3327. svr2.wait_until_ready();
  3328. Client cli("localhost", svr2_port);
  3329. cli.set_follow_location(true);
  3330. auto res = cli.Get("/2");
  3331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3332. EXPECT_EQ(StatusCode::OK_200, res->status);
  3333. EXPECT_EQ("Hello World!", res->body);
  3334. }
  3335. // GET /redir on one server redirects to /target on another port, so the
  3336. // client follows it with a new client.
  3337. static Result
  3338. GetThroughRedirectToDifferentPort(Server::Handler target,
  3339. const std::function<void(Client &)> &setup,
  3340. const Headers &headers = Headers()) {
  3341. Server target_svr;
  3342. target_svr.Get("/target", target);
  3343. int target_port = 0;
  3344. auto target_thread = std::thread([&]() {
  3345. target_port = target_svr.bind_to_any_port(HOST);
  3346. target_svr.listen_after_bind();
  3347. });
  3348. Server origin_svr;
  3349. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3350. res.set_redirect(
  3351. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3352. });
  3353. int origin_port = 0;
  3354. auto origin_thread = std::thread([&]() {
  3355. origin_port = origin_svr.bind_to_any_port(HOST);
  3356. origin_svr.listen_after_bind();
  3357. });
  3358. auto se = detail::scope_exit([&] {
  3359. origin_svr.stop();
  3360. origin_thread.join();
  3361. target_svr.stop();
  3362. target_thread.join();
  3363. });
  3364. target_svr.wait_until_ready();
  3365. origin_svr.wait_until_ready();
  3366. Client cli("localhost", origin_port);
  3367. cli.set_follow_location(true);
  3368. setup(cli);
  3369. return cli.Get("/redir", headers);
  3370. }
  3371. static void
  3372. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3373. std::string captured_authorization;
  3374. auto result = GetThroughRedirectToDifferentPort(
  3375. [&](const Request &req, Response &res) {
  3376. captured_authorization = req.get_header_value("Authorization");
  3377. res.set_content("OK", "text/plain");
  3378. },
  3379. set_auth);
  3380. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3381. EXPECT_EQ(StatusCode::OK_200, result->status);
  3382. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3383. EXPECT_TRUE(captured_authorization.empty());
  3384. }
  3385. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3386. TestDoNotForwardCredentialsOnRedirect(
  3387. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3388. }
  3389. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3390. TestDoNotForwardCredentialsOnRedirect(
  3391. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3392. }
  3393. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3394. std::string captured_cookie;
  3395. auto result = GetThroughRedirectToDifferentPort(
  3396. [&](const Request &req, Response &res) {
  3397. captured_cookie = req.get_header_value("Cookie");
  3398. res.set_content("OK", "text/plain");
  3399. },
  3400. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3401. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3402. EXPECT_EQ(StatusCode::OK_200, result->status);
  3403. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3404. EXPECT_TRUE(captured_cookie.empty());
  3405. }
  3406. TEST(RedirectToSamePort, ForwardCookie) {
  3407. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3408. // header so that ordinary session flows keep working.
  3409. Server svr;
  3410. std::string captured_cookie;
  3411. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3412. res.set_redirect("/target", 302);
  3413. });
  3414. svr.Get("/target", [&](const Request &req, Response &res) {
  3415. captured_cookie = req.get_header_value("Cookie");
  3416. res.set_content("OK", "text/plain");
  3417. });
  3418. auto port = svr.bind_to_any_port(HOST);
  3419. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3420. auto se = detail::scope_exit([&] {
  3421. svr.stop();
  3422. thread.join();
  3423. ASSERT_FALSE(svr.is_running());
  3424. });
  3425. svr.wait_until_ready();
  3426. Client cli(HOST, port);
  3427. cli.set_follow_location(true);
  3428. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3429. auto res = cli.Get("/redir", headers);
  3430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3431. EXPECT_EQ(StatusCode::OK_200, res->status);
  3432. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3433. }
  3434. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3435. std::string authorization;
  3436. std::string trace_id;
  3437. auto result = GetThroughRedirectToDifferentPort(
  3438. [&](const Request &req, Response &res) {
  3439. authorization = req.get_header_value("Authorization");
  3440. trace_id = req.get_header_value("X-Trace-Id");
  3441. res.set_content("OK", "text/plain");
  3442. },
  3443. [](Client &cli) {
  3444. cli.set_default_headers(
  3445. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3446. });
  3447. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3448. EXPECT_EQ(StatusCode::OK_200, result->status);
  3449. // Like a header given with the request, a default one goes along unless it
  3450. // carries credentials (RFC 9110 15.4).
  3451. EXPECT_TRUE(authorization.empty());
  3452. EXPECT_EQ("42", trace_id);
  3453. }
  3454. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3455. auto result = GetThroughRedirectToDifferentPort(
  3456. [](const Request &, Response &res) {
  3457. res.set_content(std::string(2048, 'x'), "text/plain");
  3458. },
  3459. [](Client &cli) { cli.set_payload_max_length(1024); });
  3460. EXPECT_FALSE(result);
  3461. }
  3462. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3463. auto result = GetThroughRedirectToDifferentPort(
  3464. [](const Request &req, Response &res) {
  3465. // Answer after a second, or once the client gives up.
  3466. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3467. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3468. }
  3469. res.set_content("late", "text/plain");
  3470. },
  3471. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3472. ASSERT_FALSE(result);
  3473. EXPECT_EQ(Error::Read, result.error());
  3474. }
  3475. #ifdef CPPHTTPLIB_SSL_ENABLED
  3476. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3477. auto result = GetThroughRedirectToDifferentPort(
  3478. [](const Request &, Response &res) {
  3479. res.status = StatusCode::Unauthorized_401;
  3480. res.set_header("WWW-Authenticate",
  3481. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3482. },
  3483. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3484. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3485. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3486. }
  3487. #endif
  3488. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3489. Server svr;
  3490. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3491. // Port number that overflows int — should not crash
  3492. res.set_redirect("http://localhost:99999999999999999999/target");
  3493. });
  3494. auto port = svr.bind_to_any_port(HOST);
  3495. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3496. auto se = detail::scope_exit([&] {
  3497. svr.stop();
  3498. thread.join();
  3499. ASSERT_FALSE(svr.is_running());
  3500. });
  3501. svr.wait_until_ready();
  3502. Client cli(HOST, port);
  3503. cli.set_follow_location(true);
  3504. auto res = cli.Get("/redir");
  3505. // Should fail gracefully, not crash (no valid response due to bad port)
  3506. EXPECT_FALSE(res);
  3507. }
  3508. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3509. Server svr;
  3510. auto port = svr.bind_to_any_port(HOST);
  3511. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3512. // The server's own port followed by junk must not be followed
  3513. res.set_redirect("http://" + std::string(HOST) + ":" +
  3514. std::to_string(port) + "junk/target");
  3515. });
  3516. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3517. res.set_content("target", "text/plain");
  3518. });
  3519. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3520. auto se = detail::scope_exit([&] {
  3521. svr.stop();
  3522. thread.join();
  3523. ASSERT_FALSE(svr.is_running());
  3524. });
  3525. svr.wait_until_ready();
  3526. Client cli(HOST, port);
  3527. cli.set_follow_location(true);
  3528. auto res = cli.Get("/redir");
  3529. EXPECT_FALSE(res);
  3530. }
  3531. TEST(RedirectFromPageWithContent, Redirect) {
  3532. Server svr;
  3533. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3534. res.set_content("___", "text/plain");
  3535. res.set_redirect("/2");
  3536. });
  3537. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3538. res.set_content("Hello World!", "text/plain");
  3539. });
  3540. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3541. auto se = detail::scope_exit([&] {
  3542. svr.stop();
  3543. th.join();
  3544. ASSERT_FALSE(svr.is_running());
  3545. });
  3546. svr.wait_until_ready();
  3547. {
  3548. Client cli("localhost", PORT);
  3549. cli.set_follow_location(true);
  3550. std::string body;
  3551. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3552. body.append(data, data_length);
  3553. return true;
  3554. });
  3555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3556. EXPECT_EQ(StatusCode::OK_200, res->status);
  3557. EXPECT_EQ("Hello World!", body);
  3558. }
  3559. {
  3560. Client cli("localhost", PORT);
  3561. std::string body;
  3562. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3563. body.append(data, data_length);
  3564. return true;
  3565. });
  3566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3567. EXPECT_EQ(StatusCode::Found_302, res->status);
  3568. EXPECT_EQ("___", body);
  3569. }
  3570. }
  3571. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3572. Server svr;
  3573. auto port_str = std::to_string(PORT);
  3574. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3575. auto expected_host = "[::1]:" + port_str;
  3576. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3577. res.set_content("___", "text/plain");
  3578. // res.set_redirect("/2");
  3579. res.set_redirect(redirect_url);
  3580. });
  3581. svr.Get("/2", [&](const Request &req, Response &res) {
  3582. auto host_header = req.headers.find("Host");
  3583. ASSERT_TRUE(host_header != req.headers.end());
  3584. EXPECT_EQ(expected_host, host_header->second);
  3585. res.set_content("Hello World!", "text/plain");
  3586. });
  3587. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3588. auto se = detail::scope_exit([&] {
  3589. svr.stop();
  3590. th.join();
  3591. ASSERT_FALSE(svr.is_running());
  3592. });
  3593. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3594. // actually starts anything, so the condition !svr.is_running() will
  3595. // always remain true, and the loop never stops.
  3596. // This basically counts how many milliseconds have passed since the
  3597. // call to svr.listen(), and if after 5 seconds nothing started yet
  3598. // aborts the test.
  3599. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3600. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3601. ASSERT_LT(milliseconds, 5000U);
  3602. }
  3603. {
  3604. Client cli("::1", PORT);
  3605. cli.set_follow_location(true);
  3606. std::string body;
  3607. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3608. body.append(data, data_length);
  3609. return true;
  3610. });
  3611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3612. EXPECT_EQ(StatusCode::OK_200, res->status);
  3613. EXPECT_EQ("Hello World!", body);
  3614. }
  3615. {
  3616. Client cli("::1", PORT);
  3617. std::string body;
  3618. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3619. body.append(data, data_length);
  3620. return true;
  3621. });
  3622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3623. EXPECT_EQ(StatusCode::Found_302, res->status);
  3624. EXPECT_EQ("___", body);
  3625. }
  3626. }
  3627. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3628. Server svr;
  3629. svr.Get("/foo", [](const Request &req, Response &res) {
  3630. auto a = req.params.find("a");
  3631. if (a != req.params.end()) {
  3632. res.set_content((*a).second, "text/plain");
  3633. res.status = StatusCode::OK_200;
  3634. } else {
  3635. res.status = StatusCode::BadRequest_400;
  3636. }
  3637. });
  3638. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3639. auto se = detail::scope_exit([&] {
  3640. svr.stop();
  3641. thread.join();
  3642. ASSERT_FALSE(svr.is_running());
  3643. });
  3644. svr.wait_until_ready();
  3645. {
  3646. Client cli(HOST, PORT);
  3647. cli.set_path_encode(false);
  3648. auto res = cli.Get("/foo?a=explicitly+encoded");
  3649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3650. EXPECT_EQ(StatusCode::OK_200, res->status);
  3651. // This expects it back with a space, as the `+` won't have been
  3652. // url-encoded, and server-side the params get decoded turning `+`
  3653. // into spaces.
  3654. EXPECT_EQ("explicitly encoded", res->body);
  3655. }
  3656. }
  3657. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3658. // When path encoding is disabled the client must transmit the supplied
  3659. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3660. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3661. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3662. // than a space (0x20). Assert on the raw wire target to catch this.
  3663. Server svr;
  3664. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3665. svr.Get("/foo", [&](const Request &req, Response &res) {
  3666. EXPECT_EQ(expected_target, req.target);
  3667. res.status = StatusCode::OK_200;
  3668. });
  3669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3670. auto se = detail::scope_exit([&] {
  3671. svr.stop();
  3672. thread.join();
  3673. ASSERT_FALSE(svr.is_running());
  3674. });
  3675. svr.wait_until_ready();
  3676. {
  3677. Client cli(HOST, PORT);
  3678. cli.set_path_encode(false);
  3679. auto res = cli.Get(expected_target.c_str());
  3680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3681. EXPECT_EQ(StatusCode::OK_200, res->status);
  3682. }
  3683. }
  3684. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3685. // `open_stream()` used to skip the path encoding that the buffered send
  3686. // path applies, so the same `path` produced different bytes in the request
  3687. // line depending on which API was used. Assert the two agree.
  3688. Server svr;
  3689. std::string target;
  3690. svr.Get(".*", [&](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. struct {
  3703. const char *path;
  3704. const char *expected;
  3705. } cases[] = {
  3706. {"/a b?x=1", "/a%20b?x=1"},
  3707. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3708. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3709. };
  3710. for (const auto &c : cases) {
  3711. Client cli(HOST, port);
  3712. target.clear();
  3713. auto res = cli.Get(c.path);
  3714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3715. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3716. auto buffered_target = target;
  3717. target.clear();
  3718. auto handle = cli.open_stream("GET", c.path);
  3719. EXPECT_TRUE(handle.is_valid())
  3720. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3721. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3722. }
  3723. }
  3724. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3725. // The `set_path_encode(false)` contract — transmit the supplied target
  3726. // verbatim — must hold for the streaming API too.
  3727. Server svr;
  3728. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3729. std::string target;
  3730. svr.Get("/foo", [&](const Request &req, Response &res) {
  3731. target = req.target;
  3732. res.status = StatusCode::OK_200;
  3733. });
  3734. auto port = svr.bind_to_any_port(HOST);
  3735. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3736. auto se = detail::scope_exit([&] {
  3737. svr.stop();
  3738. thread.join();
  3739. ASSERT_FALSE(svr.is_running());
  3740. });
  3741. svr.wait_until_ready();
  3742. {
  3743. Client cli(HOST, port);
  3744. cli.set_path_encode(false);
  3745. auto handle = cli.open_stream("GET", expected_target);
  3746. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3747. EXPECT_EQ(expected_target, target);
  3748. }
  3749. }
  3750. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3751. // With path encoding enabled a CR/LF in the target is percent-encoded
  3752. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3753. // write_request_line still backstops `set_path_encode(false)`, which is
  3754. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3755. Server svr;
  3756. // Captured before routing: the decoded path contains a newline, which a
  3757. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3758. std::string target;
  3759. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3760. target = req.target;
  3761. res.status = StatusCode::OK_200;
  3762. return Server::HandlerResponse::Handled;
  3763. });
  3764. auto port = svr.bind_to_any_port(HOST);
  3765. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3766. auto se = detail::scope_exit([&] {
  3767. svr.stop();
  3768. thread.join();
  3769. ASSERT_FALSE(svr.is_running());
  3770. });
  3771. svr.wait_until_ready();
  3772. {
  3773. Client cli(HOST, port);
  3774. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3775. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3776. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3777. }
  3778. }
  3779. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3780. // Every control character is percent-encoded, not just CR/LF, so the target
  3781. // passes the request-target check in write_request_line.
  3782. Server svr;
  3783. std::string target;
  3784. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3785. target = req.target;
  3786. res.status = StatusCode::OK_200;
  3787. return Server::HandlerResponse::Handled;
  3788. });
  3789. auto port = svr.bind_to_any_port(HOST);
  3790. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3791. auto se = detail::scope_exit([&] {
  3792. svr.stop();
  3793. thread.join();
  3794. ASSERT_FALSE(svr.is_running());
  3795. });
  3796. svr.wait_until_ready();
  3797. {
  3798. Client cli(HOST, port);
  3799. auto res = cli.Get("/a\tb\x1b\x7f");
  3800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3801. EXPECT_EQ("/a%09b%1B%7F", target);
  3802. }
  3803. }
  3804. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3805. // Nothing may reach the wire: a raw CR/LF target would split the request
  3806. // line and inject headers.
  3807. Server svr;
  3808. // Pre-routing so that "not called" means nothing reached the server at all,
  3809. // rather than merely failing to match a handler pattern.
  3810. auto handler_called = false;
  3811. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3812. handler_called = true;
  3813. res.status = StatusCode::OK_200;
  3814. return Server::HandlerResponse::Handled;
  3815. });
  3816. auto port = svr.bind_to_any_port(HOST);
  3817. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3818. auto se = detail::scope_exit([&] {
  3819. svr.stop();
  3820. thread.join();
  3821. ASSERT_FALSE(svr.is_running());
  3822. });
  3823. svr.wait_until_ready();
  3824. {
  3825. Client cli(HOST, port);
  3826. cli.set_path_encode(false);
  3827. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3828. EXPECT_FALSE(handle.is_valid());
  3829. EXPECT_EQ(Error::Write, handle.error);
  3830. EXPECT_FALSE(handler_called);
  3831. }
  3832. }
  3833. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3834. // Which of the two branches runs is decided by whether the query component
  3835. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3836. // an empty query and must still fall back to building one from
  3837. // `req.params`, while a non-empty query must win over `req.params`.
  3838. Server svr;
  3839. std::string target;
  3840. svr.Get("/foo", [&](const Request &req, Response &res) {
  3841. target = req.target;
  3842. res.status = StatusCode::OK_200;
  3843. });
  3844. auto port = svr.bind_to_any_port(HOST);
  3845. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3846. auto se = detail::scope_exit([&] {
  3847. svr.stop();
  3848. thread.join();
  3849. ASSERT_FALSE(svr.is_running());
  3850. });
  3851. svr.wait_until_ready();
  3852. {
  3853. // Trailing `?` -> empty query component -> `req.params` is used.
  3854. Client cli(HOST, port);
  3855. Request req;
  3856. req.method = "GET";
  3857. req.path = "/foo?";
  3858. req.params.emplace("a", "1");
  3859. target.clear();
  3860. auto res = cli.send(req);
  3861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3862. EXPECT_EQ("/foo?a=1", target);
  3863. }
  3864. {
  3865. // Non-empty query in `req.path` -> `req.params` is not appended.
  3866. Client cli(HOST, port);
  3867. Request req;
  3868. req.method = "GET";
  3869. req.path = "/foo?b=2";
  3870. req.params.emplace("a", "1");
  3871. target.clear();
  3872. auto res = cli.send(req);
  3873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3874. EXPECT_EQ("/foo?b=2", target);
  3875. }
  3876. }
  3877. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3878. Server svr;
  3879. svr.Get("/", [](const Request &req, Response &) {
  3880. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3881. });
  3882. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3883. auto se = detail::scope_exit([&] {
  3884. svr.stop();
  3885. thread.join();
  3886. ASSERT_FALSE(svr.is_running());
  3887. });
  3888. svr.wait_until_ready();
  3889. {
  3890. Client cli(HOST, PORT);
  3891. cli.set_path_encode(false);
  3892. auto res = cli.Get("/?something=%0A");
  3893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3894. EXPECT_EQ(StatusCode::OK_200, res->status);
  3895. }
  3896. }
  3897. TEST(BindServerTest, BindDualStack) {
  3898. Server svr;
  3899. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3900. res.set_content("Hello World!", "text/plain");
  3901. });
  3902. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3903. auto se = detail::scope_exit([&] {
  3904. svr.stop();
  3905. thread.join();
  3906. ASSERT_FALSE(svr.is_running());
  3907. });
  3908. svr.wait_until_ready();
  3909. {
  3910. Client cli("127.0.0.1", PORT);
  3911. auto res = cli.Get("/1");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. EXPECT_EQ("Hello World!", res->body);
  3915. }
  3916. {
  3917. Client cli("::1", PORT);
  3918. auto res = cli.Get("/1");
  3919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3920. EXPECT_EQ(StatusCode::OK_200, res->status);
  3921. EXPECT_EQ("Hello World!", res->body);
  3922. }
  3923. }
  3924. TEST(BindServerTest, BindAndListenSeparately) {
  3925. Server svr;
  3926. int port = svr.bind_to_any_port("0.0.0.0");
  3927. ASSERT_TRUE(svr.is_valid());
  3928. ASSERT_TRUE(port > 0);
  3929. svr.stop();
  3930. }
  3931. // Reports whether anything is still listening on a loopback port. A plain
  3932. // connect() is used instead of a Client request because a socket left bound by
  3933. // mistake accepts the connection into its backlog and never answers, which
  3934. // would hang the test instead of failing it.
  3935. static bool is_loopback_port_accepting(int port) {
  3936. sockaddr_in addr{};
  3937. addr.sin_family = AF_INET;
  3938. addr.sin_port = htons(static_cast<uint16_t>(port));
  3939. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3940. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3941. EXPECT_NE(sock, INVALID_SOCKET);
  3942. if (sock == INVALID_SOCKET) { return false; }
  3943. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3944. static_cast<socklen_t>(sizeof(addr)));
  3945. detail::close_socket(sock);
  3946. return ret == 0;
  3947. }
  3948. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3949. Server svr;
  3950. auto port = svr.bind_to_any_port("127.0.0.1");
  3951. ASSERT_TRUE(port > 0);
  3952. svr.stop();
  3953. // bind_to_any_port() already called listen(2), so until stop() closed the
  3954. // descriptor the port kept accepting connections into the backlog. ASSERT
  3955. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3956. // below blocks forever in the accept loop.
  3957. ASSERT_FALSE(is_loopback_port_accepting(port));
  3958. // Nothing is left to accept on, so listen_after_bind() must report failure
  3959. // instead of returning success without ever serving.
  3960. EXPECT_FALSE(svr.listen_after_bind());
  3961. // The failed listen marks the server decommissioned, so a waiter returns
  3962. // instead of spinning forever.
  3963. svr.wait_until_ready();
  3964. }
  3965. #ifdef CPPHTTPLIB_SSL_ENABLED
  3966. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3968. CLIENT_CA_CERT_DIR);
  3969. int port = svr.bind_to_any_port("0.0.0.0");
  3970. ASSERT_TRUE(svr.is_valid());
  3971. ASSERT_TRUE(port > 0);
  3972. svr.stop();
  3973. }
  3974. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3975. // or a rejected CustomRoute() registration would not stop the server binding.
  3976. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3978. CLIENT_CA_CERT_DIR);
  3979. ASSERT_TRUE(svr.is_valid());
  3980. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3981. EXPECT_FALSE(svr.is_valid());
  3982. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3983. }
  3984. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3985. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3986. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3987. int port = svr.bind_to_any_port("0.0.0.0");
  3988. ASSERT_TRUE(svr.is_valid());
  3989. ASSERT_TRUE(port > 0);
  3990. svr.stop();
  3991. }
  3992. TEST(BindServerTest, UpdateCertsPem) {
  3993. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3994. int port = svr.bind_to_any_port("0.0.0.0");
  3995. ASSERT_TRUE(svr.is_valid());
  3996. ASSERT_TRUE(port > 0);
  3997. // Read PEM files
  3998. std::string cert_pem, key_pem, ca_pem;
  3999. read_file(SERVER_CERT_FILE, cert_pem);
  4000. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4001. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4002. // Update server certificates using PEM API
  4003. ASSERT_TRUE(
  4004. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4005. ASSERT_TRUE(svr.is_valid());
  4006. svr.stop();
  4007. }
  4008. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4009. // Start server with client CA (enables client auth)
  4010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4011. ASSERT_TRUE(svr.is_valid());
  4012. bool handler_called = false;
  4013. svr.Get("/test", [&](const Request &req, Response &res) {
  4014. handler_called = true;
  4015. // Verify client certificate is present
  4016. auto cert = req.peer_cert();
  4017. EXPECT_TRUE(static_cast<bool>(cert));
  4018. res.set_content("ok", "text/plain");
  4019. });
  4020. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4021. auto se = detail::scope_exit([&] {
  4022. svr.stop();
  4023. t.join();
  4024. ASSERT_FALSE(svr.is_running());
  4025. });
  4026. svr.wait_until_ready();
  4027. // Read PEM files
  4028. std::string cert_pem, key_pem, ca_pem;
  4029. read_file(SERVER_CERT_FILE, cert_pem);
  4030. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4031. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4032. // Update server certificates and client CA using PEM API while server running
  4033. ASSERT_TRUE(
  4034. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4035. // Connect with client certificate
  4036. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4037. cli.enable_server_certificate_verification(false);
  4038. cli.set_connection_timeout(30);
  4039. auto res = cli.Get("/test");
  4040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4041. ASSERT_EQ(StatusCode::OK_200, res->status);
  4042. ASSERT_TRUE(handler_called);
  4043. EXPECT_EQ("ok", res->body);
  4044. }
  4045. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4047. ASSERT_TRUE(svr.is_valid());
  4048. svr.Get("/test", [](const Request &, Response &res) {
  4049. res.set_content("ok", "text/plain");
  4050. });
  4051. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4052. auto se = detail::scope_exit([&] {
  4053. svr.stop();
  4054. t.join();
  4055. ASSERT_FALSE(svr.is_running());
  4056. });
  4057. svr.wait_until_ready();
  4058. auto get = [] {
  4059. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4060. cli.enable_server_certificate_verification(false);
  4061. return cli.Get("/test");
  4062. };
  4063. ASSERT_TRUE(get());
  4064. // A CA that did not sign the client's certificate takes the old one's place.
  4065. std::string cert_pem, key_pem, ca_pem;
  4066. read_file(SERVER_CERT_FILE, cert_pem);
  4067. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4068. read_file(SERVER_CERT2_FILE, ca_pem);
  4069. ASSERT_TRUE(
  4070. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4071. EXPECT_FALSE(get());
  4072. }
  4073. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4075. ASSERT_TRUE(svr.is_valid());
  4076. svr.Get("/test", [](const Request &, Response &res) {
  4077. res.set_content("ok", "text/plain");
  4078. });
  4079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4080. auto se = detail::scope_exit([&] {
  4081. svr.stop();
  4082. t.join();
  4083. ASSERT_FALSE(svr.is_running());
  4084. });
  4085. svr.wait_until_ready();
  4086. // A connection that sends no ClientHello keeps its handshake in progress,
  4087. // once the server has had a moment to start it.
  4088. auto error = Error::Success;
  4089. auto sock = detail::create_client_socket(
  4090. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4091. /*connection_timeout_sec=*/5, 0,
  4092. /*read_timeout_sec=*/5, 0,
  4093. /*write_timeout_sec=*/5, 0, std::string(), error);
  4094. ASSERT_NE(INVALID_SOCKET, sock);
  4095. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4096. std::string cert_pem, key_pem;
  4097. read_file(SERVER_CERT_FILE, cert_pem);
  4098. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4099. auto update = std::async(std::launch::async, [&]() {
  4100. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4101. });
  4102. EXPECT_EQ(std::future_status::timeout,
  4103. update.wait_for(std::chrono::milliseconds(200)));
  4104. detail::close_socket(sock);
  4105. EXPECT_TRUE(update.get());
  4106. SSLClient cli(HOST, PORT);
  4107. cli.enable_server_certificate_verification(false);
  4108. auto res = cli.Get("/test");
  4109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4110. EXPECT_EQ(StatusCode::OK_200, res->status);
  4111. }
  4112. #endif
  4113. TEST(ErrorHandlerTest, ContentLength) {
  4114. Server svr;
  4115. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4116. res.status = StatusCode::OK_200;
  4117. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4118. "text/html"); // <= Content-Length still 13
  4119. });
  4120. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4121. res.set_content("Hello World!\n", "text/plain");
  4122. res.status = 524;
  4123. });
  4124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4125. auto se = detail::scope_exit([&] {
  4126. svr.stop();
  4127. thread.join();
  4128. ASSERT_FALSE(svr.is_running());
  4129. });
  4130. svr.wait_until_ready();
  4131. {
  4132. Client cli(HOST, PORT);
  4133. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4135. EXPECT_EQ(StatusCode::OK_200, res->status);
  4136. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4137. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4138. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4139. }
  4140. }
  4141. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4142. TEST(ExceptionTest, WithoutExceptionHandler) {
  4143. Server svr;
  4144. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4145. throw std::runtime_error("exception...");
  4146. });
  4147. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4148. throw std::runtime_error("exception\r\n...");
  4149. });
  4150. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4151. auto se = detail::scope_exit([&] {
  4152. svr.stop();
  4153. listen_thread.join();
  4154. ASSERT_FALSE(svr.is_running());
  4155. });
  4156. svr.wait_until_ready();
  4157. Client cli("localhost", PORT);
  4158. {
  4159. auto res = cli.Get("/exception");
  4160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4162. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4163. }
  4164. {
  4165. auto res = cli.Get("/unknown");
  4166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4167. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4168. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4169. }
  4170. }
  4171. TEST(ExceptionTest, WithExceptionHandler) {
  4172. Server svr;
  4173. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4174. std::exception_ptr ep) {
  4175. EXPECT_FALSE(ep == nullptr);
  4176. try {
  4177. std::rethrow_exception(ep);
  4178. } catch (std::exception &e) {
  4179. EXPECT_EQ("abc", std::string(e.what()));
  4180. } catch (...) {}
  4181. res.status = StatusCode::InternalServerError_500;
  4182. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4183. "text/html"); // <= Content-Length still 13 at this point
  4184. });
  4185. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4186. res.set_content("Hello World!\n", "text/plain");
  4187. throw std::runtime_error("abc");
  4188. });
  4189. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4190. auto se = detail::scope_exit([&] {
  4191. svr.stop();
  4192. thread.join();
  4193. ASSERT_FALSE(svr.is_running());
  4194. });
  4195. svr.wait_until_ready();
  4196. for (size_t i = 0; i < 10; i++) {
  4197. Client cli(HOST, PORT);
  4198. for (size_t j = 0; j < 100; j++) {
  4199. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4201. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4202. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4203. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4204. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4205. }
  4206. cli.set_keep_alive(true);
  4207. for (size_t j = 0; j < 100; j++) {
  4208. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4210. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4211. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4212. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4213. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4214. }
  4215. }
  4216. }
  4217. TEST(ExceptionTest, AndErrorHandler) {
  4218. Server svr;
  4219. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4220. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4221. });
  4222. svr.set_exception_handler(
  4223. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4224. EXPECT_FALSE(ep == nullptr);
  4225. try {
  4226. std::rethrow_exception(ep);
  4227. } catch (std::exception &e) {
  4228. res.set_content(e.what(), "text/html");
  4229. } catch (...) {}
  4230. res.status = StatusCode::InternalServerError_500;
  4231. });
  4232. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4233. throw std::runtime_error("EXCEPTION");
  4234. });
  4235. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4236. res.set_content("ERROR", "text/html");
  4237. res.status = StatusCode::InternalServerError_500;
  4238. });
  4239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4240. auto se = detail::scope_exit([&] {
  4241. svr.stop();
  4242. thread.join();
  4243. ASSERT_FALSE(svr.is_running());
  4244. });
  4245. svr.wait_until_ready();
  4246. Client cli(HOST, PORT);
  4247. {
  4248. auto res = cli.Get("/exception");
  4249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4250. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4251. EXPECT_EQ("EXCEPTION", res->body);
  4252. }
  4253. {
  4254. auto res = cli.Get("/error");
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4257. EXPECT_EQ("ERROR", res->body);
  4258. }
  4259. {
  4260. auto res = cli.Get("/invalid");
  4261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4262. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4263. EXPECT_EQ("NOT_FOUND", res->body);
  4264. }
  4265. }
  4266. #endif
  4267. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4268. // process_request() wraps only routing() in a try/catch, so an exception from
  4269. // any other user callback used to unwind into the task queue - which does not
  4270. // catch - and terminate the process. Each test below runs the server on a
  4271. // single worker thread: a guard that catches the exception but still loses the
  4272. // thread would otherwise be hidden by a spare worker serving the follow-up
  4273. // request. Note that a regression here aborts the whole test binary rather
  4274. // than failing one test.
  4275. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4276. Server svr;
  4277. svr.new_task_queue = [] { return new ThreadPool(1); };
  4278. std::atomic<int> reported{0};
  4279. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4280. if (err == Error::UserCallbackException) { reported++; }
  4281. });
  4282. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4283. res.set_content_provider(
  4284. 1024, "text/plain",
  4285. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4286. sink.write("hello", 5);
  4287. throw std::runtime_error("from the content provider");
  4288. });
  4289. });
  4290. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4291. res.set_content("ok", "text/plain");
  4292. });
  4293. auto port = svr.bind_to_any_port(HOST);
  4294. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4295. auto se = detail::scope_exit([&] {
  4296. svr.stop();
  4297. listen_thread.join();
  4298. ASSERT_FALSE(svr.is_running());
  4299. });
  4300. svr.wait_until_ready();
  4301. {
  4302. Client cli(HOST, port);
  4303. cli.set_read_timeout(5, 0);
  4304. EXPECT_FALSE(cli.Get("/throw"));
  4305. }
  4306. EXPECT_TRUE(svr.is_running());
  4307. EXPECT_EQ(1, reported.load());
  4308. // A request on a fresh connection is still served.
  4309. {
  4310. Client cli(HOST, port);
  4311. auto res = cli.Get("/ok");
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. EXPECT_EQ(StatusCode::OK_200, res->status);
  4314. EXPECT_EQ("ok", res->body);
  4315. }
  4316. }
  4317. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4318. Server svr;
  4319. svr.new_task_queue = [] { return new ThreadPool(1); };
  4320. std::atomic<bool> should_throw{true};
  4321. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4322. res.set_content("hi", "text/plain");
  4323. });
  4324. svr.set_post_routing_handler(
  4325. [&](const Request & /*req*/, Response & /*res*/) {
  4326. if (should_throw) {
  4327. throw std::runtime_error("from the post-routing handler");
  4328. }
  4329. });
  4330. auto port = svr.bind_to_any_port(HOST);
  4331. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4332. auto se = detail::scope_exit([&] {
  4333. svr.stop();
  4334. listen_thread.join();
  4335. ASSERT_FALSE(svr.is_running());
  4336. });
  4337. svr.wait_until_ready();
  4338. {
  4339. Client cli(HOST, port);
  4340. cli.set_read_timeout(5, 0);
  4341. EXPECT_FALSE(cli.Get("/hi"));
  4342. }
  4343. EXPECT_TRUE(svr.is_running());
  4344. should_throw = false;
  4345. {
  4346. Client cli(HOST, port);
  4347. auto res = cli.Get("/hi");
  4348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4349. EXPECT_EQ(StatusCode::OK_200, res->status);
  4350. EXPECT_EQ("hi", res->body);
  4351. }
  4352. }
  4353. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4354. // The guard reports the caught exception through the error logger, which is
  4355. // a user callback too. A logger that throws has to be contained as well, or
  4356. // the process would terminate from inside the catch.
  4357. Server svr;
  4358. svr.new_task_queue = [] { return new ThreadPool(1); };
  4359. std::atomic<int> reported{0};
  4360. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4361. if (err == Error::UserCallbackException) {
  4362. reported++;
  4363. throw std::runtime_error("from the error logger");
  4364. }
  4365. });
  4366. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4367. res.set_content_provider(
  4368. 1024, "text/plain",
  4369. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4370. sink.write("hello", 5);
  4371. throw std::runtime_error("from the content provider");
  4372. });
  4373. });
  4374. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4375. res.set_content("ok", "text/plain");
  4376. });
  4377. auto port = svr.bind_to_any_port(HOST);
  4378. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4379. auto se = detail::scope_exit([&] {
  4380. svr.stop();
  4381. listen_thread.join();
  4382. ASSERT_FALSE(svr.is_running());
  4383. });
  4384. svr.wait_until_ready();
  4385. {
  4386. Client cli(HOST, port);
  4387. cli.set_read_timeout(5, 0);
  4388. EXPECT_FALSE(cli.Get("/throw"));
  4389. }
  4390. EXPECT_TRUE(svr.is_running());
  4391. EXPECT_EQ(1, reported.load());
  4392. {
  4393. Client cli(HOST, port);
  4394. auto res = cli.Get("/ok");
  4395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("ok", res->body);
  4398. }
  4399. }
  4400. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4401. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4402. // so the exception unwinds through the ws::WebSocket object on its way to
  4403. // the guard. None of the HTTP cases above cross that.
  4404. Server svr;
  4405. svr.new_task_queue = [] { return new ThreadPool(1); };
  4406. std::atomic<int> reported{0};
  4407. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4408. if (err == Error::UserCallbackException) { reported++; }
  4409. });
  4410. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4411. throw std::runtime_error("from the WebSocket handler");
  4412. });
  4413. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4414. res.set_content("ok", "text/plain");
  4415. });
  4416. auto port = svr.bind_to_any_port(HOST);
  4417. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4418. auto se = detail::scope_exit([&] {
  4419. svr.stop();
  4420. listen_thread.join();
  4421. ASSERT_FALSE(svr.is_running());
  4422. });
  4423. svr.wait_until_ready();
  4424. {
  4425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4426. "/ws");
  4427. auto res = client.connect();
  4428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4429. // The server dropped the connection instead of dying.
  4430. std::string msg;
  4431. EXPECT_FALSE(client.read(msg));
  4432. client.close();
  4433. }
  4434. EXPECT_TRUE(svr.is_running());
  4435. EXPECT_EQ(1, reported.load());
  4436. {
  4437. Client cli(HOST, port);
  4438. auto res = cli.Get("/ok");
  4439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4440. EXPECT_EQ(StatusCode::OK_200, res->status);
  4441. EXPECT_EQ("ok", res->body);
  4442. }
  4443. }
  4444. #ifdef CPPHTTPLIB_SSL_ENABLED
  4445. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4446. // SSLServer::process_and_close_socket() is a separate overload with its own
  4447. // guard, so it is exercised on its own.
  4448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4449. ASSERT_TRUE(svr.is_valid());
  4450. svr.new_task_queue = [] { return new ThreadPool(1); };
  4451. std::atomic<int> reported{0};
  4452. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4453. if (err == Error::UserCallbackException) { reported++; }
  4454. });
  4455. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4456. res.set_content_provider(
  4457. 1024, "text/plain",
  4458. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4459. sink.write("hello", 5);
  4460. throw std::runtime_error("from the content provider");
  4461. });
  4462. });
  4463. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4464. res.set_content("ok", "text/plain");
  4465. });
  4466. auto port = svr.bind_to_any_port(HOST);
  4467. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4468. auto se = detail::scope_exit([&] {
  4469. svr.stop();
  4470. listen_thread.join();
  4471. ASSERT_FALSE(svr.is_running());
  4472. });
  4473. svr.wait_until_ready();
  4474. {
  4475. SSLClient cli(HOST, port);
  4476. cli.enable_server_certificate_verification(false);
  4477. cli.set_read_timeout(5, 0);
  4478. EXPECT_FALSE(cli.Get("/throw"));
  4479. }
  4480. EXPECT_TRUE(svr.is_running());
  4481. EXPECT_EQ(1, reported.load());
  4482. {
  4483. SSLClient cli(HOST, port);
  4484. cli.enable_server_certificate_verification(false);
  4485. auto res = cli.Get("/ok");
  4486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4487. EXPECT_EQ(StatusCode::OK_200, res->status);
  4488. EXPECT_EQ("ok", res->body);
  4489. }
  4490. }
  4491. #endif
  4492. #endif
  4493. TEST(NoContentTest, ContentLength) {
  4494. Server svr;
  4495. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4496. res.status = StatusCode::NoContent_204;
  4497. });
  4498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4499. auto se = detail::scope_exit([&] {
  4500. svr.stop();
  4501. thread.join();
  4502. ASSERT_FALSE(svr.is_running());
  4503. });
  4504. svr.wait_until_ready();
  4505. {
  4506. Client cli(HOST, PORT);
  4507. auto res = cli.Get("/hi");
  4508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4509. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4510. // RFC 9110 8.6: none in a 204 response
  4511. EXPECT_FALSE(res->has_header("Content-Length"));
  4512. }
  4513. }
  4514. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4515. Server svr;
  4516. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4517. res.set_header("Content-Length", "5");
  4518. res.set_content("hello world", "text/plain");
  4519. });
  4520. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4521. // A body that reads as the last chunk, were it taken as chunked
  4522. res.set_header("Transfer-Encoding", "chunked");
  4523. res.set_content("0\r\n\r\n", "text/plain");
  4524. });
  4525. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4526. res.set_header("Content-Length", "2");
  4527. res.set_content_provider(5, "text/plain",
  4528. [](size_t offset, size_t length, DataSink &sink) {
  4529. sink.write(&"hello"[offset], length);
  4530. return true;
  4531. });
  4532. });
  4533. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4534. res.set_header("Content-Length", "1234");
  4535. });
  4536. thread t = thread([&] { svr.listen(HOST, PORT); });
  4537. auto se = detail::scope_exit([&] {
  4538. svr.stop();
  4539. t.join();
  4540. ASSERT_FALSE(svr.is_running());
  4541. });
  4542. svr.wait_until_ready();
  4543. Client cli(HOST, PORT);
  4544. cli.set_read_timeout(1, 0);
  4545. auto expect_body = [&](const Result &res, const std::string &body) {
  4546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4547. EXPECT_EQ(body, res->body);
  4548. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4549. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4550. };
  4551. Headers identity{{"Accept-Encoding", ""}};
  4552. expect_body(cli.Get("/body", identity), "hello world");
  4553. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4554. expect_body(cli.Get("/body",
  4555. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4556. "he");
  4557. expect_body(cli.Get("/provider", identity), "hello");
  4558. expect_body(cli.Get("/empty", identity), "");
  4559. // A HEAD response may give the length of the body a GET would get.
  4560. auto res = cli.Head("/empty");
  4561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4562. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4563. }
  4564. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4565. Server svr;
  4566. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4567. res.set_content("short", "text/plain");
  4568. });
  4569. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4570. res.body += " with a footer";
  4571. res.set_header("Transfer-Encoding", "chunked");
  4572. });
  4573. thread t = thread([&] { svr.listen(HOST, PORT); });
  4574. auto se = detail::scope_exit([&] {
  4575. svr.stop();
  4576. t.join();
  4577. ASSERT_FALSE(svr.is_running());
  4578. });
  4579. svr.wait_until_ready();
  4580. Client cli(HOST, PORT);
  4581. cli.set_read_timeout(1, 0);
  4582. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4584. EXPECT_EQ("short with a footer", res->body);
  4585. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4586. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4587. }
  4588. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4589. #ifdef CPPHTTPLIB_SSL_ENABLED
  4590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4591. ASSERT_TRUE(svr.is_valid());
  4592. #else
  4593. Server svr;
  4594. #endif
  4595. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4596. if (req.path == "/routing_handler") {
  4597. res.set_header("PRE_ROUTING", "on");
  4598. res.set_content("Routing Handler", "text/plain");
  4599. return httplib::Server::HandlerResponse::Handled;
  4600. }
  4601. return httplib::Server::HandlerResponse::Unhandled;
  4602. });
  4603. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4604. res.set_content("Error", "text/html");
  4605. });
  4606. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4607. if (req.path == "/routing_handler") {
  4608. res.set_header("POST_ROUTING", "on");
  4609. }
  4610. });
  4611. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4612. res.set_content("Hello World!\n", "text/plain");
  4613. });
  4614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4615. auto se = detail::scope_exit([&] {
  4616. svr.stop();
  4617. thread.join();
  4618. ASSERT_FALSE(svr.is_running());
  4619. });
  4620. svr.wait_until_ready();
  4621. {
  4622. #ifdef CPPHTTPLIB_SSL_ENABLED
  4623. SSLClient cli(HOST, PORT);
  4624. cli.enable_server_certificate_verification(false);
  4625. #else
  4626. Client cli(HOST, PORT);
  4627. #endif
  4628. auto res = cli.Get("/routing_handler");
  4629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4630. EXPECT_EQ(StatusCode::OK_200, res->status);
  4631. EXPECT_EQ("Routing Handler", res->body);
  4632. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4633. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4634. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4635. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4636. }
  4637. {
  4638. #ifdef CPPHTTPLIB_SSL_ENABLED
  4639. SSLClient cli(HOST, PORT);
  4640. cli.enable_server_certificate_verification(false);
  4641. #else
  4642. Client cli(HOST, PORT);
  4643. #endif
  4644. auto res = cli.Get("/hi");
  4645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4646. EXPECT_EQ(StatusCode::OK_200, res->status);
  4647. EXPECT_EQ("Hello World!\n", res->body);
  4648. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4649. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4650. }
  4651. {
  4652. #ifdef CPPHTTPLIB_SSL_ENABLED
  4653. SSLClient cli(HOST, PORT);
  4654. cli.enable_server_certificate_verification(false);
  4655. #else
  4656. Client cli(HOST, PORT);
  4657. #endif
  4658. auto res = cli.Get("/aaa");
  4659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4660. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4661. EXPECT_EQ("Error", res->body);
  4662. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4663. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4664. }
  4665. }
  4666. TEST(RequestHandlerTest, PreRequestHandler) {
  4667. auto route_path = "/user/:user";
  4668. Server svr;
  4669. svr.Get("/hi", [](const Request &, Response &res) {
  4670. res.set_content("hi", "text/plain");
  4671. });
  4672. svr.Get(route_path, [](const Request &req, Response &res) {
  4673. res.set_content(req.path_params.at("user"), "text/plain");
  4674. });
  4675. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4676. if (req.matched_route == route_path) {
  4677. auto user = req.path_params.at("user");
  4678. if (user != "john") {
  4679. res.status = StatusCode::Forbidden_403;
  4680. res.set_content("error", "text/html");
  4681. return Server::HandlerResponse::Handled;
  4682. }
  4683. }
  4684. return Server::HandlerResponse::Unhandled;
  4685. });
  4686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4687. auto se = detail::scope_exit([&] {
  4688. svr.stop();
  4689. thread.join();
  4690. ASSERT_FALSE(svr.is_running());
  4691. });
  4692. svr.wait_until_ready();
  4693. Client cli(HOST, PORT);
  4694. {
  4695. auto res = cli.Get("/hi");
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. EXPECT_EQ("hi", res->body);
  4699. }
  4700. {
  4701. auto res = cli.Get("/user/john");
  4702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("john", res->body);
  4705. }
  4706. {
  4707. auto res = cli.Get("/user/invalid-user");
  4708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4709. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4710. EXPECT_EQ("error", res->body);
  4711. }
  4712. }
  4713. // The pre-request handler must run before the request body is read, so a
  4714. // rejected request never forces the server to buffer a (potentially large)
  4715. // body. Here the posted body is larger than the payload limit: if the body
  4716. // were read first the server would answer 413, but because the pre-request
  4717. // handler runs first it answers 403 and the body is never read.
  4718. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4719. Server svr;
  4720. svr.set_payload_max_length(8);
  4721. auto handler_ran = false;
  4722. svr.Post("/reject", [&](const Request &req, Response &res) {
  4723. handler_ran = true;
  4724. res.set_content(req.body, "text/plain");
  4725. });
  4726. svr.Post("/accept", [](const Request &req, Response &res) {
  4727. res.set_content(req.body, "text/plain");
  4728. });
  4729. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4730. if (req.matched_route == "/reject") {
  4731. res.status = StatusCode::Forbidden_403;
  4732. res.set_content("denied", "text/plain");
  4733. return Server::HandlerResponse::Handled;
  4734. }
  4735. return Server::HandlerResponse::Unhandled;
  4736. });
  4737. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4738. auto se = detail::scope_exit([&] {
  4739. svr.stop();
  4740. thread.join();
  4741. ASSERT_FALSE(svr.is_running());
  4742. });
  4743. svr.wait_until_ready();
  4744. Client cli(HOST, PORT);
  4745. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4746. // rejects with 403 before the body is read, so 413 is never reached.
  4747. {
  4748. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4750. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4751. EXPECT_EQ("denied", res->body);
  4752. EXPECT_FALSE(handler_ran);
  4753. }
  4754. // An approved route still reads the body and enforces the payload limit.
  4755. {
  4756. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4758. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4759. }
  4760. }
  4761. TEST(UserDataTest, BasicOperations) {
  4762. httplib::UserData ud;
  4763. // Initially empty
  4764. EXPECT_FALSE(ud.has("key"));
  4765. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4766. // set and get
  4767. ud.set("key", 42);
  4768. EXPECT_TRUE(ud.has("key"));
  4769. auto *p = ud.get<int>("key");
  4770. ASSERT_NE(nullptr, p);
  4771. EXPECT_EQ(42, *p);
  4772. // Type mismatch → nullptr
  4773. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4774. // Overwrite with different type
  4775. ud.set("key", std::string("hello"));
  4776. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4777. auto *s = ud.get<std::string>("key");
  4778. ASSERT_NE(nullptr, s);
  4779. EXPECT_EQ("hello", *s);
  4780. // erase
  4781. ud.erase("key");
  4782. EXPECT_FALSE(ud.has("key"));
  4783. // clear
  4784. ud.set("a", 1);
  4785. ud.set("b", 2);
  4786. ud.clear();
  4787. EXPECT_FALSE(ud.has("a"));
  4788. EXPECT_FALSE(ud.has("b"));
  4789. }
  4790. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4791. struct AuthCtx {
  4792. std::string user_id;
  4793. };
  4794. Server svr;
  4795. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4796. res.user_data.set("auth", AuthCtx{"alice"});
  4797. return Server::HandlerResponse::Unhandled;
  4798. });
  4799. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4800. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4801. ASSERT_NE(nullptr, ctx);
  4802. res.set_content("Hello " + ctx->user_id, "text/plain");
  4803. });
  4804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4805. auto se = detail::scope_exit([&] {
  4806. svr.stop();
  4807. thread.join();
  4808. ASSERT_FALSE(svr.is_running());
  4809. });
  4810. svr.wait_until_ready();
  4811. Client cli(HOST, PORT);
  4812. auto res = cli.Get("/me");
  4813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. EXPECT_EQ("Hello alice", res->body);
  4816. }
  4817. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4818. struct RoleCtx {
  4819. std::string role;
  4820. };
  4821. Server svr;
  4822. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4823. res.user_data.set("role", RoleCtx{"admin"});
  4824. return Server::HandlerResponse::Unhandled;
  4825. });
  4826. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4827. auto *ctx = res.user_data.get<RoleCtx>("role");
  4828. ASSERT_NE(nullptr, ctx);
  4829. res.set_content(ctx->role, "text/plain");
  4830. });
  4831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4832. auto se = detail::scope_exit([&] {
  4833. svr.stop();
  4834. thread.join();
  4835. ASSERT_FALSE(svr.is_running());
  4836. });
  4837. svr.wait_until_ready();
  4838. Client cli(HOST, PORT);
  4839. auto res = cli.Get("/role");
  4840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4841. EXPECT_EQ(StatusCode::OK_200, res->status);
  4842. EXPECT_EQ("admin", res->body);
  4843. }
  4844. TEST(InvalidFormatTest, StatusCode) {
  4845. Server svr;
  4846. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4847. res.set_content("Hello World!\n", "text/plain");
  4848. res.status = 9999; // Status should be a three-digit code...
  4849. });
  4850. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4851. auto se = detail::scope_exit([&] {
  4852. svr.stop();
  4853. thread.join();
  4854. ASSERT_FALSE(svr.is_running());
  4855. });
  4856. svr.wait_until_ready();
  4857. {
  4858. Client cli(HOST, PORT);
  4859. auto res = cli.Get("/hi");
  4860. ASSERT_FALSE(res);
  4861. }
  4862. }
  4863. TEST(URLFragmentTest, WithFragment) {
  4864. Server svr;
  4865. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4866. EXPECT_TRUE(req.target == "/hi");
  4867. });
  4868. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4869. auto se = detail::scope_exit([&] {
  4870. svr.stop();
  4871. thread.join();
  4872. ASSERT_FALSE(svr.is_running());
  4873. });
  4874. svr.wait_until_ready();
  4875. {
  4876. Client cli(HOST, PORT);
  4877. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4878. EXPECT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::OK_200, res->status);
  4880. res = cli.Get("/hi%23key1=val1=key2=val2");
  4881. EXPECT_TRUE(res);
  4882. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4883. }
  4884. }
  4885. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  4886. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  4887. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  4888. Server svr;
  4889. std::vector<std::string> targets;
  4890. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  4891. targets.push_back(req.target);
  4892. });
  4893. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4894. auto se = detail::scope_exit([&] {
  4895. svr.stop();
  4896. thread.join();
  4897. ASSERT_FALSE(svr.is_running());
  4898. });
  4899. svr.wait_until_ready();
  4900. Client cli(HOST, PORT);
  4901. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  4902. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  4903. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  4904. // A '?' after the '#' belongs to the fragment, not to the query.
  4905. Request req;
  4906. req.method = "GET";
  4907. req.path = "/hi#f?x=1";
  4908. req.params.emplace("a", "1");
  4909. Response res;
  4910. auto error = Error::Success;
  4911. EXPECT_TRUE(cli.send(req, res, error));
  4912. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  4913. "/hi?a=1"}),
  4914. targets);
  4915. }
  4916. TEST(HeaderWriter, SetHeaderWriter) {
  4917. Server svr;
  4918. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4919. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4920. return detail::write_headers(strm, hdrs);
  4921. });
  4922. svr.Get("/hi", [](const Request &req, Response &res) {
  4923. auto it = req.headers.find("CustomClientHeader");
  4924. EXPECT_TRUE(it != req.headers.end());
  4925. EXPECT_EQ(it->second, "CustomClientValue");
  4926. res.set_content("Hello World!\n", "text/plain");
  4927. });
  4928. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4929. auto se = detail::scope_exit([&] {
  4930. svr.stop();
  4931. thread.join();
  4932. ASSERT_FALSE(svr.is_running());
  4933. });
  4934. svr.wait_until_ready();
  4935. {
  4936. Client cli(HOST, PORT);
  4937. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4938. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4939. return detail::write_headers(strm, hdrs);
  4940. });
  4941. auto res = cli.Get("/hi");
  4942. EXPECT_TRUE(res);
  4943. EXPECT_EQ(StatusCode::OK_200, res->status);
  4944. auto it = res->headers.find("CustomServerHeader");
  4945. EXPECT_TRUE(it != res->headers.end());
  4946. EXPECT_EQ(it->second, "CustomServerValue");
  4947. }
  4948. }
  4949. class ServerTest : public ::testing::Test {
  4950. protected:
  4951. ServerTest()
  4952. : cli_(HOST, PORT)
  4953. #ifdef CPPHTTPLIB_SSL_ENABLED
  4954. ,
  4955. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4956. #endif
  4957. {
  4958. #ifdef CPPHTTPLIB_SSL_ENABLED
  4959. cli_.enable_server_certificate_verification(false);
  4960. #endif
  4961. // Allow LARGE_DATA (100MB) responses
  4962. cli_.set_payload_max_length(200 * 1024 * 1024);
  4963. }
  4964. virtual void SetUp() {
  4965. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4966. svr_.set_payload_max_length(200 * 1024 * 1024);
  4967. svr_.set_mount_point("/", "./www");
  4968. svr_.set_mount_point("/mount", "./www2");
  4969. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4970. svr_.Get("/hi",
  4971. [&](const Request & /*req*/, Response &res) {
  4972. res.set_content("Hello World!", "text/plain");
  4973. })
  4974. .Get("/file_content",
  4975. [&](const Request & /*req*/, Response &res) {
  4976. res.set_file_content("./www/dir/test.html");
  4977. })
  4978. .Get("/file_content_with_content_type",
  4979. [&](const Request & /*req*/, Response &res) {
  4980. res.set_file_content("./www/file", "text/plain");
  4981. })
  4982. .Get("/invalid_file_content",
  4983. [&](const Request & /*req*/, Response &res) {
  4984. res.set_file_content("./www/dir/invalid_file_path");
  4985. })
  4986. .Get("/http_response_splitting",
  4987. [&](const Request & /*req*/, Response &res) {
  4988. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4989. EXPECT_EQ(0U, res.headers.size());
  4990. EXPECT_FALSE(res.has_header("a"));
  4991. res.set_header("a", "1\nSet-Cookie: a=1");
  4992. EXPECT_EQ(0U, res.headers.size());
  4993. EXPECT_FALSE(res.has_header("a"));
  4994. res.set_header("a", "1\rSet-Cookie: a=1");
  4995. EXPECT_EQ(0U, res.headers.size());
  4996. EXPECT_FALSE(res.has_header("a"));
  4997. res.set_header("a\r\nb", "0");
  4998. EXPECT_EQ(0U, res.headers.size());
  4999. EXPECT_FALSE(res.has_header("a"));
  5000. res.set_header("a\rb", "0");
  5001. EXPECT_EQ(0U, res.headers.size());
  5002. EXPECT_FALSE(res.has_header("a"));
  5003. res.set_header("a\nb", "0");
  5004. EXPECT_EQ(0U, res.headers.size());
  5005. EXPECT_FALSE(res.has_header("a"));
  5006. res.set_redirect("1\r\nSet-Cookie: a=1");
  5007. EXPECT_EQ(0U, res.headers.size());
  5008. EXPECT_FALSE(res.has_header("Location"));
  5009. })
  5010. .Get("/slow",
  5011. [&](const Request & /*req*/, Response &res) {
  5012. std::this_thread::sleep_for(std::chrono::seconds(4));
  5013. res.set_content("slow", "text/plain");
  5014. })
  5015. #if 0
  5016. .Post("/slowpost",
  5017. [&](const Request & /*req*/, Response &res) {
  5018. std::this_thread::sleep_for(std::chrono::seconds(2));
  5019. res.set_content("slow", "text/plain");
  5020. })
  5021. #endif
  5022. .Get("/remote_addr",
  5023. [&](const Request &req, Response &res) {
  5024. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5025. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5026. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5027. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5028. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5029. #endif
  5030. res.set_content(req.remote_addr, "text/plain");
  5031. })
  5032. .Get("/local_addr",
  5033. [&](const Request &req, Response &res) {
  5034. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5035. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5036. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5037. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5038. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5039. #endif
  5040. auto local_addr = req.local_addr;
  5041. auto local_port = std::to_string(req.local_port);
  5042. res.set_content(local_addr.append(":").append(local_port),
  5043. "text/plain");
  5044. })
  5045. .Get("/endwith%",
  5046. [&](const Request & /*req*/, Response &res) {
  5047. res.set_content("Hello World!", "text/plain");
  5048. })
  5049. .Get("/a\\+\\+b",
  5050. [&](const Request &req, Response &res) {
  5051. ASSERT_TRUE(req.has_param("a +b"));
  5052. auto val = req.get_param_value("a +b");
  5053. res.set_content(val, "text/plain");
  5054. })
  5055. .Get("/", [&](const Request & /*req*/,
  5056. Response &res) { res.set_redirect("/hi"); })
  5057. .Post("/1",
  5058. [](const Request & /*req*/, Response &res) {
  5059. res.set_redirect("/2", StatusCode::SeeOther_303);
  5060. })
  5061. .Get("/2",
  5062. [](const Request & /*req*/, Response &res) {
  5063. res.set_content("redirected.", "text/plain");
  5064. res.status = StatusCode::OK_200;
  5065. })
  5066. .Post("/person",
  5067. [&](const Request &req, Response &res) {
  5068. if (req.has_param("name") && req.has_param("note")) {
  5069. persons_[req.get_param_value("name")] =
  5070. req.get_param_value("note");
  5071. } else {
  5072. res.status = StatusCode::BadRequest_400;
  5073. }
  5074. })
  5075. .Put("/person",
  5076. [&](const Request &req, Response &res) {
  5077. if (req.has_param("name") && req.has_param("note")) {
  5078. persons_[req.get_param_value("name")] =
  5079. req.get_param_value("note");
  5080. } else {
  5081. res.status = StatusCode::BadRequest_400;
  5082. }
  5083. })
  5084. .Get("/person/(.*)",
  5085. [&](const Request &req, Response &res) {
  5086. string name = req.matches[1];
  5087. if (persons_.find(name) != persons_.end()) {
  5088. auto note = persons_[name];
  5089. res.set_content(note, "text/plain");
  5090. } else {
  5091. res.status = StatusCode::NotFound_404;
  5092. }
  5093. })
  5094. .Delete("/person",
  5095. [&](const Request &req, Response &res) {
  5096. if (req.has_param("name")) {
  5097. string name = req.get_param_value("name");
  5098. if (persons_.find(name) != persons_.end()) {
  5099. persons_.erase(name);
  5100. res.set_content("DELETED", "text/plain");
  5101. } else {
  5102. res.status = StatusCode::NotFound_404;
  5103. }
  5104. } else {
  5105. res.status = StatusCode::BadRequest_400;
  5106. }
  5107. })
  5108. .Post("/x-www-form-urlencoded-json",
  5109. [&](const Request &req, Response &res) {
  5110. auto json = req.get_param_value("json");
  5111. ASSERT_EQ(JSON_DATA, json);
  5112. res.set_content(json, "appliation/json");
  5113. res.status = StatusCode::OK_200;
  5114. })
  5115. .Get("/streamed-chunked",
  5116. [&](const Request & /*req*/, Response &res) {
  5117. res.set_chunked_content_provider(
  5118. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5119. sink.os << "123";
  5120. sink.os << "456";
  5121. sink.os << "789";
  5122. sink.done();
  5123. return true;
  5124. });
  5125. })
  5126. .Get("/streamed-chunked-with-prohibited-trailer",
  5127. [&](const Request & /*req*/, Response &res) {
  5128. auto i = new int(0);
  5129. // Declare both a prohibited trailer (Content-Length) and an
  5130. // allowed one
  5131. res.set_header("Trailer", "Content-Length, X-Allowed");
  5132. res.set_chunked_content_provider(
  5133. "text/plain",
  5134. [i](size_t /*offset*/, DataSink &sink) {
  5135. switch (*i) {
  5136. case 0: sink.os << "123"; break;
  5137. case 1: sink.os << "456"; break;
  5138. case 2: sink.os << "789"; break;
  5139. case 3: {
  5140. sink.done_with_trailer(
  5141. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5142. } break;
  5143. }
  5144. (*i)++;
  5145. return true;
  5146. },
  5147. [i](bool success) {
  5148. EXPECT_TRUE(success);
  5149. delete i;
  5150. });
  5151. })
  5152. .Get("/streamed-chunked2",
  5153. [&](const Request & /*req*/, Response &res) {
  5154. auto i = new int(0);
  5155. res.set_chunked_content_provider(
  5156. "text/plain",
  5157. [i](size_t /*offset*/, DataSink &sink) {
  5158. switch (*i) {
  5159. case 0: sink.os << "123"; break;
  5160. case 1: sink.os << "456"; break;
  5161. case 2: sink.os << "789"; break;
  5162. case 3: sink.done(); break;
  5163. }
  5164. (*i)++;
  5165. return true;
  5166. },
  5167. [i](bool success) {
  5168. EXPECT_TRUE(success);
  5169. delete i;
  5170. });
  5171. })
  5172. .Get("/streamed-chunked-with-trailer",
  5173. [&](const Request & /*req*/, Response &res) {
  5174. auto i = new int(0);
  5175. res.set_header("Trailer", "Dummy1, Dummy2");
  5176. res.set_chunked_content_provider(
  5177. "text/plain",
  5178. [i](size_t /*offset*/, DataSink &sink) {
  5179. switch (*i) {
  5180. case 0: sink.os << "123"; break;
  5181. case 1: sink.os << "456"; break;
  5182. case 2: sink.os << "789"; break;
  5183. case 3: {
  5184. sink.done_with_trailer(
  5185. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5186. } break;
  5187. }
  5188. (*i)++;
  5189. return true;
  5190. },
  5191. [i](bool success) {
  5192. EXPECT_TRUE(success);
  5193. delete i;
  5194. });
  5195. })
  5196. .Get("/streamed",
  5197. [&](const Request & /*req*/, Response &res) {
  5198. res.set_content_provider(
  5199. 6, "text/plain",
  5200. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5201. sink.os << (offset < 3 ? "a" : "b");
  5202. return true;
  5203. });
  5204. })
  5205. .Get("/streamed-without-length",
  5206. [&](const Request & /*req*/, Response &res) {
  5207. auto data = new std::string("abcdefg");
  5208. res.set_content_provider(
  5209. "text/plain",
  5210. [data](size_t offset, DataSink &sink) {
  5211. if (offset < data->size()) {
  5212. sink.os << data->substr(offset);
  5213. }
  5214. sink.done();
  5215. return true;
  5216. },
  5217. [data](bool success) {
  5218. EXPECT_TRUE(success);
  5219. delete data;
  5220. });
  5221. })
  5222. .Get("/streamed-with-range",
  5223. [&](const Request &req, Response &res) {
  5224. auto data = new std::string("abcdefg");
  5225. // An explicit status keeps the server from picking the 206 it
  5226. // would otherwise choose for a ranged request, so the response
  5227. // is not a partial representation.
  5228. auto status = req.get_param_value("status");
  5229. if (status == "200") {
  5230. res.status = StatusCode::OK_200;
  5231. } else if (status == "403") {
  5232. res.status = StatusCode::Forbidden_403;
  5233. }
  5234. res.set_content_provider(
  5235. data->size(), "text/plain",
  5236. [data](size_t offset, size_t length, DataSink &sink) {
  5237. size_t DATA_CHUNK_SIZE = 4;
  5238. const auto &d = *data;
  5239. auto out_len =
  5240. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5241. auto ret =
  5242. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5243. EXPECT_TRUE(ret);
  5244. return true;
  5245. },
  5246. [data, &req](bool success) {
  5247. EXPECT_EQ(success, !req.has_param("error"));
  5248. delete data;
  5249. });
  5250. })
  5251. .Get("/streamed-cancel",
  5252. [&](const Request & /*req*/, Response &res) {
  5253. res.set_content_provider(
  5254. size_t(-1), "text/plain",
  5255. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5256. sink.os << "data_chunk";
  5257. return true;
  5258. });
  5259. })
  5260. .Get("/regex-with-delimiter",
  5261. [&](const Request &req, Response & /*res*/) {
  5262. ASSERT_TRUE(req.has_param("key"));
  5263. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5264. })
  5265. .Get("/with-range",
  5266. [&](const Request & /*req*/, Response &res) {
  5267. res.set_content("abcdefg", "text/plain");
  5268. })
  5269. .Get("/test-start-time",
  5270. [&](const Request &req, Response & /*res*/) {
  5271. EXPECT_NE(req.start_time_,
  5272. std::chrono::steady_clock::time_point::min());
  5273. })
  5274. .Get("/with-range-customized-response",
  5275. [&](const Request & /*req*/, Response &res) {
  5276. res.status = StatusCode::BadRequest_400;
  5277. res.set_content(JSON_DATA, "application/json");
  5278. })
  5279. .Post("/chunked",
  5280. [&](const Request &req, Response & /*res*/) {
  5281. EXPECT_EQ(req.body, "dechunked post body");
  5282. })
  5283. .Post("/large-chunked",
  5284. [&](const Request &req, Response & /*res*/) {
  5285. std::string expected(6 * 30 * 1024u, 'a');
  5286. EXPECT_EQ(req.body, expected);
  5287. })
  5288. .Post("/multipart",
  5289. [&](const Request &req, Response & /*res*/) {
  5290. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5291. req.form.get_field_count("text2") +
  5292. req.form.get_field_count("file3") +
  5293. req.form.get_field_count("file4"));
  5294. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5295. req.form.get_file_count("file2"));
  5296. ASSERT_TRUE(!req.form.has_file("???"));
  5297. ASSERT_TRUE(!req.form.has_field("???"));
  5298. ASSERT_TRUE(req.body.empty());
  5299. {
  5300. const auto &text = req.form.get_field("text1");
  5301. EXPECT_EQ("text default", text);
  5302. }
  5303. {
  5304. const auto &text = req.form.get_field("text2");
  5305. EXPECT_EQ("aωb", text);
  5306. }
  5307. {
  5308. const auto &file = req.form.get_file("file1");
  5309. EXPECT_EQ("hello.txt", file.filename);
  5310. EXPECT_EQ("text/plain", file.content_type);
  5311. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5312. }
  5313. {
  5314. const auto &file = req.form.get_file("file2");
  5315. EXPECT_EQ("world.json", file.filename);
  5316. EXPECT_EQ("application/json", file.content_type);
  5317. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5318. }
  5319. {
  5320. const auto &text = req.form.get_field("file3");
  5321. EXPECT_EQ(0u, text.size());
  5322. }
  5323. {
  5324. const auto &text = req.form.get_field("file4");
  5325. EXPECT_EQ(0u, text.size());
  5326. }
  5327. })
  5328. .Post("/multipart/multi_file_values",
  5329. [&](const Request &req, Response & /*res*/) {
  5330. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5331. req.form.get_field_count("multi_text1"));
  5332. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5333. ASSERT_TRUE(!req.form.has_file("???"));
  5334. ASSERT_TRUE(!req.form.has_field("???"));
  5335. ASSERT_TRUE(req.body.empty());
  5336. {
  5337. const auto &text = req.form.get_field("text");
  5338. EXPECT_EQ("default text", text);
  5339. }
  5340. {
  5341. const auto &text1_values = req.form.get_fields("multi_text1");
  5342. EXPECT_EQ(2u, text1_values.size());
  5343. EXPECT_EQ("aaaaa", text1_values[0]);
  5344. EXPECT_EQ("bbbbb", text1_values[1]);
  5345. }
  5346. {
  5347. const auto &file1_values = req.form.get_files("multi_file1");
  5348. EXPECT_EQ(2u, file1_values.size());
  5349. auto file1 = file1_values[0];
  5350. EXPECT_EQ(file1.filename, "hello.txt");
  5351. EXPECT_EQ(file1.content_type, "text/plain");
  5352. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5353. auto file2 = file1_values[1];
  5354. EXPECT_EQ(file2.filename, "world.json");
  5355. EXPECT_EQ(file2.content_type, "application/json");
  5356. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5357. }
  5358. })
  5359. .Post("/empty",
  5360. [&](const Request &req, Response &res) {
  5361. EXPECT_EQ(req.body, "");
  5362. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5363. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5364. res.set_content("empty", "text/plain");
  5365. })
  5366. .Post("/empty-no-content-type",
  5367. [&](const Request &req, Response &res) {
  5368. EXPECT_EQ(req.body, "");
  5369. EXPECT_FALSE(req.has_header("Content-Type"));
  5370. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5371. res.set_content("empty-no-content-type", "text/plain");
  5372. })
  5373. .Post("/path-only",
  5374. [&](const Request &req, Response &res) {
  5375. EXPECT_EQ(req.body, "");
  5376. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5377. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5378. res.set_content("path-only", "text/plain");
  5379. })
  5380. .Post("/path-headers-only",
  5381. [&](const Request &req, Response &res) {
  5382. EXPECT_EQ(req.body, "");
  5383. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5384. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5385. EXPECT_EQ("world", req.get_header_value("hello"));
  5386. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5387. res.set_content("path-headers-only", "text/plain");
  5388. })
  5389. .Post("/post-large",
  5390. [&](const Request &req, Response &res) {
  5391. EXPECT_EQ(req.body, LARGE_DATA);
  5392. res.set_content(req.body, "text/plain");
  5393. })
  5394. .Post("/post-loopback",
  5395. [&](const Request &, Response &res,
  5396. ContentReader const &content_reader) {
  5397. std::string body;
  5398. content_reader([&](const char *data, size_t data_length) {
  5399. body.append(data, data_length);
  5400. return true;
  5401. });
  5402. res.set_content(body, "text/plain");
  5403. })
  5404. .Put("/put-loopback",
  5405. [&](const Request &, Response &res,
  5406. ContentReader const &content_reader) {
  5407. std::string body;
  5408. content_reader([&](const char *data, size_t data_length) {
  5409. body.append(data, data_length);
  5410. return true;
  5411. });
  5412. res.set_content(body, "text/plain");
  5413. })
  5414. .Patch("/patch-loopback",
  5415. [&](const Request &, Response &res,
  5416. ContentReader const &content_reader) {
  5417. std::string body;
  5418. content_reader([&](const char *data, size_t data_length) {
  5419. body.append(data, data_length);
  5420. return true;
  5421. });
  5422. res.set_content(body, "text/plain");
  5423. })
  5424. .Put("/empty-no-content-type",
  5425. [&](const Request &req, Response &res) {
  5426. EXPECT_EQ(req.body, "");
  5427. EXPECT_FALSE(req.has_header("Content-Type"));
  5428. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5429. res.set_content("empty-no-content-type", "text/plain");
  5430. })
  5431. .Put("/put",
  5432. [&](const Request &req, Response &res) {
  5433. EXPECT_EQ(req.body, "PUT");
  5434. res.set_content(req.body, "text/plain");
  5435. })
  5436. .Put("/put-large",
  5437. [&](const Request &req, Response &res) {
  5438. EXPECT_EQ(req.body, LARGE_DATA);
  5439. res.set_content(req.body, "text/plain");
  5440. })
  5441. .Patch("/patch",
  5442. [&](const Request &req, Response &res) {
  5443. EXPECT_EQ(req.body, "PATCH");
  5444. res.set_content(req.body, "text/plain");
  5445. })
  5446. .Delete("/delete",
  5447. [&](const Request & /*req*/, Response &res) {
  5448. res.set_content("DELETE", "text/plain");
  5449. })
  5450. .Delete("/delete-body",
  5451. [&](const Request &req, Response &res) {
  5452. EXPECT_EQ(req.body, "content");
  5453. res.set_content(req.body, "text/plain");
  5454. })
  5455. .Options(R"(\*)",
  5456. [&](const Request & /*req*/, Response &res) {
  5457. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5458. })
  5459. .CustomRoute("PROPFIND", "/dav/:id",
  5460. [&](const Request &req, Response &res) {
  5461. res.set_header("x-body-size",
  5462. std::to_string(req.body.size()));
  5463. res.set_header("x-matched-route", req.matched_route);
  5464. res.set_header("x-dav-id", req.path_params.at("id"));
  5465. res.status = StatusCode::MultiStatus_207;
  5466. res.set_content(req.body, "application/xml");
  5467. })
  5468. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5469. [&](const Request &req, Response &res) {
  5470. res.set_header("x-dav-match", req.matches[1]);
  5471. res.status = StatusCode::MultiStatus_207;
  5472. })
  5473. .CustomRoute("MKCOL", "/dav-mkcol",
  5474. [&](const Request &req, Response &res) {
  5475. EXPECT_TRUE(req.body.empty());
  5476. res.status = StatusCode::Created_201;
  5477. })
  5478. .CustomRoute(
  5479. "REPORT", "/dav-report",
  5480. [&](const Request & /*req*/, Response &res,
  5481. const ContentReader &content_reader) {
  5482. std::string body;
  5483. content_reader([&](const char *data, size_t data_length) {
  5484. body.append(data, data_length);
  5485. return true;
  5486. });
  5487. res.set_header("x-body-size", std::to_string(body.size()));
  5488. res.status = StatusCode::MultiStatus_207;
  5489. res.set_content(body, "application/xml");
  5490. })
  5491. .Get("/request-target",
  5492. [&](const Request &req, Response & /*res*/) {
  5493. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5494. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5495. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5496. })
  5497. .Get("/long-query-value",
  5498. [&](const Request &req, Response & /*res*/) {
  5499. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5500. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5501. })
  5502. .Get("/too-long-query-value",
  5503. [&](const Request &req, Response & /*res*/) {
  5504. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5505. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5506. })
  5507. .Get("/array-param",
  5508. [&](const Request &req, Response & /*res*/) {
  5509. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5510. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5511. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5512. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5513. })
  5514. .Get("/array-param-values",
  5515. [&](const Request &req, Response & /*res*/) {
  5516. auto values = req.get_param_values("array");
  5517. EXPECT_EQ(3u, values.size());
  5518. EXPECT_EQ("value1", values[0]);
  5519. EXPECT_EQ("value2", values[1]);
  5520. EXPECT_EQ("value3", values[2]);
  5521. auto empty = req.get_param_values("nonexistent");
  5522. EXPECT_TRUE(empty.empty());
  5523. })
  5524. .Post("/validate-no-multiple-headers",
  5525. [&](const Request &req, Response & /*res*/) {
  5526. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5527. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5528. })
  5529. .Post("/content_receiver",
  5530. [&](const Request &req, Response &res,
  5531. const ContentReader &content_reader) {
  5532. if (req.is_multipart_form_data()) {
  5533. std::vector<FormData> items;
  5534. content_reader(
  5535. [&](const FormData &file) {
  5536. items.push_back(file);
  5537. return true;
  5538. },
  5539. [&](const char *data, size_t data_length) {
  5540. items.back().content.append(data, data_length);
  5541. return true;
  5542. });
  5543. EXPECT_EQ(5u, items.size());
  5544. {
  5545. const auto &file = get_file_value(items, "text1");
  5546. EXPECT_TRUE(file.filename.empty());
  5547. EXPECT_EQ("text default", file.content);
  5548. }
  5549. {
  5550. const auto &file = get_file_value(items, "text2");
  5551. EXPECT_TRUE(file.filename.empty());
  5552. EXPECT_EQ("aωb", file.content);
  5553. }
  5554. {
  5555. const auto &file = get_file_value(items, "file1");
  5556. EXPECT_EQ("hello.txt", file.filename);
  5557. EXPECT_EQ("text/plain", file.content_type);
  5558. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5559. }
  5560. {
  5561. const auto &file = get_file_value(items, "file2");
  5562. EXPECT_EQ("world.json", file.filename);
  5563. EXPECT_EQ("application/json", file.content_type);
  5564. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5565. }
  5566. {
  5567. const auto &file = get_file_value(items, "file3");
  5568. EXPECT_TRUE(file.filename.empty());
  5569. EXPECT_EQ("application/octet-stream", file.content_type);
  5570. EXPECT_EQ(0u, file.content.size());
  5571. }
  5572. } else {
  5573. std::string body;
  5574. content_reader([&](const char *data, size_t data_length) {
  5575. EXPECT_EQ(7U, data_length);
  5576. body.append(data, data_length);
  5577. return true;
  5578. });
  5579. EXPECT_EQ(body, "content");
  5580. res.set_content(body, "text/plain");
  5581. }
  5582. })
  5583. .Put("/content_receiver",
  5584. [&](const Request & /*req*/, Response &res,
  5585. const ContentReader &content_reader) {
  5586. std::string body;
  5587. content_reader([&](const char *data, size_t data_length) {
  5588. body.append(data, data_length);
  5589. return true;
  5590. });
  5591. EXPECT_EQ(body, "content");
  5592. res.set_content(body, "text/plain");
  5593. })
  5594. .Patch("/content_receiver",
  5595. [&](const Request & /*req*/, Response &res,
  5596. const ContentReader &content_reader) {
  5597. std::string body;
  5598. content_reader([&](const char *data, size_t data_length) {
  5599. body.append(data, data_length);
  5600. return true;
  5601. });
  5602. EXPECT_EQ(body, "content");
  5603. res.set_content(body, "text/plain");
  5604. })
  5605. .Post("/query-string-and-body",
  5606. [&](const Request &req, Response & /*res*/) {
  5607. ASSERT_TRUE(req.has_param("key"));
  5608. EXPECT_EQ(req.get_param_value("key"), "value");
  5609. EXPECT_EQ(req.body, "content");
  5610. })
  5611. .Get("/last-request",
  5612. [&](const Request &req, Response & /*res*/) {
  5613. EXPECT_EQ("close", req.get_header_value("Connection"));
  5614. })
  5615. .Get(R"(/redirect/(\d+))",
  5616. [&](const Request &req, Response &res) {
  5617. auto num = std::stoi(req.matches[1]) + 1;
  5618. std::string url = "/redirect/" + std::to_string(num);
  5619. res.set_redirect(url);
  5620. })
  5621. .Post("/binary",
  5622. [&](const Request &req, Response &res) {
  5623. EXPECT_EQ(4U, req.body.size());
  5624. EXPECT_EQ("application/octet-stream",
  5625. req.get_header_value("Content-Type"));
  5626. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5627. res.set_content(req.body, "application/octet-stream");
  5628. })
  5629. .Put("/binary",
  5630. [&](const Request &req, Response &res) {
  5631. EXPECT_EQ(4U, req.body.size());
  5632. EXPECT_EQ("application/octet-stream",
  5633. req.get_header_value("Content-Type"));
  5634. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5635. res.set_content(req.body, "application/octet-stream");
  5636. })
  5637. .Patch("/binary",
  5638. [&](const Request &req, Response &res) {
  5639. EXPECT_EQ(4U, req.body.size());
  5640. EXPECT_EQ("application/octet-stream",
  5641. req.get_header_value("Content-Type"));
  5642. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5643. res.set_content(req.body, "application/octet-stream");
  5644. })
  5645. .Delete("/binary",
  5646. [&](const Request &req, Response &res) {
  5647. EXPECT_EQ(4U, req.body.size());
  5648. EXPECT_EQ("application/octet-stream",
  5649. req.get_header_value("Content-Type"));
  5650. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5651. res.set_content(req.body, "application/octet-stream");
  5652. })
  5653. .Get("/issue1772",
  5654. [&](const Request & /*req*/, Response &res) {
  5655. res.status = 401;
  5656. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5657. })
  5658. .Delete("/issue609",
  5659. [](const httplib::Request &, httplib::Response &res,
  5660. const httplib::ContentReader &) {
  5661. res.set_content("ok", "text/plain");
  5662. })
  5663. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5664. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5665. .Get("/compress",
  5666. [&](const Request & /*req*/, Response &res) {
  5667. res.set_content(
  5668. "12345678901234567890123456789012345678901234567890123456789"
  5669. "01234567890123456789012345678901234567890",
  5670. "text/plain");
  5671. })
  5672. .Get("/compress-with-charset",
  5673. [&](const Request & /*req*/, Response &res) {
  5674. res.set_content(
  5675. "12345678901234567890123456789012345678901234567890123456789"
  5676. "01234567890123456789012345678901234567890",
  5677. "application/json; charset=utf-8");
  5678. })
  5679. .Get("/nocompress",
  5680. [&](const Request & /*req*/, Response &res) {
  5681. res.set_content(
  5682. "12345678901234567890123456789012345678901234567890123456789"
  5683. "01234567890123456789012345678901234567890",
  5684. "application/octet-stream");
  5685. })
  5686. .Post("/compress-multipart",
  5687. [&](const Request &req, Response & /*res*/) {
  5688. EXPECT_EQ(2u, req.form.fields.size());
  5689. ASSERT_TRUE(!req.form.has_field("???"));
  5690. {
  5691. const auto &text = req.form.get_field("key1");
  5692. EXPECT_EQ("test", text);
  5693. }
  5694. {
  5695. const auto &text = req.form.get_field("key2");
  5696. EXPECT_EQ("--abcdefg123", text);
  5697. }
  5698. })
  5699. #endif
  5700. ;
  5701. persons_["john"] = "programmer";
  5702. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5703. svr_.wait_until_ready();
  5704. }
  5705. virtual void TearDown() {
  5706. svr_.stop();
  5707. if (!request_threads_.empty()) {
  5708. std::this_thread::sleep_for(std::chrono::seconds(1));
  5709. for (auto &t : request_threads_) {
  5710. t.join();
  5711. }
  5712. }
  5713. t_.join();
  5714. }
  5715. map<string, string> persons_;
  5716. #ifdef CPPHTTPLIB_SSL_ENABLED
  5717. SSLClient cli_;
  5718. SSLServer svr_;
  5719. #else
  5720. Client cli_;
  5721. Server svr_;
  5722. #endif
  5723. thread t_;
  5724. std::vector<thread> request_threads_;
  5725. };
  5726. TEST_F(ServerTest, GetMethod200) {
  5727. auto res = cli_.Get("/hi");
  5728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5729. EXPECT_EQ("HTTP/1.1", res->version);
  5730. EXPECT_EQ(StatusCode::OK_200, res->status);
  5731. EXPECT_EQ("OK", res->reason);
  5732. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5733. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5734. EXPECT_EQ("Hello World!", res->body);
  5735. }
  5736. TEST_F(ServerTest, GetEmptyFile) {
  5737. auto res = cli_.Get("/empty_file");
  5738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5739. EXPECT_EQ(StatusCode::OK_200, res->status);
  5740. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5741. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5742. EXPECT_EQ("", res->body);
  5743. }
  5744. TEST_F(ServerTest, GetFileContent) {
  5745. auto res = cli_.Get("/file_content");
  5746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5747. EXPECT_EQ(StatusCode::OK_200, res->status);
  5748. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5749. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5750. EXPECT_EQ("test.html", res->body);
  5751. }
  5752. TEST_F(ServerTest, GetFileContentWithRange) {
  5753. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5756. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5757. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5758. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5759. EXPECT_EQ("est", res->body);
  5760. }
  5761. TEST_F(ServerTest, GetFileContentWithContentType) {
  5762. auto res = cli_.Get("/file_content_with_content_type");
  5763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5764. EXPECT_EQ(StatusCode::OK_200, res->status);
  5765. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5766. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5767. EXPECT_EQ("file\n", res->body);
  5768. }
  5769. TEST_F(ServerTest, GetInvalidFileContent) {
  5770. auto res = cli_.Get("/invalid_file_content");
  5771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5772. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5773. }
  5774. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5775. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5777. EXPECT_EQ("HTTP/1.1", res->version);
  5778. EXPECT_EQ(StatusCode::OK_200, res->status);
  5779. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5780. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5781. EXPECT_EQ("Hello World!", res->body);
  5782. }
  5783. TEST_F(ServerTest, GetMethod302) {
  5784. auto res = cli_.Get("/");
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. EXPECT_EQ(StatusCode::Found_302, res->status);
  5787. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5788. }
  5789. TEST_F(ServerTest, GetMethod302Redirect) {
  5790. cli_.set_follow_location(true);
  5791. auto res = cli_.Get("/");
  5792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5793. EXPECT_EQ(StatusCode::OK_200, res->status);
  5794. EXPECT_EQ("Hello World!", res->body);
  5795. EXPECT_EQ("/hi", res->location);
  5796. }
  5797. TEST_F(ServerTest, GetMethod404) {
  5798. auto res = cli_.Get("/invalid");
  5799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5800. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5801. }
  5802. TEST_F(ServerTest, HeadMethod200) {
  5803. auto res = cli_.Head("/hi");
  5804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5805. EXPECT_EQ(StatusCode::OK_200, res->status);
  5806. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5807. EXPECT_TRUE(res->body.empty());
  5808. }
  5809. TEST_F(ServerTest, HeadMethod200Static) {
  5810. auto res = cli_.Head("/mount/dir/index.html");
  5811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5812. EXPECT_EQ(StatusCode::OK_200, res->status);
  5813. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5814. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5815. EXPECT_TRUE(res->body.empty());
  5816. }
  5817. TEST_F(ServerTest, HeadMethod404) {
  5818. auto res = cli_.Head("/invalid");
  5819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5821. EXPECT_TRUE(res->body.empty());
  5822. }
  5823. TEST_F(ServerTest, GetMethodPersonJohn) {
  5824. auto res = cli_.Get("/person/john");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::OK_200, res->status);
  5827. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5828. EXPECT_EQ("programmer", res->body);
  5829. }
  5830. TEST_F(ServerTest, PostMethod1) {
  5831. auto res = cli_.Get("/person/john1");
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5834. res = cli_.Post("/person", "name=john1&note=coder",
  5835. "application/x-www-form-urlencoded");
  5836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5837. ASSERT_EQ(StatusCode::OK_200, res->status);
  5838. res = cli_.Get("/person/john1");
  5839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5840. ASSERT_EQ(StatusCode::OK_200, res->status);
  5841. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5842. ASSERT_EQ("coder", res->body);
  5843. }
  5844. TEST_F(ServerTest, PostMethod2) {
  5845. auto res = cli_.Get("/person/john2");
  5846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5847. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5848. Params params;
  5849. params.emplace("name", "john2");
  5850. params.emplace("note", "coder");
  5851. res = cli_.Post("/person", params);
  5852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5853. ASSERT_EQ(StatusCode::OK_200, res->status);
  5854. res = cli_.Get("/person/john2");
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. ASSERT_EQ(StatusCode::OK_200, res->status);
  5857. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5858. ASSERT_EQ("coder", res->body);
  5859. }
  5860. TEST_F(ServerTest, PutMethod3) {
  5861. auto res = cli_.Get("/person/john3");
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5864. Params params;
  5865. params.emplace("name", "john3");
  5866. params.emplace("note", "coder");
  5867. res = cli_.Put("/person", params);
  5868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5869. ASSERT_EQ(StatusCode::OK_200, res->status);
  5870. res = cli_.Get("/person/john3");
  5871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5872. ASSERT_EQ(StatusCode::OK_200, res->status);
  5873. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5874. ASSERT_EQ("coder", res->body);
  5875. }
  5876. TEST_F(ServerTest, DeleteMethod1) {
  5877. auto res = cli_.Get("/person/john4");
  5878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5879. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5880. Params params;
  5881. params.emplace("name", "john4");
  5882. params.emplace("note", "coder");
  5883. res = cli_.Post("/person", params);
  5884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5885. ASSERT_EQ(StatusCode::OK_200, res->status);
  5886. res = cli_.Get("/person/john4");
  5887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5888. ASSERT_EQ(StatusCode::OK_200, res->status);
  5889. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5890. ASSERT_EQ("coder", res->body);
  5891. Params delete_params;
  5892. delete_params.emplace("name", "john4");
  5893. res = cli_.Delete("/person", delete_params);
  5894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5895. ASSERT_EQ(StatusCode::OK_200, res->status);
  5896. ASSERT_EQ("DELETED", res->body);
  5897. res = cli_.Get("/person/john4");
  5898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5899. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5900. }
  5901. TEST_F(ServerTest, DeleteMethod2) {
  5902. auto res = cli_.Get("/person/john5");
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5905. Params params;
  5906. params.emplace("name", "john5");
  5907. params.emplace("note", "developer");
  5908. res = cli_.Post("/person", params);
  5909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5910. ASSERT_EQ(StatusCode::OK_200, res->status);
  5911. res = cli_.Get("/person/john5");
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. ASSERT_EQ(StatusCode::OK_200, res->status);
  5914. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5915. ASSERT_EQ("developer", res->body);
  5916. Params delete_params;
  5917. delete_params.emplace("name", "john5");
  5918. Headers headers;
  5919. headers.emplace("Custom-Header", "test-value");
  5920. res = cli_.Delete("/person", headers, delete_params);
  5921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5922. ASSERT_EQ(StatusCode::OK_200, res->status);
  5923. ASSERT_EQ("DELETED", res->body);
  5924. res = cli_.Get("/person/john5");
  5925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5926. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5927. }
  5928. TEST_F(ServerTest, DeleteMethod3) {
  5929. auto res = cli_.Get("/person/john6");
  5930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5931. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5932. Params params;
  5933. params.emplace("name", "john6");
  5934. params.emplace("note", "tester");
  5935. res = cli_.Post("/person", params);
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. ASSERT_EQ(StatusCode::OK_200, res->status);
  5938. res = cli_.Get("/person/john6");
  5939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5940. ASSERT_EQ(StatusCode::OK_200, res->status);
  5941. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5942. ASSERT_EQ("tester", res->body);
  5943. Params delete_params;
  5944. delete_params.emplace("name", "john6");
  5945. Headers headers;
  5946. headers.emplace("Custom-Header", "test-value");
  5947. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. ASSERT_EQ(StatusCode::OK_200, res->status);
  5950. ASSERT_EQ("DELETED", res->body);
  5951. res = cli_.Get("/person/john6");
  5952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5953. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5954. }
  5955. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5956. Params params;
  5957. params.emplace("json", JSON_DATA);
  5958. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. ASSERT_EQ(StatusCode::OK_200, res->status);
  5961. ASSERT_EQ(JSON_DATA, res->body);
  5962. }
  5963. TEST_F(ServerTest, PostEmptyContent) {
  5964. auto res = cli_.Post("/empty", "", "text/plain");
  5965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5966. ASSERT_EQ(StatusCode::OK_200, res->status);
  5967. ASSERT_EQ("empty", res->body);
  5968. }
  5969. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5970. auto res = cli_.Post("/empty-no-content-type");
  5971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5972. ASSERT_EQ(StatusCode::OK_200, res->status);
  5973. ASSERT_EQ("empty-no-content-type", res->body);
  5974. }
  5975. TEST_F(ServerTest, PostPathOnly) {
  5976. auto res = cli_.Post("/path-only");
  5977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5978. ASSERT_EQ(StatusCode::OK_200, res->status);
  5979. ASSERT_EQ("path-only", res->body);
  5980. }
  5981. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5982. auto res = cli_.Post("/path-headers-only",
  5983. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5985. ASSERT_EQ(StatusCode::OK_200, res->status);
  5986. ASSERT_EQ("path-headers-only", res->body);
  5987. }
  5988. TEST_F(ServerTest, PostLarge) {
  5989. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5991. ASSERT_EQ(StatusCode::OK_200, res->status);
  5992. EXPECT_EQ(LARGE_DATA, res->body);
  5993. }
  5994. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5995. auto res = cli_.Put("/empty-no-content-type");
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. ASSERT_EQ(StatusCode::OK_200, res->status);
  5998. ASSERT_EQ("empty-no-content-type", res->body);
  5999. }
  6000. TEST_F(ServerTest, GetMethodDir) {
  6001. auto res = cli_.Get("/dir/");
  6002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6003. EXPECT_EQ(StatusCode::OK_200, res->status);
  6004. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6005. auto body = R"(<html>
  6006. <head>
  6007. </head>
  6008. <body>
  6009. <a href="/dir/test.html">Test</a>
  6010. <a href="/hi">hi</a>
  6011. </body>
  6012. </html>
  6013. )";
  6014. EXPECT_EQ(body, res->body);
  6015. }
  6016. TEST_F(ServerTest, GetMethodDirTest) {
  6017. auto res = cli_.Get("/dir/test.html");
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6021. EXPECT_EQ("test.html", res->body);
  6022. }
  6023. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6024. auto res = cli_.Get("/dir/../dir/test.html");
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::OK_200, res->status);
  6027. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6028. EXPECT_EQ("test.html", res->body);
  6029. }
  6030. TEST_F(ServerTest, GetMethodInvalidPath) {
  6031. auto res = cli_.Get("/dir/../test.html");
  6032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6033. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6034. }
  6035. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6036. auto res = cli_.Get("/../www/dir/test.html");
  6037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6038. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6039. }
  6040. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6041. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6043. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6044. }
  6045. TEST_F(ServerTest, GetMethodDirMountTest) {
  6046. auto res = cli_.Get("/mount/dir/test.html");
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ(StatusCode::OK_200, res->status);
  6049. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6050. EXPECT_EQ("test.html", res->body);
  6051. }
  6052. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6053. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6055. EXPECT_EQ(StatusCode::OK_200, res->status);
  6056. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6057. EXPECT_EQ("test.html", res->body);
  6058. }
  6059. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6060. auto res = cli_.Get("/mount/dir/../test.html");
  6061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6062. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6063. }
  6064. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6065. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6067. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6068. }
  6069. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6070. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6073. }
  6074. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6075. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6078. }
  6079. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6080. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6082. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6083. }
  6084. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6085. auto res = cli_.Get("/mount/dir");
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6088. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6089. }
  6090. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6091. auto res = cli_.Get("//dir");
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6094. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6095. }
  6096. TEST_F(ServerTest, PostMethod303) {
  6097. auto res = cli_.Post("/1", "body", "text/plain");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6100. EXPECT_EQ("/2", res->get_header_value("Location"));
  6101. }
  6102. TEST_F(ServerTest, PostMethod303Redirect) {
  6103. cli_.set_follow_location(true);
  6104. auto res = cli_.Post("/1", "body", "text/plain");
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. EXPECT_EQ("redirected.", res->body);
  6108. EXPECT_EQ("/2", res->location);
  6109. }
  6110. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6111. auto res = cli_.Get("/dir/test.abcde");
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. EXPECT_EQ(StatusCode::OK_200, res->status);
  6114. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6115. EXPECT_EQ("abcde", res->body);
  6116. }
  6117. TEST_F(ServerTest, StaticFileRange) {
  6118. auto res =
  6119. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6122. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6123. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6124. EXPECT_EQ(true, res->has_header("Content-Range"));
  6125. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6126. EXPECT_EQ(std::string("cd"), res->body);
  6127. }
  6128. TEST_F(ServerTest, StaticFileRanges) {
  6129. auto res = cli_.Get("/dir/test.abcde",
  6130. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6132. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6133. EXPECT_TRUE(
  6134. res->get_header_value("Content-Type")
  6135. .find(
  6136. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6137. 0);
  6138. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6139. }
  6140. TEST_F(ServerTest, StaticFileRangeHead) {
  6141. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6143. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6144. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6145. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6146. EXPECT_EQ(true, res->has_header("Content-Range"));
  6147. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6148. }
  6149. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6150. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6152. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6154. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6155. EXPECT_EQ(true, res->has_header("Content-Range"));
  6156. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6157. res->get_header_value("Content-Range"));
  6158. EXPECT_EQ("LAST\n", res->body);
  6159. }
  6160. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6161. auto res =
  6162. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6165. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6166. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6167. EXPECT_EQ(true, res->has_header("Content-Range"));
  6168. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6169. }
  6170. TEST_F(ServerTest, StaticFileBigFile) {
  6171. auto res = cli_.Get("/dir/1MB.txt");
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. EXPECT_EQ(StatusCode::OK_200, res->status);
  6174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6175. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6176. }
  6177. TEST_F(ServerTest, InvalidBaseDirMount) {
  6178. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6179. }
  6180. TEST_F(ServerTest, Binary) {
  6181. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6182. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6183. "application/octet-stream");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. ASSERT_EQ(StatusCode::OK_200, res->status);
  6186. ASSERT_EQ(4U, res->body.size());
  6187. res = cli_.Put("/binary", binary.data(), binary.size(),
  6188. "application/octet-stream");
  6189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6190. ASSERT_EQ(StatusCode::OK_200, res->status);
  6191. ASSERT_EQ(4U, res->body.size());
  6192. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6193. "application/octet-stream");
  6194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6195. ASSERT_EQ(StatusCode::OK_200, res->status);
  6196. ASSERT_EQ(4U, res->body.size());
  6197. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6198. "application/octet-stream");
  6199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6200. ASSERT_EQ(StatusCode::OK_200, res->status);
  6201. ASSERT_EQ(4U, res->body.size());
  6202. }
  6203. TEST_F(ServerTest, BinaryString) {
  6204. auto binary = std::string("\x00\x01\x02\x03", 4);
  6205. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. ASSERT_EQ(StatusCode::OK_200, res->status);
  6208. ASSERT_EQ(4U, res->body.size());
  6209. res = cli_.Put("/binary", binary, "application/octet-stream");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. ASSERT_EQ(StatusCode::OK_200, res->status);
  6212. ASSERT_EQ(4U, res->body.size());
  6213. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6215. ASSERT_EQ(StatusCode::OK_200, res->status);
  6216. ASSERT_EQ(4U, res->body.size());
  6217. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. ASSERT_EQ(StatusCode::OK_200, res->status);
  6220. ASSERT_EQ(4U, res->body.size());
  6221. }
  6222. TEST_F(ServerTest, EmptyRequest) {
  6223. auto res = cli_.Get("");
  6224. ASSERT_TRUE(!res);
  6225. EXPECT_EQ(Error::Connection, res.error());
  6226. }
  6227. TEST_F(ServerTest, LongRequest) {
  6228. std::string request;
  6229. for (size_t i = 0; i < 545; i++) {
  6230. request += "/TooLongRequest";
  6231. }
  6232. request += "OK";
  6233. auto res = cli_.Get(request.c_str());
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6236. }
  6237. TEST_F(ServerTest, TooLongRequest) {
  6238. std::string request;
  6239. for (size_t i = 0; i < 546; i++) {
  6240. request += "/TooLongRequest";
  6241. }
  6242. request += "_NG";
  6243. auto start = std::chrono::high_resolution_clock::now();
  6244. cli_.set_keep_alive(true);
  6245. auto res = cli_.Get(request.c_str());
  6246. auto end = std::chrono::high_resolution_clock::now();
  6247. auto elapsed =
  6248. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6249. .count();
  6250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6251. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6252. EXPECT_LE(elapsed, 1000);
  6253. EXPECT_EQ("close", res->get_header_value("Connection"));
  6254. EXPECT_FALSE(cli_.is_socket_open());
  6255. }
  6256. TEST_F(ServerTest, AlmostTooLongRequest) {
  6257. // test for #2046 - URI length check shouldn't include other content on req
  6258. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6259. // leading /, space, HTTP/1.1)
  6260. std::string request =
  6261. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6262. auto res = cli_.Get(request.c_str());
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6265. }
  6266. TEST_F(ServerTest, LongHeader) {
  6267. Request req;
  6268. req.method = "GET";
  6269. req.path = "/hi";
  6270. std::string host_and_port;
  6271. host_and_port += HOST;
  6272. host_and_port += ":";
  6273. host_and_port += std::to_string(PORT);
  6274. req.headers.emplace("Host", host_and_port.c_str());
  6275. req.headers.emplace("Accept", "*/*");
  6276. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6277. req.headers.emplace(
  6278. "Header-Name",
  6279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6286. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6305. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6306. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6307. "@@@@@@@@@@@@@@@@");
  6308. auto res = std::make_shared<Response>();
  6309. auto error = Error::Success;
  6310. auto ret = cli_.send(req, *res, error);
  6311. ASSERT_TRUE(ret);
  6312. EXPECT_EQ(StatusCode::OK_200, res->status);
  6313. }
  6314. TEST_F(ServerTest, LongQueryValue) {
  6315. auto start = std::chrono::high_resolution_clock::now();
  6316. cli_.set_keep_alive(true);
  6317. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6318. auto end = std::chrono::high_resolution_clock::now();
  6319. auto elapsed =
  6320. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6321. .count();
  6322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6323. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6324. EXPECT_LE(elapsed, 1000);
  6325. EXPECT_EQ("close", res->get_header_value("Connection"));
  6326. EXPECT_FALSE(cli_.is_socket_open());
  6327. }
  6328. TEST_F(ServerTest, TooLongQueryValue) {
  6329. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6330. ASSERT_FALSE(res);
  6331. EXPECT_EQ(Error::Read, res.error());
  6332. }
  6333. TEST_F(ServerTest, TooLongHeader) {
  6334. Request req;
  6335. req.method = "GET";
  6336. req.path = "/hi";
  6337. std::string host_and_port;
  6338. host_and_port += HOST;
  6339. host_and_port += ":";
  6340. host_and_port += std::to_string(PORT);
  6341. req.headers.emplace("Host", host_and_port.c_str());
  6342. req.headers.emplace("Accept", "*/*");
  6343. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6344. req.headers.emplace(
  6345. "Header-Name",
  6346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6373. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6374. "@@@@@@@@@@@@@@@@@");
  6375. auto res = std::make_shared<Response>();
  6376. auto error = Error::Success;
  6377. auto ret = cli_.send(req, *res, error);
  6378. ASSERT_TRUE(ret);
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. }
  6381. TEST_F(ServerTest, HeaderCountAtLimit) {
  6382. // Test with headers just under the 100 limit
  6383. httplib::Headers headers;
  6384. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6385. // This should keep us just under the 100 header limit
  6386. for (int i = 0; i < 95; i++) {
  6387. std::string name = "X-Test-Header-" + std::to_string(i);
  6388. std::string value = "value" + std::to_string(i);
  6389. headers.emplace(name, value);
  6390. }
  6391. // This should work fine as we're under the limit
  6392. auto res = cli_.Get("/hi", headers);
  6393. EXPECT_TRUE(res);
  6394. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6395. }
  6396. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6397. // Test with many headers to exceed the 100 limit
  6398. httplib::Headers headers;
  6399. // Add 150 headers to definitely exceed the 100 limit
  6400. for (int i = 0; i < 150; i++) {
  6401. std::string name = "X-Test-Header-" + std::to_string(i);
  6402. std::string value = "value" + std::to_string(i);
  6403. headers.emplace(name, value);
  6404. }
  6405. // This should fail due to exceeding header count limit
  6406. cli_.set_keep_alive(true);
  6407. auto res = cli_.Get("/hi", headers);
  6408. // The server should respond with 400 Bad Request
  6409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6410. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6411. EXPECT_EQ("close", res->get_header_value("Connection"));
  6412. EXPECT_FALSE(cli_.is_socket_open());
  6413. }
  6414. TEST_F(ServerTest, PercentEncoding) {
  6415. auto res = cli_.Get("/e%6edwith%");
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::OK_200, res->status);
  6418. }
  6419. TEST_F(ServerTest, PercentEncodingUnicode) {
  6420. auto res = cli_.Get("/e%u006edwith%");
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::OK_200, res->status);
  6423. }
  6424. TEST_F(ServerTest, InvalidPercentEncoding) {
  6425. auto res = cli_.Get("/%endwith%");
  6426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6427. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6428. }
  6429. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6430. auto res = cli_.Get("/%uendwith%");
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6433. }
  6434. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6435. auto res = cli_.Get("/hello?aaa=bbb%");
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6438. }
  6439. TEST_F(ServerTest, PlusSignEncoding) {
  6440. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ("a +b", res->body);
  6444. }
  6445. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6446. // This test simulates a potential DoS attack using many headers
  6447. // to verify our security fix prevents memory exhaustion
  6448. httplib::Headers attack_headers;
  6449. // Attempt to add many headers like an attacker would (200 headers to far
  6450. // exceed limit)
  6451. for (int i = 0; i < 200; i++) {
  6452. std::string name = "X-Attack-Header-" + std::to_string(i);
  6453. std::string value = "attack_payload_" + std::to_string(i);
  6454. attack_headers.emplace(name, value);
  6455. }
  6456. // Try to POST with excessive headers
  6457. cli_.set_keep_alive(true);
  6458. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6459. // Should either fail or return 400 Bad Request due to security limit
  6460. if (res) {
  6461. // If we get a response, it should be 400 Bad Request
  6462. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6463. EXPECT_EQ("close", res->get_header_value("Connection"));
  6464. }
  6465. EXPECT_FALSE(cli_.is_socket_open());
  6466. }
  6467. TEST_F(ServerTest, MultipartFormData) {
  6468. UploadFormDataItems items = {
  6469. {"text1", "text default", "", ""},
  6470. {"text2", "aωb", "", ""},
  6471. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6472. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6473. {"file3", "", "", "application/octet-stream"},
  6474. {"file4", "", "", " application/json tmp-string "}};
  6475. auto res = cli_.Post("/multipart", items);
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::OK_200, res->status);
  6478. }
  6479. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6480. UploadFormDataItems items = {
  6481. {"text", "default text", "", ""},
  6482. {"multi_text1", "aaaaa", "", ""},
  6483. {"multi_text1", "bbbbb", "", ""},
  6484. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6485. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6486. "application/json"},
  6487. };
  6488. auto res = cli_.Post("/multipart/multi_file_values", items);
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ(StatusCode::OK_200, res->status);
  6491. }
  6492. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6493. auto res = cli_.Get("/hi");
  6494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6495. EXPECT_EQ(StatusCode::OK_200, res->status);
  6496. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6497. EXPECT_EQ("Hello World!", res->body);
  6498. }
  6499. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6500. Request req;
  6501. req.method = "POST";
  6502. req.path = "/chunked";
  6503. std::string host_and_port;
  6504. host_and_port += HOST;
  6505. host_and_port += ":";
  6506. host_and_port += std::to_string(PORT);
  6507. req.headers.emplace("Host", host_and_port.c_str());
  6508. req.headers.emplace("Accept", "*/*");
  6509. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6510. req.headers.emplace("Content-Type", "text/plain");
  6511. req.headers.emplace("Content-Length", "0");
  6512. req.headers.emplace(
  6513. "Transfer-Encoding",
  6514. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6515. // Client does not chunk, so make a chunked body manually.
  6516. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6517. auto res = std::make_shared<Response>();
  6518. auto error = Error::Success;
  6519. auto ret = cli_.send(req, *res, error);
  6520. ASSERT_TRUE(ret);
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. }
  6523. template <typename ClientT>
  6524. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6525. int expected_status) {
  6526. Request req;
  6527. req.method = "POST";
  6528. req.path = "/chunked";
  6529. std::string host_and_port;
  6530. host_and_port += HOST;
  6531. host_and_port += ":";
  6532. host_and_port += std::to_string(PORT);
  6533. req.headers.emplace("Host", host_and_port.c_str());
  6534. req.headers.emplace("Content-Length", "0");
  6535. req.headers.emplace("Transfer-Encoding", "chunked");
  6536. req.body = body;
  6537. auto res = std::make_shared<Response>();
  6538. auto error = Error::Success;
  6539. ASSERT_TRUE(cli.send(req, *res, error));
  6540. EXPECT_EQ(expected_status, res->status);
  6541. }
  6542. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6543. // rather than treat them as valid lengths.
  6544. template <typename ClientT>
  6545. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6546. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6547. }
  6548. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6549. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6550. }
  6551. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6552. expect_chunked_body_rejected(
  6553. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6554. }
  6555. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6556. // chunk-size line carries no CR, LF or other control character ahead of its
  6557. // terminator. Such a line must be refused rather than read as extension text.
  6558. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6559. expect_chunked_body_rejected(
  6560. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6561. }
  6562. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6563. expect_chunked_body_rejected(
  6564. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6565. }
  6566. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6567. expect_chunked_body_rejected(
  6568. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6569. }
  6570. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6571. // The literal stays split: a hex escape consumes every hex digit that
  6572. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6573. expect_chunked_body_rejected(
  6574. cli_, "4;a\x01"
  6575. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6576. }
  6577. TEST_F(ServerTest, AcceptsChunkExtension) {
  6578. expect_chunked_body_status(cli_,
  6579. "4;name=value\r\ndech\r\n"
  6580. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6581. "0;last\r\n\r\n",
  6582. StatusCode::OK_200);
  6583. }
  6584. TEST_F(ServerTest, GetStreamed2) {
  6585. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6588. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6589. EXPECT_EQ(true, res->has_header("Content-Range"));
  6590. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6591. EXPECT_EQ(std::string("ab"), res->body);
  6592. }
  6593. TEST_F(ServerTest, GetStreamed) {
  6594. auto res = cli_.Get("/streamed");
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6598. EXPECT_EQ(std::string("aaabbb"), res->body);
  6599. }
  6600. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6601. auto res = cli_.Get("/streamed-without-length",
  6602. Headers{make_range_header({{0, -1}})});
  6603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. EXPECT_EQ(false, res->has_header("Content-Length"));
  6606. EXPECT_EQ(false, res->has_header("Content-Range"));
  6607. EXPECT_EQ(std::string("abcdefg"), res->body);
  6608. }
  6609. TEST_F(ServerTest, GetStreamedWithRange1) {
  6610. auto res =
  6611. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6614. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6615. EXPECT_EQ(true, res->has_header("Content-Range"));
  6616. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6617. EXPECT_EQ(std::string("def"), res->body);
  6618. }
  6619. TEST_F(ServerTest, GetStreamedWithRange2) {
  6620. auto res =
  6621. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6624. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6625. EXPECT_EQ(true, res->has_header("Content-Range"));
  6626. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6627. EXPECT_EQ(std::string("bcdefg"), res->body);
  6628. }
  6629. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6630. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6633. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6634. EXPECT_EQ(true, res->has_header("Content-Range"));
  6635. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6636. EXPECT_EQ(std::string("efg"), res->body);
  6637. }
  6638. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6639. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6640. // the entire representation.
  6641. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6642. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6644. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6645. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6646. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6647. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6648. }
  6649. }
  6650. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6651. auto res =
  6652. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6655. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6656. EXPECT_EQ(false, res->has_header("Content-Range"));
  6657. EXPECT_EQ(0U, res->body.size());
  6658. }
  6659. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6660. // Only a 206 is served as a partial representation. Under any other status
  6661. // `apply_ranges()` reported the full content length, so the body must match
  6662. // that header, and the content provider must never be asked for an offset
  6663. // outside the representation.
  6664. auto check = [&](int status, const char *range) {
  6665. auto path =
  6666. std::string("/streamed-with-range?status=") + std::to_string(status);
  6667. auto ctx = path + " Range: " + range;
  6668. auto res = cli_.Get(path, Headers{{"Range", range}});
  6669. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6670. EXPECT_EQ(status, res->status) << ctx;
  6671. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6672. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6673. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6674. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6675. };
  6676. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6677. check(403, "bytes=3-5");
  6678. // The offset is far past the representation.
  6679. check(403, "bytes=100000-100200");
  6680. // `first_pos` is still -1 here, and the bounds asserts in
  6681. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6682. check(403, "bytes=-3");
  6683. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6684. // multipart branch would have written one that is empty.
  6685. check(403, "bytes=1-2, 4-5");
  6686. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6687. // covers the whole representation.
  6688. check(200, "bytes=3-5");
  6689. check(200, "bytes=1-2, 4-5");
  6690. }
  6691. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6692. auto res =
  6693. cli_.Get("/streamed-with-range",
  6694. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6695. "92233720368547758079223372036854775807"}});
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6698. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6699. EXPECT_EQ(false, res->has_header("Content-Range"));
  6700. EXPECT_EQ(0U, res->body.size());
  6701. }
  6702. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6703. auto res = cli_.Get(
  6704. "/with-range",
  6705. Headers{{"Range",
  6706. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6707. {"Accept-Encoding", ""}});
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6710. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6711. EXPECT_EQ(true, res->has_header("Content-Range"));
  6712. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6713. EXPECT_EQ(std::string("abcdefg"), res->body);
  6714. }
  6715. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6716. auto res = cli_.Get("/with-range", Headers{
  6717. {"Range", "bytes=0-"},
  6718. {"Accept-Encoding", ""},
  6719. });
  6720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6722. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6723. EXPECT_EQ(true, res->has_header("Content-Range"));
  6724. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6725. EXPECT_EQ(std::string("abcdefg"), res->body);
  6726. }
  6727. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6728. auto res = cli_.Get("/streamed-with-range",
  6729. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6732. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6733. EXPECT_EQ(false, res->has_header("Content-Range"));
  6734. EXPECT_EQ(267U, res->body.size());
  6735. // Check that both range contents are present
  6736. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6737. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6738. // Check that Content-Range headers are present for both ranges
  6739. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6740. std::string::npos);
  6741. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6742. std::string::npos);
  6743. }
  6744. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6745. Ranges ranges;
  6746. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6747. ranges.emplace_back(0, -1);
  6748. }
  6749. auto res = cli_.Get("/streamed-with-range?error",
  6750. Headers{{make_range_header(ranges)}});
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6753. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6754. EXPECT_EQ(false, res->has_header("Content-Range"));
  6755. EXPECT_EQ(0U, res->body.size());
  6756. }
  6757. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6758. auto res = cli_.Get("/streamed-with-range",
  6759. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6762. EXPECT_EQ(5U, res->body.size());
  6763. // Check that overlapping ranges are coalesced into a single range
  6764. EXPECT_EQ("bcdef", res->body);
  6765. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6766. // Should be single range, not multipart
  6767. EXPECT_TRUE(res->has_header("Content-Range"));
  6768. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6769. }
  6770. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6771. auto res = cli_.Get("/streamed-with-range",
  6772. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6775. EXPECT_EQ(268U, res->body.size());
  6776. // Check that both range contents are present
  6777. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6778. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6779. // Check that Content-Range headers are present for both ranges
  6780. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6781. std::string::npos);
  6782. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6783. std::string::npos);
  6784. }
  6785. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6786. auto res = cli_.Get("/streamed-with-range",
  6787. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6789. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6790. EXPECT_EQ(269U, res->body.size());
  6791. // Check that both duplicate range contents are present
  6792. size_t first_abc = res->body.find("abc\r\n");
  6793. EXPECT_TRUE(first_abc != std::string::npos);
  6794. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6795. EXPECT_TRUE(second_abc != std::string::npos);
  6796. // Check that Content-Range headers are present for both ranges
  6797. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6798. EXPECT_TRUE(first_range != std::string::npos);
  6799. size_t second_range =
  6800. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6801. EXPECT_TRUE(second_range != std::string::npos);
  6802. }
  6803. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6804. auto res =
  6805. cli_.Get("/streamed-with-range?error",
  6806. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6809. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6810. EXPECT_EQ(false, res->has_header("Content-Range"));
  6811. EXPECT_EQ(0U, res->body.size());
  6812. }
  6813. TEST_F(ServerTest, GetStreamedEndless) {
  6814. uint64_t offset = 0;
  6815. auto res = cli_.Get("/streamed-cancel",
  6816. [&](const char * /*data*/, uint64_t data_length) {
  6817. if (offset < 100) {
  6818. offset += data_length;
  6819. return true;
  6820. }
  6821. return false;
  6822. });
  6823. ASSERT_TRUE(!res);
  6824. EXPECT_EQ(Error::Canceled, res.error());
  6825. }
  6826. TEST_F(ServerTest, ClientStop) {
  6827. std::atomic_size_t count{4};
  6828. std::vector<std::thread> threads;
  6829. for (auto i = count.load(); i != 0; --i) {
  6830. threads.emplace_back([&]() {
  6831. auto res = cli_.Get("/streamed-cancel",
  6832. [&](const char *, uint64_t) { return true; });
  6833. --count;
  6834. ASSERT_TRUE(!res);
  6835. EXPECT_TRUE(res.error() == Error::Canceled ||
  6836. res.error() == Error::Read || res.error() == Error::Write);
  6837. });
  6838. }
  6839. std::this_thread::sleep_for(std::chrono::seconds(2));
  6840. while (count != 0) {
  6841. cli_.stop();
  6842. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6843. }
  6844. for (auto &t : threads) {
  6845. t.join();
  6846. }
  6847. }
  6848. TEST_F(ServerTest, GetWithRange1) {
  6849. auto res = cli_.Get("/with-range", Headers{
  6850. make_range_header({{3, 5}}),
  6851. {"Accept-Encoding", ""},
  6852. });
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6855. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6856. EXPECT_EQ(true, res->has_header("Content-Range"));
  6857. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6858. EXPECT_EQ(std::string("def"), res->body);
  6859. }
  6860. TEST_F(ServerTest, GetWithRange2) {
  6861. auto res = cli_.Get("/with-range", Headers{
  6862. make_range_header({{1, -1}}),
  6863. {"Accept-Encoding", ""},
  6864. });
  6865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6866. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6867. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6868. EXPECT_EQ(true, res->has_header("Content-Range"));
  6869. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6870. EXPECT_EQ(std::string("bcdefg"), res->body);
  6871. }
  6872. TEST_F(ServerTest, GetWithRange3) {
  6873. auto res = cli_.Get("/with-range", Headers{
  6874. make_range_header({{0, 0}}),
  6875. {"Accept-Encoding", ""},
  6876. });
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6879. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6880. EXPECT_EQ(true, res->has_header("Content-Range"));
  6881. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6882. EXPECT_EQ(std::string("a"), res->body);
  6883. }
  6884. TEST_F(ServerTest, GetWithRange4) {
  6885. auto res = cli_.Get("/with-range", Headers{
  6886. make_range_header({{-1, 2}}),
  6887. {"Accept-Encoding", ""},
  6888. });
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6891. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6892. EXPECT_EQ(true, res->has_header("Content-Range"));
  6893. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6894. EXPECT_EQ(std::string("fg"), res->body);
  6895. }
  6896. TEST_F(ServerTest, GetWithRange5) {
  6897. auto res = cli_.Get("/with-range", Headers{
  6898. make_range_header({{0, 5}}),
  6899. {"Accept-Encoding", ""},
  6900. });
  6901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6902. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6903. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6904. EXPECT_EQ(true, res->has_header("Content-Range"));
  6905. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6906. EXPECT_EQ(std::string("abcdef"), res->body);
  6907. }
  6908. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6909. auto res =
  6910. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6913. }
  6914. TEST_F(ServerTest, GetWithRangeMultipart) {
  6915. auto res =
  6916. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6919. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6920. EXPECT_EQ(false, res->has_header("Content-Range"));
  6921. EXPECT_EQ(267U, res->body.size());
  6922. }
  6923. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6924. auto res = cli_.Get("/with-range",
  6925. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6927. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6928. }
  6929. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6930. auto res = cli_.Get("/with-range-customized-response",
  6931. Headers{{make_range_header({{1, 2}})}});
  6932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6933. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6934. EXPECT_EQ(true, res->has_header("Content-Length"));
  6935. EXPECT_EQ(false, res->has_header("Content-Range"));
  6936. EXPECT_EQ(JSON_DATA, res->body);
  6937. }
  6938. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6939. auto res = cli_.Get("/with-range-customized-response",
  6940. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6943. EXPECT_EQ(true, res->has_header("Content-Length"));
  6944. EXPECT_EQ(false, res->has_header("Content-Range"));
  6945. EXPECT_EQ(JSON_DATA, res->body);
  6946. }
  6947. TEST_F(ServerTest, Issue1772) {
  6948. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6950. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6951. }
  6952. TEST_F(ServerTest, Issue609) {
  6953. auto res = cli_.Delete("/issue609");
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::OK_200, res->status);
  6956. EXPECT_EQ(std::string("ok"), res->body);
  6957. }
  6958. TEST_F(ServerTest, GetStreamedChunked) {
  6959. auto res = cli_.Get("/streamed-chunked");
  6960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6961. EXPECT_EQ(StatusCode::OK_200, res->status);
  6962. EXPECT_EQ(std::string("123456789"), res->body);
  6963. }
  6964. TEST_F(ServerTest, GetStreamedChunked2) {
  6965. auto res = cli_.Get("/streamed-chunked2");
  6966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6967. EXPECT_EQ(StatusCode::OK_200, res->status);
  6968. EXPECT_EQ(std::string("123456789"), res->body);
  6969. }
  6970. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6971. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6973. EXPECT_EQ(StatusCode::OK_200, res->status);
  6974. EXPECT_EQ(std::string("123456789"), res->body);
  6975. EXPECT_TRUE(res->has_header("Trailer"));
  6976. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6977. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6978. // Trailers are now stored separately from headers (security fix)
  6979. EXPECT_EQ(2U, res->trailers.size());
  6980. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6981. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6982. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6983. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6984. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6985. // Verify trailers are NOT in headers (security verification)
  6986. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6987. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6988. }
  6989. TEST_F(ServerTest, LargeChunkedPost) {
  6990. Request req;
  6991. req.method = "POST";
  6992. req.path = "/large-chunked";
  6993. std::string host_and_port;
  6994. host_and_port += HOST;
  6995. host_and_port += ":";
  6996. host_and_port += std::to_string(PORT);
  6997. req.headers.emplace("Host", host_and_port.c_str());
  6998. req.headers.emplace("Accept", "*/*");
  6999. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7000. req.headers.emplace("Content-Type", "text/plain");
  7001. req.headers.emplace("Content-Length", "0");
  7002. req.headers.emplace("Transfer-Encoding", "chunked");
  7003. std::string long_string(30 * 1024u, 'a');
  7004. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7005. // Attempt to make a large enough post to exceed OS buffers, to test that
  7006. // the server handles short reads if the full chunk data isn't available.
  7007. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7008. auto res = std::make_shared<Response>();
  7009. auto error = Error::Success;
  7010. auto ret = cli_.send(req, *res, error);
  7011. ASSERT_TRUE(ret);
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. }
  7014. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7015. auto res = cli_.Get("/remote_addr");
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::OK_200, res->status);
  7018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7019. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7020. }
  7021. TEST_F(ServerTest, GetMethodLocalAddr) {
  7022. auto res = cli_.Get("/local_addr");
  7023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7024. EXPECT_EQ(StatusCode::OK_200, res->status);
  7025. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7026. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7027. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7028. }
  7029. TEST_F(ServerTest, HTTPResponseSplitting) {
  7030. auto res = cli_.Get("/http_response_splitting");
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::OK_200, res->status);
  7033. }
  7034. TEST_F(ServerTest, SlowRequest) {
  7035. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7036. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7037. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7038. }
  7039. #if 0
  7040. TEST_F(ServerTest, SlowPost) {
  7041. char buffer[64 * 1024];
  7042. memset(buffer, 0x42, sizeof(buffer));
  7043. auto res = cli_.Post(
  7044. "/slowpost", 64 * 1024 * 1024,
  7045. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7046. auto ret = sink.write(buffer, sizeof(buffer));
  7047. EXPECT_TRUE(ret);
  7048. return true;
  7049. },
  7050. "text/plain");
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. }
  7054. TEST_F(ServerTest, SlowPostFail) {
  7055. char buffer[64 * 1024];
  7056. memset(buffer, 0x42, sizeof(buffer));
  7057. cli_.set_write_timeout(std::chrono::seconds(0));
  7058. auto res = cli_.Post(
  7059. "/slowpost", 64 * 1024 * 1024,
  7060. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7061. sink.write(buffer, sizeof(buffer));
  7062. return true;
  7063. },
  7064. "text/plain");
  7065. ASSERT_TRUE(!res);
  7066. EXPECT_EQ(Error::Write, res.error());
  7067. }
  7068. #endif
  7069. TEST_F(ServerTest, Put) {
  7070. auto res = cli_.Put("/put", "PUT", "text/plain");
  7071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7072. EXPECT_EQ(StatusCode::OK_200, res->status);
  7073. EXPECT_EQ("PUT", res->body);
  7074. }
  7075. TEST_F(ServerTest, PutWithContentProvider) {
  7076. auto res = cli_.Put(
  7077. "/put", 3,
  7078. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7079. sink.os << "PUT";
  7080. return true;
  7081. },
  7082. "text/plain");
  7083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7084. EXPECT_EQ(StatusCode::OK_200, res->status);
  7085. EXPECT_EQ("PUT", res->body);
  7086. }
  7087. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7088. auto res = cli_.Post(
  7089. "/post", 42,
  7090. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7091. return false;
  7092. },
  7093. "text/plain");
  7094. ASSERT_TRUE(!res);
  7095. EXPECT_EQ(Error::Canceled, res.error());
  7096. }
  7097. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7098. auto res = cli_.Put(
  7099. "/put",
  7100. [](size_t /*offset*/, DataSink &sink) {
  7101. sink.os << "PUT";
  7102. sink.done();
  7103. return true;
  7104. },
  7105. "text/plain");
  7106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7107. EXPECT_EQ(StatusCode::OK_200, res->status);
  7108. EXPECT_EQ("PUT", res->body);
  7109. }
  7110. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7111. auto res = cli_.Post(
  7112. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7113. "text/plain");
  7114. ASSERT_TRUE(!res);
  7115. EXPECT_EQ(Error::Canceled, res.error());
  7116. }
  7117. TEST_F(ServerTest, PostLoopBack) {
  7118. std::string body;
  7119. auto res = cli_.Post(
  7120. "/post-loopback", 9,
  7121. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7122. EXPECT_EQ(9u, length);
  7123. sink.write("123", 3);
  7124. sink.write("456", 3);
  7125. sink.write("789", 3);
  7126. return true;
  7127. },
  7128. "text/plain",
  7129. [&body](const char *data, size_t data_length) {
  7130. body.append(data, data_length);
  7131. return true;
  7132. });
  7133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7134. EXPECT_EQ(StatusCode::OK_200, res->status);
  7135. EXPECT_EQ("123456789", body);
  7136. }
  7137. TEST_F(ServerTest, PutLoopBack) {
  7138. std::string body;
  7139. auto res = cli_.Put(
  7140. "/put-loopback", 9,
  7141. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7142. EXPECT_EQ(9u, length);
  7143. sink.write("123", 3);
  7144. sink.write("456", 3);
  7145. sink.write("789", 3);
  7146. return true;
  7147. },
  7148. "text/plain",
  7149. [&body](const char *data, size_t data_length) {
  7150. body.append(data, data_length);
  7151. return true;
  7152. });
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. EXPECT_EQ("123456789", body);
  7156. }
  7157. TEST_F(ServerTest, PatchLoopBack) {
  7158. std::string body;
  7159. auto res = cli_.Patch(
  7160. "/patch-loopback", 9,
  7161. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7162. EXPECT_EQ(9u, length);
  7163. sink.write("123", 3);
  7164. sink.write("456", 3);
  7165. sink.write("789", 3);
  7166. return true;
  7167. },
  7168. "text/plain",
  7169. [&body](const char *data, size_t data_length) {
  7170. body.append(data, data_length);
  7171. return true;
  7172. });
  7173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7174. EXPECT_EQ(StatusCode::OK_200, res->status);
  7175. EXPECT_EQ("123456789", body);
  7176. }
  7177. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7178. std::string body;
  7179. auto res = cli_.Post(
  7180. "/post-loopback",
  7181. [](size_t /*offset*/, DataSink &sink) {
  7182. sink.write("123", 3);
  7183. sink.write("456", 3);
  7184. sink.write("789", 3);
  7185. sink.done();
  7186. return true;
  7187. },
  7188. "text/plain",
  7189. [&body](const char *data, size_t data_length) {
  7190. body.append(data, data_length);
  7191. return true;
  7192. });
  7193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7194. EXPECT_EQ(StatusCode::OK_200, res->status);
  7195. EXPECT_EQ("123456789", body);
  7196. }
  7197. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7198. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7199. cli_.set_compress(true);
  7200. auto res = cli_.Put(
  7201. "/put", 3,
  7202. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7203. sink.os << "PUT";
  7204. return true;
  7205. },
  7206. "text/plain");
  7207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7208. EXPECT_EQ(StatusCode::OK_200, res->status);
  7209. EXPECT_EQ("PUT", res->body);
  7210. }
  7211. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7212. cli_.set_compress(true);
  7213. auto res = cli_.Post(
  7214. "/post", 42,
  7215. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7216. return false;
  7217. },
  7218. "text/plain");
  7219. ASSERT_TRUE(!res);
  7220. EXPECT_EQ(Error::Canceled, res.error());
  7221. }
  7222. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7223. cli_.set_compress(true);
  7224. auto res = cli_.Put(
  7225. "/put",
  7226. [](size_t /*offset*/, DataSink &sink) {
  7227. sink.os << "PUT";
  7228. sink.done();
  7229. return true;
  7230. },
  7231. "text/plain");
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::OK_200, res->status);
  7234. EXPECT_EQ("PUT", res->body);
  7235. }
  7236. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7237. cli_.set_compress(true);
  7238. auto res = cli_.Post(
  7239. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7240. "text/plain");
  7241. ASSERT_TRUE(!res);
  7242. EXPECT_EQ(Error::Canceled, res.error());
  7243. }
  7244. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7245. cli_.set_compress(true);
  7246. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::OK_200, res->status);
  7249. EXPECT_EQ(LARGE_DATA, res->body);
  7250. }
  7251. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7252. #ifdef CPPHTTPLIB_SSL_ENABLED
  7253. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7254. Client cli(s.c_str());
  7255. cli.enable_server_certificate_verification(false);
  7256. #else
  7257. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7258. Client cli(s.c_str());
  7259. #endif
  7260. cli.set_compress(true);
  7261. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::OK_200, res->status);
  7264. EXPECT_EQ(LARGE_DATA, res->body);
  7265. // The compressed size should be less than a 10th of the original. May vary
  7266. // depending on the zlib library.
  7267. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7268. static_cast<uint64_t>(10 * 1024 * 1024));
  7269. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7270. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7271. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7272. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7273. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7274. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7275. #endif
  7276. }
  7277. TEST_F(ServerTest, PutContentWithDeflate) {
  7278. cli_.set_compress(false);
  7279. Headers headers;
  7280. headers.emplace("Content-Encoding", "deflate");
  7281. // PUT in deflate format:
  7282. auto res = cli_.Put("/put", headers,
  7283. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7285. EXPECT_EQ(StatusCode::OK_200, res->status);
  7286. EXPECT_EQ("PUT", res->body);
  7287. }
  7288. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7289. Headers headers;
  7290. headers.emplace("Accept-Encoding", "gzip, deflate");
  7291. auto res = cli_.Get("/streamed-chunked", headers);
  7292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7293. EXPECT_EQ(StatusCode::OK_200, res->status);
  7294. EXPECT_EQ(std::string("123456789"), res->body);
  7295. }
  7296. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7297. Headers headers;
  7298. headers.emplace("Accept-Encoding", "gzip, deflate");
  7299. auto res = cli_.Get("/streamed-chunked2", headers);
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ(std::string("123456789"), res->body);
  7303. }
  7304. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7305. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7307. EXPECT_EQ(StatusCode::OK_200, res->status);
  7308. }
  7309. TEST(GzipDecompressor, ChunkedDecompression) {
  7310. std::string data;
  7311. for (size_t i = 0; i < 32 * 1024; ++i) {
  7312. data.push_back(static_cast<char>('a' + i % 26));
  7313. }
  7314. std::string compressed_data;
  7315. {
  7316. httplib::detail::gzip_compressor compressor;
  7317. bool result = compressor.compress(
  7318. data.data(), data.size(),
  7319. /*last=*/true,
  7320. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7321. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7322. compressed_data_size);
  7323. return true;
  7324. });
  7325. ASSERT_TRUE(result);
  7326. }
  7327. std::string decompressed_data;
  7328. {
  7329. httplib::detail::gzip_decompressor decompressor;
  7330. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7331. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7332. size_t chunk_size = 130;
  7333. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7334. chunk_begin += chunk_size) {
  7335. size_t current_chunk_size =
  7336. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7337. bool result = decompressor.decompress(
  7338. compressed_data.data() + chunk_begin, current_chunk_size,
  7339. [&](const char *decompressed_data_chunk,
  7340. size_t decompressed_data_chunk_size) {
  7341. decompressed_data.insert(decompressed_data.size(),
  7342. decompressed_data_chunk,
  7343. decompressed_data_chunk_size);
  7344. return true;
  7345. });
  7346. ASSERT_TRUE(result);
  7347. }
  7348. }
  7349. ASSERT_EQ(data, decompressed_data);
  7350. }
  7351. TEST(GzipDecompressor, DeflateDecompression) {
  7352. std::string original_text = "Raw deflate without gzip";
  7353. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7354. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7355. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7356. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7357. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7358. std::string decompressed_data;
  7359. {
  7360. httplib::detail::gzip_decompressor decompressor;
  7361. bool result = decompressor.decompress(
  7362. compressed_data.data(), compressed_data.size(),
  7363. [&](const char *decompressed_data_chunk,
  7364. size_t decompressed_data_chunk_size) {
  7365. decompressed_data.insert(decompressed_data.size(),
  7366. decompressed_data_chunk,
  7367. decompressed_data_chunk_size);
  7368. return true;
  7369. });
  7370. ASSERT_TRUE(result);
  7371. }
  7372. ASSERT_EQ(original_text, decompressed_data);
  7373. }
  7374. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7375. std::string original_text = "Raw deflate without gzip";
  7376. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7377. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7378. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7379. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7380. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7381. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7382. std::string decompressed_data;
  7383. {
  7384. httplib::detail::gzip_decompressor decompressor;
  7385. bool result = decompressor.decompress(
  7386. compressed_data.data(), compressed_data.size(),
  7387. [&](const char *decompressed_data_chunk,
  7388. size_t decompressed_data_chunk_size) {
  7389. decompressed_data.insert(decompressed_data.size(),
  7390. decompressed_data_chunk,
  7391. decompressed_data_chunk_size);
  7392. return true;
  7393. });
  7394. ASSERT_TRUE(result);
  7395. }
  7396. ASSERT_EQ(original_text, decompressed_data);
  7397. }
  7398. #endif
  7399. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7400. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7401. Headers headers;
  7402. headers.emplace("Accept-Encoding", "br");
  7403. auto res = cli_.Get("/streamed-chunked", headers);
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. EXPECT_EQ(std::string("123456789"), res->body);
  7407. }
  7408. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7409. Headers headers;
  7410. headers.emplace("Accept-Encoding", "br");
  7411. auto res = cli_.Get("/streamed-chunked2", headers);
  7412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7413. EXPECT_EQ(StatusCode::OK_200, res->status);
  7414. EXPECT_EQ(std::string("123456789"), res->body);
  7415. }
  7416. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7417. cli_.set_compress(true);
  7418. auto res = cli_.Put(
  7419. "/put", 3,
  7420. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7421. sink.os << "PUT";
  7422. return true;
  7423. },
  7424. "text/plain");
  7425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7426. EXPECT_EQ(StatusCode::OK_200, res->status);
  7427. EXPECT_EQ("PUT", res->body);
  7428. }
  7429. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7430. cli_.set_compress(true);
  7431. auto res = cli_.Put(
  7432. "/put",
  7433. [](size_t /*offset*/, DataSink &sink) {
  7434. sink.os << "PUT";
  7435. sink.done();
  7436. return true;
  7437. },
  7438. "text/plain");
  7439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7440. EXPECT_EQ(StatusCode::OK_200, res->status);
  7441. EXPECT_EQ("PUT", res->body);
  7442. }
  7443. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7444. cli_.set_compress(true);
  7445. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7447. EXPECT_EQ(StatusCode::OK_200, res->status);
  7448. EXPECT_EQ(LARGE_DATA, res->body);
  7449. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7450. }
  7451. #endif
  7452. TEST_F(ServerTest, Patch) {
  7453. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. EXPECT_EQ("PATCH", res->body);
  7457. }
  7458. TEST_F(ServerTest, Delete) {
  7459. auto res = cli_.Delete("/delete");
  7460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7461. EXPECT_EQ(StatusCode::OK_200, res->status);
  7462. EXPECT_EQ("DELETE", res->body);
  7463. }
  7464. TEST_F(ServerTest, DeleteContentReceiver) {
  7465. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. EXPECT_EQ("content", res->body);
  7469. }
  7470. TEST_F(ServerTest, Options) {
  7471. auto res = cli_.Options("*");
  7472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7473. EXPECT_EQ(StatusCode::OK_200, res->status);
  7474. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7475. EXPECT_TRUE(res->body.empty());
  7476. }
  7477. TEST_F(ServerTest, URL) {
  7478. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::OK_200, res->status);
  7481. }
  7482. TEST_F(ServerTest, ArrayParam) {
  7483. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7485. EXPECT_EQ(StatusCode::OK_200, res->status);
  7486. }
  7487. TEST_F(ServerTest, ArrayParamValues) {
  7488. auto res =
  7489. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7491. EXPECT_EQ(StatusCode::OK_200, res->status);
  7492. }
  7493. TEST_F(ServerTest, NoMultipleHeaders) {
  7494. Headers headers = {{"Content-Length", "5"}};
  7495. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7496. "text/plain");
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::OK_200, res->status);
  7499. }
  7500. TEST_F(ServerTest, PostContentReceiver) {
  7501. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7503. ASSERT_EQ(StatusCode::OK_200, res->status);
  7504. ASSERT_EQ("content", res->body);
  7505. }
  7506. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7507. UploadFormDataItems items = {
  7508. {"text1", "text default", "", ""},
  7509. {"text2", "aωb", "", ""},
  7510. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7511. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7512. {"file3", "", "", "application/octet-stream"},
  7513. };
  7514. auto res = cli_.Post("/content_receiver", items);
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. }
  7518. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7519. UploadFormDataItems items = {
  7520. {"text1", "text default", "", ""},
  7521. {"text2", "aωb", "", ""},
  7522. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7523. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7524. {"file3", "", "", "application/octet-stream"},
  7525. };
  7526. auto boundary = std::string("+++++");
  7527. std::string body;
  7528. for (const auto &item : items) {
  7529. body += "--" + boundary + "\r\n";
  7530. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7531. if (!item.filename.empty()) {
  7532. body += "; filename=\"" + item.filename + "\"";
  7533. }
  7534. body += "\r\n";
  7535. if (!item.content_type.empty()) {
  7536. body += "Content-Type: " + item.content_type + "\r\n";
  7537. }
  7538. body += "\r\n";
  7539. body += item.content + "\r\n";
  7540. }
  7541. body += "--" + boundary + "--\r\n";
  7542. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7543. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7545. EXPECT_EQ(StatusCode::OK_200, res->status);
  7546. }
  7547. TEST(MultipartFormDataTest, FieldEscaping) {
  7548. Server svr;
  7549. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7550. const ContentReader &content_reader) {
  7551. ASSERT_TRUE(req.is_multipart_form_data());
  7552. std::vector<FormData> received;
  7553. content_reader(
  7554. [&](const FormData &file) {
  7555. received.push_back(file);
  7556. return true;
  7557. },
  7558. [&](const char *data, size_t data_length) {
  7559. received.back().content.append(data, data_length);
  7560. return true;
  7561. });
  7562. // '"', CR and LF in names and filenames are escaped following the
  7563. // WHATWG HTML standard, so each part still parses as a single part
  7564. // with no injected headers. Content types get CR/LF escaped too,
  7565. // while '"' (legal there, e.g. quoted charset) is preserved.
  7566. ASSERT_EQ(4U, received.size());
  7567. EXPECT_EQ("na%22me", received[0].name);
  7568. EXPECT_EQ("quoted name", received[0].content);
  7569. EXPECT_EQ("file", received[1].name);
  7570. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7571. received[1].filename);
  7572. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7573. EXPECT_EQ("injected", received[1].content);
  7574. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7575. EXPECT_EQ("my%22file.txt", received[2].filename);
  7576. EXPECT_EQ("cr lf name", received[2].content);
  7577. EXPECT_EQ("typed", received[3].name);
  7578. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7579. received[3].content_type);
  7580. EXPECT_EQ("typed content", received[3].content);
  7581. });
  7582. auto port = svr.bind_to_any_port("localhost");
  7583. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7584. auto se = detail::scope_exit([&] {
  7585. svr.stop();
  7586. t.join();
  7587. ASSERT_FALSE(svr.is_running());
  7588. });
  7589. svr.wait_until_ready();
  7590. Client cli("localhost", port);
  7591. UploadFormDataItems items = {
  7592. {"na\"me", "quoted name", "", ""},
  7593. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7594. "application/octet-stream"},
  7595. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7596. {"typed", "typed content", "",
  7597. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7598. };
  7599. auto res = cli.Post("/post", items);
  7600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7601. EXPECT_EQ(StatusCode::OK_200, res->status);
  7602. }
  7603. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7604. const UploadFormDataItems items = {
  7605. {"name1", "Content 1", "", ""},
  7606. {"name2", "Content 2", "file2.txt", "text/plain"},
  7607. };
  7608. Server svr;
  7609. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7610. const ContentReader &content_reader) {
  7611. ASSERT_TRUE(req.is_multipart_form_data());
  7612. std::vector<FormData> received;
  7613. content_reader(
  7614. [&](const FormData &file) {
  7615. received.push_back(file);
  7616. return true;
  7617. },
  7618. [&](const char *data, size_t data_length) {
  7619. received.back().content.append(data, data_length);
  7620. return true;
  7621. });
  7622. ASSERT_EQ(2U, received.size());
  7623. EXPECT_EQ("name1", received[0].name);
  7624. EXPECT_EQ("Content 1", received[0].content);
  7625. EXPECT_EQ("name2", received[1].name);
  7626. EXPECT_EQ("Content 2", received[1].content);
  7627. EXPECT_EQ("file2.txt", received[1].filename);
  7628. EXPECT_EQ("text/plain", received[1].content_type);
  7629. });
  7630. auto port = svr.bind_to_any_port("localhost");
  7631. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7632. auto se = detail::scope_exit([&] {
  7633. svr.stop();
  7634. t.join();
  7635. ASSERT_FALSE(svr.is_running());
  7636. });
  7637. svr.wait_until_ready();
  7638. Client cli("localhost", port);
  7639. // Whole-body serialization with a generated boundary
  7640. {
  7641. MultipartFormDataWriter writer;
  7642. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7643. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7644. writer.content_type());
  7645. auto body = writer.serialize(items);
  7646. EXPECT_EQ(body.size(), writer.content_length(items));
  7647. auto res = cli.Post("/post", body, writer.content_type());
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. }
  7651. // Per-part framing with a custom boundary via a content provider
  7652. {
  7653. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7654. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7655. MultipartFormDataWriter writer("custom-boundary_123");
  7656. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7657. std::string body;
  7658. for (const auto &item : items) {
  7659. body += writer.item_begin(item);
  7660. body += item.content;
  7661. body += MultipartFormDataWriter::item_end();
  7662. }
  7663. body += writer.finish();
  7664. EXPECT_EQ(body.size(), writer.content_length(items));
  7665. auto res = cli.Post(
  7666. "/post", body.size(),
  7667. [&](size_t offset, size_t length, DataSink &sink) {
  7668. sink.write(body.data() + offset, length);
  7669. return true;
  7670. },
  7671. writer.content_type());
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::OK_200, res->status);
  7674. }
  7675. }
  7676. TEST_F(ServerTest, PostContentReceiverGzip) {
  7677. cli_.set_compress(true);
  7678. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. ASSERT_EQ(StatusCode::OK_200, res->status);
  7681. ASSERT_EQ("content", res->body);
  7682. }
  7683. TEST_F(ServerTest, PutContentReceiver) {
  7684. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7686. ASSERT_EQ(StatusCode::OK_200, res->status);
  7687. ASSERT_EQ("content", res->body);
  7688. }
  7689. TEST_F(ServerTest, PatchContentReceiver) {
  7690. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7692. ASSERT_EQ(StatusCode::OK_200, res->status);
  7693. ASSERT_EQ("content", res->body);
  7694. }
  7695. template <typename ClientType>
  7696. void TestWithHeadersAndContentReceiver(
  7697. ClientType &cli,
  7698. std::function<Result(ClientType &, const std::string &, const Headers &,
  7699. const std::string &, const std::string &,
  7700. ContentReceiver, DownloadProgress)>
  7701. request_func) {
  7702. Headers headers;
  7703. headers.emplace("X-Custom-Header", "test-value");
  7704. std::string received_body;
  7705. auto res = request_func(
  7706. cli, "/content_receiver", headers, "content", "application/json",
  7707. [&](const char *data, size_t data_length) {
  7708. received_body.append(data, data_length);
  7709. return true;
  7710. },
  7711. nullptr);
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ("content", received_body);
  7715. }
  7716. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7717. #ifdef CPPHTTPLIB_SSL_ENABLED
  7718. using ClientT = SSLClient;
  7719. #else
  7720. using ClientT = Client;
  7721. #endif
  7722. TestWithHeadersAndContentReceiver<ClientT>(
  7723. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7724. const std::string &body, const std::string &content_type,
  7725. ContentReceiver receiver, DownloadProgress progress) {
  7726. return cli.Post(path, headers, body, content_type, receiver, progress);
  7727. });
  7728. }
  7729. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7730. #ifdef CPPHTTPLIB_SSL_ENABLED
  7731. using ClientT = SSLClient;
  7732. #else
  7733. using ClientT = Client;
  7734. #endif
  7735. TestWithHeadersAndContentReceiver<ClientT>(
  7736. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7737. const std::string &body, const std::string &content_type,
  7738. ContentReceiver receiver, DownloadProgress progress) {
  7739. return cli.Put(path, headers, body, content_type, receiver, progress);
  7740. });
  7741. }
  7742. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7743. #ifdef CPPHTTPLIB_SSL_ENABLED
  7744. using ClientT = SSLClient;
  7745. #else
  7746. using ClientT = Client;
  7747. #endif
  7748. TestWithHeadersAndContentReceiver<ClientT>(
  7749. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7750. const std::string &body, const std::string &content_type,
  7751. ContentReceiver receiver, DownloadProgress progress) {
  7752. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7753. });
  7754. }
  7755. template <typename ClientType>
  7756. void TestWithHeadersAndContentReceiverWithProgress(
  7757. ClientType &cli,
  7758. std::function<Result(ClientType &, const std::string &, const Headers &,
  7759. const std::string &, const std::string &,
  7760. ContentReceiver, DownloadProgress)>
  7761. request_func) {
  7762. Headers headers;
  7763. headers.emplace("X-Test-Header", "progress-test");
  7764. std::string received_body;
  7765. auto progress_called = false;
  7766. auto res = request_func(
  7767. cli, "/content_receiver", headers, "content", "text/plain",
  7768. [&](const char *data, size_t data_length) {
  7769. received_body.append(data, data_length);
  7770. return true;
  7771. },
  7772. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7773. progress_called = true;
  7774. return true;
  7775. });
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::OK_200, res->status);
  7778. EXPECT_EQ("content", received_body);
  7779. EXPECT_TRUE(progress_called);
  7780. }
  7781. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7782. #ifdef CPPHTTPLIB_SSL_ENABLED
  7783. using ClientT = SSLClient;
  7784. #else
  7785. using ClientT = Client;
  7786. #endif
  7787. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7788. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7789. const std::string &body, const std::string &content_type,
  7790. ContentReceiver receiver, DownloadProgress progress) {
  7791. return cli.Post(path, headers, body, content_type, receiver, progress);
  7792. });
  7793. }
  7794. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7795. #ifdef CPPHTTPLIB_SSL_ENABLED
  7796. using ClientT = SSLClient;
  7797. #else
  7798. using ClientT = Client;
  7799. #endif
  7800. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7801. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7802. const std::string &body, const std::string &content_type,
  7803. ContentReceiver receiver, DownloadProgress progress) {
  7804. return cli.Put(path, headers, body, content_type, receiver, progress);
  7805. });
  7806. }
  7807. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7808. #ifdef CPPHTTPLIB_SSL_ENABLED
  7809. using ClientT = SSLClient;
  7810. #else
  7811. using ClientT = Client;
  7812. #endif
  7813. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7814. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7815. const std::string &body, const std::string &content_type,
  7816. ContentReceiver receiver, DownloadProgress progress) {
  7817. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7818. });
  7819. }
  7820. template <typename ClientType>
  7821. void TestWithHeadersAndContentReceiverError(
  7822. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7823. const Headers &, const std::string &,
  7824. const std::string &, ContentReceiver)>
  7825. request_func) {
  7826. Headers headers;
  7827. headers.emplace("X-Error-Test", "true");
  7828. std::string received_body;
  7829. auto receiver_failed = false;
  7830. auto res =
  7831. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7832. [&](const char *data, size_t data_length) {
  7833. received_body.append(data, data_length);
  7834. receiver_failed = true;
  7835. return false;
  7836. });
  7837. ASSERT_FALSE(res);
  7838. EXPECT_TRUE(receiver_failed);
  7839. }
  7840. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7841. #ifdef CPPHTTPLIB_SSL_ENABLED
  7842. using ClientT = SSLClient;
  7843. #else
  7844. using ClientT = Client;
  7845. #endif
  7846. TestWithHeadersAndContentReceiverError<ClientT>(
  7847. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7848. const std::string &body, const std::string &content_type,
  7849. ContentReceiver receiver) {
  7850. return cli.Post(path, headers, body, content_type, receiver);
  7851. });
  7852. }
  7853. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7854. #ifdef CPPHTTPLIB_SSL_ENABLED
  7855. using ClientT = SSLClient;
  7856. #else
  7857. using ClientT = Client;
  7858. #endif
  7859. TestWithHeadersAndContentReceiverError<ClientT>(
  7860. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7861. const std::string &body, const std::string &content_type,
  7862. ContentReceiver receiver) {
  7863. return cli.Put(path, headers, body, content_type, receiver);
  7864. });
  7865. }
  7866. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7867. #ifdef CPPHTTPLIB_SSL_ENABLED
  7868. using ClientT = SSLClient;
  7869. #else
  7870. using ClientT = Client;
  7871. #endif
  7872. TestWithHeadersAndContentReceiverError<ClientT>(
  7873. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7874. const std::string &body, const std::string &content_type,
  7875. ContentReceiver receiver) {
  7876. return cli.Patch(path, headers, body, content_type, receiver);
  7877. });
  7878. }
  7879. TEST_F(ServerTest, PostQueryStringAndBody) {
  7880. auto res =
  7881. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7883. ASSERT_EQ(StatusCode::OK_200, res->status);
  7884. }
  7885. TEST_F(ServerTest, HTTP2Magic) {
  7886. Request req;
  7887. req.method = "PRI";
  7888. req.path = "*";
  7889. req.body = "SM";
  7890. auto res = std::make_shared<Response>();
  7891. auto error = Error::Success;
  7892. auto ret = cli_.send(req, *res, error);
  7893. ASSERT_TRUE(ret);
  7894. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7895. }
  7896. TEST_F(ServerTest, KeepAlive) {
  7897. auto res = cli_.Get("/hi");
  7898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7901. EXPECT_EQ("Hello World!", res->body);
  7902. res = cli_.Get("/hi");
  7903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7904. EXPECT_EQ(StatusCode::OK_200, res->status);
  7905. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7906. EXPECT_EQ("Hello World!", res->body);
  7907. res = cli_.Get("/hi");
  7908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7909. EXPECT_EQ(StatusCode::OK_200, res->status);
  7910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7911. EXPECT_EQ("Hello World!", res->body);
  7912. res = cli_.Get("/not-exist");
  7913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7914. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7915. res = cli_.Post("/empty", "", "text/plain");
  7916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7917. EXPECT_EQ(StatusCode::OK_200, res->status);
  7918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7919. EXPECT_EQ("empty", res->body);
  7920. EXPECT_EQ("close", res->get_header_value("Connection"));
  7921. res = cli_.Post(
  7922. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7923. "text/plain");
  7924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7925. EXPECT_EQ(StatusCode::OK_200, res->status);
  7926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7927. EXPECT_EQ("empty", res->body);
  7928. cli_.set_keep_alive(false);
  7929. res = cli_.Get("/last-request");
  7930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7931. EXPECT_EQ(StatusCode::OK_200, res->status);
  7932. EXPECT_EQ("close", res->get_header_value("Connection"));
  7933. }
  7934. TEST_F(ServerTest, TooManyRedirect) {
  7935. cli_.set_follow_location(true);
  7936. auto res = cli_.Get("/redirect/0");
  7937. ASSERT_TRUE(!res);
  7938. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7939. }
  7940. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7941. Request req;
  7942. req.method = "FOOBAR";
  7943. req.path = "/hi";
  7944. cli_.set_keep_alive(true);
  7945. auto res = cli_.send(req);
  7946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7947. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7948. EXPECT_EQ("close", res->get_header_value("Connection"));
  7949. EXPECT_FALSE(cli_.is_socket_open());
  7950. }
  7951. TEST_F(ServerTest, CustomRouteReadsBody) {
  7952. const std::string xml =
  7953. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7954. Request req;
  7955. req.method = "PROPFIND";
  7956. req.path = "/dav/dir";
  7957. req.set_header("Depth", "1");
  7958. req.body = xml;
  7959. auto res = cli_.send(req);
  7960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7961. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7962. EXPECT_EQ(xml, res->body);
  7963. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7964. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7965. }
  7966. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7967. Request req;
  7968. req.method = "PROPFIND";
  7969. req.path = "/dav/42";
  7970. auto res = cli_.send(req);
  7971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7972. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7973. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7974. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7975. }
  7976. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7977. Request req;
  7978. req.method = "PROPFIND";
  7979. req.path = "/dav-re/123";
  7980. auto res = cli_.send(req);
  7981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7982. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7983. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7984. }
  7985. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7986. Request req;
  7987. req.method = "MKCOL";
  7988. req.path = "/dav-mkcol";
  7989. auto res = cli_.send(req);
  7990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7991. EXPECT_EQ(StatusCode::Created_201, res->status);
  7992. }
  7993. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7994. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7995. Request req;
  7996. req.method = "REPORT";
  7997. req.path = "/dav-report";
  7998. req.body = xml;
  7999. auto res = cli_.send(req);
  8000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8001. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8002. EXPECT_EQ(xml, res->body);
  8003. }
  8004. // A content reader route must fire even when the request carries no body,
  8005. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8006. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8007. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8008. Request req;
  8009. req.method = "REPORT";
  8010. req.path = "/dav-report";
  8011. auto res = cli_.send(req);
  8012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8013. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8014. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8015. }
  8016. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8017. Request req;
  8018. req.method = "PROPFIND";
  8019. req.path = "/not-dav";
  8020. auto res = cli_.send(req);
  8021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8022. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8023. }
  8024. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8025. Request req;
  8026. req.method = "UNLOCK";
  8027. req.path = "/dav/dir";
  8028. cli_.set_keep_alive(true);
  8029. auto res = cli_.send(req);
  8030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8031. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8032. EXPECT_EQ("close", res->get_header_value("Connection"));
  8033. EXPECT_FALSE(cli_.is_socket_open());
  8034. }
  8035. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8036. // The mount point serves this path, but only for GET and HEAD.
  8037. auto get_res = cli_.Get("/dir/index.html");
  8038. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8039. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8040. Request req;
  8041. req.method = "PROPFIND";
  8042. req.path = "/dir/index.html";
  8043. auto res = cli_.send(req);
  8044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8045. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8046. }
  8047. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8048. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8049. cli_.set_keep_alive(true);
  8050. for (auto i = 0; i < 2; i++) {
  8051. Request req;
  8052. req.method = "PROPFIND";
  8053. req.path = "/dav/dir";
  8054. req.body = xml;
  8055. auto res = cli_.send(req);
  8056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8057. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8058. EXPECT_EQ(xml, res->body);
  8059. EXPECT_TRUE(cli_.is_socket_open());
  8060. }
  8061. // A built-in method must still be served on the same connection.
  8062. cli_.set_keep_alive(false);
  8063. auto res = cli_.Get("/hi");
  8064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8065. EXPECT_EQ(StatusCode::OK_200, res->status);
  8066. EXPECT_EQ("close", res->get_header_value("Connection"));
  8067. }
  8068. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8069. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8070. Request req;
  8071. req.method = "PROPFIND";
  8072. req.path = "/dav/dir";
  8073. req.set_header("Expect", "100-continue");
  8074. req.body = xml;
  8075. auto res = cli_.send(req);
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8078. EXPECT_EQ(xml, res->body);
  8079. }
  8080. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8081. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8082. TEST_F(ServerTest, Gzip) {
  8083. Headers headers;
  8084. headers.emplace("Accept-Encoding", "gzip, deflate");
  8085. auto res = cli_.Get("/compress", headers);
  8086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8087. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8088. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8089. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8090. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8091. "7890123456789012345678901234567890",
  8092. res->body);
  8093. EXPECT_EQ(StatusCode::OK_200, res->status);
  8094. }
  8095. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8096. Headers headers;
  8097. headers.emplace("Accept-Encoding", "gzip, deflate");
  8098. auto res = cli_.Get("/compress-with-charset", headers);
  8099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8100. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8101. EXPECT_EQ("application/json; charset=utf-8",
  8102. res->get_header_value("Content-Type"));
  8103. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8104. "7890123456789012345678901234567890",
  8105. res->body);
  8106. EXPECT_EQ(StatusCode::OK_200, res->status);
  8107. }
  8108. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8109. Headers headers;
  8110. headers.emplace("Accept-Encoding", "");
  8111. auto res = cli_.Get("/compress", headers);
  8112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8113. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8114. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8115. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8116. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8117. "7890123456789012345678901234567890",
  8118. res->body);
  8119. EXPECT_EQ(StatusCode::OK_200, res->status);
  8120. }
  8121. TEST_F(ServerTest, GzipWithContentReceiver) {
  8122. Headers headers;
  8123. headers.emplace("Accept-Encoding", "gzip, deflate");
  8124. std::string body;
  8125. auto res = cli_.Get("/compress", headers,
  8126. [&](const char *data, uint64_t data_length) {
  8127. EXPECT_EQ(100U, data_length);
  8128. body.append(data, data_length);
  8129. return true;
  8130. });
  8131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8132. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8134. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8135. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8136. "7890123456789012345678901234567890",
  8137. body);
  8138. EXPECT_EQ(StatusCode::OK_200, res->status);
  8139. }
  8140. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8141. Headers headers;
  8142. headers.emplace("Accept-Encoding", "gzip, deflate");
  8143. cli_.set_decompress(false);
  8144. auto res = cli_.Get("/compress", headers);
  8145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8146. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8147. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8148. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8149. EXPECT_EQ(33U, res->body.size());
  8150. EXPECT_EQ(StatusCode::OK_200, res->status);
  8151. }
  8152. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8153. Headers headers;
  8154. headers.emplace("Accept-Encoding", "");
  8155. std::string body;
  8156. auto res = cli_.Get("/compress", headers,
  8157. [&](const char *data, uint64_t data_length) {
  8158. EXPECT_EQ(100U, data_length);
  8159. body.append(data, data_length);
  8160. return true;
  8161. });
  8162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8163. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8164. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8165. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8166. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8167. "7890123456789012345678901234567890",
  8168. body);
  8169. EXPECT_EQ(StatusCode::OK_200, res->status);
  8170. }
  8171. TEST_F(ServerTest, NoGzip) {
  8172. Headers headers;
  8173. headers.emplace("Accept-Encoding", "gzip, deflate");
  8174. auto res = cli_.Get("/nocompress", headers);
  8175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8176. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8177. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8178. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8179. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8180. "7890123456789012345678901234567890",
  8181. res->body);
  8182. EXPECT_EQ(StatusCode::OK_200, res->status);
  8183. }
  8184. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8185. Headers headers;
  8186. headers.emplace("Accept-Encoding", "gzip, deflate");
  8187. std::string body;
  8188. auto res = cli_.Get("/nocompress", headers,
  8189. [&](const char *data, uint64_t data_length) {
  8190. EXPECT_EQ(100U, data_length);
  8191. body.append(data, data_length);
  8192. return true;
  8193. });
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8196. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8197. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8198. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8199. "7890123456789012345678901234567890",
  8200. body);
  8201. EXPECT_EQ(StatusCode::OK_200, res->status);
  8202. }
  8203. TEST_F(ServerTest, MultipartFormDataGzip) {
  8204. UploadFormDataItems items = {
  8205. {"key1", "test", "", ""},
  8206. {"key2", "--abcdefg123", "", ""},
  8207. };
  8208. cli_.set_compress(true);
  8209. auto res = cli_.Post("/compress-multipart", items);
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::OK_200, res->status);
  8212. }
  8213. #endif
  8214. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8215. // Static file compression is opt-in, so these run their own server rather than
  8216. // flipping it on for the shared ServerTest fixture, which would silently
  8217. // rewrite what every other static file test is asserting.
  8218. class StaticFileCompressionTest : public ::testing::Test {
  8219. protected:
  8220. void TearDown() override {
  8221. if (t_.joinable()) {
  8222. svr_.stop();
  8223. t_.join();
  8224. }
  8225. }
  8226. int start(const std::function<void(Server &)> &configure = nullptr) {
  8227. // Serves the same tree as a directory of build-time compressed assets
  8228. // would be served: the mount point names the coding the files are already
  8229. // stored in. Registered before "/" so it is the one that matches.
  8230. svr_.set_mount_point("/pre-encoded", "./www",
  8231. {{"Content-Encoding", "gzip"}});
  8232. svr_.set_mount_point("/", "./www");
  8233. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8234. res.set_file_content("./www/dir/index.html", "text/html");
  8235. });
  8236. svr_.Get("/pre-encoded-file-content",
  8237. [](const Request & /*req*/, Response &res) {
  8238. res.set_header("Content-Encoding", "gzip");
  8239. res.set_file_content("./www/dir/index.html", "text/html");
  8240. });
  8241. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8242. res.set_content_provider(
  8243. 6, "text/plain",
  8244. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8245. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8246. return true;
  8247. });
  8248. });
  8249. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8250. res.set_content_provider(
  8251. 1000, "text/plain",
  8252. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8253. if (offset < 100) {
  8254. std::string data(100, 'A');
  8255. sink.write(data.data(), data.size());
  8256. return true;
  8257. }
  8258. std::this_thread::sleep_for(std::chrono::seconds(2));
  8259. std::string data(900, 'B');
  8260. sink.write(data.data(), data.size());
  8261. return true;
  8262. });
  8263. });
  8264. if (configure) { configure(svr_); }
  8265. auto port = svr_.bind_to_any_port(HOST);
  8266. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8267. svr_.wait_until_ready();
  8268. return port;
  8269. }
  8270. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8271. // Every file under ./www except 1MB.txt is smaller than the default
  8272. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8273. // it out of the way.
  8274. static void enable_without_floor(Server &svr) {
  8275. svr.set_static_file_compression(true);
  8276. svr.set_static_file_compression_min_length(0);
  8277. }
  8278. Server svr_;
  8279. std::thread t_;
  8280. };
  8281. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8282. auto port = start();
  8283. Client cli(HOST, port);
  8284. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8286. EXPECT_EQ(StatusCode::OK_200, res->status);
  8287. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8288. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8289. EXPECT_EQ(1048576U, res->body.size());
  8290. }
  8291. TEST_F(StaticFileCompressionTest, MountPoint) {
  8292. auto port = start(enable);
  8293. Client cli(HOST, port);
  8294. cli.set_decompress(false);
  8295. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::OK_200, res->status);
  8298. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8299. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8300. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8301. // The response stays self-delimiting: a length, not a chunked body.
  8302. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8303. EXPECT_EQ(std::to_string(res->body.size()),
  8304. res->get_header_value("Content-Length"));
  8305. EXPECT_LT(res->body.size(), 1048576U);
  8306. EXPECT_FALSE(res->body.empty());
  8307. }
  8308. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8309. auto port = start(enable);
  8310. Client cli(HOST, port);
  8311. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8313. EXPECT_EQ(StatusCode::OK_200, res->status);
  8314. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8315. EXPECT_EQ(1048576U, res->body.size());
  8316. }
  8317. TEST_F(StaticFileCompressionTest, FileContent) {
  8318. auto port = start(enable_without_floor);
  8319. Client cli(HOST, port);
  8320. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8322. EXPECT_EQ(StatusCode::OK_200, res->status);
  8323. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8324. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8325. EXPECT_EQ(104U, res->body.size());
  8326. }
  8327. // A handler that serves an already-encoded file names the coding itself. The
  8328. // file-backed path decided its coding from Accept-Encoding and the content
  8329. // type alone, so it compressed the stored bytes a second time and appended a
  8330. // second Content-Encoding field line.
  8331. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8332. auto port = start(enable_without_floor);
  8333. Client cli(HOST, port);
  8334. cli.set_decompress(false);
  8335. auto res = cli.Get("/pre-encoded-file-content",
  8336. Headers{{"Accept-Encoding", "gzip"}});
  8337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8338. EXPECT_EQ(StatusCode::OK_200, res->status);
  8339. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8340. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8341. // Vary belongs to a coding the server chose, and it chose none here.
  8342. EXPECT_FALSE(res->has_header("Vary"));
  8343. // The file travels exactly as it is stored on disk.
  8344. EXPECT_EQ(104U, res->body.size());
  8345. }
  8346. // The 1MB file clears the default floor, so this one runs the configuration a
  8347. // deployment would actually have.
  8348. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8349. auto port = start(enable);
  8350. Client cli(HOST, port);
  8351. cli.set_decompress(false);
  8352. auto res =
  8353. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ(StatusCode::OK_200, res->status);
  8356. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8357. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8358. EXPECT_FALSE(res->has_header("Vary"));
  8359. EXPECT_EQ(1048576U, res->body.size());
  8360. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8361. }
  8362. TEST_F(StaticFileCompressionTest, Head) {
  8363. auto port = start(enable);
  8364. Client cli(HOST, port);
  8365. cli.set_decompress(false);
  8366. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8367. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8368. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8370. EXPECT_EQ(StatusCode::OK_200, res->status);
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8373. // HEAD still reports the size a GET would return.
  8374. EXPECT_EQ(get->get_header_value("Content-Length"),
  8375. res->get_header_value("Content-Length"));
  8376. EXPECT_TRUE(res->body.empty());
  8377. }
  8378. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8379. auto port = start(enable);
  8380. Client cli(HOST, port);
  8381. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8382. {"Accept-Encoding", "gzip"}});
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8385. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8386. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8387. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8388. EXPECT_EQ("cd", res->body);
  8389. }
  8390. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8391. auto port = start(enable);
  8392. Client cli(HOST, port);
  8393. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8395. EXPECT_EQ(StatusCode::OK_200, res->status);
  8396. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8397. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8398. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8399. }
  8400. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8401. auto port = start(enable);
  8402. Client cli(HOST, port);
  8403. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8405. EXPECT_EQ(StatusCode::OK_200, res->status);
  8406. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8407. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8408. EXPECT_TRUE(res->body.empty());
  8409. }
  8410. TEST_F(StaticFileCompressionTest, MinLength) {
  8411. auto port = start(enable);
  8412. Client cli(HOST, port);
  8413. // 104 bytes, well under the default floor. Compressing it would add the
  8414. // gzip header and trailer to a body that already fits in one packet.
  8415. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ(StatusCode::OK_200, res->status);
  8418. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8419. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8420. }
  8421. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8422. auto port = start([](Server &svr) {
  8423. svr.set_static_file_compression(true);
  8424. svr.set_static_file_compression_min_length(1);
  8425. });
  8426. Client cli(HOST, port);
  8427. cli.set_decompress(false);
  8428. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8431. // A 9-byte file comes back larger than it went in, because gzip's header and
  8432. // trailer outweigh anything deflate can save. That is the end of the range
  8433. // the floor exists to keep out.
  8434. EXPECT_GT(res->body.size(), 9U);
  8435. }
  8436. TEST_F(StaticFileCompressionTest, MaxLength) {
  8437. auto port = start([](Server &svr) {
  8438. svr.set_static_file_compression(true);
  8439. svr.set_static_file_compression_min_length(0);
  8440. svr.set_static_file_compression_max_length(1024);
  8441. });
  8442. Client cli(HOST, port);
  8443. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8444. // defines `small` as a macro on Windows.
  8445. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8446. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8447. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8448. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8449. // Under it: compressed.
  8450. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8451. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8452. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8453. }
  8454. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8455. auto port = start(enable_without_floor);
  8456. Client cli(HOST, port);
  8457. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8458. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8459. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8460. auto identity_etag = identity->get_header_value("ETag");
  8461. ASSERT_FALSE(identity_etag.empty());
  8462. auto gzipped =
  8463. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8464. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8465. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8466. auto gzip_etag = gzipped->get_header_value("ETag");
  8467. ASSERT_FALSE(gzip_etag.empty());
  8468. // Two representations, two validators.
  8469. EXPECT_NE(identity_etag, gzip_etag);
  8470. // Each one revalidates against the request that would produce it...
  8471. auto fresh =
  8472. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8473. {"If-None-Match", gzip_etag}});
  8474. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8475. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8476. auto fresh_identity =
  8477. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8478. {"If-None-Match", identity_etag}});
  8479. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8480. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8481. // ...and not against the other representation.
  8482. auto crossed =
  8483. cli.Get("/dir/index.html",
  8484. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8485. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8486. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8487. }
  8488. // The opt-in covers responses the server reads off disk itself. A caller's own
  8489. // known-length provider keeps its Content-Length and, more importantly, keeps
  8490. // delivering incrementally: routing it through a compressor would hold every
  8491. // write back until zlib's window filled.
  8492. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8493. auto port = start(enable);
  8494. Client cli(HOST, port);
  8495. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8497. EXPECT_EQ(StatusCode::OK_200, res->status);
  8498. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8499. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8500. EXPECT_EQ("aaabbb", res->body);
  8501. }
  8502. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8503. auto port = start(enable);
  8504. Client cli(HOST, port);
  8505. cli.set_read_timeout(1, 0);
  8506. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8507. Headers{{"Accept-Encoding", "gzip"}});
  8508. ASSERT_TRUE(handle.is_valid());
  8509. // The provider writes 100 bytes and then stalls for longer than the read
  8510. // timeout. Those first bytes have to arrive anyway: run the response through
  8511. // a compressor and zlib holds them until its window fills, so the read would
  8512. // come back empty instead.
  8513. char buf[256];
  8514. auto n = handle.read(buf, sizeof(buf));
  8515. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8516. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8517. }
  8518. #endif
  8519. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8520. TEST_F(ServerTest, Brotli) {
  8521. Headers headers;
  8522. headers.emplace("Accept-Encoding", "br");
  8523. auto res = cli_.Get("/compress", headers);
  8524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8525. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8526. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8527. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8528. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8529. "7890123456789012345678901234567890",
  8530. res->body);
  8531. EXPECT_EQ(StatusCode::OK_200, res->status);
  8532. }
  8533. #endif
  8534. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8535. TEST_F(ServerTest, Zstd) {
  8536. Headers headers;
  8537. headers.emplace("Accept-Encoding", "zstd");
  8538. auto res = cli_.Get("/compress", headers);
  8539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8540. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8542. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8543. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8544. "7890123456789012345678901234567890",
  8545. res->body);
  8546. EXPECT_EQ(StatusCode::OK_200, res->status);
  8547. }
  8548. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8549. Headers headers;
  8550. headers.emplace("Accept-Encoding", "");
  8551. auto res = cli_.Get("/compress", headers);
  8552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8553. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8554. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8555. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8556. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8557. "7890123456789012345678901234567890",
  8558. res->body);
  8559. EXPECT_EQ(StatusCode::OK_200, res->status);
  8560. }
  8561. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8562. Headers headers;
  8563. headers.emplace("Accept-Encoding", "zstd");
  8564. std::string body;
  8565. auto res = cli_.Get("/compress", headers,
  8566. [&](const char *data, uint64_t data_length) {
  8567. EXPECT_EQ(100U, data_length);
  8568. body.append(data, data_length);
  8569. return true;
  8570. });
  8571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8572. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8573. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8574. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8575. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8576. "7890123456789012345678901234567890",
  8577. body);
  8578. EXPECT_EQ(StatusCode::OK_200, res->status);
  8579. }
  8580. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8581. Headers headers;
  8582. headers.emplace("Accept-Encoding", "zstd");
  8583. cli_.set_decompress(false);
  8584. auto res = cli_.Get("/compress", headers);
  8585. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8586. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8587. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8588. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8590. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8591. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8592. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8593. EXPECT_EQ(StatusCode::OK_200, res->status);
  8594. ASSERT_EQ(26U, res->body.size());
  8595. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8596. 0);
  8597. }
  8598. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8599. Headers headers;
  8600. headers.emplace("Accept-Encoding", "");
  8601. std::string body;
  8602. auto res = cli_.Get("/compress", headers,
  8603. [&](const char *data, uint64_t data_length) {
  8604. EXPECT_EQ(100U, data_length);
  8605. body.append(data, data_length);
  8606. return true;
  8607. });
  8608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8609. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8610. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8611. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8612. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8613. "7890123456789012345678901234567890",
  8614. body);
  8615. EXPECT_EQ(StatusCode::OK_200, res->status);
  8616. }
  8617. TEST_F(ServerTest, NoZstd) {
  8618. Headers headers;
  8619. headers.emplace("Accept-Encoding", "zstd");
  8620. auto res = cli_.Get("/nocompress", headers);
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8623. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8624. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8625. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8626. "7890123456789012345678901234567890",
  8627. res->body);
  8628. EXPECT_EQ(StatusCode::OK_200, res->status);
  8629. }
  8630. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8631. Headers headers;
  8632. headers.emplace("Accept-Encoding", "zstd");
  8633. std::string body;
  8634. auto res = cli_.Get("/nocompress", headers,
  8635. [&](const char *data, uint64_t data_length) {
  8636. EXPECT_EQ(100U, data_length);
  8637. body.append(data, data_length);
  8638. return true;
  8639. });
  8640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8641. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8642. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8643. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8644. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8645. "7890123456789012345678901234567890",
  8646. body);
  8647. EXPECT_EQ(StatusCode::OK_200, res->status);
  8648. }
  8649. // TODO: How to enable zstd ??
  8650. TEST_F(ServerTest, MultipartFormDataZstd) {
  8651. UploadFormDataItems items = {
  8652. {"key1", "test", "", ""},
  8653. {"key2", "--abcdefg123", "", ""},
  8654. };
  8655. Headers headers;
  8656. headers.emplace("Accept-Encoding", "zstd");
  8657. cli_.set_compress(true);
  8658. auto res = cli_.Post("/compress-multipart", headers, items);
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. }
  8662. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8663. Headers headers;
  8664. headers.emplace("Accept-Encoding", "zstd");
  8665. cli_.set_compress(true);
  8666. auto res = cli_.Put(
  8667. "/put", headers, 3,
  8668. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8669. sink.os << "PUT";
  8670. return true;
  8671. },
  8672. "text/plain");
  8673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8674. EXPECT_EQ(StatusCode::OK_200, res->status);
  8675. EXPECT_EQ("PUT", res->body);
  8676. }
  8677. // Pre-compression logging tests
  8678. TEST_F(ServerTest, PreCompressionLogging) {
  8679. // Test data for compression (matches the actual /compress endpoint content)
  8680. const std::string test_content =
  8681. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8682. "3456789012345678901234567890";
  8683. // Variables to capture logging data
  8684. std::string pre_compression_body;
  8685. std::string pre_compression_content_type;
  8686. std::string pre_compression_content_encoding;
  8687. std::string post_compression_body;
  8688. std::string post_compression_content_type;
  8689. std::string post_compression_content_encoding;
  8690. // Set up pre-compression logger
  8691. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8692. const Response &res) {
  8693. pre_compression_body = res.body;
  8694. pre_compression_content_type = res.get_header_value("Content-Type");
  8695. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8696. });
  8697. // Set up post-compression logger
  8698. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8699. post_compression_body = res.body;
  8700. post_compression_content_type = res.get_header_value("Content-Type");
  8701. post_compression_content_encoding =
  8702. res.get_header_value("Content-Encoding");
  8703. });
  8704. // Test with gzip compression
  8705. Headers headers;
  8706. headers.emplace("Accept-Encoding", "gzip");
  8707. auto res = cli_.Get("/compress", headers);
  8708. // Verify response was compressed
  8709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8710. EXPECT_EQ(StatusCode::OK_200, res->status);
  8711. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8712. // Verify pre-compression logger captured uncompressed content
  8713. EXPECT_EQ(test_content, pre_compression_body);
  8714. EXPECT_EQ("text/plain", pre_compression_content_type);
  8715. EXPECT_TRUE(pre_compression_content_encoding
  8716. .empty()); // No encoding header before compression
  8717. // Verify post-compression logger captured compressed content
  8718. EXPECT_NE(test_content,
  8719. post_compression_body); // Should be different after compression
  8720. EXPECT_EQ("text/plain", post_compression_content_type);
  8721. EXPECT_EQ("gzip", post_compression_content_encoding);
  8722. // Verify compressed content is smaller
  8723. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8724. }
  8725. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8726. const std::string test_content =
  8727. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8728. "3456789012345678901234567890";
  8729. std::string pre_compression_body;
  8730. std::string post_compression_body;
  8731. svr_.set_pre_compression_logger(
  8732. [&](const Request & /*req*/, const Response &res) {
  8733. pre_compression_body = res.body;
  8734. });
  8735. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8736. post_compression_body = res.body;
  8737. });
  8738. Headers headers;
  8739. headers.emplace("Accept-Encoding", "br");
  8740. auto res = cli_.Get("/compress", headers);
  8741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8742. EXPECT_EQ(StatusCode::OK_200, res->status);
  8743. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8744. // Verify pre-compression content is uncompressed
  8745. EXPECT_EQ(test_content, pre_compression_body);
  8746. // Verify post-compression content is compressed
  8747. EXPECT_NE(test_content, post_compression_body);
  8748. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8749. }
  8750. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8751. const std::string test_content =
  8752. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8753. "3456789012345678901234567890";
  8754. std::string pre_compression_body;
  8755. std::string post_compression_body;
  8756. svr_.set_pre_compression_logger(
  8757. [&](const Request & /*req*/, const Response &res) {
  8758. pre_compression_body = res.body;
  8759. });
  8760. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8761. post_compression_body = res.body;
  8762. });
  8763. // Request without compression (use /nocompress endpoint)
  8764. Headers headers;
  8765. auto res = cli_.Get("/nocompress", headers);
  8766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8767. EXPECT_EQ(StatusCode::OK_200, res->status);
  8768. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8769. // Pre-compression logger should not be called when no compression is applied
  8770. EXPECT_TRUE(
  8771. pre_compression_body.empty()); // Pre-compression logger not called
  8772. EXPECT_EQ(
  8773. test_content,
  8774. post_compression_body); // Post-compression logger captures final content
  8775. }
  8776. TEST_F(ServerTest, LoggerSeesContentLength) {
  8777. size_t logged_content_length = 0;
  8778. std::string logged_content_length_header;
  8779. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8780. logged_content_length = res.content_length_;
  8781. logged_content_length_header = res.get_header_value("Content-Length");
  8782. });
  8783. auto res = cli_.Get("/nocompress");
  8784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8785. EXPECT_EQ(StatusCode::OK_200, res->status);
  8786. EXPECT_EQ(res->body.size(), logged_content_length);
  8787. EXPECT_EQ(std::to_string(logged_content_length),
  8788. logged_content_length_header);
  8789. }
  8790. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8791. const std::string test_content =
  8792. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8793. "3456789012345678901234567890";
  8794. std::string pre_compression_body;
  8795. bool pre_logger_called = false;
  8796. // Set only pre-compression logger
  8797. svr_.set_pre_compression_logger(
  8798. [&](const Request & /*req*/, const Response &res) {
  8799. pre_compression_body = res.body;
  8800. pre_logger_called = true;
  8801. });
  8802. Headers headers;
  8803. headers.emplace("Accept-Encoding", "gzip");
  8804. auto res = cli_.Get("/compress", headers);
  8805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8806. EXPECT_EQ(StatusCode::OK_200, res->status);
  8807. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8808. // Verify pre-compression logger was called
  8809. EXPECT_TRUE(pre_logger_called);
  8810. EXPECT_EQ(test_content, pre_compression_body);
  8811. }
  8812. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8813. {
  8814. // Test with Expect: 100-continue header - success case
  8815. // Server returns 100 Continue, client sends body, server returns 200 OK
  8816. Request req;
  8817. req.method = "POST";
  8818. req.path = "/post-large";
  8819. req.set_header("Expect", "100-continue");
  8820. req.body = LARGE_DATA;
  8821. Response res;
  8822. auto error = Error::Success;
  8823. cli_.set_keep_alive(true);
  8824. auto ret = cli_.send(req, res, error);
  8825. EXPECT_TRUE(ret);
  8826. EXPECT_EQ(StatusCode::OK_200, res.status);
  8827. EXPECT_EQ(LARGE_DATA, res.body);
  8828. }
  8829. {
  8830. // Test with Expect: 100-continue header - error case
  8831. // Client should not send the body when server returns an error
  8832. Request req;
  8833. req.method = "POST";
  8834. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8835. req.set_header("Expect", "100-continue");
  8836. req.body = LARGE_DATA;
  8837. Response res;
  8838. auto error = Error::Success;
  8839. auto start = std::chrono::high_resolution_clock::now();
  8840. cli_.set_keep_alive(true);
  8841. auto ret = cli_.send(req, res, error);
  8842. auto end = std::chrono::high_resolution_clock::now();
  8843. auto elapsed =
  8844. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8845. .count();
  8846. // With Expect: 100-continue, request completes successfully but with error
  8847. EXPECT_TRUE(ret);
  8848. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8849. EXPECT_EQ("close", res.get_header_value("Connection"));
  8850. EXPECT_FALSE(cli_.is_socket_open());
  8851. EXPECT_LE(elapsed, 2000);
  8852. }
  8853. {
  8854. // Send an extra GET request to ensure error recovery without hanging
  8855. Request req;
  8856. req.method = "GET";
  8857. req.path = "/hi";
  8858. auto start = std::chrono::high_resolution_clock::now();
  8859. auto res = cli_.send(req);
  8860. auto end = std::chrono::high_resolution_clock::now();
  8861. auto elapsed =
  8862. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8863. .count();
  8864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8865. EXPECT_EQ(StatusCode::OK_200, res->status);
  8866. EXPECT_EQ("Hello World!", res->body);
  8867. EXPECT_LE(elapsed, 500);
  8868. }
  8869. }
  8870. TEST(ZstdDecompressor, ChunkedDecompression) {
  8871. std::string data;
  8872. for (size_t i = 0; i < 32 * 1024; ++i) {
  8873. data.push_back(static_cast<char>('a' + i % 26));
  8874. }
  8875. std::string compressed_data;
  8876. {
  8877. httplib::detail::zstd_compressor compressor;
  8878. bool result = compressor.compress(
  8879. data.data(), data.size(),
  8880. /*last=*/true,
  8881. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8882. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8883. compressed_data_size);
  8884. return true;
  8885. });
  8886. ASSERT_TRUE(result);
  8887. }
  8888. std::string decompressed_data;
  8889. {
  8890. httplib::detail::zstd_decompressor decompressor;
  8891. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8892. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8893. size_t chunk_size = 130;
  8894. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8895. chunk_begin += chunk_size) {
  8896. size_t current_chunk_size =
  8897. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8898. bool result = decompressor.decompress(
  8899. compressed_data.data() + chunk_begin, current_chunk_size,
  8900. [&](const char *decompressed_data_chunk,
  8901. size_t decompressed_data_chunk_size) {
  8902. decompressed_data.insert(decompressed_data.size(),
  8903. decompressed_data_chunk,
  8904. decompressed_data_chunk_size);
  8905. return true;
  8906. });
  8907. ASSERT_TRUE(result);
  8908. }
  8909. }
  8910. ASSERT_EQ(data, decompressed_data);
  8911. }
  8912. TEST(ZstdDecompressor, Decompress) {
  8913. std::string original_text = "Compressed with ZSTD";
  8914. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8915. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8916. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8917. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8918. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8919. std::string decompressed_data;
  8920. {
  8921. httplib::detail::zstd_decompressor decompressor;
  8922. bool result = decompressor.decompress(
  8923. compressed_data.data(), compressed_data.size(),
  8924. [&](const char *decompressed_data_chunk,
  8925. size_t decompressed_data_chunk_size) {
  8926. decompressed_data.insert(decompressed_data.size(),
  8927. decompressed_data_chunk,
  8928. decompressed_data_chunk_size);
  8929. return true;
  8930. });
  8931. ASSERT_TRUE(result);
  8932. }
  8933. ASSERT_EQ(original_text, decompressed_data);
  8934. }
  8935. #endif
  8936. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8937. // separate chunks so that the server sees each part in its own read(). Used to
  8938. // place a read boundary at a specific offset of a request body.
  8939. static bool send_request_in_parts(time_t read_timeout_sec,
  8940. const std::vector<std::string> &parts,
  8941. std::string *resp = nullptr,
  8942. int port = PORT) {
  8943. auto error = Error::Success;
  8944. auto client_sock = detail::create_client_socket(
  8945. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8946. /*connection_timeout_sec=*/5, 0,
  8947. /*read_timeout_sec=*/5, 0,
  8948. /*write_timeout_sec=*/5, 0, std::string(), error);
  8949. if (client_sock == INVALID_SOCKET) { return false; }
  8950. auto ret = detail::process_client_socket(
  8951. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8952. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8953. for (size_t i = 0; i < parts.size(); i++) {
  8954. const auto &part = parts[i];
  8955. if (part.size() !=
  8956. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8957. return false;
  8958. }
  8959. if (i + 1 < parts.size()) {
  8960. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8961. }
  8962. }
  8963. char buf[512];
  8964. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8965. while (line_reader.getline()) {
  8966. if (resp) { *resp += line_reader.ptr(); }
  8967. }
  8968. return true;
  8969. });
  8970. detail::close_socket(client_sock);
  8971. return ret;
  8972. }
  8973. // Sends a raw request to a server listening at HOST:PORT.
  8974. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8975. std::string *resp = nullptr, int port = PORT) {
  8976. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8977. }
  8978. #ifdef CPPHTTPLIB_SSL_ENABLED
  8979. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8981. ASSERT_TRUE(svr.is_valid());
  8982. svr.set_read_timeout(1, 0);
  8983. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8984. auto se = detail::scope_exit([&] {
  8985. svr.stop();
  8986. t.join();
  8987. ASSERT_FALSE(svr.is_running());
  8988. });
  8989. svr.wait_until_ready();
  8990. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8991. // keeps each wait well within the read timeout. The server gives up a
  8992. // second in, so the bytes sent after that fail.
  8993. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8994. parts.resize(26, std::string(1, '\0'));
  8995. EXPECT_FALSE(send_request_in_parts(5, parts));
  8996. }
  8997. #endif
  8998. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8999. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9000. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9001. const std::vector<std::string> &parts,
  9002. std::string *resp = nullptr,
  9003. int port = PORT) {
  9004. auto error = Error::Success;
  9005. auto sock = detail::create_client_socket(
  9006. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9007. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9008. /*write_timeout_sec=*/5, 0, std::string(), error);
  9009. if (sock == INVALID_SOCKET) { return false; }
  9010. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9011. auto ctx = SSL_CTX_new(TLS_client_method());
  9012. auto ssl = SSL_new(ctx);
  9013. auto ssl_se = detail::scope_exit([&] {
  9014. SSL_free(ssl);
  9015. SSL_CTX_free(ctx);
  9016. });
  9017. SSL_set_fd(ssl, static_cast<int>(sock));
  9018. if (SSL_connect(ssl) != 1) { return false; }
  9019. for (size_t i = 0; i < parts.size(); i++) {
  9020. const auto &part = parts[i];
  9021. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9022. static_cast<int>(part.size())) {
  9023. return false;
  9024. }
  9025. if (i + 1 < parts.size()) {
  9026. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9027. }
  9028. }
  9029. char buf[512];
  9030. int n;
  9031. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9032. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9033. }
  9034. return true;
  9035. }
  9036. #endif
  9037. // The request line, then a header value a byte at a time.
  9038. static std::vector<std::string> slow_request_head_parts() {
  9039. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9040. parts.resize(26, "a");
  9041. parts.emplace_back("\r\n\r\n");
  9042. return parts;
  9043. }
  9044. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9045. // within the one-second read timeout. The server gives up a second in, before
  9046. // the head is complete.
  9047. static void
  9048. expect_slow_request_head_dropped(Server &svr,
  9049. const std::function<std::string()> &send) {
  9050. std::atomic<bool> handled(false);
  9051. svr.Get("/", [&](const Request &, Response &res) {
  9052. handled = true;
  9053. res.set_content("ok", "text/plain");
  9054. });
  9055. svr.set_read_timeout(1, 0);
  9056. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9057. auto se = detail::scope_exit([&] {
  9058. svr.stop();
  9059. t.join();
  9060. ASSERT_FALSE(svr.is_running());
  9061. });
  9062. svr.wait_until_ready();
  9063. auto resp = send();
  9064. EXPECT_FALSE(handled);
  9065. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9066. }
  9067. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9068. Server svr;
  9069. expect_slow_request_head_dropped(svr, [] {
  9070. std::string resp;
  9071. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9072. return resp;
  9073. });
  9074. }
  9075. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9076. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9078. ASSERT_TRUE(svr.is_valid());
  9079. expect_slow_request_head_dropped(svr, [] {
  9080. std::string resp;
  9081. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9082. return resp;
  9083. });
  9084. }
  9085. #endif
  9086. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9087. Server svr;
  9088. std::string header_value;
  9089. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9090. header_value = req.get_header_value("foo");
  9091. res.set_content("ok", "text/plain");
  9092. });
  9093. thread t = thread([&] { svr.listen(HOST, PORT); });
  9094. auto se = detail::scope_exit([&] {
  9095. svr.stop();
  9096. t.join();
  9097. ASSERT_FALSE(svr.is_running());
  9098. });
  9099. svr.wait_until_ready();
  9100. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9101. // like characters are not treated the same - use vertical tab and escape.
  9102. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9103. "foo: \t \v bar \x1B\t \r\n"
  9104. "Connection: close\r\n"
  9105. "\r\n";
  9106. std::string res;
  9107. ASSERT_TRUE(send_request(5, req, &res));
  9108. EXPECT_EQ(header_value, "");
  9109. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9110. }
  9111. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9112. Server svr;
  9113. std::string received;
  9114. svr.Get("/order", [&](const Request &req, Response &res) {
  9115. received = entries_to_string(req.headers);
  9116. res.set_content("ok", "text/plain");
  9117. });
  9118. auto port = svr.bind_to_any_port(HOST);
  9119. thread t = thread([&] { svr.listen_after_bind(); });
  9120. auto se = detail::scope_exit([&] {
  9121. svr.stop();
  9122. t.join();
  9123. ASSERT_FALSE(svr.is_running());
  9124. });
  9125. svr.wait_until_ready();
  9126. const std::string req = "GET /order HTTP/1.1\r\n"
  9127. "Host: localhost\r\n"
  9128. "X-First: 1\r\n"
  9129. "X-Dup: a\r\n"
  9130. "X-Second: 2\r\n"
  9131. "X-Dup: b\r\n"
  9132. "Connection: close\r\n"
  9133. "\r\n";
  9134. std::string res;
  9135. ASSERT_TRUE(send_request(5, req, &res, port));
  9136. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9137. EXPECT_EQ(
  9138. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9139. received);
  9140. }
  9141. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9142. Server svr;
  9143. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9144. res.set_header("Set-Cookie", "first=1");
  9145. res.set_header("X-Between", "y");
  9146. res.set_header("Set-Cookie", "second=2");
  9147. res.set_content("ok", "text/plain");
  9148. });
  9149. auto port = svr.bind_to_any_port(HOST);
  9150. thread t = thread([&] { svr.listen_after_bind(); });
  9151. auto se = detail::scope_exit([&] {
  9152. svr.stop();
  9153. t.join();
  9154. ASSERT_FALSE(svr.is_running());
  9155. });
  9156. svr.wait_until_ready();
  9157. Client cli(HOST, port);
  9158. auto res = cli.Get("/cookies");
  9159. ASSERT_TRUE(res);
  9160. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9161. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9162. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9163. }
  9164. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9165. Server svr;
  9166. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9167. auto i = new int(0);
  9168. res.set_header("Trailer", "X-Safe, X-Reflected");
  9169. res.set_chunked_content_provider(
  9170. "text/plain",
  9171. [i](size_t /*offset*/, DataSink &sink) {
  9172. if (*i == 0) {
  9173. sink.os << "body";
  9174. } else {
  9175. Headers trailer;
  9176. // A valid trailer that must survive.
  9177. trailer.emplace("X-Safe", "safe");
  9178. // Attacker-controlled value carrying CR/LF (response splitting).
  9179. trailer.emplace("X-Reflected",
  9180. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9181. // Attacker-controlled name carrying CR/LF.
  9182. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9183. sink.done_with_trailer(trailer);
  9184. }
  9185. (*i)++;
  9186. return true;
  9187. },
  9188. [i](bool /*success*/) { delete i; });
  9189. });
  9190. thread t = thread([&] { svr.listen(HOST, PORT); });
  9191. auto se = detail::scope_exit([&] {
  9192. svr.stop();
  9193. t.join();
  9194. ASSERT_FALSE(svr.is_running());
  9195. });
  9196. svr.wait_until_ready();
  9197. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9198. "Host: " + HOST +
  9199. "\r\n"
  9200. "Connection: close\r\n"
  9201. "\r\n";
  9202. std::string res;
  9203. ASSERT_TRUE(send_request(5, req, &res));
  9204. // The injected fields must not appear anywhere in the raw response.
  9205. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9206. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9207. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9208. // Invalid trailers are dropped entirely, matching set_header().
  9209. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9210. // The valid trailer still passes through.
  9211. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9212. }
  9213. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9214. Server svr;
  9215. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9216. // res.headers is a public field an application can populate directly,
  9217. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9218. // A valid header that must survive.
  9219. res.headers.emplace("X-Safe", "safe");
  9220. // Attacker-controlled value carrying CR/LF (response splitting).
  9221. res.headers.emplace("X-Reflected",
  9222. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9223. // Attacker-controlled name carrying CR/LF.
  9224. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9225. res.set_content("body", "text/plain");
  9226. });
  9227. thread t = thread([&] { svr.listen(HOST, PORT); });
  9228. auto se = detail::scope_exit([&] {
  9229. svr.stop();
  9230. t.join();
  9231. ASSERT_FALSE(svr.is_running());
  9232. });
  9233. svr.wait_until_ready();
  9234. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9235. "Host: " + HOST +
  9236. "\r\n"
  9237. "Connection: close\r\n"
  9238. "\r\n";
  9239. std::string res;
  9240. ASSERT_TRUE(send_request(5, req, &res));
  9241. // The injected fields must not appear anywhere in the raw response.
  9242. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9243. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9244. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9245. // Invalid headers are dropped entirely, matching set_header().
  9246. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9247. // The valid header still passes through.
  9248. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9249. }
  9250. // Forward declaration: in split builds split.py strips `inline` and moves the
  9251. // definition into httplib.cc, so detail::write_request_line is not visible from
  9252. // the public httplib.h. Re-declaring it here lets the tests link against the
  9253. // symbol in both header-only and split builds.
  9254. namespace httplib {
  9255. namespace detail {
  9256. ssize_t write_request_line(Stream &strm, const std::string &method,
  9257. const std::string &path);
  9258. } // namespace detail
  9259. } // namespace httplib
  9260. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9261. // A well-formed target is written verbatim.
  9262. {
  9263. detail::BufferStream strm;
  9264. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9265. EXPECT_GT(n, 0);
  9266. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9267. }
  9268. // A target carrying CR/LF, SP or other control octets must be rejected
  9269. // before anything reaches the wire, otherwise it splits the request line and
  9270. // injects a header or a whole request.
  9271. const std::string evil_targets[] = {
  9272. "/a\r\nInjected: pwned",
  9273. "/a\rInjected",
  9274. "/a\nInjected",
  9275. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9276. "/a b",
  9277. "/a\tb",
  9278. "/a\x7f",
  9279. };
  9280. for (const auto &evil : evil_targets) {
  9281. detail::BufferStream strm;
  9282. auto n = detail::write_request_line(strm, "GET", evil);
  9283. EXPECT_LT(n, 0);
  9284. EXPECT_TRUE(strm.get_buffer().empty());
  9285. }
  9286. }
  9287. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9288. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9289. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9290. // target reaches write_request. The client must fail cleanly with
  9291. // Error::Write instead of putting a request-line-less, header-injecting
  9292. // request on the wire.
  9293. Server svr;
  9294. svr.Get("/a", [](const Request &, Response &res) {
  9295. res.set_content("ok", "text/plain");
  9296. });
  9297. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9298. auto se = detail::scope_exit([&] {
  9299. svr.stop();
  9300. thread.join();
  9301. ASSERT_FALSE(svr.is_running());
  9302. });
  9303. svr.wait_until_ready();
  9304. {
  9305. Client cli(HOST, PORT);
  9306. cli.set_path_encode(false);
  9307. // The request is rejected before anything is written, so the connection
  9308. // stays silent and the subsequent response read would otherwise block for
  9309. // the full default read timeout. Shorten it -- the assertion is on the
  9310. // error, not the timeout.
  9311. cli.set_read_timeout(1, 0);
  9312. auto res = cli.Get("/a\r\nInjected: pwned");
  9313. EXPECT_FALSE(res);
  9314. EXPECT_EQ(Error::Write, res.error());
  9315. }
  9316. }
  9317. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9318. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9319. // including extension methods.
  9320. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9321. for (const auto &method : good_methods) {
  9322. detail::BufferStream strm;
  9323. auto n = detail::write_request_line(strm, method, "/");
  9324. EXPECT_GT(n, 0);
  9325. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9326. }
  9327. // A method carrying CR/LF would split the request line and smuggle a whole
  9328. // request ahead of the real one. A space or an empty method corrupts the
  9329. // request line. All must be rejected before anything reaches the wire.
  9330. const std::string evil_methods[] = {
  9331. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9332. "GET\r\nInjected: pwned",
  9333. "GET\r",
  9334. "GET\n",
  9335. "GE T",
  9336. "",
  9337. };
  9338. for (const auto &evil : evil_methods) {
  9339. detail::BufferStream strm;
  9340. auto n = detail::write_request_line(strm, evil, "/");
  9341. EXPECT_LT(n, 0);
  9342. EXPECT_TRUE(strm.get_buffer().empty());
  9343. }
  9344. }
  9345. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9346. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9347. // through Client::send must fail with Error::Write and no request, neither
  9348. // the smuggled one nor the real one, may reach the server.
  9349. Server svr;
  9350. std::atomic<int> request_count(0);
  9351. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9352. request_count++;
  9353. res.status = StatusCode::OK_200;
  9354. return Server::HandlerResponse::Handled;
  9355. });
  9356. auto port = svr.bind_to_any_port(HOST);
  9357. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9358. auto se = detail::scope_exit([&] {
  9359. svr.stop();
  9360. thread.join();
  9361. ASSERT_FALSE(svr.is_running());
  9362. });
  9363. svr.wait_until_ready();
  9364. {
  9365. Client cli(HOST, port);
  9366. const std::string evil_methods[] = {
  9367. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9368. "GE T",
  9369. "",
  9370. };
  9371. for (const auto &evil : evil_methods) {
  9372. Request req;
  9373. req.method = evil;
  9374. req.path = "/";
  9375. auto res = cli.send(req);
  9376. EXPECT_FALSE(res);
  9377. EXPECT_EQ(Error::Write, res.error());
  9378. }
  9379. auto handle =
  9380. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9381. EXPECT_FALSE(handle.is_valid());
  9382. EXPECT_EQ(Error::Write, handle.error);
  9383. // A valid request on the same client still goes through.
  9384. auto res = cli.Get("/");
  9385. ASSERT_TRUE(res);
  9386. EXPECT_EQ(StatusCode::OK_200, res->status);
  9387. }
  9388. EXPECT_EQ(1, request_count.load());
  9389. }
  9390. // Sends a raw request and verifies that there isn't a crash or exception.
  9391. static void test_raw_request(const std::string &req,
  9392. std::string *out = nullptr) {
  9393. Server svr;
  9394. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9395. res.set_content("ok", "text/plain");
  9396. });
  9397. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9398. res.set_content("ok", "text/plain");
  9399. });
  9400. svr.Get("/header_field_value_check",
  9401. [&](const Request & /*req*/, Response &res) {
  9402. res.set_content("ok", "text/plain");
  9403. });
  9404. svr.CustomRoute("PROPFIND", "/dav",
  9405. [&](const Request & /*req*/, Response &res) {
  9406. res.status = StatusCode::MultiStatus_207;
  9407. });
  9408. // Server read timeout must be longer than the client read timeout for the
  9409. // bug to reproduce, probably to force the server to process a request
  9410. // without a trailing blank line.
  9411. const time_t client_read_timeout_sec = 1;
  9412. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9413. bool listen_thread_ok = false;
  9414. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9415. auto se = detail::scope_exit([&] {
  9416. svr.stop();
  9417. t.join();
  9418. ASSERT_FALSE(svr.is_running());
  9419. EXPECT_TRUE(listen_thread_ok);
  9420. });
  9421. svr.wait_until_ready();
  9422. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9423. }
  9424. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9425. // A certain header line causes an exception if the header property is parsed
  9426. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9427. test_raw_request(
  9428. "GET /hi HTTP/1.1\r\n"
  9429. " : "
  9430. " "
  9431. " ");
  9432. }
  9433. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9434. // A certain header line causes an exception if the header property *name* is
  9435. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9436. // greedy matcher and requires backtracking when there are a lot of ":"
  9437. // characters.
  9438. // This occurs with libc++ but not libstdc++.
  9439. test_raw_request(
  9440. "GET /hi HTTP/1.1\r\n"
  9441. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9442. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9443. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9444. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9445. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9446. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9447. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9448. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9449. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9450. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9451. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9452. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9453. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9454. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9455. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9456. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9457. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9458. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9459. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9460. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9461. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9462. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9463. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9464. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9465. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9466. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9467. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9468. "&&&%%%");
  9469. }
  9470. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9471. // Make sure this doesn't crash the server.
  9472. // In a previous version of the header line regex, the "\r" rendered the line
  9473. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9474. // a new position where the leading white space ended and the field value
  9475. // began.
  9476. // The crash occurs with libc++ but not libstdc++.
  9477. test_raw_request("GET /hi HTTP/1.1\r\n"
  9478. "a:" +
  9479. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9480. "\r\n"
  9481. "\r\n");
  9482. }
  9483. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9484. const char *rejected[] = {
  9485. // RFC 9112 §3: one SP between the parts, and nothing else
  9486. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9487. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9488. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9489. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9490. // A request-target has no fragment
  9491. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9492. // An HTTP/1.1 request needs a Host
  9493. "GET /hi HTTP/1.1\r\n\r\n",
  9494. };
  9495. for (auto request : rejected) {
  9496. std::string out;
  9497. test_raw_request(request, &out);
  9498. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9499. }
  9500. std::string out;
  9501. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9502. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9503. }
  9504. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9505. // RFC 9112 §6.1
  9506. const char *requests[] = {
  9507. "PUT /put_hi HTTP/1.1\r\n"
  9508. "Host: localhost\r\n"
  9509. "Content-Length: 0\r\n"
  9510. "Transfer-Encoding: chunked\r\n"
  9511. "\r\n"
  9512. "0\r\n\r\n",
  9513. "PUT /put_hi HTTP/1.0\r\n"
  9514. "Connection: keep-alive\r\n"
  9515. "Transfer-Encoding: chunked\r\n"
  9516. "\r\n"
  9517. "0\r\n\r\n",
  9518. };
  9519. for (auto request : requests) {
  9520. std::string out;
  9521. test_raw_request(request, &out);
  9522. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9523. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9524. }
  9525. }
  9526. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9527. std::string out;
  9528. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9529. "Content-Type: text/plain\r\n"
  9530. "Transfer-Encoding: chunked\r\n"
  9531. "\r\n"
  9532. "nothex\r\n",
  9533. &out);
  9534. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9535. }
  9536. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9537. std::string out;
  9538. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9539. "Content-Type: text/plain\r\n"
  9540. "Transfer-Encoding: chunked\r\n"
  9541. "\r\n"
  9542. "3\r\n"
  9543. "xyz\r\n"
  9544. "NaN\r\n",
  9545. &out);
  9546. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9547. }
  9548. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9549. std::string out;
  9550. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9551. "Content-Type: text/plain\r\n"
  9552. "Transfer-Encoding: chunked\r\n"
  9553. "\r\n"
  9554. // Length is too large for 64 bits.
  9555. "1ffffffffffffffff\r\n"
  9556. "xyz\r\n",
  9557. &out);
  9558. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9559. }
  9560. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9561. test_raw_request("GET /hi HTTP/1.1\r\n"
  9562. "Content-Type: text/plain\r\n\r");
  9563. }
  9564. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9565. std::string out;
  9566. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9567. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9568. }
  9569. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9570. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9571. std::string out;
  9572. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9573. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9574. }
  9575. }
  9576. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9577. std::string out;
  9578. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9579. "Host: localhost\r\n"
  9580. "Connection: close\r\n\r\n",
  9581. &out);
  9582. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9583. }
  9584. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9585. Server svr;
  9586. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9587. EXPECT_TRUE(!req.remote_addr.empty());
  9588. });
  9589. thread t = thread([&] { svr.listen(HOST, PORT); });
  9590. auto se = detail::scope_exit([&] {
  9591. svr.stop();
  9592. t.join();
  9593. ASSERT_FALSE(svr.is_running());
  9594. });
  9595. svr.wait_until_ready();
  9596. // Send an invalid request line to trigger Bad Request
  9597. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9598. std::string out;
  9599. ASSERT_TRUE(send_request(5, bad_req, &out));
  9600. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9601. }
  9602. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9603. // answered right away rather than blocking on a read that waits for EOF.
  9604. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9605. std::string out;
  9606. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9607. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9608. }
  9609. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9610. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9611. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9612. for (const auto *method : methods) {
  9613. Server svr;
  9614. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9615. EXPECT_FALSE(svr.is_valid()) << method;
  9616. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9617. }
  9618. }
  9619. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9620. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9621. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9622. for (const auto *method : methods) {
  9623. Server svr;
  9624. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9625. EXPECT_FALSE(svr.is_valid()) << method;
  9626. }
  9627. }
  9628. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9629. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9630. "COPY", "MOVE", "LOCK",
  9631. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9632. Server svr;
  9633. for (const auto *method : methods) {
  9634. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9635. }
  9636. EXPECT_TRUE(svr.is_valid());
  9637. }
  9638. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9639. Server svr;
  9640. svr.CustomRoute("POST", "/x",
  9641. [](const Request &, Response &, const ContentReader &) {});
  9642. EXPECT_FALSE(svr.is_valid());
  9643. }
  9644. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9645. Server svr;
  9646. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9647. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9648. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9649. EXPECT_FALSE(svr.is_valid());
  9650. }
  9651. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9652. Server svr;
  9653. auto captured = Error::Success;
  9654. svr.set_error_logger(
  9655. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9656. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9657. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9658. }
  9659. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9660. std::string out;
  9661. std::string request(
  9662. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9663. test_raw_request(request, &out);
  9664. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9665. }
  9666. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9667. std::string out;
  9668. std::string request(
  9669. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9670. test_raw_request(request, &out);
  9671. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9672. }
  9673. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9674. std::string out;
  9675. std::string request(
  9676. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9677. test_raw_request(request, &out);
  9678. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9679. }
  9680. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9681. std::string out;
  9682. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9683. "Host: localhost\r\n"
  9684. "Test: \r\n\r\n",
  9685. &out);
  9686. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9687. }
  9688. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9689. Server svr;
  9690. std::string x_custom;
  9691. std::string cookie;
  9692. std::string xff;
  9693. std::string x_unicode;
  9694. std::string x_iis;
  9695. svr.Get("/check", [&](const Request &req, Response &res) {
  9696. x_custom = req.get_header_value("X-Custom");
  9697. cookie = req.get_header_value("Cookie");
  9698. xff = req.get_header_value("X-Forwarded-For");
  9699. x_unicode = req.get_header_value("X-Unicode");
  9700. x_iis = req.get_header_value("X-IIS");
  9701. res.set_content("ok", "text/plain");
  9702. });
  9703. thread t = thread([&] { svr.listen(HOST, PORT); });
  9704. auto se = detail::scope_exit([&] {
  9705. svr.stop();
  9706. t.join();
  9707. ASSERT_FALSE(svr.is_running());
  9708. });
  9709. svr.wait_until_ready();
  9710. const std::string req = "GET /check HTTP/1.1\r\n"
  9711. "Host: localhost\r\n"
  9712. "X-Custom: a%0D%0AInjected: b\r\n"
  9713. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9714. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9715. "X-Unicode: %E3%81%82\r\n"
  9716. "X-IIS: %u00E9\r\n"
  9717. "Connection: close\r\n"
  9718. "\r\n";
  9719. std::string res;
  9720. ASSERT_TRUE(send_request(5, req, &res));
  9721. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9722. // Every value must be returned verbatim (wire form), with no decoding.
  9723. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9724. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9725. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9726. EXPECT_EQ("%E3%81%82", x_unicode);
  9727. EXPECT_EQ("%u00E9", x_iis);
  9728. }
  9729. // Applications that previously relied on automatic percent-decoding can
  9730. // reproduce the old behavior by explicitly calling decode_path_component()
  9731. // or, for RFC 3986 conformance, decode_uri_component().
  9732. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9733. Server svr;
  9734. std::string decoded;
  9735. svr.Get("/check", [&](const Request &req, Response &res) {
  9736. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9737. res.set_content("ok", "text/plain");
  9738. });
  9739. thread t = thread([&] { svr.listen(HOST, PORT); });
  9740. auto se = detail::scope_exit([&] {
  9741. svr.stop();
  9742. t.join();
  9743. ASSERT_FALSE(svr.is_running());
  9744. });
  9745. svr.wait_until_ready();
  9746. const std::string req = "GET /check HTTP/1.1\r\n"
  9747. "Host: localhost\r\n"
  9748. "X-Custom: hello%20world\r\n"
  9749. "Connection: close\r\n"
  9750. "\r\n";
  9751. std::string res;
  9752. ASSERT_TRUE(send_request(5, req, &res));
  9753. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9754. EXPECT_EQ("hello world", decoded);
  9755. }
  9756. // Regression test for #2033. Browsers send Referer values that include
  9757. // percent-encoded characters such as %0A inside the URL. Decoding the
  9758. // header value would either trip the post-decode CR/LF/NUL guard (the
  9759. // original bug, returning 400) or, after that guard was relaxed, silently
  9760. // store a literal LF — both unacceptable. The wire form must round-trip.
  9761. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9762. Server svr;
  9763. std::string referer;
  9764. svr.Get("/check", [&](const Request &req, Response &res) {
  9765. referer = req.get_header_value("Referer");
  9766. res.set_content("ok", "text/plain");
  9767. });
  9768. thread t = thread([&] { svr.listen(HOST, PORT); });
  9769. auto se = detail::scope_exit([&] {
  9770. svr.stop();
  9771. t.join();
  9772. ASSERT_FALSE(svr.is_running());
  9773. });
  9774. svr.wait_until_ready();
  9775. const std::string req = "GET /check HTTP/1.1\r\n"
  9776. "Host: localhost\r\n"
  9777. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9778. "Connection: close\r\n"
  9779. "\r\n";
  9780. std::string res;
  9781. ASSERT_TRUE(send_request(5, req, &res));
  9782. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9783. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9784. }
  9785. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9786. Server svr;
  9787. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9788. res.set_header("Cache-Control", "no-cache");
  9789. res.set_chunked_content_provider(
  9790. "text/event-stream", [](size_t offset, DataSink &sink) {
  9791. std::string s = "data:";
  9792. s += std::to_string(offset);
  9793. s += "\n\n";
  9794. auto ret = sink.write(s.data(), s.size());
  9795. EXPECT_TRUE(ret);
  9796. std::this_thread::sleep_for(std::chrono::seconds(1));
  9797. return true;
  9798. });
  9799. });
  9800. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9801. svr.wait_until_ready();
  9802. Client client(HOST, PORT);
  9803. const Headers headers = {{"Accept", "text/event-stream"}};
  9804. auto get_thread = std::thread([&client, &headers]() {
  9805. auto res = client.Get(
  9806. "/events", headers,
  9807. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9808. });
  9809. auto se = detail::scope_exit([&] {
  9810. svr.stop();
  9811. get_thread.join();
  9812. listen_thread.join();
  9813. ASSERT_FALSE(svr.is_running());
  9814. });
  9815. // Give GET time to get a few messages.
  9816. std::this_thread::sleep_for(std::chrono::seconds(2));
  9817. }
  9818. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9819. httplib::Server svr;
  9820. svr.Post("/hi",
  9821. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9822. res.status = StatusCode::OK_200;
  9823. });
  9824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9825. svr.wait_until_ready();
  9826. Client cli(HOST, PORT);
  9827. auto res = cli.Post("/hi", "data", "text/plain");
  9828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9829. EXPECT_EQ(StatusCode::OK_200, res->status);
  9830. svr.stop();
  9831. thread.join();
  9832. ASSERT_FALSE(svr.is_running());
  9833. res = cli.Post("/hi", "data", "text/plain");
  9834. ASSERT_FALSE(res);
  9835. }
  9836. TEST(ServerStopTest, ListenFailure) {
  9837. Server svr;
  9838. auto t = thread([&]() {
  9839. auto ret = svr.listen("????", PORT);
  9840. EXPECT_FALSE(ret);
  9841. });
  9842. svr.wait_until_ready();
  9843. svr.stop();
  9844. t.join();
  9845. }
  9846. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9847. TEST(ServerStopTest, Decommision) {
  9848. Server svr;
  9849. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9850. for (int i = 0; i < 4; i++) {
  9851. auto is_even = !(i % 2);
  9852. std::thread t{[&] {
  9853. try {
  9854. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9855. if (is_even) {
  9856. throw std::runtime_error("Some thing that happens to go wrong.");
  9857. }
  9858. svr.listen(HOST, PORT);
  9859. } catch (...) { svr.decommission(); }
  9860. }};
  9861. svr.wait_until_ready();
  9862. // Server is up
  9863. {
  9864. Client cli(HOST, PORT);
  9865. auto res = cli.Get("/hi");
  9866. if (is_even) {
  9867. EXPECT_FALSE(res);
  9868. } else {
  9869. EXPECT_TRUE(res);
  9870. EXPECT_EQ("hi...", res->body);
  9871. }
  9872. }
  9873. svr.stop();
  9874. t.join();
  9875. // Server is down...
  9876. {
  9877. Client cli(HOST, PORT);
  9878. auto res = cli.Get("/hi");
  9879. EXPECT_FALSE(res);
  9880. }
  9881. }
  9882. }
  9883. #endif
  9884. // Helper function for string body upload progress tests
  9885. template <typename SetupHandler, typename ClientCall>
  9886. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9887. ClientCall &&client_call,
  9888. const string &body) {
  9889. Server svr;
  9890. setup_handler(svr);
  9891. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9892. auto se = detail::scope_exit([&] {
  9893. svr.stop();
  9894. t.join();
  9895. });
  9896. svr.wait_until_ready();
  9897. Client cli(HOST, PORT);
  9898. vector<uint64_t> progress_values;
  9899. bool progress_called = false;
  9900. auto res =
  9901. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9902. progress_values.push_back(current);
  9903. progress_called = true;
  9904. return true;
  9905. });
  9906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9907. EXPECT_EQ(200, res->status);
  9908. EXPECT_TRUE(progress_called);
  9909. }
  9910. TEST(UploadProgressTest, PostStringBodyBasic) {
  9911. TestStringBodyUploadProgress(
  9912. [](Server &svr) {
  9913. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9914. res.set_content("received", "text/plain");
  9915. });
  9916. },
  9917. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9918. return cli.Post("/test", body, "text/plain", progress_callback);
  9919. },
  9920. "test data for upload progress");
  9921. }
  9922. TEST(UploadProgressTest, PutStringBodyBasic) {
  9923. TestStringBodyUploadProgress(
  9924. [](Server &svr) {
  9925. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9926. res.set_content("put received", "text/plain");
  9927. });
  9928. },
  9929. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9930. return cli.Put("/test", body, "text/plain", progress_callback);
  9931. },
  9932. "put test data for upload progress");
  9933. }
  9934. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9935. TestStringBodyUploadProgress(
  9936. [](Server &svr) {
  9937. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9938. res.set_content("patch received", "text/plain");
  9939. });
  9940. },
  9941. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9942. return cli.Patch("/test", body, "text/plain", progress_callback);
  9943. },
  9944. "patch test data for upload progress");
  9945. }
  9946. // Helper function for content provider upload progress tests
  9947. template <typename SetupHandler, typename ClientCall>
  9948. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9949. ClientCall &&client_call) {
  9950. Server svr;
  9951. setup_handler(svr);
  9952. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9953. auto se = detail::scope_exit([&] {
  9954. svr.stop();
  9955. t.join();
  9956. });
  9957. svr.wait_until_ready();
  9958. Client cli(HOST, PORT);
  9959. vector<uint64_t> progress_values;
  9960. auto res =
  9961. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9962. progress_values.push_back(current);
  9963. return true;
  9964. });
  9965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9966. EXPECT_EQ(200, res->status);
  9967. EXPECT_FALSE(progress_values.empty());
  9968. }
  9969. TEST(UploadProgressTest, PostContentProviderProgress) {
  9970. TestContentProviderUploadProgress(
  9971. [](Server &svr) {
  9972. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9973. res.set_content("provider received", "text/plain");
  9974. });
  9975. },
  9976. [](Client &cli, UploadProgress progress_callback) {
  9977. return cli.Post(
  9978. "/test", 9,
  9979. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9980. sink.os << "test data";
  9981. return true;
  9982. },
  9983. "text/plain", progress_callback);
  9984. });
  9985. }
  9986. // Helper function for multipart upload progress tests
  9987. template <typename SetupHandler, typename ClientCall>
  9988. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9989. ClientCall &&client_call,
  9990. const string &endpoint) {
  9991. Server svr;
  9992. setup_handler(svr);
  9993. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9994. auto se = detail::scope_exit([&] {
  9995. svr.stop();
  9996. t.join();
  9997. });
  9998. svr.wait_until_ready();
  9999. Client cli(HOST, PORT);
  10000. vector<uint64_t> progress_values;
  10001. UploadFormDataItems items = {
  10002. {"field1", "value1", "", ""},
  10003. {"field2", "longer value for progress tracking test", "", ""},
  10004. {"file1", "file content data for upload progress", "test.txt",
  10005. "text/plain"}};
  10006. auto res = client_call(cli, endpoint, items,
  10007. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10008. progress_values.push_back(current);
  10009. return true;
  10010. });
  10011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10012. EXPECT_EQ(200, res->status);
  10013. EXPECT_FALSE(progress_values.empty());
  10014. }
  10015. TEST(UploadProgressTest, PostMultipartProgress) {
  10016. TestMultipartUploadProgress(
  10017. [](Server &svr) {
  10018. svr.Post("/multipart", [](const Request &req, Response &res) {
  10019. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10020. res.set_content("multipart received", "text/plain");
  10021. });
  10022. },
  10023. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10024. UploadProgress progress_callback) {
  10025. return cli.Post(endpoint, items, progress_callback);
  10026. },
  10027. "/multipart");
  10028. }
  10029. // Helper function for basic download progress tests
  10030. template <typename SetupHandler, typename ClientCall>
  10031. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10032. ClientCall &&client_call, const string &endpoint,
  10033. size_t expected_content_size) {
  10034. Server svr;
  10035. setup_handler(svr);
  10036. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. t.join();
  10040. });
  10041. svr.wait_until_ready();
  10042. Client cli(HOST, PORT);
  10043. vector<uint64_t> progress_values;
  10044. auto res = client_call(cli, endpoint,
  10045. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10046. progress_values.push_back(current);
  10047. return true;
  10048. });
  10049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10050. EXPECT_EQ(200, res->status);
  10051. EXPECT_FALSE(progress_values.empty());
  10052. EXPECT_EQ(expected_content_size, res->body.size());
  10053. }
  10054. TEST(DownloadProgressTest, GetBasic) {
  10055. TestBasicDownloadProgress(
  10056. [](Server &svr) {
  10057. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10058. string content(1000, 'D');
  10059. res.set_content(content, "text/plain");
  10060. });
  10061. },
  10062. [](Client &cli, const string &endpoint,
  10063. DownloadProgress progress_callback) {
  10064. return cli.Get(endpoint, progress_callback);
  10065. },
  10066. "/download", 1000u);
  10067. }
  10068. // Helper function for content receiver download progress tests
  10069. template <typename SetupHandler, typename ClientCall>
  10070. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10071. ClientCall &&client_call,
  10072. const string &endpoint,
  10073. size_t expected_content_size) {
  10074. Server svr;
  10075. setup_handler(svr);
  10076. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10077. auto se = detail::scope_exit([&] {
  10078. svr.stop();
  10079. t.join();
  10080. });
  10081. svr.wait_until_ready();
  10082. Client cli(HOST, PORT);
  10083. vector<uint64_t> progress_values;
  10084. string received_body;
  10085. auto res = client_call(
  10086. cli, endpoint,
  10087. [&](const char *data, size_t data_length) -> bool {
  10088. received_body.append(data, data_length);
  10089. return true;
  10090. },
  10091. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10092. progress_values.push_back(current);
  10093. return true;
  10094. });
  10095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10096. EXPECT_EQ(200, res->status);
  10097. EXPECT_FALSE(progress_values.empty());
  10098. EXPECT_EQ(expected_content_size, received_body.size());
  10099. EXPECT_TRUE(res->body.empty());
  10100. }
  10101. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10102. TestContentReceiverDownloadProgress(
  10103. [](Server &svr) {
  10104. svr.Get("/download-receiver",
  10105. [](const Request & /*req*/, Response &res) {
  10106. string content(2000, 'R');
  10107. res.set_content(content, "text/plain");
  10108. });
  10109. },
  10110. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10111. DownloadProgress progress_callback) {
  10112. return cli.Get(endpoint, content_receiver, progress_callback);
  10113. },
  10114. "/download-receiver", 2000u);
  10115. }
  10116. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10117. // A provider reaching a pass with nothing to hand over - an empty buffer
  10118. // popped off a queue, say - must not be taken to mean the body is finished.
  10119. // It used to end the loop with the terminating chunk unwritten while the
  10120. // server still considered the response complete, so the peer waited for an
  10121. // end that never arrived.
  10122. Server svr;
  10123. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10124. auto step = std::make_shared<int>(0);
  10125. res.set_chunked_content_provider("text/plain",
  10126. [step](size_t /*offset*/, DataSink &sink) {
  10127. switch ((*step)++) {
  10128. case 0: sink.write("", 0); break;
  10129. case 1: sink.write("hello", 5); break;
  10130. default: sink.done(); break;
  10131. }
  10132. return true;
  10133. });
  10134. });
  10135. auto port = svr.bind_to_any_port(HOST);
  10136. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10137. auto listen_se = detail::scope_exit([&] {
  10138. svr.stop();
  10139. listen_thread.join();
  10140. ASSERT_FALSE(svr.is_running());
  10141. });
  10142. svr.wait_until_ready();
  10143. Client cli(HOST, port);
  10144. // Without the fix the body is never terminated, so bound the wait rather
  10145. // than letting the test hang on the default read timeout.
  10146. cli.set_read_timeout(5, 0);
  10147. auto res = cli.Get("/stream");
  10148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10149. EXPECT_EQ(StatusCode::OK_200, res->status);
  10150. EXPECT_EQ("hello", res->body);
  10151. }
  10152. TEST(StreamingTest, NoContentLengthStreaming) {
  10153. Server svr;
  10154. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10155. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10156. if (offset < 6) {
  10157. sink.os << (offset < 3 ? "a" : "b");
  10158. } else {
  10159. sink.done();
  10160. }
  10161. return true;
  10162. });
  10163. });
  10164. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10165. auto listen_se = detail::scope_exit([&] {
  10166. svr.stop();
  10167. listen_thread.join();
  10168. ASSERT_FALSE(svr.is_running());
  10169. });
  10170. svr.wait_until_ready();
  10171. Client client(HOST, PORT);
  10172. auto get_thread = std::thread([&client]() {
  10173. std::string s;
  10174. auto res =
  10175. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10176. s += std::string(data, len);
  10177. return true;
  10178. });
  10179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10180. EXPECT_EQ(StatusCode::OK_200, res->status);
  10181. EXPECT_EQ("aaabbb", s);
  10182. });
  10183. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10184. // Give GET time to get a few messages.
  10185. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10186. }
  10187. TEST(MountTest, Unmount) {
  10188. Server svr;
  10189. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. listen_thread.join();
  10193. ASSERT_FALSE(svr.is_running());
  10194. });
  10195. svr.wait_until_ready();
  10196. Client cli("localhost", PORT);
  10197. svr.set_mount_point("/mount2", "./www2");
  10198. auto res = cli.Get("/");
  10199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10200. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10201. res = cli.Get("/mount2/dir/test.html");
  10202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10203. EXPECT_EQ(StatusCode::OK_200, res->status);
  10204. svr.set_mount_point("/", "./www");
  10205. res = cli.Get("/dir/");
  10206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10207. EXPECT_EQ(StatusCode::OK_200, res->status);
  10208. svr.remove_mount_point("/");
  10209. res = cli.Get("/dir/");
  10210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10211. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10212. svr.remove_mount_point("/mount2");
  10213. res = cli.Get("/mount2/dir/test.html");
  10214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10216. }
  10217. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10218. Server svr;
  10219. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10220. svr.Get("/api/hello", [](const Request &, Response &res) {
  10221. res.set_content("api", "text/plain");
  10222. });
  10223. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10224. auto se = detail::scope_exit([&] {
  10225. svr.stop();
  10226. listen_thread.join();
  10227. ASSERT_FALSE(svr.is_running());
  10228. });
  10229. svr.wait_until_ready();
  10230. Client cli(HOST, PORT);
  10231. auto res = cli.Get("/dir/test.html");
  10232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10233. EXPECT_EQ(StatusCode::OK_200, res->status);
  10234. res = cli.Get("/api/hello");
  10235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10236. EXPECT_EQ(StatusCode::OK_200, res->status);
  10237. EXPECT_EQ("api", res->body);
  10238. }
  10239. TEST(MountTest, PathSegmentBoundary) {
  10240. Server svr;
  10241. svr.set_mount_point("/mount2", "./www2");
  10242. svr.set_mount_point("/", "./www");
  10243. auto port = svr.bind_to_any_port(HOST);
  10244. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10245. auto se = detail::scope_exit([&] {
  10246. svr.stop();
  10247. listen_thread.join();
  10248. ASSERT_FALSE(svr.is_running());
  10249. });
  10250. svr.wait_until_ready();
  10251. Client cli(HOST, port);
  10252. auto res = cli.Get("/mount2/dir/test.html");
  10253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10254. EXPECT_EQ(StatusCode::OK_200, res->status);
  10255. // "/mount2" must not match part-way through a path segment.
  10256. res = cli.Get("/mount2dir/test.html");
  10257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10258. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10259. // A mount point ending in '/' keeps matching every path below it.
  10260. res = cli.Get("/dir/test.html");
  10261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10262. EXPECT_EQ(StatusCode::OK_200, res->status);
  10263. }
  10264. TEST(MountTest, Redicect) {
  10265. Server svr;
  10266. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10267. auto se = detail::scope_exit([&] {
  10268. svr.stop();
  10269. listen_thread.join();
  10270. ASSERT_FALSE(svr.is_running());
  10271. });
  10272. svr.set_mount_point("/", "./www");
  10273. svr.wait_until_ready();
  10274. Client cli("localhost", PORT);
  10275. auto res = cli.Get("/dir/");
  10276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10277. EXPECT_EQ(StatusCode::OK_200, res->status);
  10278. res = cli.Get("/dir");
  10279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10280. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10281. res = cli.Get("/file");
  10282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10283. EXPECT_EQ(StatusCode::OK_200, res->status);
  10284. res = cli.Get("/file/");
  10285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10287. cli.set_follow_location(true);
  10288. res = cli.Get("/dir");
  10289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10290. EXPECT_EQ(StatusCode::OK_200, res->status);
  10291. }
  10292. TEST(MountTest, MultibytesPathName) {
  10293. Server svr;
  10294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10295. auto se = detail::scope_exit([&] {
  10296. svr.stop();
  10297. listen_thread.join();
  10298. ASSERT_FALSE(svr.is_running());
  10299. });
  10300. svr.set_mount_point("/", "./www");
  10301. svr.wait_until_ready();
  10302. Client cli("localhost", PORT);
  10303. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10305. EXPECT_EQ(StatusCode::OK_200, res->status);
  10306. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10307. }
  10308. #ifdef _WIN32
  10309. // Issue #2435: mmap::open() must succeed even when another handle holds
  10310. // the file open for writing (e.g. an active log file).
  10311. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10312. const char *path = "mmap_concurrent_writer_test.txt";
  10313. const char *content = "hello";
  10314. {
  10315. std::ofstream f(path, std::ios::binary);
  10316. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10317. }
  10318. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10319. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10320. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10321. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10322. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10323. detail::mmap m(path);
  10324. ASSERT_TRUE(m.is_open());
  10325. EXPECT_EQ(strlen(content), m.size());
  10326. char buf[8];
  10327. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10328. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10329. }
  10330. #endif
  10331. #ifndef _WIN32
  10332. // A directory or a device has no size to serve.
  10333. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10334. const char *path = "./mmap_not_regular_test_dir";
  10335. ASSERT_EQ(0, ::mkdir(path, 0755));
  10336. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10337. for (auto p : {path, "/dev/null"}) {
  10338. detail::mmap m(p);
  10339. EXPECT_FALSE(m.is_open()) << p;
  10340. EXPECT_EQ(0U, m.size()) << p;
  10341. }
  10342. Server svr;
  10343. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10344. res.set_file_content("/dev/null");
  10345. });
  10346. auto port = svr.bind_to_any_port(HOST);
  10347. thread t = thread([&] { svr.listen_after_bind(); });
  10348. auto se = detail::scope_exit([&] {
  10349. svr.stop();
  10350. t.join();
  10351. });
  10352. svr.wait_until_ready();
  10353. auto res = Client(HOST, port).Get("/null");
  10354. ASSERT_TRUE(res);
  10355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10356. }
  10357. #endif
  10358. #ifdef __linux__
  10359. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10360. TEST(MmapTest, FileIsNotMapped) {
  10361. const char *path = "mmap_not_mapped_test.txt";
  10362. {
  10363. std::ofstream f(path, std::ios::binary);
  10364. f << "hello";
  10365. }
  10366. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10367. detail::mmap m(path);
  10368. ASSERT_TRUE(m.is_open());
  10369. std::ifstream maps("/proc/self/maps");
  10370. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10371. std::istreambuf_iterator<char>());
  10372. EXPECT_EQ(std::string::npos, mappings.find(path));
  10373. }
  10374. #endif
  10375. TEST(KeepAliveTest, ReadTimeout) {
  10376. Server svr;
  10377. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10378. std::this_thread::sleep_for(std::chrono::seconds(2));
  10379. res.set_content("a", "text/plain");
  10380. });
  10381. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10382. res.set_content("b", "text/plain");
  10383. });
  10384. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10385. auto se = detail::scope_exit([&] {
  10386. svr.stop();
  10387. listen_thread.join();
  10388. ASSERT_FALSE(svr.is_running());
  10389. });
  10390. svr.wait_until_ready();
  10391. Client cli("localhost", PORT);
  10392. cli.set_keep_alive(true);
  10393. cli.set_read_timeout(std::chrono::seconds(1));
  10394. auto resa = cli.Get("/a");
  10395. ASSERT_FALSE(resa);
  10396. EXPECT_EQ(Error::Read, resa.error());
  10397. auto resb = cli.Get("/b");
  10398. ASSERT_TRUE(resb);
  10399. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10400. EXPECT_EQ("b", resb->body);
  10401. }
  10402. TEST(KeepAliveTest, MaxCount) {
  10403. size_t keep_alive_max_count = 3;
  10404. Server svr;
  10405. svr.set_keep_alive_max_count(keep_alive_max_count);
  10406. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10407. res.set_content("Hello World!", "text/plain");
  10408. });
  10409. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10410. auto se = detail::scope_exit([&] {
  10411. svr.stop();
  10412. listen_thread.join();
  10413. ASSERT_FALSE(svr.is_running());
  10414. });
  10415. svr.wait_until_ready();
  10416. Client cli(HOST, PORT);
  10417. cli.set_keep_alive(true);
  10418. for (size_t i = 0; i < 5; i++) {
  10419. auto result = cli.Get("/hi");
  10420. ASSERT_TRUE(result);
  10421. EXPECT_EQ(StatusCode::OK_200, result->status);
  10422. if (i == keep_alive_max_count - 1) {
  10423. EXPECT_EQ("close", result->get_header_value("Connection"));
  10424. } else {
  10425. EXPECT_FALSE(result->has_header("Connection"));
  10426. }
  10427. }
  10428. }
  10429. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10430. // can pull the next one into the server's buffer. The server must serve it
  10431. // without waiting for the socket to become readable again. The keep-alive
  10432. // timeout outlasts the client's read timeout, so a request left waiting for it
  10433. // shows up as a missing response.
  10434. static void serve_pipelining_routes(Server &svr,
  10435. const std::function<void(int)> &client) {
  10436. svr.set_keep_alive_timeout(5);
  10437. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10438. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10439. });
  10440. svr.Post("/echo", [](const Request &req, Response &res) {
  10441. res.set_content("echo " + req.body, "text/plain");
  10442. });
  10443. auto port = svr.bind_to_any_port(HOST);
  10444. thread t = thread([&] { svr.listen_after_bind(); });
  10445. auto se = detail::scope_exit([&] {
  10446. svr.stop();
  10447. t.join();
  10448. });
  10449. svr.wait_until_ready();
  10450. client(port);
  10451. }
  10452. static std::string
  10453. send_pipelined_requests(const std::vector<std::string> &parts) {
  10454. Server svr;
  10455. std::string res;
  10456. serve_pipelining_routes(svr, [&](int port) {
  10457. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10458. });
  10459. return res;
  10460. }
  10461. static void expect_in_order(const std::string &res,
  10462. const std::vector<std::string> &bodies) {
  10463. size_t pos = 0;
  10464. for (const auto &body : bodies) {
  10465. pos = res.find(body, pos);
  10466. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10467. pos += body.size();
  10468. }
  10469. }
  10470. TEST(KeepAliveTest, PipelinedRequests) {
  10471. auto res = send_pipelined_requests(
  10472. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10473. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10474. "Content-Length: 4\r\n\r\nbody"
  10475. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10476. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10477. }
  10478. // The second request starts in the server's buffer and ends on the socket.
  10479. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10480. auto res =
  10481. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10482. "GET /hi/2 HTTP/1.1\r\nHo",
  10483. "st: localhost\r\nConnection: close\r\n\r\n"});
  10484. expect_in_order(res, {"hi 1", "hi 2"});
  10485. }
  10486. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10487. // CRLF after a body does not turn into a 400 for the next request.
  10488. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10489. auto res = send_pipelined_requests(
  10490. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10491. "Content-Length: 4\r\n\r\nbody\r\n"
  10492. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10493. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10494. expect_in_order(res, {"echo body", "hi 2"});
  10495. }
  10496. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10497. // must not be served as the next request.
  10498. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10499. auto res = send_pipelined_requests(
  10500. {"INVALID REQUEST LINE\r\n\r\n"
  10501. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10502. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10503. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10504. }
  10505. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10506. // Over TLS, the next request is held by the TLS library as already decrypted
  10507. // data rather than on the socket.
  10508. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10509. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10510. std::string res;
  10511. serve_pipelining_routes(svr, [&](int port) {
  10512. // One part, so all three requests arrive in one TLS record
  10513. EXPECT_TRUE(send_ssl_request_in_parts(
  10514. 2,
  10515. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10516. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10517. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10518. &res, port));
  10519. });
  10520. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10521. }
  10522. #endif
  10523. TEST(KeepAliveTest, Issue1041) {
  10524. Server svr;
  10525. svr.set_keep_alive_timeout(3);
  10526. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10527. res.set_content("Hello World!", "text/plain");
  10528. });
  10529. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10530. auto se = detail::scope_exit([&] {
  10531. svr.stop();
  10532. listen_thread.join();
  10533. ASSERT_FALSE(svr.is_running());
  10534. });
  10535. svr.wait_until_ready();
  10536. Client cli(HOST, PORT);
  10537. cli.set_keep_alive(true);
  10538. auto result = cli.Get("/hi");
  10539. ASSERT_TRUE(result);
  10540. EXPECT_EQ(StatusCode::OK_200, result->status);
  10541. std::this_thread::sleep_for(std::chrono::seconds(5));
  10542. result = cli.Get("/hi");
  10543. ASSERT_TRUE(result);
  10544. EXPECT_EQ(StatusCode::OK_200, result->status);
  10545. }
  10546. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10547. Server svr;
  10548. svr.set_keep_alive_max_count(0);
  10549. std::set<int> remote_ports;
  10550. svr.Get("/hi", [&](const Request &req, Response &res) {
  10551. remote_ports.insert(req.remote_port);
  10552. res.set_content("hi", "text/plain");
  10553. });
  10554. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  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. cli.set_keep_alive(true);
  10563. for (int i = 0; i < 3; i++) {
  10564. auto res = cli.Get("/hi");
  10565. ASSERT_TRUE(res);
  10566. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10567. }
  10568. // All three over one connection
  10569. EXPECT_EQ(1u, remote_ports.size());
  10570. }
  10571. TEST(KeepAliveTest, Issue1959) {
  10572. Server svr;
  10573. svr.set_keep_alive_timeout(5);
  10574. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10575. res.set_content("a", "text/plain");
  10576. });
  10577. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10578. auto se = detail::scope_exit([&] {
  10579. if (!svr.is_running()) return;
  10580. svr.stop();
  10581. listen_thread.join();
  10582. ASSERT_FALSE(svr.is_running());
  10583. });
  10584. svr.wait_until_ready();
  10585. Client cli("localhost", PORT);
  10586. cli.set_keep_alive(true);
  10587. using namespace std::chrono;
  10588. auto start = steady_clock::now();
  10589. cli.Get("/a");
  10590. svr.stop();
  10591. listen_thread.join();
  10592. auto end = steady_clock::now();
  10593. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10594. EXPECT_LT(elapsed, 5000);
  10595. }
  10596. #ifdef CPPHTTPLIB_SSL_ENABLED
  10597. TEST(KeepAliveTest, SSLClientReconnection) {
  10598. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10599. ASSERT_TRUE(svr.is_valid());
  10600. svr.set_keep_alive_timeout(1);
  10601. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10602. res.set_content("Hello World!", "text/plain");
  10603. });
  10604. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10605. auto se = detail::scope_exit([&] {
  10606. svr.stop();
  10607. listen_thread.join();
  10608. ASSERT_FALSE(svr.is_running());
  10609. });
  10610. svr.wait_until_ready();
  10611. SSLClient cli(HOST, PORT);
  10612. cli.enable_server_certificate_verification(false);
  10613. cli.set_keep_alive(true);
  10614. auto result = cli.Get("/hi");
  10615. ASSERT_TRUE(result);
  10616. EXPECT_EQ(StatusCode::OK_200, result->status);
  10617. result = cli.Get("/hi");
  10618. ASSERT_TRUE(result);
  10619. EXPECT_EQ(StatusCode::OK_200, result->status);
  10620. std::this_thread::sleep_for(std::chrono::seconds(2));
  10621. // Recoonect
  10622. result = cli.Get("/hi");
  10623. ASSERT_TRUE(result);
  10624. EXPECT_EQ(StatusCode::OK_200, result->status);
  10625. result = cli.Get("/hi");
  10626. ASSERT_TRUE(result);
  10627. EXPECT_EQ(StatusCode::OK_200, result->status);
  10628. }
  10629. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10631. ASSERT_TRUE(svr.is_valid());
  10632. svr.set_keep_alive_timeout(1);
  10633. std::string content = "reconnect";
  10634. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10635. res.set_content("Hello World!", "text/plain");
  10636. });
  10637. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10638. auto se = detail::scope_exit([&] {
  10639. svr.stop();
  10640. listen_thread.join();
  10641. ASSERT_FALSE(svr.is_running());
  10642. });
  10643. svr.wait_until_ready();
  10644. SSLClient cli(HOST, PORT);
  10645. cli.enable_server_certificate_verification(false);
  10646. cli.set_keep_alive(true);
  10647. auto result = cli.Post(
  10648. "/hi", content.size(),
  10649. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10650. sink.write(content.c_str(), content.size());
  10651. return true;
  10652. },
  10653. "text/plain");
  10654. ASSERT_TRUE(result);
  10655. EXPECT_EQ(200, result->status);
  10656. std::this_thread::sleep_for(std::chrono::seconds(2));
  10657. // Recoonect
  10658. result = cli.Post(
  10659. "/hi", content.size(),
  10660. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10661. sink.write(content.c_str(), content.size());
  10662. return true;
  10663. },
  10664. "text/plain");
  10665. ASSERT_TRUE(result);
  10666. EXPECT_EQ(200, result->status);
  10667. result = cli.Post(
  10668. "/hi", content.size(),
  10669. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10670. sink.write(content.c_str(), content.size());
  10671. return true;
  10672. },
  10673. "text/plain");
  10674. ASSERT_TRUE(result);
  10675. EXPECT_EQ(200, result->status);
  10676. }
  10677. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10678. using namespace httplib::tls;
  10679. {
  10680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10681. ASSERT_TRUE(svr.is_valid());
  10682. svr.Get("/sni", [&](const Request &req, Response &res) {
  10683. std::string expected = req.sni();
  10684. EXPECT_EQ(expected, req.get_param_value("expected"));
  10685. res.set_content("ok", "text/plain");
  10686. });
  10687. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10688. auto se = detail::scope_exit([&] {
  10689. svr.stop();
  10690. listen_thread.join();
  10691. ASSERT_FALSE(svr.is_running());
  10692. });
  10693. svr.wait_until_ready();
  10694. {
  10695. SSLClient cli("localhost", PORT);
  10696. cli.enable_server_certificate_verification(false);
  10697. auto res = cli.Get("/sni?expected=localhost");
  10698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10699. }
  10700. {
  10701. SSLClient cli("::1", PORT);
  10702. cli.enable_server_certificate_verification(false);
  10703. auto res = cli.Get("/sni?expected=");
  10704. // NOTE: This may fail if the server is listening on IPv4 only
  10705. // (e.g., when localhost resolves to 127.0.0.1 only)
  10706. if (res) {
  10707. EXPECT_EQ(StatusCode::OK_200, res->status);
  10708. } else {
  10709. EXPECT_EQ(Error::Connection, res.error());
  10710. }
  10711. }
  10712. }
  10713. }
  10714. #endif
  10715. TEST(ClientProblemDetectionTest, ContentProvider) {
  10716. Server svr;
  10717. size_t content_length = 1024 * 1024;
  10718. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10719. res.set_content_provider(
  10720. content_length, "text/plain",
  10721. [&](size_t offset, size_t length, DataSink &sink) {
  10722. auto out_len = std::min(length, static_cast<size_t>(1024));
  10723. std::string out(out_len, '@');
  10724. sink.write(out.data(), out_len);
  10725. return offset < 4096;
  10726. },
  10727. [](bool success) { ASSERT_FALSE(success); });
  10728. });
  10729. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10730. res.set_content_provider(
  10731. 0, "text/plain",
  10732. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10733. EXPECT_TRUE(false);
  10734. return true;
  10735. },
  10736. [](bool success) { ASSERT_FALSE(success); });
  10737. });
  10738. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10739. auto se = detail::scope_exit([&] {
  10740. svr.stop();
  10741. listen_thread.join();
  10742. ASSERT_FALSE(svr.is_running());
  10743. });
  10744. svr.wait_until_ready();
  10745. Client cli("localhost", PORT);
  10746. {
  10747. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10748. size_t /*data_length*/) { return false; });
  10749. ASSERT_FALSE(res);
  10750. }
  10751. {
  10752. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10753. size_t /*data_length*/) { return false; });
  10754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10755. }
  10756. }
  10757. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10758. // A provider that reports success without writing anything and without
  10759. // calling done() used to be handed the same offset and length again on every
  10760. // pass, so it spun for as long as the peer stayed connected.
  10761. Server svr;
  10762. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10763. res.set_content("ok", "text/plain");
  10764. });
  10765. auto port = svr.bind_to_any_port(HOST);
  10766. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10767. auto se = detail::scope_exit([&] {
  10768. svr.stop();
  10769. listen_thread.join();
  10770. ASSERT_FALSE(svr.is_running());
  10771. });
  10772. svr.wait_until_ready();
  10773. std::atomic<int> call_count{0};
  10774. Client cli(HOST, port);
  10775. auto res = cli.Post(
  10776. "/", 1024,
  10777. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10778. // Give up after enough passes to show the spin, so that losing the
  10779. // check below fails this test instead of hanging it.
  10780. return ++call_count < 100;
  10781. },
  10782. "text/plain");
  10783. ASSERT_FALSE(res);
  10784. EXPECT_EQ(Error::Write, res.error());
  10785. EXPECT_EQ(1, call_count.load());
  10786. }
  10787. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10788. // A writer only has to assign `write`. The other three used to be left as
  10789. // empty std::functions, so a provider calling one threw
  10790. // std::bad_function_call out of the thread running it and took the whole
  10791. // process down.
  10792. DataSink sink;
  10793. std::string written;
  10794. sink.write = [&](const char *data, size_t data_len) {
  10795. written.append(data, data_len);
  10796. return true;
  10797. };
  10798. EXPECT_TRUE(sink.is_writable());
  10799. sink.done();
  10800. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10801. EXPECT_TRUE(written.empty());
  10802. }
  10803. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10804. // A sink that cannot carry trailers still has to finish.
  10805. DataSink sink;
  10806. auto done_count = 0;
  10807. sink.done = [&]() { done_count++; };
  10808. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10809. EXPECT_EQ(1, done_count);
  10810. }
  10811. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10812. Server svr;
  10813. const std::string body(4096, 'x');
  10814. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10815. res.set_content_provider(body.size(), "text/plain",
  10816. [&](size_t offset, size_t length, DataSink &sink) {
  10817. sink.write(body.data() + offset, length);
  10818. sink.done();
  10819. return true;
  10820. });
  10821. });
  10822. auto port = svr.bind_to_any_port(HOST);
  10823. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10824. auto se = detail::scope_exit([&] {
  10825. svr.stop();
  10826. listen_thread.join();
  10827. ASSERT_FALSE(svr.is_running());
  10828. });
  10829. svr.wait_until_ready();
  10830. Client cli(HOST, port);
  10831. auto res = cli.Get("/");
  10832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10833. EXPECT_EQ(StatusCode::OK_200, res->status);
  10834. EXPECT_EQ(body, res->body);
  10835. }
  10836. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10837. Server svr;
  10838. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10839. res.set_content_provider(
  10840. 1024, "text/plain",
  10841. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10842. sink.write("hello", 5);
  10843. sink.done(); // short of the 1024 bytes the response promised
  10844. return true;
  10845. });
  10846. });
  10847. auto port = svr.bind_to_any_port(HOST);
  10848. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10849. auto se = detail::scope_exit([&] {
  10850. svr.stop();
  10851. listen_thread.join();
  10852. ASSERT_FALSE(svr.is_running());
  10853. });
  10854. svr.wait_until_ready();
  10855. Client cli(HOST, port);
  10856. cli.set_read_timeout(5, 0);
  10857. // The response is short of its Content-Length, so the client cannot read a
  10858. // complete body. What matters is that this returns at all: a no-op done()
  10859. // would leave the writer looping over a provider that never makes progress.
  10860. auto res = cli.Get("/");
  10861. EXPECT_FALSE(res);
  10862. }
  10863. // Read as the next response by a peer that sees it after a framed body.
  10864. static const std::string smuggled_response =
  10865. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  10866. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  10867. Server svr;
  10868. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10869. res.set_content_provider(
  10870. 5, "text/plain",
  10871. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10872. auto data = "AAAAA" + smuggled_response;
  10873. sink.write(data.data(), data.size());
  10874. return true;
  10875. });
  10876. });
  10877. thread t = thread([&] { svr.listen(HOST, PORT); });
  10878. auto se = detail::scope_exit([&] {
  10879. svr.stop();
  10880. t.join();
  10881. ASSERT_FALSE(svr.is_running());
  10882. });
  10883. svr.wait_until_ready();
  10884. std::string resp;
  10885. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10886. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  10887. resp.clear();
  10888. ASSERT_TRUE(send_request(
  10889. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  10890. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  10891. }
  10892. TEST(NoContentTest, BodyIsNotSent) {
  10893. Server svr;
  10894. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  10895. res.status = StatusCode::NoContent_204;
  10896. res.set_content(smuggled_response, "text/plain");
  10897. });
  10898. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  10899. res.status = StatusCode::NotModified_304;
  10900. res.set_chunked_content_provider(
  10901. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  10902. sink.write(smuggled_response.data(), smuggled_response.size());
  10903. sink.done();
  10904. return true;
  10905. });
  10906. });
  10907. thread t = thread([&] { svr.listen(HOST, PORT); });
  10908. auto se = detail::scope_exit([&] {
  10909. svr.stop();
  10910. t.join();
  10911. ASSERT_FALSE(svr.is_running());
  10912. });
  10913. svr.wait_until_ready();
  10914. for (auto path : {"/204", "/304"}) {
  10915. std::string resp;
  10916. ASSERT_TRUE(send_request(
  10917. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10918. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  10919. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  10920. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  10921. }
  10922. }
  10923. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  10924. Server svr;
  10925. std::atomic<bool> smuggled(false);
  10926. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10927. res.set_content("ok", "text/plain");
  10928. });
  10929. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  10930. smuggled = true;
  10931. });
  10932. auto port = svr.bind_to_any_port(HOST);
  10933. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10934. auto se = detail::scope_exit([&] {
  10935. svr.stop();
  10936. listen_thread.join();
  10937. ASSERT_FALSE(svr.is_running());
  10938. });
  10939. svr.wait_until_ready();
  10940. // What follows the body would be read as the next request.
  10941. Client cli(HOST, port);
  10942. auto res = cli.Post(
  10943. "/", 5,
  10944. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10945. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  10946. sink.write(data.data(), data.size());
  10947. return true;
  10948. },
  10949. "text/plain");
  10950. ASSERT_FALSE(res);
  10951. EXPECT_EQ(Error::Write, res.error());
  10952. EXPECT_FALSE(smuggled);
  10953. }
  10954. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10955. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10956. // The compressed path builds the whole body before connecting, so this
  10957. // fails client-side and never reaches a server.
  10958. Client cli(HOST, PORT);
  10959. cli.set_compress(true);
  10960. auto res = cli.Post(
  10961. "/", 1024,
  10962. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10963. sink.write("hello", 5);
  10964. sink.done(); // short of the 1024 bytes the request announced
  10965. return true;
  10966. },
  10967. "text/plain");
  10968. ASSERT_FALSE(res);
  10969. EXPECT_EQ(Error::Write, res.error());
  10970. }
  10971. #endif
  10972. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10973. Server svr;
  10974. svr.set_error_handler([](Request const &, Response &res) -> void {
  10975. res.set_chunked_content_provider(
  10976. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10977. sink.os << "hello";
  10978. sink.os << "world";
  10979. sink.done();
  10980. return true;
  10981. });
  10982. });
  10983. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10984. auto se = detail::scope_exit([&] {
  10985. svr.stop();
  10986. listen_thread.join();
  10987. ASSERT_FALSE(svr.is_running());
  10988. });
  10989. svr.wait_until_ready();
  10990. Client cli("localhost", PORT);
  10991. auto res = cli.Get("/");
  10992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10993. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10994. EXPECT_EQ("helloworld", res->body);
  10995. }
  10996. // A body set after a content provider must replace it, not be sent through it.
  10997. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10998. Server svr;
  10999. svr.set_mount_point("/", "./www");
  11000. svr.set_file_request_handler([](const Request &req, Response &res) {
  11001. if (req.path == "/dir/test.html") {
  11002. res.status = StatusCode::Forbidden_403;
  11003. res.set_content(std::string(5000, 'D'), "text/plain");
  11004. } else if (req.path == "/file") {
  11005. res.status = StatusCode::Forbidden_403;
  11006. res.body = "Denied";
  11007. }
  11008. });
  11009. auto port = svr.bind_to_any_port(HOST);
  11010. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11011. auto se = detail::scope_exit([&] {
  11012. svr.stop();
  11013. t.join();
  11014. ASSERT_FALSE(svr.is_running());
  11015. });
  11016. svr.wait_until_ready();
  11017. Client cli(HOST, port);
  11018. {
  11019. auto res = cli.Get("/dir/test.html");
  11020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11021. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11022. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11023. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11024. }
  11025. {
  11026. auto res = cli.Get("/file");
  11027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11028. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11029. EXPECT_EQ("Denied", res->body);
  11030. }
  11031. {
  11032. auto res = cli.Get("/dir/index.html");
  11033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11034. EXPECT_EQ(StatusCode::OK_200, res->status);
  11035. EXPECT_EQ(0U, res->body.find("<html>"));
  11036. }
  11037. }
  11038. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11039. Server svr;
  11040. std::vector<bool> released;
  11041. std::mutex released_mutex;
  11042. auto releaser = [&](bool success) {
  11043. std::lock_guard<std::mutex> guard(released_mutex);
  11044. released.push_back(success);
  11045. };
  11046. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11047. return sink.write(&"hello"[offset], length);
  11048. };
  11049. svr.Get("/sized", [&](const Request &, Response &res) {
  11050. res.status = StatusCode::NotFound_404;
  11051. res.set_content_provider(5, "text/plain", provider, releaser);
  11052. });
  11053. svr.Get("/chunked", [&](const Request &, Response &res) {
  11054. res.status = StatusCode::ServiceUnavailable_503;
  11055. res.set_chunked_content_provider(
  11056. "text/plain",
  11057. [](size_t, DataSink &sink) {
  11058. sink.os << "chunk";
  11059. sink.done();
  11060. return true;
  11061. },
  11062. releaser);
  11063. });
  11064. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11065. res.set_content_provider(5, "text/plain", provider, releaser);
  11066. throw std::runtime_error("after the provider");
  11067. });
  11068. svr.set_error_handler([](const Request &req, Response &res) {
  11069. // Leave the exception handler's content to it.
  11070. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11071. res.set_content(std::string(1000, 'E'), "text/html");
  11072. return Server::HandlerResponse::Handled;
  11073. });
  11074. svr.set_exception_handler(
  11075. [](const Request &, Response &res, std::exception_ptr) {
  11076. res.status = StatusCode::InternalServerError_500;
  11077. res.set_content(std::string(1000, 'X'), "text/html");
  11078. });
  11079. auto port = svr.bind_to_any_port(HOST);
  11080. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11081. auto se = detail::scope_exit([&] {
  11082. svr.stop();
  11083. t.join();
  11084. ASSERT_FALSE(svr.is_running());
  11085. });
  11086. svr.wait_until_ready();
  11087. Client cli(HOST, port);
  11088. {
  11089. auto res = cli.Get("/sized");
  11090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11092. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11093. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11094. }
  11095. {
  11096. auto res = cli.Get("/chunked");
  11097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11098. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11099. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11100. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11101. }
  11102. {
  11103. auto res = cli.Get("/throw");
  11104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11105. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11106. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11107. }
  11108. std::lock_guard<std::mutex> guard(released_mutex);
  11109. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11110. }
  11111. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11112. Server svr;
  11113. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11114. return sink.write(&"abc"[offset], length);
  11115. };
  11116. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11117. res.set_file_content("./www/dir/test.html");
  11118. res.set_content("body", "text/plain");
  11119. });
  11120. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11121. res.set_content(std::string(100, 'B'), "text/plain");
  11122. res.set_file_content("./www/dir/test.html");
  11123. });
  11124. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11125. res.set_content(std::string(100, 'B'), "text/plain");
  11126. res.set_content_provider(3, "text/plain", abc);
  11127. });
  11128. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11129. res.set_content_provider(3, "text/plain", abc);
  11130. res.set_content(std::string(100, 'B'), "text/plain");
  11131. });
  11132. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11133. res.set_content_provider(3, "text/plain", abc);
  11134. res.body = "direct";
  11135. });
  11136. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11137. res.set_file_content("./www/dir/test.html");
  11138. res.body = "direct";
  11139. });
  11140. auto port = svr.bind_to_any_port(HOST);
  11141. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11142. auto se = detail::scope_exit([&] {
  11143. svr.stop();
  11144. t.join();
  11145. ASSERT_FALSE(svr.is_running());
  11146. });
  11147. svr.wait_until_ready();
  11148. Client cli(HOST, port);
  11149. auto expect_body = [&](const char *path, const std::string &body) {
  11150. // Uncompressed, so Content-Length can be compared with the body.
  11151. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11152. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11153. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11154. EXPECT_EQ(body, res->body) << path;
  11155. EXPECT_EQ(std::to_string(body.size()),
  11156. res->get_header_value("Content-Length"))
  11157. << path;
  11158. };
  11159. expect_body("/file-then-body", "body");
  11160. expect_body("/body-then-file", "test.html");
  11161. expect_body("/body-then-provider", "abc");
  11162. expect_body("/provider-then-body", std::string(100, 'B'));
  11163. expect_body("/provider-then-direct-body", "direct");
  11164. expect_body("/file-then-direct-body", "direct");
  11165. // Ranges are checked against the body, not the dropped provider.
  11166. {
  11167. auto res = cli.Get("/provider-then-direct-body",
  11168. Headers{{make_range_header({{1, 2}})}});
  11169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11171. EXPECT_EQ("ir", res->body);
  11172. }
  11173. {
  11174. auto res = cli.Get("/file-then-direct-body",
  11175. Headers{{make_range_header({{7, 8}})}});
  11176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11177. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11178. }
  11179. }
  11180. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11181. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11182. const char *path = "./truncated_while_served.txt";
  11183. const size_t size = 32 * 1024 * 1024;
  11184. {
  11185. std::ofstream f(path, std::ios::binary);
  11186. f << std::string(size, 'x');
  11187. }
  11188. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11189. // Over TLS, where the bytes are encrypted in this process rather than
  11190. // copied by send().
  11191. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11192. svr.Get("/file", [&](const Request &, Response &res) {
  11193. res.set_file_content(path, "text/plain");
  11194. });
  11195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11196. auto se = detail::scope_exit([&] {
  11197. svr.stop();
  11198. thread.join();
  11199. ASSERT_FALSE(svr.is_running());
  11200. });
  11201. svr.wait_until_ready();
  11202. // The file shrinks once the first bytes are in, as a rewrite in place
  11203. // would, and reading the mapping past its new end used to raise SIGBUS.
  11204. SSLClient cli(HOST, PORT);
  11205. cli.enable_server_certificate_verification(false);
  11206. size_t received = 0;
  11207. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11208. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11209. received += len;
  11210. return true;
  11211. });
  11212. EXPECT_FALSE(res);
  11213. EXPECT_LT(received, size);
  11214. }
  11215. #endif
  11216. // Forward declaration (see the base64_encode note).
  11217. namespace httplib {
  11218. namespace detail {
  11219. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11220. const std::string &content_type,
  11221. EncodingType encoding);
  11222. } // namespace detail
  11223. } // namespace httplib
  11224. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11225. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11226. ASSERT_TRUE(mm->is_open());
  11227. Response res;
  11228. detail::set_file_content_provider(res, mm, "text/html",
  11229. detail::EncodingType::None);
  11230. std::string out;
  11231. DataSink sink;
  11232. sink.write = [&](const char *d, size_t l) {
  11233. out.append(d, l);
  11234. return true;
  11235. };
  11236. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11237. EXPECT_EQ("test.html", out);
  11238. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11239. EXPECT_EQ("test.html", out);
  11240. }
  11241. TEST(LongPollingTest, ClientCloseDetection) {
  11242. Server svr;
  11243. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11244. res.set_chunked_content_provider(
  11245. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11246. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11247. sink.os << "hello";
  11248. auto count = 10;
  11249. while (count > 0 && sink.is_writable()) {
  11250. this_thread::sleep_for(chrono::milliseconds(10));
  11251. count--;
  11252. }
  11253. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11254. return true;
  11255. });
  11256. });
  11257. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11258. auto se = detail::scope_exit([&] {
  11259. svr.stop();
  11260. listen_thread.join();
  11261. ASSERT_FALSE(svr.is_running());
  11262. });
  11263. svr.wait_until_ready();
  11264. Client cli("localhost", PORT);
  11265. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11266. EXPECT_EQ("hello", string(data, data_length));
  11267. return false; // close the socket immediately.
  11268. });
  11269. ASSERT_FALSE(res);
  11270. }
  11271. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11272. Server svr;
  11273. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11274. res.set_chunked_content_provider(
  11275. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11276. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11277. sink.os << "hello";
  11278. EXPECT_TRUE(sink.os.good());
  11279. // Wait for the client to close the connection
  11280. auto count = 10;
  11281. while (count > 0 && sink.is_writable()) {
  11282. this_thread::sleep_for(chrono::milliseconds(10));
  11283. count--;
  11284. }
  11285. // After client disconnect, write repeatedly until the socket
  11286. // write actually fails (small writes may be absorbed by the
  11287. // kernel buffer)
  11288. std::string chunk(1024, 'x');
  11289. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11290. sink.os << chunk;
  11291. }
  11292. EXPECT_TRUE(sink.os.fail());
  11293. return true;
  11294. });
  11295. });
  11296. auto port = svr.bind_to_any_port("localhost");
  11297. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. listen_thread.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.wait_until_ready();
  11304. Client cli("localhost", port);
  11305. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11306. EXPECT_EQ("hello", string(data, data_length));
  11307. return false; // close the socket immediately.
  11308. });
  11309. ASSERT_FALSE(res);
  11310. }
  11311. TEST(GetWithParametersTest, GetWithParameters) {
  11312. Server svr;
  11313. svr.Get("/", [&](const Request &req, Response &) {
  11314. EXPECT_EQ("world", req.get_param_value("hello"));
  11315. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11316. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11317. });
  11318. svr.Get("/params", [&](const Request &req, Response &) {
  11319. EXPECT_EQ("world", req.get_param_value("hello"));
  11320. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11321. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11322. });
  11323. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11324. EXPECT_EQ("resource-id", req.matches[1]);
  11325. EXPECT_EQ("foo", req.get_param_value("param1"));
  11326. EXPECT_EQ("bar", req.get_param_value("param2"));
  11327. });
  11328. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11329. EXPECT_EQ("user-id", req.path_params.at("id"));
  11330. EXPECT_EQ("foo", req.get_param_value("param1"));
  11331. EXPECT_EQ("bar", req.get_param_value("param2"));
  11332. });
  11333. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11334. auto se = detail::scope_exit([&] {
  11335. svr.stop();
  11336. listen_thread.join();
  11337. ASSERT_FALSE(svr.is_running());
  11338. });
  11339. svr.wait_until_ready();
  11340. {
  11341. Client cli(HOST, PORT);
  11342. Params params;
  11343. params.emplace("hello", "world");
  11344. params.emplace("hello2", "world2");
  11345. params.emplace("hello3", "world3");
  11346. auto res = cli.Get("/", params, Headers{});
  11347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11348. EXPECT_EQ(StatusCode::OK_200, res->status);
  11349. }
  11350. {
  11351. Client cli(HOST, PORT);
  11352. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11354. EXPECT_EQ(StatusCode::OK_200, res->status);
  11355. }
  11356. {
  11357. Client cli(HOST, PORT);
  11358. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11360. EXPECT_EQ(StatusCode::OK_200, res->status);
  11361. }
  11362. {
  11363. Client cli(HOST, PORT);
  11364. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11366. EXPECT_EQ(StatusCode::OK_200, res->status);
  11367. }
  11368. }
  11369. TEST(GetWithParametersTest, GetWithParameters2) {
  11370. Server svr;
  11371. svr.Get("/", [&](const Request &req, Response &res) {
  11372. auto text = req.get_param_value("hello");
  11373. res.set_content(text, "text/plain");
  11374. });
  11375. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11376. auto se = detail::scope_exit([&] {
  11377. svr.stop();
  11378. listen_thread.join();
  11379. ASSERT_FALSE(svr.is_running());
  11380. });
  11381. svr.wait_until_ready();
  11382. Client cli("localhost", PORT);
  11383. Params params;
  11384. params.emplace("hello", "world");
  11385. std::string body;
  11386. auto res = cli.Get("/", params, Headers{},
  11387. [&](const char *data, size_t data_length) {
  11388. body.append(data, data_length);
  11389. return true;
  11390. });
  11391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11392. EXPECT_EQ(StatusCode::OK_200, res->status);
  11393. EXPECT_EQ("world", body);
  11394. }
  11395. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11396. Server svr;
  11397. svr.Get("/search", [&](const Request &req, Response &res) {
  11398. auto q = req.get_param_value("q");
  11399. res.set_content(q, "text/plain");
  11400. });
  11401. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11402. auto se = detail::scope_exit([&] {
  11403. svr.stop();
  11404. listen_thread.join();
  11405. ASSERT_FALSE(svr.is_running());
  11406. });
  11407. svr.wait_until_ready();
  11408. Client cli("localhost", PORT);
  11409. // Verify that Get(path, params) works without requiring Headers argument
  11410. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11412. EXPECT_EQ(StatusCode::OK_200, res->status);
  11413. EXPECT_EQ("cpp-httplib", res->body);
  11414. }
  11415. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11416. auto host = "httpbingo.org";
  11417. auto path = std::string{"/range/32"};
  11418. #ifdef CPPHTTPLIB_SSL_ENABLED
  11419. SSLClient cli(host);
  11420. #else
  11421. Client cli(host);
  11422. #endif
  11423. cli.set_default_headers({make_range_header({{1, 10}})});
  11424. cli.set_connection_timeout(5);
  11425. {
  11426. auto res = cli.Get(path);
  11427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11428. EXPECT_EQ("bcdefghijk", res->body);
  11429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11430. }
  11431. {
  11432. auto res = cli.Get(path);
  11433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11434. EXPECT_EQ("bcdefghijk", res->body);
  11435. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11436. }
  11437. }
  11438. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11439. Server svr;
  11440. svr.set_default_headers({{"Hello", "World"}});
  11441. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11442. res.set_content("ok", "text/plain");
  11443. });
  11444. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11445. auto se = detail::scope_exit([&] {
  11446. svr.stop();
  11447. listen_thread.join();
  11448. ASSERT_FALSE(svr.is_running());
  11449. });
  11450. svr.wait_until_ready();
  11451. Client cli("localhost", PORT);
  11452. auto res = cli.Get("/");
  11453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11454. EXPECT_EQ(StatusCode::OK_200, res->status);
  11455. EXPECT_EQ("ok", res->body);
  11456. EXPECT_EQ("World", res->get_header_value("Hello"));
  11457. }
  11458. #ifdef CPPHTTPLIB_SSL_ENABLED
  11459. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11460. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11461. ASSERT_TRUE(svr.is_valid());
  11462. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11463. std::this_thread::sleep_for(std::chrono::seconds(2));
  11464. res.set_content("a", "text/plain");
  11465. });
  11466. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11467. res.set_content("b", "text/plain");
  11468. });
  11469. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11470. auto se = detail::scope_exit([&] {
  11471. svr.stop();
  11472. listen_thread.join();
  11473. ASSERT_FALSE(svr.is_running());
  11474. });
  11475. svr.wait_until_ready();
  11476. SSLClient cli("localhost", PORT);
  11477. cli.enable_server_certificate_verification(false);
  11478. cli.set_keep_alive(true);
  11479. cli.set_read_timeout(std::chrono::seconds(1));
  11480. auto resa = cli.Get("/a");
  11481. ASSERT_TRUE(!resa);
  11482. EXPECT_EQ(Error::Read, resa.error());
  11483. auto resb = cli.Get("/b");
  11484. ASSERT_TRUE(resb);
  11485. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11486. EXPECT_EQ("b", resb->body);
  11487. }
  11488. // Closing an idle keep-alive connection sends close_notify and returns. The
  11489. // server must not wait for the client's close_notify: an idle client never
  11490. // sends one, so the worker would be held until the read timeout expires, and
  11491. // stop() would wait for it.
  11492. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11494. ASSERT_TRUE(svr.is_valid());
  11495. svr.set_keep_alive_timeout(1);
  11496. svr.set_read_timeout(10, 0);
  11497. svr.Get("/", [](const Request &, Response &res) {
  11498. res.set_content("ok", "text/plain");
  11499. });
  11500. auto port = svr.bind_to_any_port(HOST);
  11501. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11502. auto se = detail::scope_exit([&] {
  11503. if (listen_thread.joinable()) {
  11504. svr.stop();
  11505. listen_thread.join();
  11506. }
  11507. });
  11508. svr.wait_until_ready();
  11509. SSLClient cli(HOST, port);
  11510. cli.enable_server_certificate_verification(false);
  11511. cli.set_keep_alive(true);
  11512. auto res = cli.Get("/");
  11513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11514. EXPECT_EQ(StatusCode::OK_200, res->status);
  11515. // Stay idle past the keep-alive timeout so the server closes the connection.
  11516. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11517. auto start = std::chrono::steady_clock::now();
  11518. svr.stop();
  11519. listen_thread.join();
  11520. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11521. std::chrono::steady_clock::now() - start)
  11522. .count();
  11523. EXPECT_LT(elapsed, 3000);
  11524. }
  11525. #endif
  11526. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11527. protected:
  11528. ServerTestWithAI_PASSIVE()
  11529. : cli_(HOST, PORT)
  11530. #ifdef CPPHTTPLIB_SSL_ENABLED
  11531. ,
  11532. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11533. #endif
  11534. {
  11535. #ifdef CPPHTTPLIB_SSL_ENABLED
  11536. cli_.enable_server_certificate_verification(false);
  11537. #endif
  11538. }
  11539. virtual void SetUp() {
  11540. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11541. res.set_content("Hello World!", "text/plain");
  11542. });
  11543. t_ = thread(
  11544. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11545. svr_.wait_until_ready();
  11546. }
  11547. virtual void TearDown() {
  11548. svr_.stop();
  11549. t_.join();
  11550. }
  11551. #ifdef CPPHTTPLIB_SSL_ENABLED
  11552. SSLClient cli_;
  11553. SSLServer svr_;
  11554. #else
  11555. Client cli_;
  11556. Server svr_;
  11557. #endif
  11558. thread t_;
  11559. };
  11560. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11561. auto res = cli_.Get("/hi");
  11562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11563. EXPECT_EQ(StatusCode::OK_200, res->status);
  11564. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11565. EXPECT_EQ("Hello World!", res->body);
  11566. }
  11567. class ServerUpDownTest : public ::testing::Test {
  11568. protected:
  11569. ServerUpDownTest() : cli_(HOST, PORT) {}
  11570. virtual void SetUp() {
  11571. t_ = thread([&]() {
  11572. svr_.bind_to_any_port(HOST);
  11573. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11574. ASSERT_TRUE(svr_.listen_after_bind());
  11575. });
  11576. svr_.wait_until_ready();
  11577. }
  11578. virtual void TearDown() {
  11579. svr_.stop();
  11580. t_.join();
  11581. }
  11582. Client cli_;
  11583. Server svr_;
  11584. thread t_;
  11585. };
  11586. TEST_F(ServerUpDownTest, QuickStartStop) {
  11587. // Should not crash, especially when run with
  11588. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11589. }
  11590. class PayloadMaxLengthTest : public ::testing::Test {
  11591. protected:
  11592. PayloadMaxLengthTest()
  11593. : cli_(HOST, PORT)
  11594. #ifdef CPPHTTPLIB_SSL_ENABLED
  11595. ,
  11596. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11597. #endif
  11598. {
  11599. #ifdef CPPHTTPLIB_SSL_ENABLED
  11600. cli_.enable_server_certificate_verification(false);
  11601. #endif
  11602. }
  11603. virtual void SetUp() {
  11604. svr_.set_payload_max_length(8);
  11605. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11606. res.set_content("test", "text/plain");
  11607. });
  11608. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11609. svr_.wait_until_ready();
  11610. }
  11611. virtual void TearDown() {
  11612. svr_.stop();
  11613. t_.join();
  11614. }
  11615. #ifdef CPPHTTPLIB_SSL_ENABLED
  11616. SSLClient cli_;
  11617. SSLServer svr_;
  11618. #else
  11619. Client cli_;
  11620. Server svr_;
  11621. #endif
  11622. thread t_;
  11623. };
  11624. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11625. auto res = cli_.Post("/test", "123456789", "text/plain");
  11626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11627. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11628. res = cli_.Post("/test", "12345678", "text/plain");
  11629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11630. EXPECT_EQ(StatusCode::OK_200, res->status);
  11631. }
  11632. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11633. // Test chunked encoding with payload exceeding the 8-byte limit
  11634. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11635. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11637. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11638. }
  11639. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11640. // Test chunked encoding with payload within the 8-byte limit
  11641. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11642. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11644. EXPECT_EQ(StatusCode::OK_200, res->status);
  11645. }
  11646. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11647. // Test using send_request to send chunked data exceeding payload limit
  11648. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11649. "Host: " +
  11650. std::string(HOST) + ":" + std::to_string(PORT) +
  11651. "\r\n"
  11652. "Transfer-Encoding: chunked\r\n"
  11653. "Connection: close\r\n"
  11654. "\r\n"
  11655. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11656. "0123456789\r\n"
  11657. "0\r\n" // End chunk
  11658. "\r\n";
  11659. std::string response;
  11660. bool result = send_request(1, chunked_request, &response);
  11661. if (!result) {
  11662. // If send_request fails, it might be because the server closed the
  11663. // connection due to payload limit enforcement, which is acceptable
  11664. SUCCEED()
  11665. << "Server rejected oversized chunked request (connection closed)";
  11666. } else {
  11667. // If we got a response, check if it's an error response or connection was
  11668. // closed early Short response length indicates connection was closed due to
  11669. // payload limit
  11670. if (response.length() <= 10) {
  11671. SUCCEED() << "Server closed connection for oversized chunked request";
  11672. } else {
  11673. // Check for error status codes
  11674. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11675. response.find("Payload Too Large") != std::string::npos ||
  11676. response.find("400") != std::string::npos);
  11677. }
  11678. }
  11679. }
  11680. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11681. // Test request without Content-Length header exceeding payload limit
  11682. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11683. "Host: " +
  11684. std::string(HOST) + ":" +
  11685. std::to_string(PORT) +
  11686. "\r\n"
  11687. "Connection: close\r\n"
  11688. "\r\n";
  11689. // Add payload exceeding the 8-byte limit
  11690. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11691. request_without_content_length += large_payload;
  11692. std::string response;
  11693. bool result = send_request(1, request_without_content_length, &response);
  11694. if (!result) {
  11695. // If send_request fails, server likely closed connection due to payload
  11696. // limit
  11697. SUCCEED() << "Server rejected oversized request without Content-Length "
  11698. "(connection closed)";
  11699. } else {
  11700. // Check if server responded with error or closed connection early
  11701. if (response.length() <= 10) {
  11702. SUCCEED() << "Server closed connection for oversized request without "
  11703. "Content-Length";
  11704. } else {
  11705. // Check for error status codes
  11706. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11707. response.find("Payload Too Large") != std::string::npos ||
  11708. response.find("400") != std::string::npos);
  11709. }
  11710. }
  11711. }
  11712. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11713. // Test request without Content-Length header within payload limit
  11714. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11715. "Host: " +
  11716. std::string(HOST) + ":" +
  11717. std::to_string(PORT) +
  11718. "\r\n"
  11719. "Connection: close\r\n"
  11720. "\r\n";
  11721. // Add payload within the 8-byte limit
  11722. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11723. request_without_content_length += small_payload;
  11724. std::string response;
  11725. bool result = send_request(1, request_without_content_length, &response);
  11726. // For requests without Content-Length, the server may have different behavior
  11727. // The key is that it should not reject due to payload limit for small
  11728. // payloads
  11729. if (result) {
  11730. // Check for any HTTP response (success or error, but not connection closed)
  11731. if (response.length() > 10) {
  11732. SUCCEED()
  11733. << "Server processed request without Content-Length within limit";
  11734. } else {
  11735. // Short response might indicate connection closed, which is acceptable
  11736. SUCCEED() << "Server closed connection for request without "
  11737. "Content-Length (acceptable behavior)";
  11738. }
  11739. } else {
  11740. // Connection failure might be due to protocol requirements
  11741. SUCCEED() << "Connection issue with request without Content-Length "
  11742. "(environment-specific)";
  11743. }
  11744. }
  11745. class LargePayloadMaxLengthTest : public ::testing::Test {
  11746. protected:
  11747. LargePayloadMaxLengthTest()
  11748. : cli_(HOST, PORT)
  11749. #ifdef CPPHTTPLIB_SSL_ENABLED
  11750. ,
  11751. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11752. #endif
  11753. {
  11754. #ifdef CPPHTTPLIB_SSL_ENABLED
  11755. cli_.enable_server_certificate_verification(false);
  11756. #endif
  11757. }
  11758. virtual void SetUp() {
  11759. // Set 10MB payload limit
  11760. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11761. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11762. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11763. res.set_content("Large payload test", "text/plain");
  11764. });
  11765. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11766. svr_.wait_until_ready();
  11767. }
  11768. virtual void TearDown() {
  11769. svr_.stop();
  11770. t_.join();
  11771. }
  11772. #ifdef CPPHTTPLIB_SSL_ENABLED
  11773. SSLClient cli_;
  11774. SSLServer svr_;
  11775. #else
  11776. Client cli_;
  11777. Server svr_;
  11778. #endif
  11779. thread t_;
  11780. };
  11781. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11782. // Test chunked encoding with payload within 10MB limit
  11783. std::string medium_payload(5 * 1024 * 1024,
  11784. 'A'); // 5MB payload, within 10MB limit
  11785. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11787. EXPECT_EQ(StatusCode::OK_200, res->status);
  11788. }
  11789. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11790. // Test chunked encoding with payload exceeding 10MB limit
  11791. std::string large_payload(12 * 1024 * 1024,
  11792. 'B'); // 12MB payload, exceeds 10MB limit
  11793. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11794. // Server may either return 413 or close the connection
  11795. if (res) {
  11796. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11797. } else {
  11798. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11799. }
  11800. }
  11801. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11802. // Test request without Content-Length header within 10MB limit
  11803. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11804. "Host: " +
  11805. std::string(HOST) + ":" +
  11806. std::to_string(PORT) +
  11807. "\r\n"
  11808. "Connection: close\r\n"
  11809. "\r\n";
  11810. // Add 1MB payload (within 10MB limit)
  11811. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11812. request_without_content_length += medium_payload;
  11813. std::string response;
  11814. bool result = send_request(5, request_without_content_length, &response);
  11815. if (result) {
  11816. // Should get a proper HTTP response for payloads within limit
  11817. if (response.length() > 10) {
  11818. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11819. "10MB limit";
  11820. } else {
  11821. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11822. "Content-Length)";
  11823. }
  11824. } else {
  11825. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11826. }
  11827. }
  11828. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11829. // Test request without Content-Length header exceeding 10MB limit
  11830. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11831. "Host: " +
  11832. std::string(HOST) + ":" +
  11833. std::to_string(PORT) +
  11834. "\r\n"
  11835. "Connection: close\r\n"
  11836. "\r\n";
  11837. // Add 12MB payload (exceeds 10MB limit)
  11838. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11839. request_without_content_length += large_payload;
  11840. std::string response;
  11841. bool result = send_request(10, request_without_content_length, &response);
  11842. if (!result) {
  11843. // Server should close connection due to payload limit
  11844. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11845. "(connection closed)";
  11846. } else {
  11847. // Check for error response
  11848. if (response.length() <= 10) {
  11849. SUCCEED()
  11850. << "Server closed connection for 12MB request exceeding 10MB limit";
  11851. } else {
  11852. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11853. response.find("Payload Too Large") != std::string::npos ||
  11854. response.find("400") != std::string::npos);
  11855. }
  11856. }
  11857. }
  11858. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11859. Server svr;
  11860. svr.Get("/", [](const Request &, Response &res) {
  11861. // Claims far more than it sends, then drops the connection.
  11862. res.set_content_provider(size_t(1) << 41, "text/plain",
  11863. [](size_t, size_t, DataSink &sink) {
  11864. sink.write("abc", 3);
  11865. return false;
  11866. });
  11867. });
  11868. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11869. auto se = detail::scope_exit([&] {
  11870. svr.stop();
  11871. thread.join();
  11872. ASSERT_FALSE(svr.is_running());
  11873. });
  11874. svr.wait_until_ready();
  11875. Client cli(HOST, PORT);
  11876. cli.set_payload_max_length(0);
  11877. EXPECT_FALSE(cli.Get("/"));
  11878. }
  11879. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11880. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11881. // path.
  11882. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11883. Server svr;
  11884. const size_t LIMIT = 64 * 1024; // 64KB
  11885. svr.set_payload_max_length(LIMIT);
  11886. size_t total = 0;
  11887. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11888. const ContentReader &content_reader) {
  11889. content_reader([&](const char * /*data*/, size_t len) {
  11890. total += len;
  11891. return true;
  11892. });
  11893. res.status = 200;
  11894. res.set_content("stream_ok", "text/plain");
  11895. });
  11896. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11897. auto se = detail::scope_exit([&] {
  11898. svr.stop();
  11899. thread.join();
  11900. ASSERT_FALSE(svr.is_running());
  11901. });
  11902. svr.wait_until_ready();
  11903. // Prepare 256KB raw data and gzip-compress it
  11904. std::string raw(256 * 1024, 'A');
  11905. std::string gz;
  11906. {
  11907. z_stream zs{};
  11908. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11909. Z_DEFAULT_STRATEGY);
  11910. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11911. zs.avail_in = static_cast<uInt>(raw.size());
  11912. char outbuf[4096];
  11913. int ret;
  11914. do {
  11915. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11916. zs.avail_out = sizeof(outbuf);
  11917. ret = deflate(&zs, Z_FINISH);
  11918. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11919. } while (ret != Z_STREAM_END);
  11920. deflateEnd(&zs);
  11921. }
  11922. Client cli(HOST, PORT);
  11923. cli.set_connection_timeout(std::chrono::seconds(5));
  11924. Headers headers = {{"Content-Encoding", "gzip"}};
  11925. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11926. "application/octet-stream");
  11927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11928. // Server must reject oversized decompressed payloads with 413.
  11929. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11930. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11931. EXPECT_LE(total, LIMIT);
  11932. }
  11933. #ifndef CPPHTTPLIB_SSL_ENABLED
  11934. // For a request with neither Content-Length nor Transfer-Encoding, the
  11935. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11936. // compressed wire bytes straight to the ContentReader without ever routing
  11937. // them through the decompressor, so payload_max_length_ only bounded the
  11938. // compressed size on the wire, not the decompressed size.
  11939. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11940. Server svr;
  11941. const size_t LIMIT = 64 * 1024; // 64KB
  11942. svr.set_payload_max_length(LIMIT);
  11943. size_t total = 0;
  11944. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11945. const ContentReader &content_reader) {
  11946. content_reader([&](const char * /*data*/, size_t len) {
  11947. total += len;
  11948. return true;
  11949. });
  11950. res.status = 200;
  11951. res.set_content("stream_ok", "text/plain");
  11952. });
  11953. auto port = svr.bind_to_any_port(HOST);
  11954. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11955. auto se = detail::scope_exit([&] {
  11956. svr.stop();
  11957. thread.join();
  11958. ASSERT_FALSE(svr.is_running());
  11959. });
  11960. svr.wait_until_ready();
  11961. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11962. // StreamingGzipDecompression test above.
  11963. std::string raw(256 * 1024, 'A');
  11964. std::string gz;
  11965. {
  11966. httplib::detail::gzip_compressor compressor;
  11967. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11968. [&](const char *chunk, size_t len) {
  11969. gz.append(chunk, len);
  11970. return true;
  11971. });
  11972. ASSERT_TRUE(result);
  11973. }
  11974. // Send the gzip body over raw TCP with neither Content-Length nor
  11975. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11976. // kicks in.
  11977. std::string req = "POST /stream HTTP/1.1\r\n"
  11978. "Host: " +
  11979. std::string(HOST) + ":" + std::to_string(port) +
  11980. "\r\n"
  11981. "Content-Encoding: gzip\r\n"
  11982. "Connection: close\r\n"
  11983. "\r\n" +
  11984. gz;
  11985. std::string response;
  11986. ASSERT_TRUE(send_request(5, req, &response, port));
  11987. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11988. EXPECT_LE(total, LIMIT);
  11989. }
  11990. #endif
  11991. #endif
  11992. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11993. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11994. // the payload must be passed through untouched instead of being rejected.
  11995. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11996. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11997. Server svr;
  11998. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11999. res.set_content(body, "image/jpeg");
  12000. res.set_header("Content-Encoding", "UTF-8");
  12001. });
  12002. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12003. res.set_content(body, "image/jpeg");
  12004. res.set_header("Content-Encoding", "identity");
  12005. });
  12006. svr.Post("/echo", [](const Request &req, Response &res) {
  12007. res.set_content(req.body, "image/jpeg");
  12008. });
  12009. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12010. auto se = detail::scope_exit([&] {
  12011. svr.stop();
  12012. t.join();
  12013. ASSERT_FALSE(svr.is_running());
  12014. });
  12015. svr.wait_until_ready();
  12016. Client cli(HOST, PORT);
  12017. {
  12018. auto res = cli.Get("/image");
  12019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12020. EXPECT_EQ(StatusCode::OK_200, res->status);
  12021. EXPECT_EQ(body, res->body);
  12022. }
  12023. {
  12024. auto res = cli.Get("/identity");
  12025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12026. EXPECT_EQ(StatusCode::OK_200, res->status);
  12027. EXPECT_EQ(body, res->body);
  12028. }
  12029. {
  12030. // The same applies to a request body reaching the server.
  12031. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12032. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12034. EXPECT_EQ(StatusCode::OK_200, res->status);
  12035. EXPECT_EQ(body, res->body);
  12036. }
  12037. }
  12038. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12039. // gzip-encoded response even when the build has no zlib support.
  12040. static const char GZIPPED_HELLO_WORLD[] = {
  12041. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12042. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12043. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12044. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12045. // A content coding is a whole token, not something the field value merely
  12046. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12047. // as "fibre" look like Brotli, and turned a multi-coding value like
  12048. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12049. // it was never meant to see.
  12050. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12051. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12052. Server svr;
  12053. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12054. res.set_content(body, "image/jpeg");
  12055. res.set_header("Content-Encoding", "fibre");
  12056. });
  12057. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12058. res.set_content(body, "image/jpeg");
  12059. res.set_header("Content-Encoding", "gzip, br");
  12060. });
  12061. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12062. res.set_content(body, "image/jpeg");
  12063. res.set_header("Content-Encoding", "x-zstd-ish");
  12064. });
  12065. auto port = svr.bind_to_any_port(HOST);
  12066. thread t = thread([&]() { svr.listen_after_bind(); });
  12067. auto se = detail::scope_exit([&] {
  12068. svr.stop();
  12069. t.join();
  12070. ASSERT_FALSE(svr.is_running());
  12071. });
  12072. svr.wait_until_ready();
  12073. Client cli(HOST, port);
  12074. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12075. auto res = cli.Get(path);
  12076. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12077. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12078. // Not a coding we recognize, so the payload comes back untouched
  12079. EXPECT_EQ(body, res->body) << path;
  12080. }
  12081. }
  12082. // A content coding cpp-httplib recognizes but was not built with must be
  12083. // reported as such. Handing the still-compressed payload back to the caller
  12084. // would silently corrupt it.
  12085. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12086. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12087. Server svr;
  12088. // "image/jpeg" keeps the server from applying a content coding of its own,
  12089. // so the hand-crafted Content-Encoding below survives.
  12090. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12091. res.set_content(gzipped, "image/jpeg");
  12092. res.set_header("Content-Encoding", "gzip");
  12093. });
  12094. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12095. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12096. res.set_content(gzipped, "image/jpeg");
  12097. res.set_header("Content-Encoding", "GZIP");
  12098. });
  12099. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12100. auto se = detail::scope_exit([&] {
  12101. svr.stop();
  12102. t.join();
  12103. ASSERT_FALSE(svr.is_running());
  12104. });
  12105. svr.wait_until_ready();
  12106. Client cli(HOST, PORT);
  12107. {
  12108. auto res = cli.Get("/gzipped");
  12109. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12111. EXPECT_EQ("Hello World!", res->body);
  12112. #else
  12113. ASSERT_FALSE(res);
  12114. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12115. #endif
  12116. }
  12117. {
  12118. // open_stream() must behave the same way.
  12119. auto handle = cli.open_stream("GET", "/gzipped");
  12120. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12121. ASSERT_TRUE(handle.is_valid());
  12122. std::string received;
  12123. char buf[256];
  12124. ssize_t n;
  12125. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12126. received.append(buf, static_cast<size_t>(n));
  12127. }
  12128. EXPECT_EQ("Hello World!", received);
  12129. #else
  12130. EXPECT_FALSE(handle.is_valid());
  12131. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12132. #endif
  12133. }
  12134. {
  12135. // A differently-cased coding must not be mistaken for an unknown one, or
  12136. // the body would be handed back still compressed.
  12137. auto res = cli.Get("/gzipped-uppercase");
  12138. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12140. EXPECT_EQ("Hello World!", res->body);
  12141. #else
  12142. ASSERT_FALSE(res);
  12143. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12144. #endif
  12145. }
  12146. }
  12147. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12148. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12149. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12150. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12151. // body a second time and appending a second Content-Encoding field line, so
  12152. // clients that decode one coding per listed value handed back raw gzip bytes.
  12153. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12154. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12155. Server svr;
  12156. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12157. // keeps the server from applying a coding of its own.
  12158. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12159. res.set_content(gzipped, "text/plain");
  12160. res.set_header("Content-Encoding", "gzip");
  12161. });
  12162. auto port = svr.bind_to_any_port(HOST);
  12163. thread t = thread([&]() { svr.listen_after_bind(); });
  12164. auto se = detail::scope_exit([&] {
  12165. svr.stop();
  12166. t.join();
  12167. ASSERT_FALSE(svr.is_running());
  12168. });
  12169. svr.wait_until_ready();
  12170. Client cli(HOST, port);
  12171. Headers headers = {{"Accept-Encoding", "gzip"}};
  12172. auto res = cli.Get("/pre-gzipped", headers);
  12173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12174. EXPECT_EQ(StatusCode::OK_200, res->status);
  12175. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12176. EXPECT_EQ("Hello World!", res->body);
  12177. }
  12178. // A chunked provider settles its coding where the headers are written and
  12179. // reuses it at write time. Both ends of that have to hold: a handler's own
  12180. // Content-Encoding suppresses the coding, and a response without one is still
  12181. // compressed as it always was.
  12182. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12183. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12184. const std::string plain = "Hello World! Hello World! Hello World!";
  12185. Server svr;
  12186. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12187. res.set_header("Content-Encoding", "gzip");
  12188. res.set_chunked_content_provider(
  12189. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12190. sink.write(gzipped.data(), gzipped.size());
  12191. sink.done();
  12192. return true;
  12193. });
  12194. });
  12195. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12196. res.set_chunked_content_provider(
  12197. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12198. sink.write(plain.data(), plain.size());
  12199. sink.done();
  12200. return true;
  12201. });
  12202. });
  12203. auto port = svr.bind_to_any_port(HOST);
  12204. thread t = thread([&]() { svr.listen_after_bind(); });
  12205. auto se = detail::scope_exit([&] {
  12206. svr.stop();
  12207. t.join();
  12208. ASSERT_FALSE(svr.is_running());
  12209. });
  12210. svr.wait_until_ready();
  12211. Client cli(HOST, port);
  12212. Headers headers = {{"Accept-Encoding", "gzip"}};
  12213. {
  12214. auto res = cli.Get("/pre-gzipped", headers);
  12215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12216. EXPECT_EQ(StatusCode::OK_200, res->status);
  12217. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12218. EXPECT_EQ("Hello World!", res->body);
  12219. }
  12220. {
  12221. auto res = cli.Get("/negotiated", headers);
  12222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12223. EXPECT_EQ(StatusCode::OK_200, res->status);
  12224. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12225. EXPECT_EQ(plain, res->body);
  12226. }
  12227. }
  12228. #endif
  12229. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12230. // the same message as the comma-joined one, so both have to be read the same
  12231. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12232. // single gzip coding, and a body the sender says was encoded twice was handed
  12233. // back after one pass, still compressed but presented as decoded.
  12234. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12235. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12236. Server svr;
  12237. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12238. res.set_content(body, "image/jpeg");
  12239. res.headers.emplace("Content-Encoding", "gzip");
  12240. res.headers.emplace("Content-Encoding", "gzip");
  12241. });
  12242. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12243. res.set_content(body, "image/jpeg");
  12244. res.set_header("Content-Encoding", "gzip, gzip");
  12245. });
  12246. auto port = svr.bind_to_any_port(HOST);
  12247. thread t = thread([&]() { svr.listen_after_bind(); });
  12248. auto se = detail::scope_exit([&] {
  12249. svr.stop();
  12250. t.join();
  12251. ASSERT_FALSE(svr.is_running());
  12252. });
  12253. svr.wait_until_ready();
  12254. Client cli(HOST, port);
  12255. // Two codings is not something cpp-httplib decodes, so both representations
  12256. // take the pass-through path rather than one of them being gunzipped once.
  12257. for (const char *path : {"/split", "/joined"}) {
  12258. auto res = cli.Get(path);
  12259. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12260. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12261. EXPECT_EQ(body, res->body) << path;
  12262. }
  12263. }
  12264. // Regression test for DoS vulnerability: a malicious server sending a response
  12265. // without Content-Length header must not cause unbounded memory consumption on
  12266. // the client side. The client should stop reading after a reasonable limit,
  12267. // similar to the server-side set_payload_max_length protection.
  12268. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12269. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12270. #ifndef _WIN32
  12271. signal(SIGPIPE, SIG_IGN);
  12272. #endif
  12273. auto server_thread = std::thread([] {
  12274. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12275. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12276. default_socket_options(srv);
  12277. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12278. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12279. sockaddr_in addr{};
  12280. addr.sin_family = AF_INET;
  12281. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12282. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12283. int opt = 1;
  12284. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12285. #ifdef _WIN32
  12286. reinterpret_cast<const char *>(&opt),
  12287. #else
  12288. &opt,
  12289. #endif
  12290. sizeof(opt));
  12291. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12292. ::listen(srv, 1);
  12293. sockaddr_in cli_addr{};
  12294. socklen_t cli_len = sizeof(cli_addr);
  12295. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12296. if (cli != INVALID_SOCKET) {
  12297. char buf[4096];
  12298. ::recv(cli, buf, sizeof(buf), 0);
  12299. // Malicious response: no Content-Length, no chunked encoding
  12300. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12301. "Connection: close\r\n"
  12302. "\r\n";
  12303. ::send(cli,
  12304. #ifdef _WIN32
  12305. static_cast<const char *>(response_header.c_str()),
  12306. static_cast<int>(response_header.size()),
  12307. #else
  12308. response_header.c_str(), response_header.size(),
  12309. #endif
  12310. 0);
  12311. // Send 10MB of data
  12312. std::string chunk(64 * 1024, 'A');
  12313. size_t total_sent = 0;
  12314. while (total_sent < MALICIOUS_DATA_SIZE) {
  12315. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12316. auto sent = ::send(cli,
  12317. #ifdef _WIN32
  12318. static_cast<const char *>(chunk.c_str()),
  12319. static_cast<int>(to_send),
  12320. #else
  12321. chunk.c_str(), to_send,
  12322. #endif
  12323. 0);
  12324. if (sent <= 0) break;
  12325. total_sent += static_cast<size_t>(sent);
  12326. }
  12327. detail::close_socket(cli);
  12328. }
  12329. detail::close_socket(srv);
  12330. });
  12331. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12332. size_t total_read = 0;
  12333. {
  12334. Client cli("127.0.0.1", PORT + 2);
  12335. cli.set_read_timeout(5, 0);
  12336. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12337. auto stream = cli.open_stream("GET", "/malicious");
  12338. ASSERT_TRUE(stream.is_valid());
  12339. char buffer[64 * 1024];
  12340. ssize_t n;
  12341. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12342. total_read += static_cast<size_t>(n);
  12343. }
  12344. } // StreamHandle and Client destroyed here, closing the socket
  12345. server_thread.join();
  12346. // With set_payload_max_length, the client must stop reading before consuming
  12347. // all 10MB. The read loop should be cut off at or near the configured limit.
  12348. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12349. << "Client read " << total_read << " bytes, exceeding the configured "
  12350. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12351. }
  12352. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12353. // the entire response body without truncation.
  12354. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12355. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12356. #ifndef _WIN32
  12357. signal(SIGPIPE, SIG_IGN);
  12358. #endif
  12359. auto server_thread = std::thread([] {
  12360. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12361. default_socket_options(srv);
  12362. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12363. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12364. sockaddr_in addr{};
  12365. addr.sin_family = AF_INET;
  12366. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12367. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12368. int opt = 1;
  12369. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12370. #ifdef _WIN32
  12371. reinterpret_cast<const char *>(&opt),
  12372. #else
  12373. &opt,
  12374. #endif
  12375. sizeof(opt));
  12376. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12377. ::listen(srv, 1);
  12378. sockaddr_in cli_addr{};
  12379. socklen_t cli_len = sizeof(cli_addr);
  12380. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12381. if (cli != INVALID_SOCKET) {
  12382. char buf[4096];
  12383. ::recv(cli, buf, sizeof(buf), 0);
  12384. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12385. "Connection: close\r\n"
  12386. "\r\n";
  12387. ::send(cli,
  12388. #ifdef _WIN32
  12389. static_cast<const char *>(response_header.c_str()),
  12390. static_cast<int>(response_header.size()),
  12391. #else
  12392. response_header.c_str(), response_header.size(),
  12393. #endif
  12394. 0);
  12395. std::string chunk(64 * 1024, 'A');
  12396. size_t total_sent = 0;
  12397. while (total_sent < DATA_SIZE) {
  12398. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12399. auto sent = ::send(cli,
  12400. #ifdef _WIN32
  12401. static_cast<const char *>(chunk.c_str()),
  12402. static_cast<int>(to_send),
  12403. #else
  12404. chunk.c_str(), to_send,
  12405. #endif
  12406. 0);
  12407. if (sent <= 0) break;
  12408. total_sent += static_cast<size_t>(sent);
  12409. }
  12410. #ifdef _WIN32
  12411. ::shutdown(cli, SD_SEND);
  12412. #else
  12413. ::shutdown(cli, SHUT_WR);
  12414. #endif
  12415. // Drain until the client closes its end, ensuring all data is delivered
  12416. char drain[1024];
  12417. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12418. detail::close_socket(cli);
  12419. }
  12420. detail::close_socket(srv);
  12421. });
  12422. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12423. size_t total_read = 0;
  12424. {
  12425. Client cli("127.0.0.1", PORT + 2);
  12426. cli.set_read_timeout(5, 0);
  12427. cli.set_payload_max_length(0); // 0 means no limit
  12428. auto stream = cli.open_stream("GET", "/data");
  12429. ASSERT_TRUE(stream.is_valid());
  12430. char buffer[64 * 1024];
  12431. ssize_t n;
  12432. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12433. total_read += static_cast<size_t>(n);
  12434. }
  12435. }
  12436. server_thread.join();
  12437. EXPECT_EQ(total_read, DATA_SIZE)
  12438. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12439. << " bytes without truncation, but only read " << total_read << " bytes.";
  12440. }
  12441. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12442. // enormous Content-Length must not cause the client to pre-allocate a huge
  12443. // response body buffer. The reservation is capped at payload_max_length_, and
  12444. // the read itself fails when the body exceeds the limit.
  12445. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12446. #ifndef _WIN32
  12447. signal(SIGPIPE, SIG_IGN);
  12448. #endif
  12449. auto server_thread = std::thread([] {
  12450. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12451. default_socket_options(srv);
  12452. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12453. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12454. sockaddr_in addr{};
  12455. addr.sin_family = AF_INET;
  12456. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12457. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12458. int opt = 1;
  12459. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12460. #ifdef _WIN32
  12461. reinterpret_cast<const char *>(&opt),
  12462. #else
  12463. &opt,
  12464. #endif
  12465. sizeof(opt));
  12466. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12467. ::listen(srv, 1);
  12468. sockaddr_in cli_addr{};
  12469. socklen_t cli_len = sizeof(cli_addr);
  12470. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12471. if (cli != INVALID_SOCKET) {
  12472. char buf[4096];
  12473. ::recv(cli, buf, sizeof(buf), 0);
  12474. // Malicious response: claim a 20GB body but send only a tiny payload.
  12475. std::string response = "HTTP/1.1 200 OK\r\n"
  12476. "Content-Length: 20000000000\r\n"
  12477. "\r\n"
  12478. "abc";
  12479. ::send(cli,
  12480. #ifdef _WIN32
  12481. static_cast<const char *>(response.c_str()),
  12482. static_cast<int>(response.size()),
  12483. #else
  12484. response.c_str(), response.size(),
  12485. #endif
  12486. 0);
  12487. detail::close_socket(cli);
  12488. }
  12489. detail::close_socket(srv);
  12490. });
  12491. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12492. {
  12493. Client cli("127.0.0.1", PORT + 2);
  12494. cli.set_read_timeout(5, 0);
  12495. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12496. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12497. // (server claims more bytes than payload_max_length permits), but it must
  12498. // not exhaust memory before getting there.
  12499. auto res = cli.Get("/malicious");
  12500. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12501. }
  12502. server_thread.join();
  12503. }
  12504. // Verify that content_receiver bypasses the default payload_max_length,
  12505. // allowing streaming downloads larger than 100MB without requiring an explicit
  12506. // set_payload_max_length call.
  12507. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12508. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12509. #ifndef _WIN32
  12510. signal(SIGPIPE, SIG_IGN);
  12511. #endif
  12512. auto server_thread = std::thread([] {
  12513. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12514. default_socket_options(srv);
  12515. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12516. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12517. sockaddr_in addr{};
  12518. addr.sin_family = AF_INET;
  12519. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12520. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12521. int opt = 1;
  12522. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12523. #ifdef _WIN32
  12524. reinterpret_cast<const char *>(&opt),
  12525. #else
  12526. &opt,
  12527. #endif
  12528. sizeof(opt));
  12529. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12530. ::listen(srv, 1);
  12531. sockaddr_in cli_addr{};
  12532. socklen_t cli_len = sizeof(cli_addr);
  12533. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12534. if (cli != INVALID_SOCKET) {
  12535. char buf[4096];
  12536. ::recv(cli, buf, sizeof(buf), 0);
  12537. // Response with Content-Length larger than default 100MB limit
  12538. auto content_length = std::to_string(DATA_SIZE);
  12539. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12540. "Content-Length: " +
  12541. content_length +
  12542. "\r\n"
  12543. "Connection: close\r\n"
  12544. "\r\n";
  12545. ::send(cli,
  12546. #ifdef _WIN32
  12547. static_cast<const char *>(response_header.c_str()),
  12548. static_cast<int>(response_header.size()),
  12549. #else
  12550. response_header.c_str(), response_header.size(),
  12551. #endif
  12552. 0);
  12553. std::string chunk(64 * 1024, 'A');
  12554. size_t total_sent = 0;
  12555. while (total_sent < DATA_SIZE) {
  12556. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12557. auto sent = ::send(cli,
  12558. #ifdef _WIN32
  12559. static_cast<const char *>(chunk.c_str()),
  12560. static_cast<int>(to_send),
  12561. #else
  12562. chunk.c_str(), to_send,
  12563. #endif
  12564. 0);
  12565. if (sent <= 0) break;
  12566. total_sent += static_cast<size_t>(sent);
  12567. }
  12568. detail::close_socket(cli);
  12569. }
  12570. detail::close_socket(srv);
  12571. });
  12572. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12573. size_t total_received = 0;
  12574. {
  12575. Client cli("127.0.0.1", PORT + 2);
  12576. cli.set_read_timeout(10, 0);
  12577. // Do NOT call set_payload_max_length — use the default 100MB limit
  12578. auto res =
  12579. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12580. total_received += data_length;
  12581. return true;
  12582. });
  12583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12584. EXPECT_EQ(StatusCode::OK_200, res->status);
  12585. }
  12586. server_thread.join();
  12587. EXPECT_EQ(total_received, DATA_SIZE)
  12588. << "With content_receiver, the client should read all " << DATA_SIZE
  12589. << " bytes despite the default 100MB payload_max_length, but only read "
  12590. << total_received << " bytes.";
  12591. }
  12592. // Verify that an explicit set_payload_max_length smaller than the response is
  12593. // enforced even when a content_receiver is used.
  12594. TEST(ClientVulnerabilityTest,
  12595. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12596. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12597. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12598. #ifndef _WIN32
  12599. signal(SIGPIPE, SIG_IGN);
  12600. #endif
  12601. auto server_thread = std::thread([] {
  12602. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12603. default_socket_options(srv);
  12604. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12605. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12606. sockaddr_in addr{};
  12607. addr.sin_family = AF_INET;
  12608. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12609. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12610. int opt = 1;
  12611. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12612. #ifdef _WIN32
  12613. reinterpret_cast<const char *>(&opt),
  12614. #else
  12615. &opt,
  12616. #endif
  12617. sizeof(opt));
  12618. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12619. ::listen(srv, 1);
  12620. sockaddr_in cli_addr{};
  12621. socklen_t cli_len = sizeof(cli_addr);
  12622. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12623. if (cli != INVALID_SOCKET) {
  12624. char buf[4096];
  12625. ::recv(cli, buf, sizeof(buf), 0);
  12626. auto content_length = std::to_string(DATA_SIZE);
  12627. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12628. "Content-Length: " +
  12629. content_length +
  12630. "\r\n"
  12631. "Connection: close\r\n"
  12632. "\r\n";
  12633. ::send(cli,
  12634. #ifdef _WIN32
  12635. static_cast<const char *>(response_header.c_str()),
  12636. static_cast<int>(response_header.size()),
  12637. #else
  12638. response_header.c_str(), response_header.size(),
  12639. #endif
  12640. 0);
  12641. std::string chunk(64 * 1024, 'A');
  12642. size_t total_sent = 0;
  12643. while (total_sent < DATA_SIZE) {
  12644. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12645. auto sent = ::send(cli,
  12646. #ifdef _WIN32
  12647. static_cast<const char *>(chunk.c_str()),
  12648. static_cast<int>(to_send),
  12649. #else
  12650. chunk.c_str(), to_send,
  12651. #endif
  12652. 0);
  12653. if (sent <= 0) break;
  12654. total_sent += static_cast<size_t>(sent);
  12655. }
  12656. detail::close_socket(cli);
  12657. }
  12658. detail::close_socket(srv);
  12659. });
  12660. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12661. size_t total_received = 0;
  12662. {
  12663. Client cli("127.0.0.1", PORT + 2);
  12664. cli.set_read_timeout(10, 0);
  12665. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12666. auto res =
  12667. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12668. total_received += data_length;
  12669. return true;
  12670. });
  12671. // Should fail because 200MB exceeds the explicit 150MB limit
  12672. EXPECT_FALSE(res);
  12673. }
  12674. server_thread.join();
  12675. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12676. << "Client with content_receiver should respect the explicit "
  12677. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12678. << total_received << " bytes.";
  12679. }
  12680. // Verify that an explicit set_payload_max_length larger than the response
  12681. // allows the content_receiver to read all data successfully.
  12682. TEST(ClientVulnerabilityTest,
  12683. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12684. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12685. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12686. #ifndef _WIN32
  12687. signal(SIGPIPE, SIG_IGN);
  12688. #endif
  12689. auto server_thread = std::thread([] {
  12690. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12691. default_socket_options(srv);
  12692. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12693. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12694. sockaddr_in addr{};
  12695. addr.sin_family = AF_INET;
  12696. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12697. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12698. int opt = 1;
  12699. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12700. #ifdef _WIN32
  12701. reinterpret_cast<const char *>(&opt),
  12702. #else
  12703. &opt,
  12704. #endif
  12705. sizeof(opt));
  12706. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12707. ::listen(srv, 1);
  12708. sockaddr_in cli_addr{};
  12709. socklen_t cli_len = sizeof(cli_addr);
  12710. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12711. if (cli != INVALID_SOCKET) {
  12712. char buf[4096];
  12713. ::recv(cli, buf, sizeof(buf), 0);
  12714. auto content_length = std::to_string(DATA_SIZE);
  12715. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12716. "Content-Length: " +
  12717. content_length +
  12718. "\r\n"
  12719. "Connection: close\r\n"
  12720. "\r\n";
  12721. ::send(cli,
  12722. #ifdef _WIN32
  12723. static_cast<const char *>(response_header.c_str()),
  12724. static_cast<int>(response_header.size()),
  12725. #else
  12726. response_header.c_str(), response_header.size(),
  12727. #endif
  12728. 0);
  12729. std::string chunk(64 * 1024, 'A');
  12730. size_t total_sent = 0;
  12731. while (total_sent < DATA_SIZE) {
  12732. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12733. auto sent = ::send(cli,
  12734. #ifdef _WIN32
  12735. static_cast<const char *>(chunk.c_str()),
  12736. static_cast<int>(to_send),
  12737. #else
  12738. chunk.c_str(), to_send,
  12739. #endif
  12740. 0);
  12741. if (sent <= 0) break;
  12742. total_sent += static_cast<size_t>(sent);
  12743. }
  12744. #ifdef _WIN32
  12745. ::shutdown(cli, SD_SEND);
  12746. #else
  12747. ::shutdown(cli, SHUT_WR);
  12748. #endif
  12749. char drain[1024];
  12750. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12751. detail::close_socket(cli);
  12752. }
  12753. detail::close_socket(srv);
  12754. });
  12755. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12756. size_t total_received = 0;
  12757. {
  12758. Client cli("127.0.0.1", PORT + 2);
  12759. cli.set_read_timeout(10, 0);
  12760. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12761. auto res =
  12762. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12763. total_received += data_length;
  12764. return true;
  12765. });
  12766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12767. EXPECT_EQ(StatusCode::OK_200, res->status);
  12768. }
  12769. server_thread.join();
  12770. EXPECT_EQ(total_received, DATA_SIZE)
  12771. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12772. << " bytes (larger than " << DATA_SIZE
  12773. << " bytes response), content_receiver should read all data, but only "
  12774. "read "
  12775. << total_received << " bytes.";
  12776. }
  12777. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12778. // Regression test for "zip bomb" attack on the client side: a malicious server
  12779. // sends a small gzip-compressed response that decompresses to a huge payload.
  12780. // The client must enforce payload_max_length on the decompressed size.
  12781. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12782. constexpr size_t DECOMPRESSED_SIZE =
  12783. 10 * 1024 * 1024; // 10MB after decompression
  12784. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12785. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12786. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12787. std::string compressed;
  12788. {
  12789. httplib::detail::gzip_compressor compressor;
  12790. bool ok =
  12791. compressor.compress(uncompressed.data(), uncompressed.size(),
  12792. /*last=*/true, [&](const char *buf, size_t len) {
  12793. compressed.append(buf, len);
  12794. return true;
  12795. });
  12796. ASSERT_TRUE(ok);
  12797. }
  12798. // Sanity: compressed data should be much smaller than the decompressed size
  12799. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12800. #ifndef _WIN32
  12801. signal(SIGPIPE, SIG_IGN);
  12802. #endif
  12803. // Set up the listening socket in the main thread so the server is guaranteed
  12804. // to be ready before the client connects (eliminates race condition).
  12805. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12806. default_socket_options(srv);
  12807. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12808. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12809. sockaddr_in addr{};
  12810. addr.sin_family = AF_INET;
  12811. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12812. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12813. int opt = 1;
  12814. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12815. #ifdef _WIN32
  12816. reinterpret_cast<const char *>(&opt),
  12817. #else
  12818. &opt,
  12819. #endif
  12820. sizeof(opt));
  12821. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12822. ASSERT_EQ(0, ::listen(srv, 1));
  12823. auto server_thread = std::thread([&compressed, srv] {
  12824. sockaddr_in cli_addr{};
  12825. socklen_t cli_len = sizeof(cli_addr);
  12826. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12827. if (cli != INVALID_SOCKET) {
  12828. // Read the full HTTP request (until \r\n\r\n)
  12829. char buf[4096];
  12830. size_t total = 0;
  12831. while (total < sizeof(buf)) {
  12832. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12833. if (n <= 0) break;
  12834. total += static_cast<size_t>(n);
  12835. // Check for end of headers
  12836. if (total >= 4) {
  12837. std::string req(buf, total);
  12838. if (req.find("\r\n\r\n") != std::string::npos) break;
  12839. }
  12840. }
  12841. // Malicious response: gzip-compressed body, no Content-Length
  12842. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12843. "Content-Encoding: gzip\r\n"
  12844. "Connection: close\r\n"
  12845. "\r\n";
  12846. ::send(cli,
  12847. #ifdef _WIN32
  12848. static_cast<const char *>(response_header.c_str()),
  12849. static_cast<int>(response_header.size()),
  12850. #else
  12851. response_header.c_str(), response_header.size(),
  12852. #endif
  12853. 0);
  12854. // Send the compressed payload (small on the wire, huge when decompressed)
  12855. size_t total_sent = 0;
  12856. while (total_sent < compressed.size()) {
  12857. auto to_send = std::min(compressed.size() - total_sent,
  12858. static_cast<size_t>(64 * 1024));
  12859. auto sent =
  12860. ::send(cli,
  12861. #ifdef _WIN32
  12862. static_cast<const char *>(compressed.c_str() + total_sent),
  12863. static_cast<int>(to_send),
  12864. #else
  12865. compressed.c_str() + total_sent, to_send,
  12866. #endif
  12867. 0);
  12868. if (sent <= 0) break;
  12869. total_sent += static_cast<size_t>(sent);
  12870. }
  12871. detail::close_socket(cli);
  12872. }
  12873. });
  12874. auto se = detail::scope_exit([&] {
  12875. detail::close_socket(srv);
  12876. server_thread.join();
  12877. });
  12878. size_t total_decompressed = 0;
  12879. {
  12880. Client cli("127.0.0.1", PORT + 3);
  12881. cli.set_read_timeout(5, 0);
  12882. cli.set_decompress(true);
  12883. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12884. auto stream = cli.open_stream("GET", "/zipbomb");
  12885. ASSERT_TRUE(stream.is_valid());
  12886. char buffer[64 * 1024];
  12887. ssize_t n;
  12888. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12889. total_decompressed += static_cast<size_t>(n);
  12890. }
  12891. }
  12892. // The decompressed size must be capped by payload_max_length. Without
  12893. // protection, the client would decompress the full 10MB from a tiny
  12894. // compressed payload, enabling a zip bomb DoS attack.
  12895. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12896. << "Client decompressed " << total_decompressed
  12897. << " bytes from a gzip response. The decompressed size should be "
  12898. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12899. }
  12900. #endif
  12901. TEST(HostAndPortPropertiesTest, NoSSL) {
  12902. httplib::Client cli("www.google.com", 1234);
  12903. ASSERT_EQ("www.google.com", cli.host());
  12904. ASSERT_EQ(1234, cli.port());
  12905. }
  12906. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12907. httplib::Client cli("www.google.com:1234");
  12908. ASSERT_EQ("www.google.com", cli.host());
  12909. ASSERT_EQ(1234, cli.port());
  12910. }
  12911. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12912. // Port number that overflows int — should not crash, client becomes invalid
  12913. httplib::Client cli("http://www.google.com:99999999999999999999");
  12914. ASSERT_FALSE(cli.is_valid());
  12915. }
  12916. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12917. // Port 99999 exceeds valid range (1-65535) — should not crash
  12918. httplib::Client cli("http://www.google.com:99999");
  12919. ASSERT_FALSE(cli.is_valid());
  12920. auto res = cli.Get("/");
  12921. EXPECT_FALSE(res);
  12922. EXPECT_EQ(Error::Connection, res.error());
  12923. }
  12924. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  12925. httplib::Client cli("http://user:pass@localhost:1234");
  12926. ASSERT_FALSE(cli.is_valid());
  12927. EXPECT_FALSE(cli.Get("/"));
  12928. }
  12929. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12930. httplib::Client cli("http://www.google.com:80abc");
  12931. ASSERT_FALSE(cli.is_valid());
  12932. }
  12933. #ifdef CPPHTTPLIB_SSL_ENABLED
  12934. TEST(HostAndPortPropertiesTest, SSL) {
  12935. httplib::SSLClient cli("www.google.com");
  12936. ASSERT_EQ("www.google.com", cli.host());
  12937. ASSERT_EQ(443, cli.port());
  12938. }
  12939. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12940. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12941. std::string cert;
  12942. read_file(CA_CERT_FILE, cert);
  12943. httplib::SSLClient httplib_client("www.google.com");
  12944. // Load CA store first time
  12945. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12946. // Load CA store second time (update)
  12947. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12948. // Verify client is still valid and can make connections
  12949. httplib_client.enable_server_certificate_verification(true);
  12950. auto res = httplib_client.Get("/");
  12951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12952. // Google may return 200 or 301 depending on various factors
  12953. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12954. res->status == StatusCode::MovedPermanently_301);
  12955. }
  12956. TEST(SSLClientTest, ServerNameIndication_Online) {
  12957. auto host = "httpbingo.org";
  12958. auto path = std::string{"/get"};
  12959. SSLClient cli(host, 443);
  12960. auto res = cli.Get(path);
  12961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12962. ASSERT_EQ(StatusCode::OK_200, res->status);
  12963. }
  12964. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12965. // Use a site that will cause SSL verification failure due to self-signed cert
  12966. SSLClient cli("self-signed.badssl.com", 443);
  12967. cli.enable_server_certificate_verification(true);
  12968. auto res = cli.Get("/");
  12969. ASSERT_TRUE(!res);
  12970. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12971. // Verify backend error is captured for SSLServerVerification
  12972. // This occurs when certificate verification fails
  12973. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12974. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12975. EXPECT_NE(0UL, res.ssl_backend_error());
  12976. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12977. // For OpenSSL, ssl_error is 0 for verification errors
  12978. EXPECT_EQ(0, res.ssl_error());
  12979. #if !defined(_WIN32) || \
  12980. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12981. // On non-Windows or when Windows Schannel is disabled, the error comes
  12982. // from OpenSSL's verification
  12983. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12984. res.ssl_backend_error());
  12985. #endif
  12986. #endif
  12987. }
  12988. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12989. // Use a site where hostname doesn't match the certificate
  12990. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12991. SSLClient cli("wrong.host.badssl.com", 443);
  12992. cli.enable_server_certificate_verification(true);
  12993. cli.enable_server_hostname_verification(true);
  12994. auto res = cli.Get("/");
  12995. ASSERT_TRUE(!res);
  12996. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12997. // Verify backend error is captured for hostname verification failure
  12998. EXPECT_NE(0UL, res.ssl_backend_error());
  12999. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13000. // For OpenSSL, ssl_error is 0 for verification errors
  13001. EXPECT_EQ(0, res.ssl_error());
  13002. #if !defined(_WIN32) || \
  13003. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13004. // On non-Windows or when Windows Schannel is disabled, the error comes
  13005. // from OpenSSL's hostname verification
  13006. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13007. res.ssl_backend_error());
  13008. #endif
  13009. #endif
  13010. }
  13011. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13012. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13013. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13014. SSLClient cli("www.google.com", 443);
  13015. cli.enable_server_certificate_verification(true);
  13016. auto res = cli.Get("/");
  13017. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13018. }
  13019. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13020. SSLClient cli("www.google.com", 443);
  13021. cli.enable_server_certificate_verification(true);
  13022. cli.enable_windows_certificate_verification(false);
  13023. auto res = cli.Get("/");
  13024. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13025. }
  13026. // The server sends an intermediate cross-signed by a root Windows trusts,
  13027. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13028. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13029. SSLClient cli("accounts.spotify.com", 443);
  13030. auto res = cli.Get("/");
  13031. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13032. << " ssl_backend_error=" << res.ssl_backend_error();
  13033. }
  13034. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13035. // policy status, which no backend reports for a self-signed certificate.
  13036. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13037. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13038. ASSERT_TRUE(svr.is_valid());
  13039. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13040. auto se = detail::scope_exit([&] {
  13041. svr.stop();
  13042. t.join();
  13043. ASSERT_FALSE(svr.is_running());
  13044. });
  13045. svr.wait_until_ready();
  13046. SSLClient cli("127.0.0.1", PORT);
  13047. cli.set_connection_timeout(30);
  13048. auto res = cli.Get("/");
  13049. ASSERT_FALSE(res);
  13050. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13051. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13052. }
  13053. #endif
  13054. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13055. Client cli("https://google.com");
  13056. auto res = cli.Get("/");
  13057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13058. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13059. }
  13060. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13061. SSLClient cli("google.com");
  13062. cli.set_ca_cert_path(CA_CERT_FILE);
  13063. auto res = cli.Get("/");
  13064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13065. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13066. }
  13067. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13068. SSLClient cli("google.com");
  13069. cli.enable_server_certificate_verification(true);
  13070. cli.set_ca_cert_path("hello");
  13071. auto res = cli.Get("/");
  13072. ASSERT_TRUE(!res);
  13073. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13074. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13075. // should be set
  13076. EXPECT_EQ(0, res.ssl_error());
  13077. // Verify backend error is captured for SSLLoadingCerts
  13078. // This error occurs when loading CA certificates fails
  13079. EXPECT_NE(0UL, res.ssl_backend_error());
  13080. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13081. // OpenSSL specific error codes:
  13082. // > openssl errstr 0x80000002
  13083. // error:80000002:system library::No such file or directory
  13084. // > openssl errstr 0xA000126
  13085. // error:0A000126:SSL routines::unexpected eof while reading
  13086. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13087. res.ssl_backend_error() == 0xA000126);
  13088. #endif
  13089. }
  13090. TEST(SSLClientTest, ServerCertificateVerification4) {
  13091. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13092. ASSERT_TRUE(svr.is_valid());
  13093. svr.Get("/test", [&](const Request &, Response &res) {
  13094. res.set_content("test", "text/plain");
  13095. svr.stop();
  13096. ASSERT_TRUE(true);
  13097. });
  13098. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13099. auto se = detail::scope_exit([&] {
  13100. t.join();
  13101. ASSERT_FALSE(svr.is_running());
  13102. });
  13103. svr.wait_until_ready();
  13104. SSLClient cli("127.0.0.1", PORT);
  13105. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13106. cli.enable_server_certificate_verification(true);
  13107. cli.set_connection_timeout(30);
  13108. auto res = cli.Get("/test");
  13109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13110. ASSERT_EQ(StatusCode::OK_200, res->status);
  13111. }
  13112. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13113. std::string cert;
  13114. read_file(CA_CERT_FILE, cert);
  13115. SSLClient cli("google.com");
  13116. cli.load_ca_cert_store(cert.data(), cert.size());
  13117. const auto res = cli.Get("/");
  13118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13119. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13120. }
  13121. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13122. // clang-format off
  13123. static constexpr char cert[] =
  13124. "GlobalSign Root CA\n"
  13125. "==================\n"
  13126. "-----BEGIN CERTIFICATE-----\n"
  13127. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13128. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13129. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13130. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13131. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13132. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13133. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13134. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13135. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13136. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13137. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13138. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13139. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13140. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13141. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13142. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13143. "-----END CERTIFICATE-----\n";
  13144. // clang-format on
  13145. SSLClient cli("google.com");
  13146. cli.load_ca_cert_store(cert, sizeof(cert));
  13147. const auto res = cli.Get("/");
  13148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13149. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13150. }
  13151. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13152. SSLClient cli("www.youtube.com");
  13153. cli.set_ca_cert_path(CA_CERT_FILE);
  13154. cli.enable_server_certificate_verification(true);
  13155. cli.set_follow_location(true);
  13156. auto res = cli.Get("/");
  13157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13158. ASSERT_EQ(StatusCode::OK_200, res->status);
  13159. }
  13160. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13161. SSLClient cli("wWw.YouTube.Com");
  13162. cli.set_ca_cert_path(CA_CERT_FILE);
  13163. cli.enable_server_certificate_verification(true);
  13164. cli.enable_server_hostname_verification(true);
  13165. cli.set_follow_location(true);
  13166. auto res = cli.Get("/");
  13167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13168. ASSERT_EQ(StatusCode::OK_200, res->status);
  13169. }
  13170. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13171. SSLClient cli("gOoGlE.COm");
  13172. cli.enable_server_certificate_verification(true);
  13173. cli.enable_server_hostname_verification(true);
  13174. cli.set_follow_location(true);
  13175. auto res = cli.Get("/");
  13176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13177. ASSERT_EQ(StatusCode::OK_200, res->status);
  13178. }
  13179. TEST(SSLClientTest, Issue2004_Online) {
  13180. Client client("https://google.com");
  13181. client.set_follow_location(true);
  13182. auto res = client.Get("/");
  13183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13184. ASSERT_EQ(StatusCode::OK_200, res->status);
  13185. auto body = res->body;
  13186. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13187. }
  13188. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13189. // Create SSLClient with invalid cert/key to make is_valid() return false
  13190. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13191. "nonexistent_key.pem");
  13192. // is_valid() should be false due to cert loading failure
  13193. ASSERT_FALSE(cli.is_valid());
  13194. auto res = cli.Get("/");
  13195. ASSERT_FALSE(res);
  13196. EXPECT_EQ(Error::SSLConnection, res.error());
  13197. }
  13198. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13199. // Test for Issue #2251: SSL error not properly reported when client cert
  13200. // and key paths are swapped or mismatched
  13201. // This simulates the scenario where user accidentally swaps the cert and key
  13202. // files
  13203. // Using client cert file as private key and vice versa (completely wrong)
  13204. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13205. // Should fail validation due to cert/key mismatch
  13206. ASSERT_FALSE(cli.is_valid());
  13207. // Attempt to make a request should fail with proper error
  13208. auto res = cli.Get("/");
  13209. ASSERT_FALSE(res);
  13210. EXPECT_EQ(Error::SSLConnection, res.error());
  13211. // SSL error should be recorded in the Result object (this is the key fix for
  13212. // Issue #2251)
  13213. auto backend_error = res.ssl_backend_error();
  13214. EXPECT_NE(0u, backend_error);
  13215. }
  13216. // Tests cert/key mismatch detection at the TLS context level
  13217. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13218. // Test that using mismatched cert/key causes connection failure.
  13219. // We verify this at the SSLClient level rather than through internal
  13220. // TLS API functions.
  13221. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13222. cli.enable_server_certificate_verification(false);
  13223. cli.set_connection_timeout(2);
  13224. // The mismatch should cause a connection or handshake error
  13225. auto res = cli.Get("/test");
  13226. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13227. // Either way, the request should fail
  13228. EXPECT_FALSE(res);
  13229. }
  13230. #endif
  13231. #if 0
  13232. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13233. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13234. ASSERT_TRUE(cli != nullptr);
  13235. cli->set_address_family(AF_INET6);
  13236. cli->set_interface("en0");
  13237. auto res = cli->Get("/get");
  13238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13239. ASSERT_EQ(StatusCode::OK_200, res->status);
  13240. }
  13241. #endif
  13242. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13243. #ifdef CPPHTTPLIB_SSL_ENABLED
  13244. void ClientCertPresent(
  13245. const std::string &client_cert_file,
  13246. const std::string &client_private_key_file,
  13247. const std::string &client_encrypted_private_key_pass = std::string()) {
  13248. using namespace httplib::tls;
  13249. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13250. CLIENT_CA_CERT_DIR);
  13251. ASSERT_TRUE(svr.is_valid());
  13252. svr.Get("/test", [&](const Request &req, Response &res) {
  13253. res.set_content("test", "text/plain");
  13254. auto cert = req.peer_cert();
  13255. ASSERT_TRUE(static_cast<bool>(cert));
  13256. std::string common_name = cert.subject_cn();
  13257. EXPECT_EQ("Common Name", common_name);
  13258. });
  13259. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13260. auto se = detail::scope_exit([&] {
  13261. svr.stop();
  13262. t.join();
  13263. ASSERT_FALSE(svr.is_running());
  13264. });
  13265. svr.wait_until_ready();
  13266. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13267. client_encrypted_private_key_pass);
  13268. cli.enable_server_certificate_verification(false);
  13269. cli.set_connection_timeout(30);
  13270. auto res = cli.Get("/test");
  13271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13272. ASSERT_EQ(StatusCode::OK_200, res->status);
  13273. }
  13274. TEST(SSLClientServerTest, ClientCertPresent) {
  13275. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13276. }
  13277. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13278. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13279. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13280. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13281. }
  13282. // PEM memory-based constructor tests (works with all TLS backends)
  13283. void PemMemoryClientCertPresent(
  13284. const std::string &client_cert_file,
  13285. const std::string &client_private_key_file,
  13286. const std::string &client_encrypted_private_key_pass = std::string()) {
  13287. // Read PEM files into memory
  13288. std::string server_cert_pem, server_key_pem;
  13289. std::string client_ca_pem;
  13290. std::string client_cert_pem, client_key_pem;
  13291. read_file(SERVER_CERT_FILE, server_cert_pem);
  13292. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13293. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13294. read_file(client_cert_file, client_cert_pem);
  13295. read_file(client_private_key_file, client_key_pem);
  13296. // Create server with PEM memory
  13297. SSLServer::PemMemory server_pem = {
  13298. server_cert_pem.c_str(),
  13299. server_cert_pem.size(),
  13300. server_key_pem.c_str(),
  13301. server_key_pem.size(),
  13302. client_ca_pem.c_str(),
  13303. client_ca_pem.size(),
  13304. nullptr // no password for server key
  13305. };
  13306. SSLServer svr(server_pem);
  13307. ASSERT_TRUE(svr.is_valid());
  13308. svr.Get("/test", [&](const Request &, Response &res) {
  13309. res.set_content("test", "text/plain");
  13310. });
  13311. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13312. auto se = detail::scope_exit([&] {
  13313. svr.stop();
  13314. t.join();
  13315. ASSERT_FALSE(svr.is_running());
  13316. });
  13317. svr.wait_until_ready();
  13318. // Create client with PEM memory
  13319. const char *password = client_encrypted_private_key_pass.empty()
  13320. ? nullptr
  13321. : client_encrypted_private_key_pass.c_str();
  13322. SSLClient::PemMemory client_pem = {
  13323. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13324. client_key_pem.size(), password};
  13325. SSLClient cli(HOST, PORT, client_pem);
  13326. cli.enable_server_certificate_verification(false);
  13327. cli.set_connection_timeout(30);
  13328. auto res = cli.Get("/test");
  13329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13330. ASSERT_EQ(StatusCode::OK_200, res->status);
  13331. }
  13332. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13333. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13334. }
  13335. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13336. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13337. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13338. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13339. }
  13340. TEST(SSLClientServerTest, ClientCertMissing) {
  13341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13342. CLIENT_CA_CERT_DIR);
  13343. ASSERT_TRUE(svr.is_valid());
  13344. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13345. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13346. auto se = detail::scope_exit([&] {
  13347. svr.stop();
  13348. t.join();
  13349. ASSERT_FALSE(svr.is_running());
  13350. });
  13351. svr.wait_until_ready();
  13352. SSLClient cli(HOST, PORT);
  13353. cli.set_connection_timeout(30);
  13354. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13355. // the chain check on Windows, so the result does not depend on the order.
  13356. cli.enable_server_hostname_verification(false);
  13357. auto res = cli.Get("/test");
  13358. ASSERT_TRUE(!res);
  13359. // When client cert is missing and server requires it, connection fails
  13360. // Error type depends on backend implementation
  13361. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13362. res.error() == Error::SSLConnection);
  13363. // Verify backend error is captured
  13364. // Note: This test may have different error codes depending on the exact
  13365. // verification failure
  13366. EXPECT_NE(0UL, res.ssl_backend_error());
  13367. }
  13368. TEST(SSLClientServerTest, TrustDirOptional) {
  13369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13370. ASSERT_TRUE(svr.is_valid());
  13371. svr.Get("/test", [&](const Request &, Response &res) {
  13372. res.set_content("test", "text/plain");
  13373. });
  13374. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13375. auto se = detail::scope_exit([&] {
  13376. svr.stop();
  13377. t.join();
  13378. ASSERT_FALSE(svr.is_running());
  13379. });
  13380. svr.wait_until_ready();
  13381. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13382. cli.enable_server_certificate_verification(false);
  13383. cli.set_connection_timeout(30);
  13384. auto res = cli.Get("/test");
  13385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13386. ASSERT_EQ(StatusCode::OK_200, res->status);
  13387. }
  13388. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13389. class NoListenSSLServer : public SSLServer {
  13390. public:
  13391. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13392. const char *client_ca_cert_file_path,
  13393. const char *client_ca_cert_dir_path = nullptr)
  13394. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13395. client_ca_cert_dir_path),
  13396. stop_(false) {}
  13397. std::atomic_bool stop_;
  13398. private:
  13399. bool process_and_close_socket(socket_t /*sock*/) override {
  13400. // Don't create SSL context
  13401. while (!stop_.load()) {
  13402. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13403. }
  13404. return true;
  13405. }
  13406. };
  13407. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13408. CLIENT_CA_CERT_FILE);
  13409. ASSERT_TRUE(svr.is_valid());
  13410. svr.Get("/test", [&](const Request &, Response &res) {
  13411. res.set_content("test", "text/plain");
  13412. });
  13413. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13414. auto se = detail::scope_exit([&] {
  13415. svr.stop_ = true;
  13416. svr.stop();
  13417. t.join();
  13418. ASSERT_FALSE(svr.is_running());
  13419. });
  13420. svr.wait_until_ready();
  13421. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13422. cli.enable_server_certificate_verification(false);
  13423. cli.set_connection_timeout(1);
  13424. auto res = cli.Get("/test");
  13425. ASSERT_TRUE(!res);
  13426. EXPECT_EQ(Error::SSLConnection, res.error());
  13427. // Timeout results in WantRead error code (maps to backend-specific value)
  13428. EXPECT_NE(0, res.ssl_error());
  13429. }
  13430. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13431. // Test SSLServer with client certificate verification using the standard
  13432. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13434. CLIENT_CA_CERT_DIR);
  13435. ASSERT_TRUE(svr.is_valid());
  13436. svr.Get("/test", [&](const Request &req, Response &res) {
  13437. res.set_content("test", "text/plain");
  13438. auto cert = req.peer_cert();
  13439. ASSERT_TRUE(static_cast<bool>(cert));
  13440. auto common_name = cert.subject_cn();
  13441. EXPECT_EQ("Common Name", common_name);
  13442. });
  13443. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13444. auto se = detail::scope_exit([&] {
  13445. svr.stop();
  13446. t.join();
  13447. ASSERT_FALSE(svr.is_running());
  13448. });
  13449. svr.wait_until_ready();
  13450. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13451. cli.enable_server_certificate_verification(false);
  13452. cli.set_connection_timeout(30);
  13453. auto res = cli.Get("/test");
  13454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13455. ASSERT_EQ(StatusCode::OK_200, res->status);
  13456. }
  13457. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13458. // Verifies that wildcard matching and exact matching work consistently
  13459. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13460. using namespace httplib::tls;
  13461. // We need a running server to test against
  13462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13463. ASSERT_TRUE(svr.is_valid());
  13464. svr.Get("/test", [](const Request &, Response &res) {
  13465. res.set_content("ok", "text/plain");
  13466. });
  13467. thread t([&]() { svr.listen(HOST, PORT); });
  13468. auto se = detail::scope_exit([&] {
  13469. svr.stop();
  13470. t.join();
  13471. });
  13472. svr.wait_until_ready();
  13473. bool verify_callback_called = false;
  13474. bool verify_result_wrong = false;
  13475. SSLClient cli(HOST, PORT);
  13476. cli.enable_server_certificate_verification(true);
  13477. cli.set_ca_cert_path(CA_CERT_FILE);
  13478. cli.set_connection_timeout(5);
  13479. // Note: Test certificate has CN="Common Name", not "localhost"
  13480. bool verify_result_cn = false;
  13481. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13482. verify_callback_called = true;
  13483. if (!ctx.cert) return false;
  13484. // Test 1: "Common Name" should match (our test server cert CN)
  13485. verify_result_cn = ctx.check_hostname("Common Name");
  13486. // Test 2: wrong hostname should not match
  13487. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13488. return true; // Accept for the purpose of this test
  13489. });
  13490. auto res = cli.Get("/test");
  13491. // The request may succeed or fail depending on cert configuration
  13492. // but the callback should have been called
  13493. ASSERT_TRUE(verify_callback_called)
  13494. << "Verify callback should have been called";
  13495. // CN="Common Name" should match our test certificate
  13496. //
  13497. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13498. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13499. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13500. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13501. // <openssl/base.h>, which is included transitively when
  13502. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13503. #if defined(OPENSSL_IS_BORINGSSL)
  13504. EXPECT_FALSE(verify_result_cn)
  13505. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13506. #else
  13507. EXPECT_TRUE(verify_result_cn)
  13508. << "verify_hostname should match 'Common Name' (certificate CN)";
  13509. #endif
  13510. // Wrong hostname should not match
  13511. EXPECT_FALSE(verify_result_wrong)
  13512. << "verify_hostname should not match 'wronghost.example.com'";
  13513. }
  13514. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13515. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13516. // X509_check_ip behavior and must hold for every backend.
  13517. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13518. using namespace httplib::tls;
  13519. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13520. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13521. ASSERT_TRUE(svr.is_valid());
  13522. svr.Get("/test", [](const Request &, Response &res) {
  13523. res.set_content("ok", "text/plain");
  13524. });
  13525. thread t([&]() { svr.listen(HOST, PORT); });
  13526. auto se = detail::scope_exit([&] {
  13527. svr.stop();
  13528. t.join();
  13529. });
  13530. svr.wait_until_ready();
  13531. bool verify_callback_called = false;
  13532. bool ip_matched_via_cn = true;
  13533. SSLClient cli(HOST, PORT);
  13534. cli.enable_server_certificate_verification(true);
  13535. cli.set_ca_cert_path(CA_CERT_FILE);
  13536. cli.set_connection_timeout(5);
  13537. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13538. verify_callback_called = true;
  13539. if (!ctx.cert) return false;
  13540. // The IP appears only in the CN, so it must NOT be accepted.
  13541. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13542. return true; // Accept for the purpose of this test
  13543. });
  13544. cli.Get("/test");
  13545. ASSERT_TRUE(verify_callback_called)
  13546. << "Verify callback should have been called";
  13547. EXPECT_FALSE(ip_matched_via_cn)
  13548. << "An IP host must not be authenticated via the certificate CN";
  13549. }
  13550. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13551. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13552. using namespace httplib::tls;
  13553. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13554. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13555. ASSERT_TRUE(svr.is_valid());
  13556. svr.Get("/test", [](const Request &, Response &res) {
  13557. res.set_content("ok", "text/plain");
  13558. });
  13559. thread t([&]() { svr.listen(HOST, PORT); });
  13560. auto se = detail::scope_exit([&] {
  13561. svr.stop();
  13562. t.join();
  13563. });
  13564. svr.wait_until_ready();
  13565. bool verify_callback_called = false;
  13566. bool san_matched = false;
  13567. bool wrong_ipv6_matched = true;
  13568. bool cn_ipv6_matched = true;
  13569. SSLClient cli(HOST, PORT);
  13570. cli.enable_server_certificate_verification(true);
  13571. cli.set_ca_cert_path(CA_CERT_FILE);
  13572. cli.set_connection_timeout(5);
  13573. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13574. verify_callback_called = true;
  13575. if (!ctx.cert) return false;
  13576. // Matches the IPv6 iPAddress SAN.
  13577. san_matched = ctx.check_hostname("2001:db8::1");
  13578. // A different IPv6 address must not match.
  13579. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13580. // "::1" lives only in the CN, so it must not be accepted.
  13581. cn_ipv6_matched = ctx.check_hostname("::1");
  13582. return true; // Accept for the purpose of this test
  13583. });
  13584. cli.Get("/test");
  13585. ASSERT_TRUE(verify_callback_called)
  13586. << "Verify callback should have been called";
  13587. EXPECT_TRUE(san_matched)
  13588. << "verify_hostname should match an IPv6 iPAddress SAN";
  13589. EXPECT_FALSE(wrong_ipv6_matched)
  13590. << "verify_hostname should not match a non-matching IPv6 address";
  13591. EXPECT_FALSE(cn_ipv6_matched)
  13592. << "An IPv6 host must not be authenticated via the certificate CN";
  13593. }
  13594. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13595. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13596. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13597. using namespace httplib::tls;
  13598. // SANs: DNS:a.zz, IP:42.46.122.122
  13599. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13600. ASSERT_TRUE(svr.is_valid());
  13601. svr.Get("/test", [](const Request &, Response &res) {
  13602. res.set_content("ok", "text/plain");
  13603. });
  13604. auto port = svr.bind_to_any_port(HOST);
  13605. thread t([&]() { svr.listen_after_bind(); });
  13606. auto se = detail::scope_exit([&] {
  13607. svr.stop();
  13608. t.join();
  13609. });
  13610. svr.wait_until_ready();
  13611. bool verify_callback_called = false;
  13612. bool dns_san_matched = false;
  13613. bool ip_san_matched = false;
  13614. bool ip_matched_via_dns_san = true;
  13615. bool dns_matched_via_ip_san = true;
  13616. SSLClient cli(HOST, port);
  13617. cli.enable_server_certificate_verification(true);
  13618. cli.set_ca_cert_path(CA_CERT_FILE);
  13619. cli.set_connection_timeout(5);
  13620. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13621. verify_callback_called = true;
  13622. if (!ctx.cert) return false;
  13623. dns_san_matched = ctx.check_hostname("a.zz");
  13624. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13625. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13626. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13627. return true; // Accept for the purpose of this test
  13628. });
  13629. cli.Get("/test");
  13630. ASSERT_TRUE(verify_callback_called)
  13631. << "Verify callback should have been called";
  13632. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13633. EXPECT_TRUE(ip_san_matched)
  13634. << "verify_hostname should match an iPAddress SAN";
  13635. EXPECT_FALSE(ip_matched_via_dns_san)
  13636. << "An IP host must not be authenticated via a dNSName SAN";
  13637. EXPECT_FALSE(dns_matched_via_ip_san)
  13638. << "A DNS host must not be authenticated via an iPAddress SAN";
  13639. }
  13640. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13641. // "www.*.example.test" names one host and not every host under example.test.
  13642. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13643. using namespace httplib::tls;
  13644. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13645. SSLServer svr(SERVER_CERT_WILDCARD_SAN_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. auto port = svr.bind_to_any_port(HOST);
  13651. thread t([&]() { svr.listen_after_bind(); });
  13652. auto se = detail::scope_exit([&] {
  13653. svr.stop();
  13654. t.join();
  13655. });
  13656. svr.wait_until_ready();
  13657. bool verify_callback_called = false;
  13658. bool leftmost_wildcard_matched = false;
  13659. bool wildcard_spanned_labels = true;
  13660. bool inner_wildcard_matched = true;
  13661. SSLClient cli(HOST, port);
  13662. cli.enable_server_certificate_verification(true);
  13663. cli.set_ca_cert_path(CA_CERT_FILE);
  13664. cli.set_connection_timeout(5);
  13665. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13666. verify_callback_called = true;
  13667. if (!ctx.cert) return false;
  13668. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13669. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13670. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13671. return true; // Accept for the purpose of this test
  13672. });
  13673. cli.Get("/test");
  13674. ASSERT_TRUE(verify_callback_called)
  13675. << "Verify callback should have been called";
  13676. EXPECT_TRUE(leftmost_wildcard_matched)
  13677. << "A leftmost wildcard should match a single label";
  13678. EXPECT_FALSE(wildcard_spanned_labels)
  13679. << "A wildcard label must not match more than one label";
  13680. EXPECT_FALSE(inner_wildcard_matched)
  13681. << "A wildcard outside the leftmost label must not be honoured";
  13682. }
  13683. // sans() must report each SAN entry under its own type.
  13684. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13685. using namespace httplib::tls;
  13686. // SANs: DNS:a.zz, IP:42.46.122.122
  13687. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13688. ASSERT_TRUE(svr.is_valid());
  13689. svr.Get("/test", [](const Request &, Response &res) {
  13690. res.set_content("ok", "text/plain");
  13691. });
  13692. auto port = svr.bind_to_any_port(HOST);
  13693. thread t([&]() { svr.listen_after_bind(); });
  13694. auto se = detail::scope_exit([&] {
  13695. svr.stop();
  13696. t.join();
  13697. });
  13698. svr.wait_until_ready();
  13699. bool verify_callback_called = false;
  13700. std::vector<SanEntry> sans;
  13701. SSLClient cli(HOST, port);
  13702. cli.enable_server_certificate_verification(true);
  13703. cli.set_ca_cert_path(CA_CERT_FILE);
  13704. cli.set_connection_timeout(5);
  13705. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13706. verify_callback_called = true;
  13707. if (!ctx.cert) return false;
  13708. sans = ctx.sans();
  13709. return true; // Accept for the purpose of this test
  13710. });
  13711. cli.Get("/test");
  13712. ASSERT_TRUE(verify_callback_called)
  13713. << "Verify callback should have been called";
  13714. auto has_san = [&](SanType type, const std::string &value) {
  13715. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13716. return san.type == type && san.value == value;
  13717. });
  13718. };
  13719. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13720. << "sans() should report the dNSName SAN";
  13721. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13722. << "sans() should report the iPAddress SAN";
  13723. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13724. << "sans() must not report the dNSName SAN as an address";
  13725. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13726. << "sans() must not report the iPAddress SAN as a DNS name";
  13727. }
  13728. #endif
  13729. // mbedTLS-specific callback constructor test
  13730. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13731. #ifdef CPPHTTPLIB_SSL_ENABLED
  13732. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13734. ASSERT_TRUE(svr.is_valid());
  13735. // Set up a handler to verify client certificate is present
  13736. bool client_cert_verified = false;
  13737. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13738. // Verify that client certificate was provided
  13739. client_cert_verified = true;
  13740. res.set_content("success", "text/plain");
  13741. });
  13742. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13743. auto se = detail::scope_exit([&] {
  13744. svr.stop();
  13745. t.join();
  13746. ASSERT_FALSE(svr.is_running());
  13747. });
  13748. svr.wait_until_ready();
  13749. // Client with certificate
  13750. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13751. cli.enable_server_certificate_verification(false);
  13752. cli.set_connection_timeout(30);
  13753. auto res = cli.Get("/test");
  13754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13755. ASSERT_EQ(StatusCode::OK_200, res->status);
  13756. ASSERT_TRUE(client_cert_verified);
  13757. EXPECT_EQ("success", res->body);
  13758. }
  13759. #endif
  13760. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13761. // backends
  13762. #ifdef CPPHTTPLIB_SSL_ENABLED
  13763. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13764. using namespace httplib::tls;
  13765. // Test that when client CA cert file is provided,
  13766. // the server properly requests and validates client certificates
  13767. // Create a server with client authentication
  13768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13769. ASSERT_TRUE(svr.is_valid());
  13770. bool handler_called = false;
  13771. svr.Get("/test", [&](const Request &req, Response &res) {
  13772. handler_called = true;
  13773. // Verify that a client certificate was provided
  13774. auto cert = req.peer_cert();
  13775. ASSERT_TRUE(static_cast<bool>(cert));
  13776. // Get the issuer name
  13777. std::string issuer_str = cert.issuer_name();
  13778. ASSERT_FALSE(issuer_str.empty());
  13779. // The client certificate should be issued by our test CA
  13780. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13781. res.set_content("authenticated", "text/plain");
  13782. });
  13783. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13784. auto se = detail::scope_exit([&] {
  13785. svr.stop();
  13786. t.join();
  13787. ASSERT_FALSE(svr.is_running());
  13788. });
  13789. svr.wait_until_ready();
  13790. // Connect with a client certificate issued by the CA
  13791. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13792. cli.enable_server_certificate_verification(false);
  13793. cli.set_connection_timeout(30);
  13794. auto res = cli.Get("/test");
  13795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13796. ASSERT_EQ(StatusCode::OK_200, res->status);
  13797. ASSERT_TRUE(handler_called);
  13798. EXPECT_EQ("authenticated", res->body);
  13799. }
  13800. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13801. using namespace httplib::tls;
  13802. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13803. ASSERT_TRUE(svr.is_valid());
  13804. svr.Get("/test", [](const Request &, Response &res) {
  13805. res.set_content("ok", "text/plain");
  13806. });
  13807. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13808. auto se = detail::scope_exit([&] {
  13809. svr.stop();
  13810. t.join();
  13811. });
  13812. svr.wait_until_ready();
  13813. SSLClient cli(HOST, PORT);
  13814. cli.enable_server_certificate_verification(false);
  13815. cli.set_connection_timeout(30);
  13816. bool cert_checked = false;
  13817. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13818. if (ctx.cert) {
  13819. auto sans = ctx.sans();
  13820. // Test certificate may or may not have SANs - just verify the API
  13821. // works If SANs exist, verify the types are valid
  13822. for (const auto &san : sans) {
  13823. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13824. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13825. san.type == SanType::OTHER);
  13826. EXPECT_FALSE(san.value.empty());
  13827. }
  13828. cert_checked = true;
  13829. }
  13830. return true;
  13831. });
  13832. auto res = cli.Get("/test");
  13833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13834. EXPECT_TRUE(cert_checked);
  13835. }
  13836. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13837. using namespace httplib::tls;
  13838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13839. ASSERT_TRUE(svr.is_valid());
  13840. svr.Get("/test", [](const Request &, Response &res) {
  13841. res.set_content("ok", "text/plain");
  13842. });
  13843. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13844. auto se = detail::scope_exit([&] {
  13845. svr.stop();
  13846. t.join();
  13847. });
  13848. svr.wait_until_ready();
  13849. SSLClient cli(HOST, PORT);
  13850. cli.enable_server_certificate_verification(false);
  13851. cli.set_connection_timeout(30);
  13852. bool validity_checked = false;
  13853. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13854. if (ctx.cert) {
  13855. time_t not_before = 0, not_after = 0;
  13856. bool result = ctx.validity(not_before, not_after);
  13857. EXPECT_TRUE(result);
  13858. // Verify that not_before < now < not_after for a valid cert
  13859. time_t now = time(nullptr);
  13860. EXPECT_LT(not_before, now);
  13861. EXPECT_GT(not_after, now);
  13862. validity_checked = true;
  13863. }
  13864. return true;
  13865. });
  13866. auto res = cli.Get("/test");
  13867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13868. EXPECT_TRUE(validity_checked);
  13869. }
  13870. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13871. using namespace httplib::tls;
  13872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13873. ASSERT_TRUE(svr.is_valid());
  13874. svr.Get("/test", [](const Request &, Response &res) {
  13875. res.set_content("ok", "text/plain");
  13876. });
  13877. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13878. auto se = detail::scope_exit([&] {
  13879. svr.stop();
  13880. t.join();
  13881. });
  13882. svr.wait_until_ready();
  13883. SSLClient cli(HOST, PORT);
  13884. cli.enable_server_certificate_verification(false);
  13885. cli.set_connection_timeout(30);
  13886. bool serial_checked = false;
  13887. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13888. if (ctx.cert) {
  13889. std::string serial = ctx.serial();
  13890. EXPECT_FALSE(serial.empty());
  13891. // Serial should be a hex string
  13892. for (char c : serial) {
  13893. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13894. (c >= 'a' && c <= 'f'));
  13895. }
  13896. serial_checked = true;
  13897. }
  13898. return true;
  13899. });
  13900. auto res = cli.Get("/test");
  13901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13902. EXPECT_TRUE(serial_checked);
  13903. }
  13904. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13905. // Test 1: Valid CA file - no error should be recorded
  13906. {
  13907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13908. CLIENT_CA_CERT_FILE);
  13909. ASSERT_TRUE(svr.is_valid());
  13910. // With valid setup, last_ssl_error should be 0
  13911. EXPECT_EQ(0, svr.ssl_last_error());
  13912. }
  13913. // Test 2: Invalid CA file content
  13914. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13915. {
  13916. // Create a temporary file with completely invalid content
  13917. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13918. {
  13919. std::ofstream ofs(temp_invalid_ca);
  13920. ofs << "This is not a certificate file at all\n";
  13921. ofs << "Just plain text content\n";
  13922. }
  13923. // Create server with invalid CA file
  13924. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13925. // Clean up temporary file
  13926. std::remove(temp_invalid_ca);
  13927. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13928. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13929. // Note: SSL_CTX_load_verify_locations typically fails first,
  13930. // but our error handling code path is still exercised
  13931. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13932. }
  13933. }
  13934. TEST(VerifyCallbackTest, VerifyContextFields) {
  13935. using namespace httplib::tls;
  13936. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13937. ASSERT_TRUE(svr.is_valid());
  13938. svr.Get("/test", [](const Request &, Response &res) {
  13939. res.set_content("ok", "text/plain");
  13940. });
  13941. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13942. auto se = detail::scope_exit([&] {
  13943. svr.stop();
  13944. t.join();
  13945. });
  13946. svr.wait_until_ready();
  13947. SSLClient cli(HOST, PORT);
  13948. cli.enable_server_certificate_verification(false);
  13949. cli.set_connection_timeout(30);
  13950. int callback_count = 0;
  13951. bool saw_leaf_cert = false;
  13952. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13953. if (ctx.cert) {
  13954. callback_count++;
  13955. // We should see at least one certificate (the leaf)
  13956. std::string cn = ctx.subject_cn();
  13957. if (!cn.empty()) { saw_leaf_cert = true; }
  13958. // Verify context fields are populated
  13959. EXPECT_NE(ctx.session, nullptr);
  13960. EXPECT_GE(ctx.depth, 0);
  13961. }
  13962. return true;
  13963. });
  13964. auto res = cli.Get("/test");
  13965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13966. EXPECT_GT(callback_count, 0);
  13967. EXPECT_TRUE(saw_leaf_cert);
  13968. }
  13969. // A verifier belongs to the client that set it, not to the thread that set it.
  13970. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13971. using namespace httplib::tls;
  13972. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13973. ASSERT_TRUE(svr.is_valid());
  13974. svr.Get("/test", [](const Request &, Response &res) {
  13975. res.set_content("ok", "text/plain");
  13976. });
  13977. auto port = svr.bind_to_any_port(HOST);
  13978. thread t([&]() { svr.listen_after_bind(); });
  13979. auto se = detail::scope_exit([&] {
  13980. svr.stop();
  13981. t.join();
  13982. });
  13983. svr.wait_until_ready();
  13984. auto rejecting_calls = 0;
  13985. SSLClient rejecting(HOST, port);
  13986. rejecting.enable_server_certificate_verification(false);
  13987. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13988. rejecting_calls++;
  13989. return false;
  13990. });
  13991. auto accepting_calls = 0;
  13992. SSLClient accepting(HOST, port);
  13993. accepting.enable_server_certificate_verification(false);
  13994. // Set on another thread than the requests below.
  13995. thread([&]() {
  13996. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13997. accepting_calls++;
  13998. return true;
  13999. });
  14000. }).join();
  14001. // Requested on another thread than the verifier was set on.
  14002. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14003. EXPECT_GT(rejecting_calls, 0);
  14004. auto res = accepting.Get("/test");
  14005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14006. EXPECT_GT(accepting_calls, 0);
  14007. }
  14008. // VerifyContext::session is the same handle the other tls:: functions take.
  14009. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14010. using namespace httplib::tls;
  14011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14012. ASSERT_TRUE(svr.is_valid());
  14013. svr.Get("/test", [](const Request &, Response &res) {
  14014. res.set_content("ok", "text/plain");
  14015. });
  14016. auto port = svr.bind_to_any_port(HOST);
  14017. thread t([&]() { svr.listen_after_bind(); });
  14018. auto se = detail::scope_exit([&] {
  14019. svr.stop();
  14020. t.join();
  14021. });
  14022. svr.wait_until_ready();
  14023. SSLClient cli(HOST, port);
  14024. cli.enable_server_certificate_verification(false);
  14025. session_t verifier_session = nullptr;
  14026. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14027. verifier_session = ctx.session;
  14028. return true;
  14029. });
  14030. session_t session_verifier_session = nullptr;
  14031. cli.set_session_verifier([&](session_t session) {
  14032. session_verifier_session = session;
  14033. return SSLVerifierResponse::NoDecisionMade;
  14034. });
  14035. auto res = cli.Get("/test");
  14036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14037. EXPECT_NE(nullptr, verifier_session);
  14038. EXPECT_EQ(session_verifier_session, verifier_session);
  14039. }
  14040. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14041. using httplib::tls::TlsError;
  14042. // Test that verify_error_to_string returns empty for success
  14043. std::string success_str = TlsError::verify_error_to_string(0);
  14044. EXPECT_TRUE(success_str.empty());
  14045. // Test that verify_error_to_string returns non-empty for error codes
  14046. // Using a common error code (certificate expired)
  14047. std::string error_str =
  14048. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14049. EXPECT_FALSE(error_str.empty());
  14050. }
  14051. TEST(SessionVerifierTest, CertificateAccepted) {
  14052. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14053. ASSERT_TRUE(svr.is_valid());
  14054. svr.Get("/test", [](const Request &, Response &res) {
  14055. res.set_content("ok", "text/plain");
  14056. });
  14057. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14058. auto se = detail::scope_exit([&] {
  14059. svr.stop();
  14060. t.join();
  14061. });
  14062. svr.wait_until_ready();
  14063. SSLClient cli(HOST, PORT);
  14064. cli.enable_server_certificate_verification(false);
  14065. cli.set_connection_timeout(30);
  14066. bool callback_called = false;
  14067. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14068. EXPECT_NE(session, nullptr);
  14069. callback_called = true;
  14070. return SSLVerifierResponse::CertificateAccepted;
  14071. });
  14072. auto res = cli.Get("/test");
  14073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14074. EXPECT_EQ(200, res->status);
  14075. EXPECT_TRUE(callback_called);
  14076. }
  14077. TEST(SessionVerifierTest, CertificateRejected) {
  14078. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14079. ASSERT_TRUE(svr.is_valid());
  14080. svr.Get("/test", [](const Request &, Response &res) {
  14081. res.set_content("ok", "text/plain");
  14082. });
  14083. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14084. auto se = detail::scope_exit([&] {
  14085. svr.stop();
  14086. t.join();
  14087. });
  14088. svr.wait_until_ready();
  14089. SSLClient cli(HOST, PORT);
  14090. cli.enable_server_certificate_verification(false);
  14091. cli.set_connection_timeout(30);
  14092. bool callback_called = false;
  14093. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14094. EXPECT_NE(session, nullptr);
  14095. callback_called = true;
  14096. return SSLVerifierResponse::CertificateRejected;
  14097. });
  14098. auto res = cli.Get("/test");
  14099. EXPECT_FALSE(res);
  14100. EXPECT_TRUE(callback_called);
  14101. }
  14102. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14103. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14104. ASSERT_TRUE(svr.is_valid());
  14105. svr.Get("/test", [](const Request &, Response &res) {
  14106. res.set_content("ok", "text/plain");
  14107. });
  14108. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14109. auto se = detail::scope_exit([&] {
  14110. svr.stop();
  14111. t.join();
  14112. });
  14113. svr.wait_until_ready();
  14114. // NoDecisionMade with verification disabled should succeed (no default check)
  14115. SSLClient cli(HOST, PORT);
  14116. cli.enable_server_certificate_verification(false);
  14117. cli.set_connection_timeout(30);
  14118. bool callback_called = false;
  14119. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14120. EXPECT_NE(session, nullptr);
  14121. callback_called = true;
  14122. return SSLVerifierResponse::NoDecisionMade;
  14123. });
  14124. auto res = cli.Get("/test");
  14125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14126. EXPECT_EQ(200, res->status);
  14127. EXPECT_TRUE(callback_called);
  14128. }
  14129. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14130. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14131. ASSERT_TRUE(svr.is_valid());
  14132. svr.Get("/test", [](const Request &, Response &res) {
  14133. res.set_content("ok", "text/plain");
  14134. });
  14135. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14136. auto se = detail::scope_exit([&] {
  14137. svr.stop();
  14138. t.join();
  14139. });
  14140. svr.wait_until_ready();
  14141. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14142. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14143. // so we only check that the request fails, not whether the callback was
  14144. // called.
  14145. SSLClient cli(HOST, PORT);
  14146. cli.enable_server_certificate_verification(true);
  14147. cli.set_connection_timeout(30);
  14148. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14149. EXPECT_NE(session, nullptr);
  14150. return SSLVerifierResponse::NoDecisionMade;
  14151. });
  14152. auto res = cli.Get("/test");
  14153. EXPECT_FALSE(res);
  14154. }
  14155. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14156. // Test SSL server using PemMemory constructor with client CA certificates
  14157. // Read PEM files
  14158. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14159. read_file(SERVER_CERT_FILE, server_cert_pem);
  14160. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14161. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14162. // Create SSLServer with PemMemory constructor including client CA
  14163. SSLServer::PemMemory server_pem = {
  14164. server_cert_pem.c_str(),
  14165. server_cert_pem.size(),
  14166. server_key_pem.c_str(),
  14167. server_key_pem.size(),
  14168. client_ca_pem.c_str(),
  14169. client_ca_pem.size(),
  14170. nullptr // no password for server key
  14171. };
  14172. SSLServer svr(server_pem);
  14173. ASSERT_TRUE(svr.is_valid());
  14174. // No SSL error should be recorded for valid setup
  14175. EXPECT_EQ(0, svr.ssl_last_error());
  14176. // Set up server endpoints
  14177. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14178. res.set_content("ok", "text/plain");
  14179. });
  14180. // Start server in a thread
  14181. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14182. svr.wait_until_ready();
  14183. // Connect with client certificate (using constructor with paths)
  14184. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14185. cli.enable_server_certificate_verification(false);
  14186. auto res = cli.Get("/test-pem-ca");
  14187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14188. EXPECT_EQ(200, res->status);
  14189. EXPECT_EQ("ok", res->body);
  14190. svr.stop();
  14191. server_thread.join();
  14192. }
  14193. #endif
  14194. #ifdef _WIN32
  14195. TEST(CleanupTest, WSACleanup) {
  14196. int ret = WSACleanup();
  14197. ASSERT_EQ(0, ret);
  14198. }
  14199. #endif
  14200. #ifndef CPPHTTPLIB_SSL_ENABLED
  14201. TEST(NoSSLSupport, SimpleInterface) {
  14202. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14203. }
  14204. #endif
  14205. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14206. TEST(InvalidScheme, SimpleInterface) {
  14207. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14208. }
  14209. #endif
  14210. TEST(NoScheme, SimpleInterface) {
  14211. Client cli("yahoo.com:80");
  14212. ASSERT_TRUE(cli.is_valid());
  14213. }
  14214. TEST(SendAPI, SimpleInterface_Online) {
  14215. Client cli("http://yahoo.com");
  14216. Request req;
  14217. req.method = "GET";
  14218. req.path = "/";
  14219. auto res = cli.send(req);
  14220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14221. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14222. }
  14223. TEST(SendAPI, WithParamsInRequest) {
  14224. Server svr;
  14225. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14226. EXPECT_TRUE(req.has_param("test"));
  14227. EXPECT_EQ("test_value", req.get_param_value("test"));
  14228. });
  14229. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14230. auto se = detail::scope_exit([&] {
  14231. svr.stop();
  14232. t.join();
  14233. ASSERT_FALSE(svr.is_running());
  14234. });
  14235. svr.wait_until_ready();
  14236. Client cli(HOST, PORT);
  14237. {
  14238. Request req;
  14239. req.method = "GET";
  14240. req.path = "/";
  14241. req.params.emplace("test", "test_value");
  14242. auto res = cli.send(req);
  14243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14244. }
  14245. {
  14246. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14248. }
  14249. }
  14250. TEST(ClientImplMethods, GetSocketTest) {
  14251. httplib::Server svr;
  14252. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14253. res.status = StatusCode::OK_200;
  14254. });
  14255. auto port = svr.bind_to_any_port("127.0.0.1");
  14256. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14257. auto se = detail::scope_exit([&] {
  14258. svr.stop();
  14259. thread.join();
  14260. ASSERT_FALSE(svr.is_running());
  14261. });
  14262. svr.wait_until_ready();
  14263. {
  14264. httplib::Client cli("127.0.0.1", port);
  14265. cli.set_keep_alive(true);
  14266. // Use the behavior of cpp-httplib of opening the connection
  14267. // only when the first request happens. If that changes,
  14268. // this test would be obsolete.
  14269. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14270. // This also implicitly tests the server. But other tests would fail much
  14271. // earlier than this one to be considered.
  14272. auto res = cli.Get("/");
  14273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14274. EXPECT_EQ(StatusCode::OK_200, res->status);
  14275. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14276. }
  14277. }
  14278. #ifdef CPPHTTPLIB_SSL_ENABLED
  14279. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14280. Client cli("http://yahoo.com");
  14281. auto res = cli.Get("/");
  14282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14283. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14284. cli.set_follow_location(true);
  14285. res = cli.Get("/");
  14286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14287. EXPECT_EQ(StatusCode::OK_200, res->status);
  14288. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14289. }
  14290. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14291. Client cli("https://yahoo.com");
  14292. auto res = cli.Get("/");
  14293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14294. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14295. cli.set_follow_location(true);
  14296. res = cli.Get("/");
  14297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14298. EXPECT_EQ(StatusCode::OK_200, res->status);
  14299. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14300. }
  14301. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14302. Client cli("https://yahoo.com");
  14303. auto res = cli.Get("/");
  14304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14305. ASSERT_FALSE(!res);
  14306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14307. ASSERT_FALSE(res == nullptr);
  14308. ASSERT_TRUE(res != nullptr);
  14309. EXPECT_EQ(Error::Success, res.error());
  14310. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14311. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14312. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14313. cli.set_follow_location(true);
  14314. res = cli.Get("/");
  14315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14316. EXPECT_EQ(Error::Success, res.error());
  14317. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14318. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14319. EXPECT_EQ(StatusCode::OK_200, res->status);
  14320. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14321. }
  14322. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14323. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14324. Client cli("https://cdnjs.cloudflare.com");
  14325. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14326. Headers{{"Accept-Encoding", "br"}});
  14327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14328. EXPECT_EQ(StatusCode::OK_200, res->status);
  14329. EXPECT_EQ(287630U, res->body.size());
  14330. EXPECT_EQ("application/javascript; charset=utf-8",
  14331. res->get_header_value("Content-Type"));
  14332. }
  14333. #endif
  14334. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14335. #undef REDIR_HOST // Silence compiler warning
  14336. #define REDIR_HOST "https://httpbingo.org"
  14337. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14338. Client cli(REDIR_HOST);
  14339. cli.set_follow_location(true);
  14340. auto res =
  14341. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14343. EXPECT_EQ(StatusCode::OK_200, res->status);
  14344. }
  14345. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14346. Client cli(REDIR_HOST);
  14347. cli.set_follow_location(true);
  14348. Params params;
  14349. params.emplace("url", "http://example.com");
  14350. params.emplace("status_code", "302");
  14351. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14353. EXPECT_EQ(StatusCode::OK_200, res->status);
  14354. }
  14355. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14356. Client cli(REDIR_HOST);
  14357. cli.set_follow_location(true);
  14358. Params params;
  14359. params.emplace("url", "http://example.com");
  14360. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14362. EXPECT_EQ(StatusCode::OK_200, res->status);
  14363. }
  14364. TEST(HttpToHttpsRedirectTest, CertFile) {
  14365. auto ssl_port = PORT + 1;
  14366. Server svr;
  14367. ASSERT_TRUE(svr.is_valid());
  14368. svr.Get("/index", [&](const Request &, Response &res) {
  14369. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14370. "/index");
  14371. svr.stop();
  14372. });
  14373. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14374. ASSERT_TRUE(ssl_svr.is_valid());
  14375. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14376. res.set_content("test", "text/plain");
  14377. ssl_svr.stop();
  14378. });
  14379. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14380. thread t2 =
  14381. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14382. auto se = detail::scope_exit([&] {
  14383. t2.join();
  14384. t.join();
  14385. ASSERT_FALSE(svr.is_running());
  14386. });
  14387. svr.wait_until_ready();
  14388. ssl_svr.wait_until_ready();
  14389. Client cli("127.0.0.1", PORT);
  14390. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14391. cli.enable_server_certificate_verification(true);
  14392. cli.set_follow_location(true);
  14393. cli.set_connection_timeout(30);
  14394. auto res = cli.Get("/index");
  14395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14396. ASSERT_EQ(StatusCode::OK_200, res->status);
  14397. }
  14398. TEST(SSLClientRedirectTest, CertFile) {
  14399. auto ssl_port = PORT + 1;
  14400. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14401. ASSERT_TRUE(ssl_svr1.is_valid());
  14402. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14403. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14404. "/index");
  14405. ssl_svr1.stop();
  14406. });
  14407. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14408. ASSERT_TRUE(ssl_svr2.is_valid());
  14409. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14410. res.set_content("test", "text/plain");
  14411. ssl_svr2.stop();
  14412. });
  14413. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14414. thread t2 =
  14415. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14416. auto se = detail::scope_exit([&] {
  14417. t2.join();
  14418. t.join();
  14419. ASSERT_FALSE(ssl_svr1.is_running());
  14420. });
  14421. ssl_svr1.wait_until_ready();
  14422. ssl_svr2.wait_until_ready();
  14423. SSLClient cli("127.0.0.1", PORT);
  14424. std::string cert;
  14425. read_file(SERVER_CERT2_FILE, cert);
  14426. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14427. cli.enable_server_certificate_verification(true);
  14428. cli.set_follow_location(true);
  14429. cli.set_connection_timeout(30);
  14430. auto res = cli.Get("/index");
  14431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14432. ASSERT_EQ(StatusCode::OK_200, res->status);
  14433. }
  14434. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14435. // another port, so the client follows it with a new client.
  14436. static Result GetThroughTlsRedirectToDifferentPort(
  14437. const std::function<void(SSLClient &)> &setup,
  14438. const char *target_cert = SERVER_CERT2_FILE) {
  14439. auto ssl_port = PORT + 1;
  14440. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14441. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14442. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14443. "/index");
  14444. });
  14445. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14446. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14447. res.set_content("test", "text/plain");
  14448. });
  14449. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14450. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14451. auto se = detail::scope_exit([&] {
  14452. ssl_svr2.stop();
  14453. ssl_svr1.stop();
  14454. t2.join();
  14455. t.join();
  14456. });
  14457. ssl_svr1.wait_until_ready();
  14458. ssl_svr2.wait_until_ready();
  14459. SSLClient cli("127.0.0.1", PORT);
  14460. cli.set_follow_location(true);
  14461. cli.set_connection_timeout(30);
  14462. setup(cli);
  14463. return cli.Get("/index");
  14464. }
  14465. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14466. auto calls = 0;
  14467. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14468. cli.enable_server_certificate_verification(false);
  14469. // Accept the first server only.
  14470. cli.set_session_verifier([&](tls::session_t) {
  14471. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14472. : SSLVerifierResponse::CertificateRejected;
  14473. });
  14474. });
  14475. EXPECT_FALSE(res);
  14476. EXPECT_EQ(2, calls);
  14477. }
  14478. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14479. std::string pinned;
  14480. auto res = GetThroughTlsRedirectToDifferentPort(
  14481. [&](SSLClient &cli) {
  14482. cli.enable_server_certificate_verification(false);
  14483. // Pin the first certificate seen.
  14484. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14485. if (pinned.empty()) { pinned = ctx.serial(); }
  14486. return ctx.serial() == pinned;
  14487. });
  14488. },
  14489. // A certificate other than the first server's.
  14490. SERVER_CERT_FILE);
  14491. EXPECT_FALSE(res);
  14492. EXPECT_FALSE(pinned.empty());
  14493. }
  14494. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14495. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14496. std::string cert;
  14497. read_file(SERVER_CERT2_FILE, cert);
  14498. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14499. });
  14500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14501. EXPECT_EQ(StatusCode::OK_200, res->status);
  14502. }
  14503. #endif
  14504. #ifdef CPPHTTPLIB_SSL_ENABLED
  14505. // Test that set_ca_cert_store() skips system certs (consistent with
  14506. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14507. // should be trusted - system certs should NOT be loaded.
  14508. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14509. // Load a specific cert that is NOT a system CA cert
  14510. std::string cert;
  14511. read_file(SERVER_CERT2_FILE, cert);
  14512. SSLClient cli("google.com");
  14513. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14514. cli.enable_server_certificate_verification(true);
  14515. // This should FAIL because:
  14516. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14517. // 2. System certs should NOT be loaded when custom store is set
  14518. // If system certs WERE loaded, this would succeed
  14519. auto res = cli.Get("/");
  14520. ASSERT_FALSE(res);
  14521. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14522. }
  14523. // Same as above, but through the native store handle path. Regression test:
  14524. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14525. // merged system certs into the user-provided store.
  14526. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14527. std::string cert;
  14528. read_file(SERVER_CERT2_FILE, cert);
  14529. SSLClient cli("google.com");
  14530. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14531. cli.enable_server_certificate_verification(true);
  14532. auto res = cli.Get("/");
  14533. ASSERT_FALSE(res);
  14534. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14535. }
  14536. // A custom store set via the native handle must still verify a server whose
  14537. // cert it does contain.
  14538. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14539. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14540. ASSERT_TRUE(svr.is_valid());
  14541. svr.Get("/test", [&](const Request &, Response &res) {
  14542. res.set_content("test", "text/plain");
  14543. });
  14544. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14545. auto se = detail::scope_exit([&] {
  14546. svr.stop();
  14547. t.join();
  14548. ASSERT_FALSE(svr.is_running());
  14549. });
  14550. svr.wait_until_ready();
  14551. SSLClient cli("127.0.0.1", PORT);
  14552. std::string cert;
  14553. read_file(SERVER_CERT2_FILE, cert);
  14554. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14555. cli.enable_server_certificate_verification(true);
  14556. cli.set_connection_timeout(30);
  14557. auto res = cli.Get("/test");
  14558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14559. ASSERT_EQ(StatusCode::OK_200, res->status);
  14560. }
  14561. // CA certs loaded through the universal Client must be transferred to the
  14562. // client created internally for following an HTTPS redirect. Regression test:
  14563. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14564. // the CA data for redirect transfer.
  14565. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14566. auto ssl_port = PORT + 1;
  14567. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14568. ASSERT_TRUE(ssl_svr1.is_valid());
  14569. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14570. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14571. "/index");
  14572. });
  14573. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14574. ASSERT_TRUE(ssl_svr2.is_valid());
  14575. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14576. res.set_content("test", "text/plain");
  14577. });
  14578. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14579. thread t2 =
  14580. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14581. auto se = detail::scope_exit([&] {
  14582. ssl_svr2.stop();
  14583. ssl_svr1.stop();
  14584. t2.join();
  14585. t.join();
  14586. ASSERT_FALSE(ssl_svr1.is_running());
  14587. });
  14588. ssl_svr1.wait_until_ready();
  14589. ssl_svr2.wait_until_ready();
  14590. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14591. std::string cert;
  14592. read_file(SERVER_CERT2_FILE, cert);
  14593. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14594. cli.enable_server_certificate_verification(true);
  14595. cli.set_follow_location(true);
  14596. cli.set_connection_timeout(30);
  14597. auto res = cli.Get("/index");
  14598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14599. ASSERT_EQ(StatusCode::OK_200, res->status);
  14600. }
  14601. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14602. // so a host signed by a system CA verifies even though a custom CA is set
  14603. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14604. std::string cert;
  14605. read_file(SERVER_CERT2_FILE, cert);
  14606. SSLClient cli("google.com");
  14607. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14608. cli.enable_system_ca(true);
  14609. cli.enable_server_certificate_verification(true);
  14610. auto res = cli.Get("/");
  14611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14612. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14613. }
  14614. // The custom CA remains effective when combined with the system CA
  14615. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14616. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14617. ASSERT_TRUE(svr.is_valid());
  14618. svr.Get("/test", [&](const Request &, Response &res) {
  14619. res.set_content("test", "text/plain");
  14620. });
  14621. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14622. auto se = detail::scope_exit([&] {
  14623. svr.stop();
  14624. t.join();
  14625. ASSERT_FALSE(svr.is_running());
  14626. });
  14627. svr.wait_until_ready();
  14628. SSLClient cli("127.0.0.1", PORT);
  14629. std::string cert;
  14630. read_file(SERVER_CERT2_FILE, cert);
  14631. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14632. cli.enable_system_ca(true);
  14633. cli.enable_server_certificate_verification(true);
  14634. cli.set_connection_timeout(30);
  14635. auto res = cli.Get("/test");
  14636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14637. ASSERT_EQ(StatusCode::OK_200, res->status);
  14638. }
  14639. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14640. // skip chain verification entirely (only the certificate identity was
  14641. // checked), so a server presenting an untrusted certificate with a matching
  14642. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14643. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14644. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14645. ASSERT_TRUE(svr.is_valid());
  14646. svr.Get("/test", [&](const Request &, Response &res) {
  14647. res.set_content("test", "text/plain");
  14648. });
  14649. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14650. auto se = detail::scope_exit([&] {
  14651. svr.stop();
  14652. t.join();
  14653. ASSERT_FALSE(svr.is_running());
  14654. });
  14655. svr.wait_until_ready();
  14656. SSLClient cli("127.0.0.1", PORT);
  14657. std::string cert;
  14658. // A trusted CA that did not sign the server certificate. The server cert
  14659. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14660. // this connection.
  14661. read_file(CLIENT_CA_CERT_FILE, cert);
  14662. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14663. cli.enable_server_certificate_verification(true);
  14664. cli.set_connection_timeout(30);
  14665. auto res = cli.Get("/test");
  14666. ASSERT_FALSE(res);
  14667. }
  14668. // enable_system_ca(false) prevents system CA loading entirely
  14669. TEST(SSLClientTest, DisableSystemCa_Online) {
  14670. SSLClient cli("google.com");
  14671. cli.enable_system_ca(false);
  14672. cli.enable_server_certificate_verification(true);
  14673. auto res = cli.Get("/");
  14674. ASSERT_FALSE(res);
  14675. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14676. // itself when the CA chain is empty
  14677. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14678. res.error() == Error::SSLConnection);
  14679. }
  14680. // The universal Client forwards enable_system_ca()
  14681. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14682. std::string cert;
  14683. read_file(SERVER_CERT2_FILE, cert);
  14684. Client cli("https://google.com");
  14685. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14686. cli.enable_system_ca(true);
  14687. cli.enable_server_certificate_verification(true);
  14688. auto res = cli.Get("/");
  14689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14690. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14691. }
  14692. // The system CA policy must carry over to the client created internally for
  14693. // following a cross-host HTTPS redirect
  14694. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14695. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14696. ASSERT_TRUE(svr.is_valid());
  14697. svr.Get("/index", [&](const Request &, Response &res) {
  14698. res.set_redirect("https://www.google.com/");
  14699. });
  14700. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14701. auto se = detail::scope_exit([&] {
  14702. svr.stop();
  14703. t.join();
  14704. ASSERT_FALSE(svr.is_running());
  14705. });
  14706. svr.wait_until_ready();
  14707. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14708. std::string cert;
  14709. read_file(SERVER_CERT2_FILE, cert);
  14710. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14711. cli.enable_system_ca(true);
  14712. cli.enable_server_certificate_verification(true);
  14713. cli.set_follow_location(true);
  14714. cli.set_connection_timeout(30);
  14715. // Receiving any response proves the redirect client completed the TLS
  14716. // handshake with a system-CA-signed host
  14717. auto res = cli.Get("/index");
  14718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14719. }
  14720. TEST(MultipartFormDataTest, LargeData) {
  14721. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14722. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14723. const ContentReader &content_reader) {
  14724. if (req.is_multipart_form_data()) {
  14725. std::vector<FormData> items;
  14726. content_reader(
  14727. [&](const FormData &file) {
  14728. items.push_back(file);
  14729. return true;
  14730. },
  14731. [&](const char *data, size_t data_length) {
  14732. items.back().content.append(data, data_length);
  14733. return true;
  14734. });
  14735. EXPECT_TRUE(std::string(items[0].name) == "document");
  14736. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14737. EXPECT_TRUE(items[0].filename == "2MB_data");
  14738. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14739. EXPECT_TRUE(items[1].name == "hello");
  14740. EXPECT_TRUE(items[1].content == "world");
  14741. EXPECT_TRUE(items[1].filename == "");
  14742. EXPECT_TRUE(items[1].content_type == "");
  14743. } else {
  14744. std::string body;
  14745. content_reader([&](const char *data, size_t data_length) {
  14746. body.append(data, data_length);
  14747. return true;
  14748. });
  14749. }
  14750. });
  14751. auto port = svr.bind_to_any_port(HOST);
  14752. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14753. auto se = detail::scope_exit([&] {
  14754. svr.stop();
  14755. t.join();
  14756. ASSERT_FALSE(svr.is_running());
  14757. });
  14758. svr.wait_until_ready();
  14759. {
  14760. std::string data(1024 * 1024 * 2, '.');
  14761. std::stringstream buffer;
  14762. buffer << data;
  14763. SSLClient cli(HOST, port);
  14764. cli.enable_server_certificate_verification(false);
  14765. UploadFormDataItems items{
  14766. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14767. {"hello", "world", "", ""},
  14768. };
  14769. auto res = cli.Post("/post", items);
  14770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14771. ASSERT_EQ(StatusCode::OK_200, res->status);
  14772. }
  14773. }
  14774. TEST(MultipartFormDataTest, DataProviderItems) {
  14775. std::random_device seed_gen;
  14776. std::mt19937 random(seed_gen());
  14777. std::string rand1;
  14778. rand1.resize(1000);
  14779. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14780. std::string rand2;
  14781. rand2.resize(3000);
  14782. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14784. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14785. const ContentReader &content_reader) {
  14786. ASSERT_FALSE(req.is_multipart_form_data());
  14787. std::string body;
  14788. content_reader([&](const char *data, size_t data_length) {
  14789. body.append(data, data_length);
  14790. return true;
  14791. });
  14792. EXPECT_EQ(body, "");
  14793. });
  14794. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14795. const ContentReader &content_reader) {
  14796. ASSERT_TRUE(req.is_multipart_form_data());
  14797. std::vector<FormData> items;
  14798. content_reader(
  14799. [&](const FormData &file) {
  14800. items.push_back(file);
  14801. return true;
  14802. },
  14803. [&](const char *data, size_t data_length) {
  14804. items.back().content.append(data, data_length);
  14805. return true;
  14806. });
  14807. ASSERT_TRUE(items.size() == 2);
  14808. EXPECT_EQ(std::string(items[0].name), "name1");
  14809. EXPECT_EQ(items[0].content, "Testing123");
  14810. EXPECT_EQ(items[0].filename, "filename1");
  14811. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14812. EXPECT_EQ(items[1].name, "name2");
  14813. EXPECT_EQ(items[1].content, "Testing456");
  14814. EXPECT_EQ(items[1].filename, "");
  14815. EXPECT_EQ(items[1].content_type, "");
  14816. });
  14817. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14818. const ContentReader &content_reader) {
  14819. ASSERT_TRUE(req.is_multipart_form_data());
  14820. std::vector<FormData> items;
  14821. content_reader(
  14822. [&](const FormData &file) {
  14823. items.push_back(file);
  14824. return true;
  14825. },
  14826. [&](const char *data, size_t data_length) {
  14827. items.back().content.append(data, data_length);
  14828. return true;
  14829. });
  14830. ASSERT_TRUE(items.size() == 2);
  14831. EXPECT_EQ(items[0].name, "name3");
  14832. EXPECT_EQ(items[0].content, rand1);
  14833. EXPECT_EQ(items[0].filename, "filename3");
  14834. EXPECT_EQ(items[0].content_type, "");
  14835. EXPECT_EQ(items[1].name, "name4");
  14836. EXPECT_EQ(items[1].content, rand2);
  14837. EXPECT_EQ(items[1].filename, "filename4");
  14838. EXPECT_EQ(items[1].content_type, "");
  14839. });
  14840. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14841. const ContentReader &content_reader) {
  14842. ASSERT_TRUE(req.is_multipart_form_data());
  14843. std::vector<FormData> items;
  14844. content_reader(
  14845. [&](const FormData &file) {
  14846. items.push_back(file);
  14847. return true;
  14848. },
  14849. [&](const char *data, size_t data_length) {
  14850. items.back().content.append(data, data_length);
  14851. return true;
  14852. });
  14853. ASSERT_TRUE(items.size() == 4);
  14854. EXPECT_EQ(std::string(items[0].name), "name1");
  14855. EXPECT_EQ(items[0].content, "Testing123");
  14856. EXPECT_EQ(items[0].filename, "filename1");
  14857. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14858. EXPECT_EQ(items[1].name, "name2");
  14859. EXPECT_EQ(items[1].content, "Testing456");
  14860. EXPECT_EQ(items[1].filename, "");
  14861. EXPECT_EQ(items[1].content_type, "");
  14862. EXPECT_EQ(items[2].name, "name3");
  14863. EXPECT_EQ(items[2].content, rand1);
  14864. EXPECT_EQ(items[2].filename, "filename3");
  14865. EXPECT_EQ(items[2].content_type, "");
  14866. EXPECT_EQ(items[3].name, "name4");
  14867. EXPECT_EQ(items[3].content, rand2);
  14868. EXPECT_EQ(items[3].filename, "filename4");
  14869. EXPECT_EQ(items[3].content_type, "");
  14870. });
  14871. auto port = svr.bind_to_any_port("localhost");
  14872. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14873. auto se = detail::scope_exit([&] {
  14874. svr.stop();
  14875. t.join();
  14876. ASSERT_FALSE(svr.is_running());
  14877. });
  14878. svr.wait_until_ready();
  14879. {
  14880. SSLClient cli("localhost", port);
  14881. cli.enable_server_certificate_verification(false);
  14882. UploadFormDataItems items{
  14883. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14884. {"name2", "Testing456", "", ""}, // not a file
  14885. };
  14886. {
  14887. auto res = cli.Post("/post-none", {}, {}, {});
  14888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14889. ASSERT_EQ(StatusCode::OK_200, res->status);
  14890. }
  14891. FormDataProviderItems providers;
  14892. {
  14893. auto res =
  14894. cli.Post("/post-items", {}, items, providers); // empty providers
  14895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14896. ASSERT_EQ(StatusCode::OK_200, res->status);
  14897. }
  14898. providers.push_back({"name3",
  14899. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14900. // test the offset is given correctly at each step
  14901. if (!offset)
  14902. sink.os.write(rand1.data(), 30);
  14903. else if (offset == 30)
  14904. sink.os.write(rand1.data() + 30, 300);
  14905. else if (offset == 330)
  14906. sink.os.write(rand1.data() + 330, 670);
  14907. else if (offset == rand1.size())
  14908. sink.done();
  14909. return true;
  14910. },
  14911. "filename3",
  14912. {}});
  14913. providers.push_back({"name4",
  14914. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14915. // test the offset is given correctly at each step
  14916. if (!offset)
  14917. sink.os.write(rand2.data(), 2000);
  14918. else if (offset == 2000)
  14919. sink.os.write(rand2.data() + 2000, 1);
  14920. else if (offset == 2001)
  14921. sink.os.write(rand2.data() + 2001, 999);
  14922. else if (offset == rand2.size())
  14923. sink.done();
  14924. return true;
  14925. },
  14926. "filename4",
  14927. {}});
  14928. {
  14929. auto res = cli.Post("/post-providers", {}, {}, providers);
  14930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14931. ASSERT_EQ(StatusCode::OK_200, res->status);
  14932. }
  14933. {
  14934. auto res = cli.Post("/post-both", {}, items, providers);
  14935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14936. ASSERT_EQ(StatusCode::OK_200, res->status);
  14937. }
  14938. }
  14939. }
  14940. TEST(MultipartFormDataTest, BadHeader) {
  14941. Server svr;
  14942. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14943. res.set_content("ok", "text/plain");
  14944. });
  14945. thread t = thread([&] { svr.listen(HOST, PORT); });
  14946. auto se = detail::scope_exit([&] {
  14947. svr.stop();
  14948. t.join();
  14949. ASSERT_FALSE(svr.is_running());
  14950. });
  14951. svr.wait_until_ready();
  14952. const std::string body =
  14953. "This is the preamble. It is to be ignored, though it\r\n"
  14954. "is a handy place for composition agents to include an\r\n"
  14955. "explanatory note to non-MIME conformant readers.\r\n"
  14956. "\r\n"
  14957. "\r\n"
  14958. "--simple boundary\r\n"
  14959. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14960. ": BAD...\r\n"
  14961. "\r\n"
  14962. "value1\r\n"
  14963. "--simple boundary\r\n"
  14964. "Content-Disposition: form-data; name=\"field2\"; "
  14965. "filename=\"example.txt\"\r\n"
  14966. "\r\n"
  14967. "value2\r\n"
  14968. "--simple boundary--\r\n"
  14969. "This is the epilogue. It is also to be ignored.\r\n";
  14970. std::string content_type =
  14971. R"(multipart/form-data; boundary="simple boundary")";
  14972. Client cli(HOST, PORT);
  14973. auto res = cli.Post("/post", body, content_type.c_str());
  14974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14975. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14976. }
  14977. TEST(MultipartFormDataTest, WithPreamble) {
  14978. Server svr;
  14979. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14980. res.set_content("ok", "text/plain");
  14981. });
  14982. thread t = thread([&] { svr.listen(HOST, PORT); });
  14983. auto se = detail::scope_exit([&] {
  14984. svr.stop();
  14985. t.join();
  14986. ASSERT_FALSE(svr.is_running());
  14987. });
  14988. svr.wait_until_ready();
  14989. const std::string body =
  14990. "This is the preamble. It is to be ignored, though it\r\n"
  14991. "is a handy place for composition agents to include an\r\n"
  14992. "explanatory note to non-MIME conformant readers.\r\n"
  14993. "\r\n"
  14994. "\r\n"
  14995. "--simple boundary\r\n"
  14996. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14997. "\r\n"
  14998. "value1\r\n"
  14999. "--simple boundary\r\n"
  15000. "Content-Disposition: form-data; name=\"field2\"; "
  15001. "filename=\"example.txt\"\r\n"
  15002. "\r\n"
  15003. "value2\r\n"
  15004. "--simple boundary--\r\n"
  15005. "This is the epilogue. It is also to be ignored.\r\n";
  15006. std::string content_type =
  15007. R"(multipart/form-data; boundary="simple boundary")";
  15008. Client cli(HOST, PORT);
  15009. auto res = cli.Post("/post", body, content_type.c_str());
  15010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15011. EXPECT_EQ(StatusCode::OK_200, res->status);
  15012. }
  15013. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15015. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15016. const ContentReader &content_reader) {
  15017. if (req.is_multipart_form_data()) {
  15018. std::vector<FormData> items;
  15019. content_reader(
  15020. [&](const FormData &file) {
  15021. items.push_back(file);
  15022. return true;
  15023. },
  15024. [&](const char *data, size_t data_length) {
  15025. items.back().content.append(data, data_length);
  15026. return true;
  15027. });
  15028. EXPECT_TRUE(std::string(items[0].name) == "document");
  15029. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15030. EXPECT_TRUE(items[0].filename == "2MB_data");
  15031. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15032. EXPECT_TRUE(items[1].name == "hello");
  15033. EXPECT_TRUE(items[1].content == "world");
  15034. EXPECT_TRUE(items[1].filename == "");
  15035. EXPECT_TRUE(items[1].content_type == "");
  15036. } else {
  15037. std::string body;
  15038. content_reader([&](const char *data, size_t data_length) {
  15039. body.append(data, data_length);
  15040. return true;
  15041. });
  15042. }
  15043. });
  15044. auto port = svr.bind_to_any_port("localhost");
  15045. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15046. auto se = detail::scope_exit([&] {
  15047. svr.stop();
  15048. t.join();
  15049. ASSERT_FALSE(svr.is_running());
  15050. });
  15051. svr.wait_until_ready();
  15052. {
  15053. std::string data(1024 * 1024 * 2, '.');
  15054. std::stringstream buffer;
  15055. buffer << data;
  15056. SSLClient cli("localhost", port);
  15057. cli.enable_server_certificate_verification(false);
  15058. UploadFormDataItems items{
  15059. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15060. {"hello", "world", "", ""},
  15061. };
  15062. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15064. ASSERT_EQ(StatusCode::OK_200, res->status);
  15065. }
  15066. }
  15067. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15068. std::string data(1024 * 1024 * 2, '&');
  15069. std::stringstream buffer;
  15070. buffer << data;
  15071. Client cli("https://localhost:8080");
  15072. UploadFormDataItems items{
  15073. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15074. {"hello", "world", "", ""},
  15075. };
  15076. for (const char &c : " \t\r\n") {
  15077. auto res =
  15078. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15079. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15080. ASSERT_FALSE(res);
  15081. }
  15082. }
  15083. TEST(MultipartFormDataTest, PutFormData) {
  15084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15085. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15086. const ContentReader &content_reader) {
  15087. if (req.is_multipart_form_data()) {
  15088. std::vector<FormData> items;
  15089. content_reader(
  15090. [&](const FormData &file) {
  15091. items.push_back(file);
  15092. return true;
  15093. },
  15094. [&](const char *data, size_t data_length) {
  15095. items.back().content.append(data, data_length);
  15096. return true;
  15097. });
  15098. EXPECT_TRUE(std::string(items[0].name) == "document");
  15099. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15100. EXPECT_TRUE(items[0].filename == "2MB_data");
  15101. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15102. EXPECT_TRUE(items[1].name == "hello");
  15103. EXPECT_TRUE(items[1].content == "world");
  15104. EXPECT_TRUE(items[1].filename == "");
  15105. EXPECT_TRUE(items[1].content_type == "");
  15106. } else {
  15107. std::string body;
  15108. content_reader([&](const char *data, size_t data_length) {
  15109. body.append(data, data_length);
  15110. return true;
  15111. });
  15112. }
  15113. });
  15114. auto port = svr.bind_to_any_port("localhost");
  15115. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15116. auto se = detail::scope_exit([&] {
  15117. svr.stop();
  15118. t.join();
  15119. ASSERT_FALSE(svr.is_running());
  15120. });
  15121. svr.wait_until_ready();
  15122. {
  15123. std::string data(1024 * 1024 * 2, '&');
  15124. std::stringstream buffer;
  15125. buffer << data;
  15126. SSLClient cli("localhost", port);
  15127. cli.enable_server_certificate_verification(false);
  15128. UploadFormDataItems items{
  15129. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15130. {"hello", "world", "", ""},
  15131. };
  15132. auto res = cli.Put("/put", items);
  15133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15134. ASSERT_EQ(StatusCode::OK_200, res->status);
  15135. }
  15136. }
  15137. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15139. svr.Put("/put_customboundary",
  15140. [&](const Request &req, const Response & /*res*/,
  15141. const ContentReader &content_reader) {
  15142. if (req.is_multipart_form_data()) {
  15143. std::vector<FormData> items;
  15144. content_reader(
  15145. [&](const FormData &file) {
  15146. items.push_back(file);
  15147. return true;
  15148. },
  15149. [&](const char *data, size_t data_length) {
  15150. items.back().content.append(data, data_length);
  15151. return true;
  15152. });
  15153. EXPECT_TRUE(std::string(items[0].name) == "document");
  15154. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15155. EXPECT_TRUE(items[0].filename == "2MB_data");
  15156. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15157. EXPECT_TRUE(items[1].name == "hello");
  15158. EXPECT_TRUE(items[1].content == "world");
  15159. EXPECT_TRUE(items[1].filename == "");
  15160. EXPECT_TRUE(items[1].content_type == "");
  15161. } else {
  15162. std::string body;
  15163. content_reader([&](const char *data, size_t data_length) {
  15164. body.append(data, data_length);
  15165. return true;
  15166. });
  15167. }
  15168. });
  15169. auto port = svr.bind_to_any_port("localhost");
  15170. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15171. auto se = detail::scope_exit([&] {
  15172. svr.stop();
  15173. t.join();
  15174. ASSERT_FALSE(svr.is_running());
  15175. });
  15176. svr.wait_until_ready();
  15177. {
  15178. std::string data(1024 * 1024 * 2, '&');
  15179. std::stringstream buffer;
  15180. buffer << data;
  15181. SSLClient cli("localhost", port);
  15182. cli.enable_server_certificate_verification(false);
  15183. UploadFormDataItems items{
  15184. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15185. {"hello", "world", "", ""},
  15186. };
  15187. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15189. ASSERT_EQ(StatusCode::OK_200, res->status);
  15190. }
  15191. }
  15192. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15193. std::string data(1024 * 1024 * 2, '&');
  15194. std::stringstream buffer;
  15195. buffer << data;
  15196. Client cli("https://localhost:8080");
  15197. cli.enable_server_certificate_verification(false);
  15198. UploadFormDataItems items{
  15199. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15200. {"hello", "world", "", ""},
  15201. };
  15202. for (const char &c : " \t\r\n") {
  15203. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15204. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15205. ASSERT_FALSE(res);
  15206. }
  15207. }
  15208. TEST(MultipartFormDataTest, AlternateFilename) {
  15209. auto handled = false;
  15210. Server svr;
  15211. svr.Post("/test", [&](const Request &req, Response &res) {
  15212. ASSERT_EQ(2u, req.form.files.size());
  15213. ASSERT_EQ(1u, req.form.fields.size());
  15214. // Test files
  15215. const auto &file1 = req.form.get_file("file1");
  15216. ASSERT_EQ("file1", file1.name);
  15217. ASSERT_EQ("A.txt", file1.filename);
  15218. ASSERT_EQ("text/plain", file1.content_type);
  15219. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15220. const auto &file2 = req.form.get_file("file2");
  15221. ASSERT_EQ("file2", file2.name);
  15222. ASSERT_EQ("a.html", file2.filename);
  15223. ASSERT_EQ("text/html", file2.content_type);
  15224. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15225. file2.content);
  15226. // Test text field
  15227. const auto &text = req.form.get_field("text");
  15228. ASSERT_EQ("text default", text);
  15229. res.set_content("ok", "text/plain");
  15230. handled = true;
  15231. });
  15232. thread t = thread([&] { svr.listen(HOST, PORT); });
  15233. auto se = detail::scope_exit([&] {
  15234. svr.stop();
  15235. t.join();
  15236. ASSERT_FALSE(svr.is_running());
  15237. ASSERT_TRUE(handled);
  15238. });
  15239. svr.wait_until_ready();
  15240. auto req = "POST /test HTTP/1.1\r\n"
  15241. "Host: localhost\r\n"
  15242. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15243. "Content-Length: 399\r\n"
  15244. "\r\n"
  15245. "----------\r\n"
  15246. "Content-Disposition: form-data; name=\"text\"\r\n"
  15247. "\r\n"
  15248. "text default\r\n"
  15249. "----------\r\n"
  15250. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15251. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15252. "Content-Type: text/plain\r\n"
  15253. "\r\n"
  15254. "Content of a.txt.\r\n"
  15255. "\r\n"
  15256. "----------\r\n"
  15257. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15258. "\"a.html\"\r\n"
  15259. "Content-Type: text/html\r\n"
  15260. "\r\n"
  15261. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15262. "\r\n"
  15263. "------------\r\n";
  15264. ASSERT_TRUE(send_request(1, req));
  15265. }
  15266. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15267. auto handled = false;
  15268. Server svr;
  15269. svr.Post("/test", [&](const Request &req, Response &res) {
  15270. // Case-insensitive "utf-8''" prefix with a long value
  15271. const auto &file = req.form.get_file("file1");
  15272. ASSERT_EQ("file1", file.name);
  15273. // 8000 chars exercises both the Content-Disposition parser and the
  15274. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15275. // Prior to the fix, std::regex_match on this header would cause O(N)
  15276. // stack recursion in libstdc++, leading to SIGSEGV.
  15277. std::string expected_filename(8000, 'A');
  15278. ASSERT_EQ(expected_filename, file.filename);
  15279. res.set_content("ok", "text/plain");
  15280. handled = true;
  15281. });
  15282. thread t = thread([&] { svr.listen(HOST, PORT); });
  15283. auto se = detail::scope_exit([&] {
  15284. svr.stop();
  15285. t.join();
  15286. ASSERT_FALSE(svr.is_running());
  15287. ASSERT_TRUE(handled);
  15288. });
  15289. svr.wait_until_ready();
  15290. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15291. // Regression test for GHSA-qq6v-r583-3h69
  15292. std::string long_filename(8000, 'A');
  15293. std::string body = "----------\r\n"
  15294. "Content-Disposition: form-data; name=\"file1\"; "
  15295. "filename*=\"Utf-8''" +
  15296. long_filename +
  15297. "\"\r\n"
  15298. "\r\n"
  15299. "hello\r\n"
  15300. "------------\r\n";
  15301. auto req = "POST /test HTTP/1.1\r\n"
  15302. "Host: localhost\r\n"
  15303. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15304. "Content-Length: " +
  15305. std::to_string(body.size()) + "\r\n\r\n" + body;
  15306. ASSERT_TRUE(send_request(1, req));
  15307. }
  15308. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15309. auto handled = false;
  15310. Server svr;
  15311. svr.Post("/test", [&](const Request &req, Response &) {
  15312. ASSERT_EQ(2u, req.form.fields.size());
  15313. const auto &text1 = req.form.get_field("text1");
  15314. ASSERT_EQ("text1", text1);
  15315. const auto &text2 = req.form.get_field("text2");
  15316. ASSERT_EQ("text2", text2);
  15317. handled = true;
  15318. });
  15319. thread t = thread([&] { svr.listen(HOST, PORT); });
  15320. auto se = detail::scope_exit([&] {
  15321. svr.stop();
  15322. t.join();
  15323. ASSERT_FALSE(svr.is_running());
  15324. ASSERT_TRUE(handled);
  15325. });
  15326. svr.wait_until_ready();
  15327. auto req = "POST /test HTTP/1.1\r\n"
  15328. "Host: localhost\r\n"
  15329. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15330. "Content-Length: 146\r\n"
  15331. "\r\n----------\r\n"
  15332. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15333. "\r\n"
  15334. "text1"
  15335. "\r\n----------\r\n"
  15336. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15337. "\r\n"
  15338. "text2"
  15339. "\r\n------------";
  15340. std::string response;
  15341. ASSERT_TRUE(send_request(1, req, &response));
  15342. ASSERT_EQ("200", response.substr(9, 3));
  15343. }
  15344. TEST(MultipartFormDataTest, ContentLength) {
  15345. auto handled = false;
  15346. Server svr;
  15347. svr.Post("/test", [&](const Request &req, Response &) {
  15348. ASSERT_EQ(2u, req.form.fields.size());
  15349. const auto &text1 = req.form.get_field("text1");
  15350. ASSERT_EQ("text1", text1);
  15351. const auto &text2 = req.form.get_field("text2");
  15352. ASSERT_EQ("text2", text2);
  15353. handled = true;
  15354. });
  15355. thread t = thread([&] { svr.listen(HOST, PORT); });
  15356. auto se = detail::scope_exit([&] {
  15357. svr.stop();
  15358. t.join();
  15359. ASSERT_FALSE(svr.is_running());
  15360. ASSERT_TRUE(handled);
  15361. });
  15362. svr.wait_until_ready();
  15363. auto req = "POST /test HTTP/1.1\r\n"
  15364. "Host: localhost\r\n"
  15365. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15366. "Content-Length: 167\r\n"
  15367. "\r\n----------\r\n"
  15368. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15369. "Content-Length: 5\r\n"
  15370. "\r\n"
  15371. "text1"
  15372. "\r\n----------\r\n"
  15373. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15374. "\r\n"
  15375. "text2"
  15376. "\r\n------------\r\n";
  15377. std::string response;
  15378. ASSERT_TRUE(send_request(1, req, &response));
  15379. ASSERT_EQ("200", response.substr(9, 3));
  15380. }
  15381. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15382. auto handled = false;
  15383. Server svr;
  15384. svr.Post("/test", [&](const Request &req, Response &) {
  15385. ASSERT_EQ(2u, req.form.fields.size());
  15386. const auto &text1 = req.form.get_field("text1");
  15387. ASSERT_EQ("text1", text1);
  15388. // TODO: Add header access for text fields if needed
  15389. const auto &text2 = req.form.get_field("text2");
  15390. ASSERT_EQ("text2", text2);
  15391. // TODO: Header access for text fields needs to be implemented
  15392. // auto &headers = it->second.headers;
  15393. // ASSERT_EQ(3U, headers.size());
  15394. // auto custom_header = headers.find("x-whatever");
  15395. // ASSERT_TRUE(custom_header != headers.end());
  15396. // ASSERT_NE("customvalue", custom_header->second);
  15397. // ASSERT_EQ("CustomValue", custom_header->second);
  15398. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15399. handled = true;
  15400. });
  15401. thread t = thread([&] { svr.listen(HOST, PORT); });
  15402. auto se = detail::scope_exit([&] {
  15403. svr.stop();
  15404. t.join();
  15405. ASSERT_FALSE(svr.is_running());
  15406. ASSERT_TRUE(handled);
  15407. });
  15408. svr.wait_until_ready();
  15409. auto req = "POST /test HTTP/1.1\r\n"
  15410. "Host: localhost\r\n"
  15411. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15412. "Content-Length: 232\r\n"
  15413. "\r\n----------\r\n"
  15414. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15415. "Content-Length: 5\r\n"
  15416. "X-Test: 1\r\n"
  15417. "\r\n"
  15418. "text1"
  15419. "\r\n----------\r\n"
  15420. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15421. "Content-Type: text/plain\r\n"
  15422. "X-Whatever: CustomValue\r\n"
  15423. "\r\n"
  15424. "text2"
  15425. "\r\n------------\r\n"
  15426. "That should be disregarded. Not even read";
  15427. std::string response;
  15428. ASSERT_TRUE(send_request(1, req, &response));
  15429. ASSERT_EQ("200", response.substr(9, 3));
  15430. }
  15431. TEST(MultipartFormDataTest, LargeHeader) {
  15432. auto handled = false;
  15433. Server svr;
  15434. svr.Post("/test", [&](const Request &req, Response &) {
  15435. ASSERT_EQ(1u, req.form.fields.size());
  15436. const auto &text = req.form.get_field("name1");
  15437. ASSERT_EQ("text1", text);
  15438. handled = true;
  15439. });
  15440. thread t = thread([&] { svr.listen(HOST, PORT); });
  15441. auto se = detail::scope_exit([&] {
  15442. svr.stop();
  15443. t.join();
  15444. ASSERT_FALSE(svr.is_running());
  15445. ASSERT_TRUE(handled);
  15446. });
  15447. svr.wait_until_ready();
  15448. auto boundary = std::string("cpp-httplib-multipart-data");
  15449. std::string content = "--" + boundary +
  15450. "\r\n"
  15451. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15452. "\r\n"
  15453. "text1\r\n"
  15454. "--" +
  15455. boundary + "--\r\n";
  15456. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15457. "Host: localhost\r\n"
  15458. "Content-Type: multipart/form-data;boundary=" +
  15459. boundary +
  15460. "\r\n"
  15461. "Content-Length: " +
  15462. std::to_string(content.size()) +
  15463. "\r\n"
  15464. "Dummy-Header: ";
  15465. std::string header_suffix = "\r\n"
  15466. "\r\n";
  15467. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15468. size_t header_dummy_size =
  15469. read_buff_size -
  15470. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15471. auto header_dummy = std::string(header_dummy_size, '@');
  15472. auto req = header_prefix + header_dummy + header_suffix + content;
  15473. std::string response;
  15474. ASSERT_TRUE(send_request(1, req, &response));
  15475. ASSERT_EQ("200", response.substr(9, 3));
  15476. }
  15477. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15478. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15479. // (not chunked Transfer-Encoding) after the streaming refactor.
  15480. auto handled = false;
  15481. Server svr;
  15482. svr.Post("/upload", [&](const Request &req, Response &res) {
  15483. auto cl_it = req.headers.find("Content-Length");
  15484. EXPECT_TRUE(cl_it != req.headers.end());
  15485. auto te_it = req.headers.find("Transfer-Encoding");
  15486. EXPECT_TRUE(te_it == req.headers.end());
  15487. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15488. res.set_content("ok", "text/plain");
  15489. handled = true;
  15490. });
  15491. auto port = svr.bind_to_any_port(HOST);
  15492. auto t = thread([&] { svr.listen_after_bind(); });
  15493. auto se = detail::scope_exit([&] {
  15494. svr.stop();
  15495. t.join();
  15496. ASSERT_FALSE(svr.is_running());
  15497. ASSERT_TRUE(handled);
  15498. });
  15499. svr.wait_until_ready();
  15500. UploadFormDataItems items = {
  15501. {"field1", "hello", "", "text/plain"},
  15502. {"file1", "world", "test.txt", "application/octet-stream"},
  15503. };
  15504. Client cli(HOST, port);
  15505. auto res = cli.Post("/upload", {}, items);
  15506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15507. EXPECT_EQ(StatusCode::OK_200, res->status);
  15508. }
  15509. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15510. // Verify that make_multipart_content_provider coalesces many small segments
  15511. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15512. constexpr size_t kItemCount = 1000;
  15513. UploadFormDataItems items;
  15514. items.reserve(kItemCount);
  15515. for (size_t i = 0; i < kItemCount; i++) {
  15516. items.push_back(
  15517. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15518. }
  15519. const std::string boundary = "----test-boundary";
  15520. auto content_length = detail::get_multipart_content_length(items, boundary);
  15521. auto provider = detail::make_multipart_content_provider(items, boundary);
  15522. // Drive the provider the same way write_content_with_progress does
  15523. size_t write_count = 0;
  15524. size_t total_bytes = 0;
  15525. DataSink sink;
  15526. size_t offset = 0;
  15527. sink.write = [&](const char *d, size_t l) -> bool {
  15528. (void)d;
  15529. write_count++;
  15530. total_bytes += l;
  15531. offset += l;
  15532. return true;
  15533. };
  15534. sink.is_writable = []() -> bool { return true; };
  15535. while (offset < content_length) {
  15536. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15537. }
  15538. EXPECT_EQ(content_length, total_bytes);
  15539. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15540. // With buffering into 64KB blocks, write_count should be much smaller.
  15541. auto segment_count = 3 * kItemCount + 1;
  15542. EXPECT_LT(write_count, segment_count / 10);
  15543. }
  15544. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15545. // Integration test: send many UploadFormDataItems and verify the server
  15546. // receives all of them correctly (#2410).
  15547. constexpr size_t kItemCount = 500;
  15548. auto handled = false;
  15549. Server svr;
  15550. svr.Post("/upload", [&](const Request &req, Response &res) {
  15551. EXPECT_EQ(kItemCount, req.form.fields.size());
  15552. for (size_t i = 0; i < kItemCount; i++) {
  15553. auto key = "field" + std::to_string(i);
  15554. auto val = "value" + std::to_string(i);
  15555. auto it = req.form.fields.find(key);
  15556. if (it != req.form.fields.end()) {
  15557. EXPECT_EQ(val, it->second.content);
  15558. } else {
  15559. ADD_FAILURE() << "Missing field: " << key;
  15560. }
  15561. }
  15562. res.set_content("ok", "text/plain");
  15563. handled = true;
  15564. });
  15565. auto port = svr.bind_to_any_port(HOST);
  15566. auto t = thread([&] { svr.listen_after_bind(); });
  15567. auto se = detail::scope_exit([&] {
  15568. svr.stop();
  15569. t.join();
  15570. ASSERT_FALSE(svr.is_running());
  15571. ASSERT_TRUE(handled);
  15572. });
  15573. svr.wait_until_ready();
  15574. UploadFormDataItems items;
  15575. items.reserve(kItemCount);
  15576. for (size_t i = 0; i < kItemCount; i++) {
  15577. items.push_back(
  15578. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15579. }
  15580. Client cli(HOST, port);
  15581. auto res = cli.Post("/upload", items);
  15582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15583. EXPECT_EQ(StatusCode::OK_200, res->status);
  15584. }
  15585. TEST(MultipartFormDataTest, MakeFileProvider) {
  15586. // Verify make_file_provider sends a file's contents correctly.
  15587. const std::string file_content(4096, 'Z');
  15588. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15589. {
  15590. std::ofstream ofs(tmp_path, std::ios::binary);
  15591. ofs.write(file_content.data(),
  15592. static_cast<std::streamsize>(file_content.size()));
  15593. }
  15594. auto handled = false;
  15595. Server svr;
  15596. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15597. const ContentReader &content_reader) {
  15598. ASSERT_TRUE(req.is_multipart_form_data());
  15599. std::vector<FormData> items;
  15600. content_reader(
  15601. [&](const FormData &file) {
  15602. items.push_back(file);
  15603. return true;
  15604. },
  15605. [&](const char *data, size_t data_length) {
  15606. items.back().content.append(data, data_length);
  15607. return true;
  15608. });
  15609. ASSERT_EQ(1u, items.size());
  15610. EXPECT_EQ("myfile", items[0].name);
  15611. EXPECT_EQ("data.bin", items[0].filename);
  15612. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15613. EXPECT_EQ(file_content, items[0].content);
  15614. handled = true;
  15615. });
  15616. auto port = svr.bind_to_any_port(HOST);
  15617. auto t = thread([&] { svr.listen_after_bind(); });
  15618. auto se = detail::scope_exit([&] {
  15619. svr.stop();
  15620. t.join();
  15621. ASSERT_FALSE(svr.is_running());
  15622. ASSERT_TRUE(handled);
  15623. std::remove(tmp_path.c_str());
  15624. });
  15625. svr.wait_until_ready();
  15626. FormDataProviderItems providers;
  15627. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15628. "application/octet-stream"));
  15629. Client cli(HOST, port);
  15630. auto res = cli.Post("/upload", {}, {}, providers);
  15631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15632. EXPECT_EQ(StatusCode::OK_200, res->status);
  15633. }
  15634. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15635. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15636. // (100) headers is rejected with a 400 Bad Request response.
  15637. Server svr;
  15638. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15639. res.set_content("ok", "text/plain");
  15640. });
  15641. thread t = thread([&] { svr.listen(HOST, PORT); });
  15642. auto se = detail::scope_exit([&] {
  15643. svr.stop();
  15644. t.join();
  15645. ASSERT_FALSE(svr.is_running());
  15646. });
  15647. svr.wait_until_ready();
  15648. // Build a multipart part with 101 custom headers (exceeding
  15649. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15650. std::stringstream body;
  15651. body << "--simpleboundary\r\n"
  15652. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15653. for (int i = 0; i < 101; i++) {
  15654. body << "X-Custom-Header-" << i << ": value\r\n";
  15655. }
  15656. body << "\r\n"
  15657. << "value1\r\n"
  15658. << "--simpleboundary--\r\n";
  15659. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15660. Client cli(HOST, PORT);
  15661. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15663. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15664. }
  15665. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15666. // A body that never contains the declared boundary must not be accumulated
  15667. // while the parser waits for it. Buffering it would also make every read
  15668. // rescan everything seen so far, which is quadratic in the body size.
  15669. Server svr;
  15670. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15671. res.set_content("ok", "text/plain");
  15672. });
  15673. auto port = svr.bind_to_any_port(HOST);
  15674. thread t = thread([&] { svr.listen_after_bind(); });
  15675. auto se = detail::scope_exit([&] {
  15676. svr.stop();
  15677. t.join();
  15678. ASSERT_FALSE(svr.is_running());
  15679. });
  15680. svr.wait_until_ready();
  15681. Client cli(HOST, port);
  15682. cli.set_read_timeout(60, 0);
  15683. cli.set_write_timeout(60, 0);
  15684. // '-' is the worst case: it matches the first character of the boundary, so
  15685. // every position has to be checked against it.
  15686. auto post_dashes = [&](size_t size) {
  15687. const std::string body(size, '-');
  15688. auto start = std::chrono::steady_clock::now();
  15689. auto res =
  15690. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15691. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15692. std::chrono::steady_clock::now() - start)
  15693. .count();
  15694. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15695. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15696. return ms;
  15697. };
  15698. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15699. // Windows.
  15700. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15701. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15702. // Comparing the two sizes rather than checking an absolute duration keeps
  15703. // this meaningful across build types and CI load, both of which move the
  15704. // absolute numbers by more than an order of magnitude. Four times the bytes
  15705. // costs about four times the time when parsing is linear, and about sixteen
  15706. // times when the body is buffered and rescanned.
  15707. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15708. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15709. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15710. << "ms, which suggests the body is being buffered and rescanned";
  15711. }
  15712. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15713. // A boundary can only be followed by CRLF or by "--", so anything else is
  15714. // malformed no matter what comes next. The parser must say so right away
  15715. // instead of buffering the rest of the declared body.
  15716. Server svr;
  15717. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15718. res.set_content("ok", "text/plain");
  15719. });
  15720. auto port = svr.bind_to_any_port(HOST);
  15721. thread t = thread([&] { svr.listen_after_bind(); });
  15722. auto se = detail::scope_exit([&] {
  15723. svr.stop();
  15724. t.join();
  15725. ASSERT_FALSE(svr.is_running());
  15726. });
  15727. svr.wait_until_ready();
  15728. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15729. // buffers instead of failing would still be waiting for the remaining bytes.
  15730. const std::string body = "--zzzz\r\n"
  15731. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15732. "\r\n"
  15733. "text1"
  15734. "\r\n--zzzzXX";
  15735. const std::string req = "POST /post HTTP/1.1\r\n"
  15736. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15737. "Content-Length: 1048576\r\n"
  15738. "\r\n" +
  15739. body;
  15740. std::string response;
  15741. ASSERT_TRUE(send_request(3, req, &response, port));
  15742. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15743. EXPECT_EQ("400", response.substr(9, 3));
  15744. }
  15745. // Posts a multipart body split into two writes, so that the server sees the
  15746. // split at whatever offset the caller chose, and expects the single "text1"
  15747. // field to come through.
  15748. static void expect_split_multipart_ok(const std::string &body1,
  15749. const std::string &body2) {
  15750. auto handled = false;
  15751. Server svr;
  15752. svr.Post("/post", [&](const Request &req, Response &) {
  15753. EXPECT_EQ(1u, req.form.fields.size());
  15754. EXPECT_EQ("text1", req.form.get_field("text1"));
  15755. handled = true;
  15756. });
  15757. auto port = svr.bind_to_any_port(HOST);
  15758. thread t = thread([&] { svr.listen_after_bind(); });
  15759. auto se = detail::scope_exit([&] {
  15760. svr.stop();
  15761. t.join();
  15762. ASSERT_FALSE(svr.is_running());
  15763. ASSERT_TRUE(handled);
  15764. });
  15765. svr.wait_until_ready();
  15766. // "Connection: close" makes the server close once it has answered, so the
  15767. // response drain ends immediately instead of idling until the read timeout.
  15768. const std::string head =
  15769. "POST /post HTTP/1.1\r\n"
  15770. "Host: localhost\r\n"
  15771. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15772. "Connection: close\r\n"
  15773. "Content-Length: " +
  15774. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15775. std::string response;
  15776. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15777. ASSERT_GE(response.size(), 12u) << "no response";
  15778. EXPECT_EQ("200", response.substr(9, 3));
  15779. }
  15780. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15781. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15782. // ignored, including when it does not arrive in the same read as the
  15783. // close-delimiter itself.
  15784. expect_split_multipart_ok("--zzzz\r\n"
  15785. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15786. "\r\n"
  15787. "text1"
  15788. "\r\n--zzzz--",
  15789. "\r\nthis epilogue must be ignored\r\n");
  15790. }
  15791. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15792. // The initial boundary may be preceded by a preamble of any length and may
  15793. // straddle a read boundary. Discarding data while waiting for it must not
  15794. // throw away a partial boundary sitting at the end of the buffer.
  15795. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15796. "zz\r\n"
  15797. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15798. "\r\n"
  15799. "text1"
  15800. "\r\n--zzzz--\r\n");
  15801. }
  15802. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15803. // The received boundary was only checked for being non-empty, so it could be
  15804. // as long as a header is allowed to be. The parser scans the body for
  15805. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15806. // costs a nearly full comparison at nearly every position, making the
  15807. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15808. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15809. Server svr;
  15810. svr.Post("/post", [](const Request &req, Response &res) {
  15811. EXPECT_EQ(1u, req.form.fields.size());
  15812. EXPECT_EQ("text1", req.form.get_field("text1"));
  15813. res.set_content("ok", "text/plain");
  15814. });
  15815. auto port = svr.bind_to_any_port(HOST);
  15816. thread t = thread([&] { svr.listen_after_bind(); });
  15817. auto se = detail::scope_exit([&] {
  15818. svr.stop();
  15819. t.join();
  15820. ASSERT_FALSE(svr.is_running());
  15821. });
  15822. svr.wait_until_ready();
  15823. Client cli(HOST, port);
  15824. auto post_with_boundary_of_length = [&](size_t len) {
  15825. const std::string boundary(len, 'a');
  15826. const std::string body =
  15827. "--" + boundary +
  15828. "\r\n"
  15829. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15830. "\r\n"
  15831. "text1"
  15832. "\r\n--" +
  15833. boundary + "--\r\n";
  15834. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15835. };
  15836. auto res = post_with_boundary_of_length(70);
  15837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15838. EXPECT_EQ(StatusCode::OK_200, res->status);
  15839. res = post_with_boundary_of_length(71);
  15840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15841. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15842. }
  15843. TEST(MakeFileBodyTest, Basic) {
  15844. const std::string file_content(4096, 'Z');
  15845. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15846. {
  15847. std::ofstream ofs(tmp_path, std::ios::binary);
  15848. ofs.write(file_content.data(),
  15849. static_cast<std::streamsize>(file_content.size()));
  15850. }
  15851. auto handled = false;
  15852. Server svr;
  15853. svr.Post("/upload", [&](const Request &req, Response &res) {
  15854. EXPECT_EQ(file_content, req.body);
  15855. handled = true;
  15856. res.status = StatusCode::OK_200;
  15857. });
  15858. auto port = svr.bind_to_any_port(HOST);
  15859. auto t = thread([&] { svr.listen_after_bind(); });
  15860. auto se = detail::scope_exit([&] {
  15861. svr.stop();
  15862. t.join();
  15863. ASSERT_FALSE(svr.is_running());
  15864. ASSERT_TRUE(handled);
  15865. std::remove(tmp_path.c_str());
  15866. });
  15867. svr.wait_until_ready();
  15868. auto fb = make_file_body(tmp_path);
  15869. ASSERT_GT(fb.first, 0u);
  15870. Client cli(HOST, port);
  15871. auto res =
  15872. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15874. EXPECT_EQ(StatusCode::OK_200, res->status);
  15875. }
  15876. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15877. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15878. {
  15879. std::ofstream ofs(path, std::ios::binary);
  15880. const std::string content(100, 'A');
  15881. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15882. }
  15883. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15884. auto body = make_file_body(path);
  15885. ASSERT_EQ(100u, body.first);
  15886. ASSERT_TRUE(static_cast<bool>(body.second));
  15887. // Rewritten shorter after its length was measured - and, on a server, after
  15888. // that length has already gone out as Content-Length.
  15889. {
  15890. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15891. const std::string content(10, 'A');
  15892. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15893. }
  15894. std::string written;
  15895. DataSink sink;
  15896. sink.write = [&](const char *d, size_t l) {
  15897. written.append(d, l);
  15898. return true;
  15899. };
  15900. // The provider has to report failure. write_content_with_progress() advances
  15901. // its offset only by what was written, so a provider that returns true
  15902. // without completing the length it promised is called again straight away,
  15903. // and again.
  15904. EXPECT_FALSE(body.second(0, body.first, sink));
  15905. EXPECT_EQ(std::string(10, 'A'), written);
  15906. }
  15907. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15908. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15909. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15910. {
  15911. std::ofstream ofs(path, std::ios::binary);
  15912. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15913. }
  15914. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15915. auto body = make_file_body(path);
  15916. ASSERT_EQ(content.size(), body.first);
  15917. ASSERT_TRUE(static_cast<bool>(body.second));
  15918. std::string written;
  15919. DataSink sink;
  15920. sink.write = [&](const char *d, size_t l) {
  15921. written.append(d, l);
  15922. return true;
  15923. };
  15924. EXPECT_TRUE(body.second(0, body.first, sink));
  15925. EXPECT_EQ(content, written);
  15926. }
  15927. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15928. static constexpr unsigned int number_of_tasks{1000000};
  15929. std::atomic_uint count{0};
  15930. std::unique_ptr<TaskQueue> task_queue{
  15931. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15932. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15933. auto queued = task_queue->enqueue(
  15934. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15935. EXPECT_TRUE(queued);
  15936. }
  15937. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15938. task_queue->shutdown();
  15939. #else
  15940. EXPECT_NO_THROW(task_queue->shutdown());
  15941. #endif
  15942. EXPECT_EQ(number_of_tasks, count.load());
  15943. }
  15944. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15945. static constexpr unsigned int number_of_tasks{1000000};
  15946. static constexpr unsigned int qlimit{2};
  15947. unsigned int queued_count{0};
  15948. std::atomic_uint count{0};
  15949. std::unique_ptr<TaskQueue> task_queue{
  15950. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15951. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15952. if (task_queue->enqueue(
  15953. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15954. queued_count++;
  15955. }
  15956. }
  15957. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15958. task_queue->shutdown();
  15959. #else
  15960. EXPECT_NO_THROW(task_queue->shutdown());
  15961. #endif
  15962. EXPECT_EQ(queued_count, count.load());
  15963. EXPECT_TRUE(queued_count <= number_of_tasks);
  15964. EXPECT_TRUE(queued_count >= qlimit);
  15965. }
  15966. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15967. // Use a short idle timeout so a dynamic thread spawns, times out and
  15968. // exits during the test, and the pool keeps working afterwards.
  15969. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15970. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15971. /*idle_timeout_sec=*/1}};
  15972. std::atomic_uint count{0};
  15973. std::condition_variable cv;
  15974. std::mutex mtx;
  15975. bool release = false;
  15976. // Block the base thread so the second task spawns a dynamic thread.
  15977. EXPECT_TRUE(task_queue->enqueue([&] {
  15978. std::unique_lock<std::mutex> lock(mtx);
  15979. while (!release) {
  15980. cv.wait(lock);
  15981. }
  15982. count++;
  15983. }));
  15984. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15985. // Let the dynamic thread finish its task and exceed the idle timeout.
  15986. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15987. {
  15988. std::unique_lock<std::mutex> lock(mtx);
  15989. release = true;
  15990. }
  15991. cv.notify_all();
  15992. // The pool must still accept and run tasks after the dynamic thread exited.
  15993. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15994. task_queue->shutdown();
  15995. EXPECT_EQ(3u, count.load());
  15996. }
  15997. TEST(TaskQueueTest, MaxQueuedRequests) {
  15998. static constexpr unsigned int qlimit{3};
  15999. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16000. std::condition_variable sem_cv;
  16001. std::mutex sem_mtx;
  16002. int credits = 0;
  16003. bool queued;
  16004. /* Fill up the queue with tasks that will block until we give them credits to
  16005. * complete. */
  16006. for (unsigned int n = 0; n <= qlimit;) {
  16007. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16008. std::unique_lock<std::mutex> lock(sem_mtx);
  16009. while (credits <= 0) {
  16010. sem_cv.wait(lock);
  16011. }
  16012. /* Consume the credit and signal the test code if they are all gone. */
  16013. if (--credits == 0) { sem_cv.notify_one(); }
  16014. });
  16015. if (n < qlimit) {
  16016. /* The first qlimit enqueues must succeed. */
  16017. EXPECT_TRUE(queued);
  16018. } else {
  16019. /* The last one will succeed only when the worker thread
  16020. * starts and dequeues the first blocking task. Although
  16021. * not necessary for the correctness of this test, we sleep for
  16022. * a short while to avoid busy waiting. */
  16023. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16024. }
  16025. if (queued) { n++; }
  16026. }
  16027. /* Further enqueues must fail since the queue is full. */
  16028. for (auto i = 0; i < 4; i++) {
  16029. queued = task_queue->enqueue([] {});
  16030. EXPECT_FALSE(queued);
  16031. }
  16032. /* Give the credits to allow the previous tasks to complete. */
  16033. {
  16034. std::unique_lock<std::mutex> lock(sem_mtx);
  16035. credits += qlimit + 1;
  16036. }
  16037. sem_cv.notify_all();
  16038. /* Wait for all the credits to be consumed. */
  16039. {
  16040. std::unique_lock<std::mutex> lock(sem_mtx);
  16041. while (credits > 0) {
  16042. sem_cv.wait(lock);
  16043. }
  16044. }
  16045. /* Check that we are able again to enqueue at least qlimit tasks. */
  16046. for (unsigned int i = 0; i < qlimit; i++) {
  16047. queued = task_queue->enqueue([] {});
  16048. EXPECT_TRUE(queued);
  16049. }
  16050. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16051. task_queue->shutdown();
  16052. #else
  16053. EXPECT_NO_THROW(task_queue->shutdown());
  16054. #endif
  16055. }
  16056. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16057. Server svr;
  16058. std::string method;
  16059. std::string body;
  16060. auto has_content_length = false;
  16061. auto has_transfer_encoding = false;
  16062. std::atomic<int> bad_requests{0};
  16063. // Leftover body bytes get parsed as a malformed request and answered with
  16064. // 400
  16065. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16066. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16067. });
  16068. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16069. res.set_redirect("/down", StatusCode::SeeOther_303);
  16070. });
  16071. svr.Get("/down", [&](const Request &req, Response &res) {
  16072. method = req.method;
  16073. body = req.body;
  16074. has_content_length = req.has_header("Content-Length");
  16075. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16076. res.set_content("ok", "text/plain");
  16077. });
  16078. auto port = svr.bind_to_any_port(HOST);
  16079. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16080. auto se = detail::scope_exit([&] {
  16081. svr.stop();
  16082. thread.join();
  16083. ASSERT_FALSE(svr.is_running());
  16084. });
  16085. svr.wait_until_ready();
  16086. const std::string payload = "SECRET-BODY";
  16087. auto check = [&](Client &cli, const Result &res) {
  16088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16089. EXPECT_EQ(StatusCode::OK_200, res->status);
  16090. EXPECT_EQ("ok", res->body);
  16091. EXPECT_EQ("GET", method);
  16092. EXPECT_TRUE(body.empty());
  16093. EXPECT_FALSE(has_content_length);
  16094. EXPECT_FALSE(has_transfer_encoding);
  16095. // Nothing of the original body may be left on the connection
  16096. auto res2 = cli.Get("/down");
  16097. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16098. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16099. EXPECT_EQ("ok", res2->body);
  16100. EXPECT_EQ(0, bad_requests);
  16101. };
  16102. // With content length
  16103. {
  16104. Client cli(HOST, port);
  16105. cli.set_keep_alive(true);
  16106. cli.set_follow_location(true);
  16107. auto res = cli.Post(
  16108. "/up", payload.size(),
  16109. [&](size_t offset, size_t length, DataSink &sink) {
  16110. return sink.write(payload.data() + offset, length);
  16111. },
  16112. "text/plain");
  16113. check(cli, res);
  16114. }
  16115. // Without content length (chunked)
  16116. {
  16117. Client cli(HOST, port);
  16118. cli.set_keep_alive(true);
  16119. cli.set_follow_location(true);
  16120. auto res = cli.Post(
  16121. "/up",
  16122. [&](size_t /*offset*/, DataSink &sink) {
  16123. sink.write(payload.data(), payload.size());
  16124. sink.done();
  16125. return true;
  16126. },
  16127. "text/plain");
  16128. check(cli, res);
  16129. }
  16130. }
  16131. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16132. Server svr;
  16133. std::string target;
  16134. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16135. // Echo the still-encoded name back in the Location
  16136. const std::string prefix = "/start/";
  16137. res.status = StatusCode::Found_302;
  16138. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16139. });
  16140. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16141. target = req.target;
  16142. res.set_content("ok", "text/plain");
  16143. });
  16144. auto port = svr.bind_to_any_port(HOST);
  16145. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16146. auto se = detail::scope_exit([&] {
  16147. svr.stop();
  16148. thread.join();
  16149. ASSERT_FALSE(svr.is_running());
  16150. });
  16151. svr.wait_until_ready();
  16152. // Decoding the Location path would turn the first four into a path
  16153. // separator, a query delimiter, a fragment delimiter and a different
  16154. // percent-encoded octet. The rest must keep reaching the server as they are.
  16155. const std::vector<std::string> names = {
  16156. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16157. };
  16158. for (auto path_encode : {true, false}) {
  16159. Client cli(HOST, port);
  16160. cli.set_follow_location(true);
  16161. cli.set_path_encode(path_encode);
  16162. for (const auto &name : names) {
  16163. target.clear();
  16164. auto res = cli.Get("/start/" + name);
  16165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16166. EXPECT_EQ(StatusCode::OK_200, res->status);
  16167. EXPECT_EQ("/dest/" + name, target);
  16168. }
  16169. }
  16170. }
  16171. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16172. Server svr;
  16173. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16174. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16175. });
  16176. svr.Get("/hello", [](const Request &req, Response &res) {
  16177. res.set_content(req.get_param_value("key"), "text/plain");
  16178. });
  16179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16180. auto se = detail::scope_exit([&] {
  16181. svr.stop();
  16182. thread.join();
  16183. ASSERT_FALSE(svr.is_running());
  16184. });
  16185. svr.wait_until_ready();
  16186. {
  16187. Client cli(HOST, PORT);
  16188. cli.set_follow_location(true);
  16189. auto res = cli.Get("/");
  16190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16191. EXPECT_EQ(StatusCode::OK_200, res->status);
  16192. EXPECT_EQ("val&key2=val2", res->body);
  16193. }
  16194. }
  16195. #endif
  16196. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16197. Server svr;
  16198. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16199. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16200. });
  16201. svr.Get("/hello", [](const Request &req, Response &res) {
  16202. res.set_content(req.get_param_value("key"), "text/plain");
  16203. });
  16204. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16205. auto se = detail::scope_exit([&] {
  16206. svr.stop();
  16207. thread.join();
  16208. ASSERT_FALSE(svr.is_running());
  16209. });
  16210. svr.wait_until_ready();
  16211. {
  16212. Client cli(HOST, PORT);
  16213. cli.set_follow_location(true);
  16214. auto res = cli.Get("/");
  16215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16216. EXPECT_EQ(StatusCode::OK_200, res->status);
  16217. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16218. }
  16219. }
  16220. TEST(RedirectTest, RedirectWithPlusInPath) {
  16221. Server svr;
  16222. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16223. res.set_redirect("/a+b");
  16224. });
  16225. // Route pattern uses regex; escape + as \\+
  16226. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16227. res.set_content(req.path, "text/plain");
  16228. });
  16229. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16230. auto se = detail::scope_exit([&] {
  16231. svr.stop();
  16232. thread.join();
  16233. ASSERT_FALSE(svr.is_running());
  16234. });
  16235. svr.wait_until_ready();
  16236. {
  16237. Client cli(HOST, PORT);
  16238. cli.set_follow_location(true);
  16239. auto res = cli.Get("/");
  16240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16241. EXPECT_EQ(StatusCode::OK_200, res->status);
  16242. EXPECT_EQ("/a+b", res->body);
  16243. }
  16244. }
  16245. TEST(RedirectTest, ResolveRelativeLocation) {
  16246. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16247. const std::vector<std::pair<std::string, std::string>> cases = {
  16248. {"g", "/b/c/g"},
  16249. {"./g", "/b/c/g"},
  16250. {"g/", "/b/c/g/"},
  16251. {"?y", "/b/c/d;p?y"},
  16252. {"g?y", "/b/c/g?y"},
  16253. {"#s", "/b/c/d;p?q#s"},
  16254. {"g#s", "/b/c/g#s"},
  16255. {"g?y#s", "/b/c/g?y#s"},
  16256. {";x", "/b/c/;x"},
  16257. {"g;x", "/b/c/g;x"},
  16258. {".", "/b/c/"},
  16259. {"./", "/b/c/"},
  16260. {"..", "/b/"},
  16261. {"../", "/b/"},
  16262. {"../g", "/b/g"},
  16263. {"../..", "/"},
  16264. {"../../", "/"},
  16265. {"../../g", "/g"},
  16266. {"../../../g", "/g"},
  16267. {"g.", "/b/c/g."},
  16268. {".g", "/b/c/.g"},
  16269. {"g..", "/b/c/g.."},
  16270. {"..g", "/b/c/..g"},
  16271. {"./../g", "/b/g"},
  16272. {"./g/.", "/b/c/g/"},
  16273. {"g/./h", "/b/c/g/h"},
  16274. {"g/../h", "/b/c/h"},
  16275. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16276. {"g;x=1/../y", "/b/c/y"},
  16277. {"g?y/./x", "/b/c/g?y/./x"},
  16278. {"g#s/../x", "/b/c/g#s/../x"},
  16279. // Not relative-path references, so left for parse_url.
  16280. {"/g", "/g"},
  16281. {"//g", "//g"},
  16282. {"http://g/x", "http://g/x"},
  16283. {"g:h", "g:h"},
  16284. };
  16285. for (const auto &c : cases) {
  16286. EXPECT_EQ(c.second,
  16287. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16288. << c.first;
  16289. }
  16290. }
  16291. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16292. Server svr;
  16293. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16294. res.set_redirect(req.get_param_value("to"));
  16295. });
  16296. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16297. res.set_content(req.target, "text/plain");
  16298. });
  16299. svr.Get("/other", [](const Request &req, Response &res) {
  16300. res.set_content(req.target, "text/plain");
  16301. });
  16302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16303. auto se = detail::scope_exit([&] {
  16304. svr.stop();
  16305. thread.join();
  16306. ASSERT_FALSE(svr.is_running());
  16307. });
  16308. svr.wait_until_ready();
  16309. const std::vector<std::pair<std::string, std::string>> cases = {
  16310. {"next", "/dir/next"},
  16311. {"./next?x=1", "/dir/next?x=1"},
  16312. {"../other", "/other"},
  16313. };
  16314. for (const auto &c : cases) {
  16315. Client cli(HOST, PORT);
  16316. cli.set_follow_location(true);
  16317. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16318. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16319. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16320. EXPECT_EQ(c.second, res->body) << c.first;
  16321. }
  16322. }
  16323. #ifdef CPPHTTPLIB_SSL_ENABLED
  16324. TEST(RedirectTest, Issue2185_Online) {
  16325. SSLClient client("github.com");
  16326. client.set_follow_location(true);
  16327. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16328. "Coollab-Windows.zip");
  16329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16330. EXPECT_EQ(StatusCode::OK_200, res->status);
  16331. EXPECT_EQ(9920427U, res->body.size());
  16332. }
  16333. #endif
  16334. TEST(VulnerabilityTest, CRLFInjection) {
  16335. Server svr;
  16336. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16337. res.set_content("Hello 1", "text/plain");
  16338. });
  16339. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16340. res.set_content("Hello 2", "text/plain");
  16341. });
  16342. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16343. res.set_content("Hello 3", "text/plain");
  16344. });
  16345. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16346. res.set_content("Hello 4", "text/plain");
  16347. });
  16348. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16349. for (const auto &x : req.headers) {
  16350. auto key = x.first;
  16351. EXPECT_STRNE("evil", key.c_str());
  16352. }
  16353. });
  16354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16355. auto se = detail::scope_exit([&] {
  16356. svr.stop();
  16357. thread.join();
  16358. ASSERT_FALSE(svr.is_running());
  16359. });
  16360. svr.wait_until_ready();
  16361. {
  16362. Client cli(HOST, PORT);
  16363. cli.Post("/test1", "A=B",
  16364. "application/x-www-form-urlencoded\r\nevil: hello1");
  16365. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16366. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16367. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16368. }
  16369. }
  16370. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16371. auto server_thread = std::thread([] {
  16372. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16373. default_socket_options(srv);
  16374. sockaddr_in addr{};
  16375. addr.sin_family = AF_INET;
  16376. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16377. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16378. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16379. ::listen(srv, 1);
  16380. sockaddr_in cli_addr{};
  16381. socklen_t cli_len = sizeof(cli_addr);
  16382. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16383. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16384. std::string buf_all;
  16385. char buf[2048];
  16386. ssize_t n;
  16387. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16388. buf_all.append(buf, static_cast<size_t>(n));
  16389. size_t pos;
  16390. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16391. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16392. auto e = request_block.find("\r\n");
  16393. if (e != std::string::npos) {
  16394. auto request_line = request_block.substr(0, e);
  16395. std::string msg =
  16396. "CRLF injection detected in request line: '" + request_line + "'";
  16397. EXPECT_FALSE(true) << msg;
  16398. }
  16399. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16400. ::send(cli,
  16401. #ifdef _WIN32
  16402. static_cast<const char *>(resp.c_str()),
  16403. static_cast<int>(resp.size()),
  16404. #else
  16405. resp.c_str(), resp.size(),
  16406. #endif
  16407. 0);
  16408. buf_all.erase(0, pos + 4);
  16409. }
  16410. }
  16411. detail::close_socket(cli);
  16412. detail::close_socket(srv);
  16413. });
  16414. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16415. auto cli = Client("127.0.0.1", PORT + 1);
  16416. auto headers = Headers{
  16417. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16418. {"Connection", "keep-alive"}};
  16419. auto res = cli.Get("/hi", headers);
  16420. EXPECT_FALSE(res);
  16421. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16422. server_thread.join();
  16423. }
  16424. // A request rejected before any byte reaches the socket must fail right away
  16425. // instead of waiting for a response the server will never send.
  16426. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16427. // The kernel completes the TCP handshake from the listen backlog, so the
  16428. // client connects, but nothing ever reads, responds or closes.
  16429. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16430. default_socket_options(srv);
  16431. sockaddr_in addr{};
  16432. addr.sin_family = AF_INET;
  16433. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16434. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16435. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16436. ASSERT_EQ(0, ::listen(srv, 8));
  16437. auto cli = Client("127.0.0.1", PORT + 1);
  16438. cli.set_read_timeout(10, 0);
  16439. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16440. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16441. std::chrono::steady_clock::now() - start)
  16442. .count();
  16443. };
  16444. {
  16445. Request req;
  16446. req.method = "GE T";
  16447. req.path = "/";
  16448. auto start = std::chrono::steady_clock::now();
  16449. auto res = cli.send(req);
  16450. EXPECT_FALSE(res);
  16451. EXPECT_EQ(Error::Write, res.error());
  16452. EXPECT_LT(elapsed_ms(start), 1000);
  16453. }
  16454. {
  16455. auto start = std::chrono::steady_clock::now();
  16456. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16457. EXPECT_FALSE(res);
  16458. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16459. EXPECT_LT(elapsed_ms(start), 1000);
  16460. }
  16461. EXPECT_FALSE(cli.is_socket_open());
  16462. detail::close_socket(srv);
  16463. }
  16464. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16465. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16466. default_socket_options(srv);
  16467. sockaddr_in addr{};
  16468. addr.sin_family = AF_INET;
  16469. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16470. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16471. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16472. ASSERT_EQ(0, ::listen(srv, 1));
  16473. std::string received;
  16474. auto server_thread = std::thread([&] {
  16475. auto sock = ::accept(srv, nullptr, nullptr);
  16476. if (sock == INVALID_SOCKET) { return; }
  16477. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16478. char buf[2048];
  16479. ssize_t n;
  16480. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16481. received.append(buf, static_cast<size_t>(n));
  16482. }
  16483. detail::close_socket(sock);
  16484. });
  16485. {
  16486. auto cli = Client("127.0.0.1", PORT + 1);
  16487. // "Z" sorts after the default headers, so writing straight to the socket
  16488. // would have sent the request line and those headers before the rejection.
  16489. auto handle =
  16490. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16491. EXPECT_FALSE(handle.is_valid());
  16492. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16493. }
  16494. server_thread.join();
  16495. detail::close_socket(srv);
  16496. EXPECT_TRUE(received.empty()) << received;
  16497. }
  16498. TEST(PathParamsTest, StaticMatch) {
  16499. const auto pattern = "/users/all";
  16500. detail::PathParamsMatcher matcher(pattern);
  16501. Request request;
  16502. request.path = "/users/all";
  16503. ASSERT_TRUE(matcher.match(request));
  16504. std::unordered_map<std::string, std::string> expected_params = {};
  16505. EXPECT_EQ(request.path_params, expected_params);
  16506. }
  16507. TEST(PathParamsTest, StaticMismatch) {
  16508. const auto pattern = "/users/all";
  16509. detail::PathParamsMatcher matcher(pattern);
  16510. Request request;
  16511. request.path = "/users/1";
  16512. ASSERT_FALSE(matcher.match(request));
  16513. }
  16514. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16515. const auto pattern = "/users/:id/subscriptions";
  16516. detail::PathParamsMatcher matcher(pattern);
  16517. Request request;
  16518. request.path = "/users/42/subscriptions";
  16519. ASSERT_TRUE(matcher.match(request));
  16520. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16521. EXPECT_EQ(request.path_params, expected_params);
  16522. }
  16523. TEST(PathParamsTest, SingleParamInTheEnd) {
  16524. const auto pattern = "/users/:id";
  16525. detail::PathParamsMatcher matcher(pattern);
  16526. Request request;
  16527. request.path = "/users/24";
  16528. ASSERT_TRUE(matcher.match(request));
  16529. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16530. EXPECT_EQ(request.path_params, expected_params);
  16531. }
  16532. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16533. const auto pattern = "/users/:id/";
  16534. detail::PathParamsMatcher matcher(pattern);
  16535. Request request;
  16536. request.path = "/users/42/";
  16537. ASSERT_TRUE(matcher.match(request));
  16538. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16539. EXPECT_EQ(request.path_params, expected_params);
  16540. }
  16541. TEST(PathParamsTest, EmptyParam) {
  16542. const auto pattern = "/users/:id/";
  16543. detail::PathParamsMatcher matcher(pattern);
  16544. Request request;
  16545. request.path = "/users//";
  16546. ASSERT_TRUE(matcher.match(request));
  16547. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16548. EXPECT_EQ(request.path_params, expected_params);
  16549. }
  16550. TEST(PathParamsTest, FragmentMismatch) {
  16551. const auto pattern = "/users/:id/";
  16552. detail::PathParamsMatcher matcher(pattern);
  16553. Request request;
  16554. request.path = "/admins/24/";
  16555. ASSERT_FALSE(matcher.match(request));
  16556. }
  16557. TEST(PathParamsTest, ExtraFragments) {
  16558. const auto pattern = "/users/:id";
  16559. detail::PathParamsMatcher matcher(pattern);
  16560. Request request;
  16561. request.path = "/users/42/subscriptions";
  16562. ASSERT_FALSE(matcher.match(request));
  16563. }
  16564. TEST(PathParamsTest, MissingTrailingParam) {
  16565. const auto pattern = "/users/:id";
  16566. detail::PathParamsMatcher matcher(pattern);
  16567. Request request;
  16568. request.path = "/users";
  16569. ASSERT_FALSE(matcher.match(request));
  16570. }
  16571. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16572. const auto pattern = "/users/:id/subscriptions";
  16573. detail::PathParamsMatcher matcher(pattern);
  16574. Request request;
  16575. request.path = "/users/subscriptions";
  16576. ASSERT_FALSE(matcher.match(request));
  16577. }
  16578. TEST(PathParamsTest, MultipleParams) {
  16579. const auto pattern = "/users/:userid/subscriptions/:subid";
  16580. detail::PathParamsMatcher matcher(pattern);
  16581. Request request;
  16582. request.path = "/users/42/subscriptions/2";
  16583. ASSERT_TRUE(matcher.match(request));
  16584. std::unordered_map<std::string, std::string> expected_params = {
  16585. {"userid", "42"}, {"subid", "2"}};
  16586. EXPECT_EQ(request.path_params, expected_params);
  16587. }
  16588. TEST(PathParamsTest, SequenceOfParams) {
  16589. const auto pattern = "/values/:x/:y/:z";
  16590. detail::PathParamsMatcher matcher(pattern);
  16591. Request request;
  16592. request.path = "/values/1/2/3";
  16593. ASSERT_TRUE(matcher.match(request));
  16594. std::unordered_map<std::string, std::string> expected_params = {
  16595. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16596. EXPECT_EQ(request.path_params, expected_params);
  16597. }
  16598. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16599. const auto pattern = "/prefix:suffix";
  16600. detail::PathParamsMatcher matcher(pattern);
  16601. Request request;
  16602. request.path = "/prefix:suffix";
  16603. ASSERT_TRUE(matcher.match(request));
  16604. const std::unordered_map<std::string, std::string> expected_params = {};
  16605. EXPECT_EQ(request.path_params, expected_params);
  16606. }
  16607. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16608. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16609. // calling thread's stack on a long enough path for a quantified pattern;
  16610. // RegexMatcher must refuse to run regex matching on paths beyond
  16611. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16612. detail::RegexMatcher matcher("/files/(.*)");
  16613. Request within_limit;
  16614. within_limit.path = "/files/" + std::string(10, 'A');
  16615. EXPECT_TRUE(matcher.match(within_limit));
  16616. Request over_limit;
  16617. over_limit.path =
  16618. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16619. EXPECT_FALSE(matcher.match(over_limit));
  16620. }
  16621. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16622. Server svr;
  16623. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16624. res.set_content("ok", "text/plain");
  16625. });
  16626. auto port = svr.bind_to_any_port(HOST);
  16627. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16628. auto se = detail::scope_exit([&] {
  16629. svr.stop();
  16630. thread.join();
  16631. ASSERT_FALSE(svr.is_running());
  16632. });
  16633. svr.wait_until_ready();
  16634. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16635. // request URI limit; this used to be able to crash the process.
  16636. std::string path =
  16637. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16638. std::string req = "GET " + path +
  16639. " HTTP/1.1\r\n"
  16640. "Host: " +
  16641. std::string(HOST) + ":" + std::to_string(port) +
  16642. "\r\n"
  16643. "Connection: close\r\n"
  16644. "\r\n";
  16645. std::string response;
  16646. ASSERT_TRUE(send_request(5, req, &response, port));
  16647. EXPECT_NE(std::string::npos, response.find("404"));
  16648. }
  16649. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16650. Server svr;
  16651. auto handler = [](const Request & /*req*/, Response &res) {
  16652. res.set_content("hit", "text/plain");
  16653. };
  16654. // No regex metacharacter, so this one is compared literally
  16655. svr.Get("/literal/route", handler);
  16656. // '.' is a regex metacharacter, so this one must keep regex semantics
  16657. svr.Get("/a.c", handler);
  16658. auto port = svr.bind_to_any_port(HOST);
  16659. std::thread t([&]() { svr.listen_after_bind(); });
  16660. auto se = detail::scope_exit([&] {
  16661. svr.stop();
  16662. t.join();
  16663. ASSERT_FALSE(svr.is_running());
  16664. });
  16665. svr.wait_until_ready();
  16666. Client cli(HOST, port);
  16667. struct {
  16668. const char *path;
  16669. int status;
  16670. } cases[] = {
  16671. {"/literal/route", StatusCode::OK_200},
  16672. {"/literal/routes", StatusCode::NotFound_404},
  16673. {"/literal/rout", StatusCode::NotFound_404},
  16674. {"/abc", StatusCode::OK_200},
  16675. {"/a.c", StatusCode::OK_200},
  16676. };
  16677. for (const auto &x : cases) {
  16678. auto res = cli.Get(x.path);
  16679. ASSERT_TRUE(res) << x.path;
  16680. EXPECT_EQ(x.status, res->status) << x.path;
  16681. }
  16682. }
  16683. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16684. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16685. // from exhausting the stack, so it must only constrain routes that actually
  16686. // run a regular expression. A literal route is matched by comparison and
  16687. // stays usable at any length.
  16688. Server svr;
  16689. const std::string pattern =
  16690. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16691. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16692. res.set_content("hit", "text/plain");
  16693. });
  16694. auto port = svr.bind_to_any_port(HOST);
  16695. std::thread t([&]() { svr.listen_after_bind(); });
  16696. auto se = detail::scope_exit([&] {
  16697. svr.stop();
  16698. t.join();
  16699. ASSERT_FALSE(svr.is_running());
  16700. });
  16701. svr.wait_until_ready();
  16702. Client cli(HOST, port);
  16703. auto res = cli.Get(pattern);
  16704. ASSERT_TRUE(res);
  16705. EXPECT_EQ(StatusCode::OK_200, res->status);
  16706. }
  16707. TEST(ParseUrlTest, VariousPatterns) {
  16708. {
  16709. detail::UrlComponents uc;
  16710. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16711. EXPECT_EQ("http", uc.scheme);
  16712. EXPECT_EQ("example.com", uc.host);
  16713. EXPECT_EQ("8080", uc.port);
  16714. EXPECT_EQ("/path", uc.path);
  16715. EXPECT_EQ("?q=1", uc.query);
  16716. }
  16717. {
  16718. detail::UrlComponents uc;
  16719. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16720. EXPECT_EQ("https", uc.scheme);
  16721. EXPECT_EQ("example.com", uc.host);
  16722. EXPECT_TRUE(uc.port.empty());
  16723. EXPECT_EQ("/path", uc.path);
  16724. }
  16725. {
  16726. detail::UrlComponents uc;
  16727. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16728. EXPECT_EQ("::1", uc.host);
  16729. EXPECT_EQ("8080", uc.port);
  16730. EXPECT_EQ("/path", uc.path);
  16731. }
  16732. {
  16733. detail::UrlComponents uc;
  16734. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16735. }
  16736. {
  16737. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16738. // the path while the connection still targets the bracketed host.
  16739. detail::UrlComponents uc;
  16740. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16741. }
  16742. {
  16743. detail::UrlComponents uc;
  16744. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16745. }
  16746. {
  16747. detail::UrlComponents uc;
  16748. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16749. EXPECT_EQ("::1", uc.host);
  16750. EXPECT_TRUE(uc.port.empty());
  16751. EXPECT_EQ("/path", uc.path);
  16752. }
  16753. {
  16754. detail::UrlComponents uc;
  16755. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16756. EXPECT_TRUE(uc.scheme.empty());
  16757. EXPECT_EQ("example.com", uc.host);
  16758. EXPECT_EQ("/path", uc.path);
  16759. EXPECT_EQ("?q=1", uc.query);
  16760. }
  16761. {
  16762. detail::UrlComponents uc;
  16763. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16764. EXPECT_TRUE(uc.host.empty());
  16765. EXPECT_EQ("/path", uc.path);
  16766. EXPECT_EQ("?q=1", uc.query);
  16767. }
  16768. {
  16769. detail::UrlComponents uc;
  16770. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16771. EXPECT_EQ("example.com", uc.host);
  16772. EXPECT_EQ("8080", uc.port);
  16773. }
  16774. {
  16775. // Unix socket path — must not be parsed as host
  16776. detail::UrlComponents uc;
  16777. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16778. EXPECT_TRUE(uc.host.empty());
  16779. }
  16780. {
  16781. detail::UrlComponents uc;
  16782. ASSERT_TRUE(detail::parse_url("", uc));
  16783. EXPECT_TRUE(uc.host.empty());
  16784. EXPECT_TRUE(uc.path.empty());
  16785. }
  16786. {
  16787. detail::UrlComponents uc;
  16788. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16789. }
  16790. {
  16791. detail::UrlComponents uc;
  16792. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16793. }
  16794. {
  16795. // Accepted by parse_url; callers restrict to http/https
  16796. detail::UrlComponents uc;
  16797. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16798. EXPECT_EQ("ftp", uc.scheme);
  16799. }
  16800. {
  16801. detail::UrlComponents uc;
  16802. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16803. }
  16804. {
  16805. detail::UrlComponents uc;
  16806. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16807. }
  16808. }
  16809. TEST(ParseUrlTest, FragmentHandling) {
  16810. {
  16811. detail::UrlComponents uc;
  16812. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16813. EXPECT_EQ("/path", uc.path);
  16814. EXPECT_TRUE(uc.query.empty());
  16815. }
  16816. {
  16817. detail::UrlComponents uc;
  16818. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16819. EXPECT_TRUE(uc.path.empty());
  16820. EXPECT_TRUE(uc.query.empty());
  16821. }
  16822. }
  16823. TEST(ParseUrlTest, UserinfoHandling) {
  16824. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16825. // parsers would see evil.com as the host.
  16826. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16827. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16828. for (auto url : urls) {
  16829. detail::UrlComponents uc;
  16830. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16831. }
  16832. }
  16833. TEST(ParseUrlTest, IPv6EdgeCases) {
  16834. {
  16835. detail::UrlComponents uc;
  16836. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16837. EXPECT_TRUE(uc.scheme.empty());
  16838. EXPECT_EQ("::1", uc.host);
  16839. EXPECT_EQ("8080", uc.port);
  16840. }
  16841. {
  16842. // Zone ID '%25' is not in [a-fA-F0-9:]
  16843. detail::UrlComponents uc;
  16844. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16845. }
  16846. }
  16847. TEST(ParseUrlTest, SchemeEdgeCases) {
  16848. {
  16849. detail::UrlComponents uc;
  16850. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16851. }
  16852. {
  16853. detail::UrlComponents uc;
  16854. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16855. }
  16856. {
  16857. detail::UrlComponents uc;
  16858. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16859. }
  16860. }
  16861. TEST(ParseUrlTest, PortEdgeCases) {
  16862. {
  16863. detail::UrlComponents uc;
  16864. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16865. EXPECT_TRUE(uc.port.empty());
  16866. EXPECT_EQ("/path", uc.path);
  16867. }
  16868. {
  16869. // parse_url accepts any port string; validation is done by parse_port
  16870. detail::UrlComponents uc;
  16871. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16872. EXPECT_EQ("abc", uc.port);
  16873. }
  16874. }
  16875. TEST(ParseUrlTest, WebSocketPatterns) {
  16876. {
  16877. detail::UrlComponents uc;
  16878. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16879. EXPECT_EQ("ws", uc.scheme);
  16880. EXPECT_EQ("echo.example.com", uc.host);
  16881. EXPECT_EQ("8080", uc.port);
  16882. EXPECT_EQ("/ws", uc.path);
  16883. }
  16884. {
  16885. detail::UrlComponents uc;
  16886. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16887. EXPECT_EQ("wss", uc.scheme);
  16888. EXPECT_EQ("echo.example.com", uc.host);
  16889. EXPECT_TRUE(uc.port.empty());
  16890. EXPECT_EQ("/ws", uc.path);
  16891. }
  16892. }
  16893. TEST(ParseUrlTest, QueryOnly) {
  16894. detail::UrlComponents uc;
  16895. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16896. EXPECT_TRUE(uc.host.empty());
  16897. EXPECT_TRUE(uc.path.empty());
  16898. EXPECT_EQ("?q=1&r=2", uc.query);
  16899. }
  16900. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16901. detail::UrlComponents uc;
  16902. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16903. EXPECT_TRUE(uc.scheme.empty());
  16904. EXPECT_EQ("example.com", uc.host);
  16905. EXPECT_EQ("443", uc.port);
  16906. EXPECT_EQ("/path", uc.path);
  16907. }
  16908. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16909. // If ipv6 regex working, regex match codepath is taken.
  16910. // else port will default to 80 in Client impl
  16911. int clientImplMagicPort = 80;
  16912. int port = 4321;
  16913. // above ports must be different to avoid false negative
  16914. EXPECT_NE(clientImplMagicPort, port);
  16915. std::string ipV6TestURL = "http://[ff06::c3]";
  16916. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16917. CLIENT_PRIVATE_KEY_FILE);
  16918. EXPECT_EQ(cli.port(), port);
  16919. }
  16920. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16921. auto file_path = "./www/dir/index.html";
  16922. auto dir_path = "./www/dir";
  16923. detail::FileStat stat_file(file_path);
  16924. EXPECT_TRUE(stat_file.is_file());
  16925. EXPECT_FALSE(stat_file.is_dir());
  16926. detail::FileStat stat_dir(dir_path);
  16927. EXPECT_FALSE(stat_dir.is_file());
  16928. EXPECT_TRUE(stat_dir.is_dir());
  16929. }
  16930. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16931. // IPv4 with default HTTP port (80)
  16932. EXPECT_EQ("example.com",
  16933. detail::make_host_and_port_string("example.com", 80, false));
  16934. // IPv4 with default HTTPS port (443)
  16935. EXPECT_EQ("example.com",
  16936. detail::make_host_and_port_string("example.com", 443, true));
  16937. // IPv4 with non-default HTTP port
  16938. EXPECT_EQ("example.com:8080",
  16939. detail::make_host_and_port_string("example.com", 8080, false));
  16940. // IPv4 with non-default HTTPS port
  16941. EXPECT_EQ("example.com:8443",
  16942. detail::make_host_and_port_string("example.com", 8443, true));
  16943. // IPv6 with default HTTP port (80)
  16944. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16945. // IPv6 with default HTTPS port (443)
  16946. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16947. // IPv6 with non-default HTTP port
  16948. EXPECT_EQ("[::1]:8080",
  16949. detail::make_host_and_port_string("::1", 8080, false));
  16950. // IPv6 with non-default HTTPS port
  16951. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16952. // IPv6 full address with default port
  16953. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16954. detail::make_host_and_port_string(
  16955. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16956. // IPv6 full address with non-default port
  16957. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16958. detail::make_host_and_port_string(
  16959. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16960. // IPv6 localhost with non-default port
  16961. EXPECT_EQ("[::1]:3000",
  16962. detail::make_host_and_port_string("::1", 3000, false));
  16963. // IPv6 with zone ID (link-local address) with default port
  16964. EXPECT_EQ("[fe80::1%eth0]",
  16965. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16966. // IPv6 with zone ID (link-local address) with non-default port
  16967. EXPECT_EQ("[fe80::1%eth0]:8080",
  16968. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16969. // Edge case: Port 443 with is_ssl=false (should add port)
  16970. EXPECT_EQ("example.com:443",
  16971. detail::make_host_and_port_string("example.com", 443, false));
  16972. // Edge case: Port 80 with is_ssl=true (should add port)
  16973. EXPECT_EQ("example.com:80",
  16974. detail::make_host_and_port_string("example.com", 80, true));
  16975. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16976. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16977. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16978. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16979. // Security fix: Already bracketed IPv6 should not get double brackets
  16980. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16981. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16982. EXPECT_EQ("[::1]:8080",
  16983. detail::make_host_and_port_string("[::1]", 8080, false));
  16984. EXPECT_EQ("[2001:db8::1]:8080",
  16985. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16986. EXPECT_EQ("[fe80::1%eth0]",
  16987. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16988. EXPECT_EQ("[fe80::1%eth0]:8080",
  16989. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16990. // Edge case: Empty host (should return as-is)
  16991. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16992. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16993. // This is a known limitation but shouldn't crash
  16994. EXPECT_EQ("[host:name]",
  16995. detail::make_host_and_port_string("host:name", 80, false));
  16996. // Port number edge cases (no validation, but should not crash)
  16997. EXPECT_EQ("example.com:0",
  16998. detail::make_host_and_port_string("example.com", 0, false));
  16999. EXPECT_EQ("example.com:-1",
  17000. detail::make_host_and_port_string("example.com", -1, false));
  17001. EXPECT_EQ("example.com:65535",
  17002. detail::make_host_and_port_string("example.com", 65535, false));
  17003. EXPECT_EQ("example.com:65536",
  17004. detail::make_host_and_port_string("example.com", 65536, false));
  17005. }
  17006. #ifdef CPPHTTPLIB_SSL_ENABLED
  17007. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17008. httplib::SSLClient cli("roblox.com", 443);
  17009. cli.set_follow_location(true);
  17010. auto res = cli.Get("/");
  17011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17012. EXPECT_EQ(StatusCode::OK_200, res->status);
  17013. }
  17014. #endif
  17015. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17016. Server svr;
  17017. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17018. EXPECT_EQ(res.status, 400);
  17019. });
  17020. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17021. auto se = detail::scope_exit([&] {
  17022. svr.stop();
  17023. thread.join();
  17024. ASSERT_FALSE(svr.is_running());
  17025. });
  17026. svr.wait_until_ready();
  17027. Client cli(HOST, PORT);
  17028. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17029. }
  17030. TEST(InvalidHeaderCharsTest, is_field_name) {
  17031. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17032. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17033. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17034. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17035. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17036. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17037. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17038. EXPECT_FALSE(detail::fields::is_field_name(""));
  17039. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17040. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17041. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17042. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17043. }
  17044. TEST(InvalidHeaderCharsTest, is_field_value) {
  17045. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17046. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17047. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17048. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17049. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17050. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17051. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17052. EXPECT_TRUE(detail::fields::is_field_value(""));
  17053. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17054. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17055. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17056. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17057. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17058. }
  17059. TEST(InvalidHeaderCharsTest, OnServer) {
  17060. Server svr;
  17061. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17062. std::string header = "Not Set";
  17063. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17064. res.set_header(header, "value");
  17065. res.set_content("Page Content Page Content", "text/plain");
  17066. });
  17067. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17068. std::string header = "Not Set";
  17069. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17070. res.set_header("X-Test", header);
  17071. res.set_content("Page Content Page Content", "text/plain");
  17072. });
  17073. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17074. auto se = detail::scope_exit([&] {
  17075. svr.stop();
  17076. thread.join();
  17077. ASSERT_FALSE(svr.is_running());
  17078. });
  17079. svr.wait_until_ready();
  17080. Client cli(HOST, PORT);
  17081. {
  17082. auto res = cli.Get(
  17083. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17085. EXPECT_EQ("Page Content Page Content", res->body);
  17086. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17087. }
  17088. {
  17089. auto res = cli.Get(
  17090. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17092. EXPECT_EQ("Page Content Page Content", res->body);
  17093. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17094. }
  17095. }
  17096. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17097. auto handled = false;
  17098. Server svr;
  17099. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17100. thread t = thread([&] { svr.listen(HOST, PORT); });
  17101. auto se = detail::scope_exit([&] {
  17102. svr.stop();
  17103. t.join();
  17104. ASSERT_FALSE(svr.is_running());
  17105. ASSERT_FALSE(handled);
  17106. });
  17107. svr.wait_until_ready();
  17108. auto req = "POST /test HTTP/1.1\r\n"
  17109. "Content-Length: x\r\n"
  17110. "\r\n";
  17111. std::string response;
  17112. ASSERT_TRUE(send_request(1, req, &response));
  17113. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17114. response.substr(0, response.find("\r\n")));
  17115. }
  17116. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17117. // case-insensitive, and a server that receives a 100-continue expectation in
  17118. // an HTTP/1.0 request MUST ignore it.
  17119. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17120. std::string response;
  17121. ASSERT_TRUE(send_request(1, req, &response, port));
  17122. *got_100 = response.find("100 Continue") != std::string::npos;
  17123. }
  17124. class ExpectTokenTest : public ::testing::Test {
  17125. protected:
  17126. void SetUp() override {
  17127. svr_.Post("/p", [](const Request &, Response &res) {
  17128. res.set_content("ok", "text/plain");
  17129. });
  17130. port_ = svr_.bind_to_any_port(HOST);
  17131. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17132. svr_.wait_until_ready();
  17133. }
  17134. void TearDown() override {
  17135. svr_.stop();
  17136. if (thread_.joinable()) { thread_.join(); }
  17137. }
  17138. std::string request(const char *version, const char *expect_value) const {
  17139. return std::string("POST /p ") + version +
  17140. "\r\n"
  17141. "Host: localhost\r\n"
  17142. "Content-Length: 2\r\n"
  17143. "Connection: close\r\n"
  17144. "Expect: " +
  17145. expect_value +
  17146. "\r\n"
  17147. "\r\n"
  17148. "hi";
  17149. }
  17150. Server svr_;
  17151. int port_ = 0;
  17152. thread thread_;
  17153. };
  17154. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17155. bool got_100 = false;
  17156. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17157. EXPECT_TRUE(got_100);
  17158. }
  17159. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17160. bool got_100 = true;
  17161. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17162. EXPECT_FALSE(got_100);
  17163. }
  17164. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17165. bool got_100 = false;
  17166. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17167. EXPECT_TRUE(got_100);
  17168. }
  17169. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17170. bool got_100 = false;
  17171. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17172. EXPECT_TRUE(got_100);
  17173. }
  17174. // `100 Continue` is sent only when the server starts reading the body, so a
  17175. // request rejected before that never invites the client to send it. The
  17176. // requests below carry the expectation but withhold the body, as a client
  17177. // waiting for `100 Continue` would.
  17178. // A POST that expects `100 Continue` and withholds its two-byte body.
  17179. static std::string expect_headers_only(const std::string &path) {
  17180. return "POST " + path +
  17181. " HTTP/1.1\r\n"
  17182. "Host: localhost\r\n"
  17183. "Content-Length: 2\r\n"
  17184. "Expect: 100-continue\r\n"
  17185. "\r\n";
  17186. }
  17187. class ExpectLazyContinueTest : public ::testing::Test {
  17188. protected:
  17189. void SetUp() override {
  17190. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17191. if (req.path == "/pre-routing") {
  17192. res.status = StatusCode::Unauthorized_401;
  17193. return Server::HandlerResponse::Handled;
  17194. }
  17195. return Server::HandlerResponse::Unhandled;
  17196. });
  17197. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17198. if (req.matched_route == "/pre-request") {
  17199. res.status = StatusCode::Forbidden_403;
  17200. return Server::HandlerResponse::Handled;
  17201. }
  17202. return Server::HandlerResponse::Unhandled;
  17203. });
  17204. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17205. res.set_content("ok", "text/plain");
  17206. });
  17207. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17208. res.set_content("ok", "text/plain");
  17209. });
  17210. svr_.Post("/reader-used", [](const Request &, Response &res,
  17211. const ContentReader &content_reader) {
  17212. std::string body;
  17213. content_reader([&](const char *data, size_t len) {
  17214. body.append(data, len);
  17215. return true;
  17216. });
  17217. res.set_content(body, "text/plain");
  17218. });
  17219. svr_.Post("/reader-unused",
  17220. [](const Request &, Response &res, const ContentReader &) {
  17221. res.set_content("ignored", "text/plain");
  17222. });
  17223. port_ = svr_.bind_to_any_port(HOST);
  17224. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17225. svr_.wait_until_ready();
  17226. }
  17227. void TearDown() override {
  17228. svr_.stop();
  17229. if (thread_.joinable()) { thread_.join(); }
  17230. }
  17231. // Sends `req` and reads until the server closes the connection. Returns
  17232. // false if the read had to wait for the client-side timeout instead.
  17233. bool send_until_closed(const std::string &req, std::string *resp) const {
  17234. auto start = std::chrono::steady_clock::now();
  17235. if (!send_request(3, req, resp, port_)) { return false; }
  17236. auto elapsed = std::chrono::steady_clock::now() - start;
  17237. return elapsed < std::chrono::seconds(2);
  17238. }
  17239. // The final response comes without `100 Continue`, and the server closes
  17240. // the connection since the body may or may not follow.
  17241. void expect_final_without_interim(const std::string &path,
  17242. const char *status_line) const {
  17243. std::string resp;
  17244. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17245. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17246. EXPECT_EQ(0u, resp.find(status_line));
  17247. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17248. }
  17249. Server svr_;
  17250. int port_ = 0;
  17251. thread thread_;
  17252. };
  17253. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17254. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17255. }
  17256. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17257. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17258. }
  17259. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17260. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17261. }
  17262. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17263. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17264. }
  17265. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17266. // The body follows once `100 Continue` has had time to arrive.
  17267. auto req = expect_headers_only("/reader-used");
  17268. req.insert(req.size() - 2, "Connection: close\r\n");
  17269. std::string resp;
  17270. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17271. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17272. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17273. EXPECT_NE(std::string::npos, resp.find("hi"));
  17274. }
  17275. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17276. // Large enough for the client to add `Expect: 100-continue` itself.
  17277. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17278. std::atomic<bool> body_sent{false};
  17279. Client cli(HOST, port_);
  17280. auto res = cli.Post(
  17281. "/pre-request", length,
  17282. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17283. body_sent = true;
  17284. std::string chunk(len, 'x');
  17285. sink.write(chunk.data(), chunk.size());
  17286. return true;
  17287. },
  17288. "application/octet-stream");
  17289. ASSERT_TRUE(res);
  17290. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17291. EXPECT_FALSE(body_sent);
  17292. }
  17293. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17294. Server svr;
  17295. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17296. return StatusCode::ExpectationFailed_417;
  17297. });
  17298. svr.Post("/p", [](const Request &, Response &res) {
  17299. res.set_content("ok", "text/plain");
  17300. });
  17301. auto port = svr.bind_to_any_port(HOST);
  17302. thread t = thread([&] { svr.listen_after_bind(); });
  17303. auto se = detail::scope_exit([&] {
  17304. svr.stop();
  17305. t.join();
  17306. });
  17307. svr.wait_until_ready();
  17308. std::string resp;
  17309. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17310. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17311. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17312. // Exactly one response: the route handler must not run after the 417.
  17313. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17314. }
  17315. #ifndef _WIN32
  17316. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17317. static constexpr char reject[] = "Unauthorized";
  17318. static constexpr char accept[] = "Upload accepted";
  17319. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17320. Server svr;
  17321. svr.set_expect_100_continue_handler(
  17322. [](const Request & /*req*/, Response &res) {
  17323. res.status = StatusCode::Unauthorized_401;
  17324. res.set_content(reject, "text/plain");
  17325. return res.status;
  17326. });
  17327. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17328. res.set_content(accept, "text/plain");
  17329. });
  17330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17331. auto se = detail::scope_exit([&] {
  17332. svr.stop();
  17333. thread.join();
  17334. ASSERT_FALSE(svr.is_running());
  17335. });
  17336. svr.wait_until_ready();
  17337. {
  17338. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17339. curl_easy_init(), &curl_easy_cleanup};
  17340. ASSERT_NE(curl, nullptr);
  17341. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17342. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17343. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17344. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17345. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17346. &curl_slist_free_all};
  17347. ASSERT_NE(list, nullptr);
  17348. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17349. struct read_data {
  17350. size_t read_size;
  17351. size_t total_size;
  17352. } data = {0, total_size};
  17353. using read_callback_t =
  17354. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17355. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17356. void *userdata) -> size_t {
  17357. read_data *d = (read_data *)userdata;
  17358. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17359. std::fill_n(ptr, size * nmemb, 'A');
  17360. d->read_size += size * nmemb;
  17361. return size * nmemb;
  17362. };
  17363. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17364. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17365. std::vector<char> buffer;
  17366. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17367. using write_callback_t =
  17368. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17369. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17370. void *userdata) -> size_t {
  17371. std::vector<char> *buf = (std::vector<char> *)userdata;
  17372. buf->reserve(buf->size() + size * nmemb + 1);
  17373. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17374. return size * nmemb;
  17375. };
  17376. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17377. {
  17378. const auto res = curl_easy_perform(curl.get());
  17379. ASSERT_EQ(res, CURLE_OK);
  17380. }
  17381. {
  17382. auto response_code = long{};
  17383. const auto res =
  17384. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17385. ASSERT_EQ(res, CURLE_OK);
  17386. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17387. }
  17388. {
  17389. auto dl = curl_off_t{};
  17390. const auto res =
  17391. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17392. ASSERT_EQ(res, CURLE_OK);
  17393. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17394. }
  17395. {
  17396. buffer.push_back('\0');
  17397. ASSERT_STRCASEEQ(buffer.data(), reject);
  17398. }
  17399. }
  17400. }
  17401. #endif
  17402. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17403. // Regression test for #2458.
  17404. //
  17405. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17406. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17407. // ticket can make the client socket spuriously readable during the
  17408. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17409. // the client withholds the body and then blocks reading a response that never
  17410. // comes, failing with `Failed to read connection`.
  17411. //
  17412. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17413. // within the timeout. This raw OpenSSL server deliberately never sends
  17414. // `100 Continue`; the client must still deliver the body and receive 200.
  17415. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17416. signal(SIGPIPE, SIG_IGN);
  17417. const auto port = PORT + 4;
  17418. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17419. ASSERT_NE(srv, INVALID_SOCKET);
  17420. int opt = 1;
  17421. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17422. sockaddr_in addr{};
  17423. addr.sin_family = AF_INET;
  17424. addr.sin_port = htons(static_cast<uint16_t>(port));
  17425. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17426. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17427. ASSERT_EQ(0, ::listen(srv, 1));
  17428. std::atomic<size_t> server_body_bytes{0};
  17429. auto server_thread = std::thread([&] {
  17430. sockaddr_in cli_addr{};
  17431. socklen_t cli_len = sizeof(cli_addr);
  17432. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17433. if (cli == INVALID_SOCKET) { return; }
  17434. // Bound the lifetime of the server side so a buggy client (which never
  17435. // sends the body) cannot make this thread block forever on join.
  17436. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17437. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17438. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17439. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17440. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17441. SSL *ssl = SSL_new(ctx);
  17442. SSL_set_fd(ssl, static_cast<int>(cli));
  17443. if (SSL_accept(ssl) > 0) {
  17444. // Read the request headers. Reading here also flushes the TLS 1.3
  17445. // session tickets to the client. Deliberately do NOT send
  17446. // `100 Continue`.
  17447. std::string buf;
  17448. char tmp[1024];
  17449. while (buf.find("\r\n\r\n") == std::string::npos) {
  17450. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17451. if (n <= 0) { break; }
  17452. buf.append(tmp, static_cast<size_t>(n));
  17453. }
  17454. // A correct client sends the body now; count what arrives.
  17455. auto pos = buf.find("\r\n\r\n");
  17456. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17457. while (body < 4096) {
  17458. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17459. if (n <= 0) { break; }
  17460. body += static_cast<size_t>(n);
  17461. }
  17462. server_body_bytes = body;
  17463. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17464. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17465. SSL_shutdown(ssl);
  17466. }
  17467. SSL_free(ssl);
  17468. detail::close_socket(cli);
  17469. SSL_CTX_free(ctx);
  17470. });
  17471. auto se = detail::scope_exit([&] {
  17472. server_thread.join();
  17473. detail::close_socket(srv);
  17474. });
  17475. SSLClient cli("127.0.0.1", port);
  17476. cli.enable_server_certificate_verification(false);
  17477. cli.set_connection_timeout(5, 0);
  17478. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17479. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17480. std::string body(4096, 'A');
  17481. auto res = cli.Put("/api/test", body, "application/json");
  17482. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17483. EXPECT_EQ(StatusCode::OK_200, res->status);
  17484. EXPECT_EQ(body.size(), server_body_bytes.load());
  17485. }
  17486. #endif
  17487. template <typename S, typename C>
  17488. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17489. svr.Get("/stream", [&](const Request &, Response &res) {
  17490. auto data = new std::string("01234567890123456789");
  17491. res.set_content_provider(
  17492. data->size(), "text/plain",
  17493. [&, data](size_t offset, size_t length, DataSink &sink) {
  17494. const size_t DATA_CHUNK_SIZE = 4;
  17495. const auto &d = *data;
  17496. std::this_thread::sleep_for(std::chrono::seconds(1));
  17497. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17498. return true;
  17499. },
  17500. [data](bool success) {
  17501. EXPECT_FALSE(success);
  17502. delete data;
  17503. });
  17504. });
  17505. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17506. auto i = new size_t(0);
  17507. res.set_content_provider(
  17508. "text/plain",
  17509. [i](size_t, DataSink &sink) {
  17510. if (*i < 5) {
  17511. std::this_thread::sleep_for(std::chrono::seconds(1));
  17512. sink.write("abcd", 4);
  17513. (*i)++;
  17514. } else {
  17515. sink.done();
  17516. }
  17517. return true;
  17518. },
  17519. [i](bool success) {
  17520. EXPECT_FALSE(success);
  17521. delete i;
  17522. });
  17523. });
  17524. svr.Get("/chunked", [&](const Request &, Response &res) {
  17525. auto i = new size_t(0);
  17526. res.set_chunked_content_provider(
  17527. "text/plain",
  17528. [i](size_t, DataSink &sink) {
  17529. if (*i < 5) {
  17530. std::this_thread::sleep_for(std::chrono::seconds(1));
  17531. sink.os << "abcd";
  17532. (*i)++;
  17533. } else {
  17534. sink.done();
  17535. }
  17536. return true;
  17537. },
  17538. [i](bool success) {
  17539. EXPECT_FALSE(success);
  17540. delete i;
  17541. });
  17542. });
  17543. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17544. auto se = detail::scope_exit([&] {
  17545. svr.stop();
  17546. listen_thread.join();
  17547. ASSERT_FALSE(svr.is_running());
  17548. });
  17549. svr.wait_until_ready();
  17550. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17551. {
  17552. auto start = std::chrono::steady_clock::now();
  17553. auto res = cli.Get("/stream");
  17554. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17555. std::chrono::steady_clock::now() - start)
  17556. .count();
  17557. ASSERT_FALSE(res);
  17558. EXPECT_EQ(Error::Read, res.error());
  17559. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17560. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17561. }
  17562. {
  17563. auto start = std::chrono::steady_clock::now();
  17564. auto res = cli.Get("/stream_without_length");
  17565. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17566. std::chrono::steady_clock::now() - start)
  17567. .count();
  17568. ASSERT_FALSE(res);
  17569. EXPECT_EQ(Error::Read, res.error());
  17570. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17571. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17572. }
  17573. {
  17574. auto start = std::chrono::steady_clock::now();
  17575. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17576. EXPECT_EQ("abcd", string(data, data_length));
  17577. return true;
  17578. });
  17579. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17580. std::chrono::steady_clock::now() - start)
  17581. .count();
  17582. ASSERT_FALSE(res);
  17583. EXPECT_EQ(Error::Read, res.error());
  17584. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17585. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17586. }
  17587. }
  17588. TEST(MaxTimeoutTest, ContentStream) {
  17589. time_t timeout = 2000;
  17590. time_t threshold = 200;
  17591. Server svr;
  17592. Client cli("localhost", PORT);
  17593. max_timeout_test(svr, cli, timeout, threshold);
  17594. }
  17595. #ifdef CPPHTTPLIB_SSL_ENABLED
  17596. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17597. time_t timeout = 2000;
  17598. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17599. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17600. SSLClient cli("localhost", PORT);
  17601. cli.enable_server_certificate_verification(false);
  17602. max_timeout_test(svr, cli, timeout, threshold);
  17603. }
  17604. #endif
  17605. class EventDispatcher {
  17606. public:
  17607. EventDispatcher() {}
  17608. bool wait_event(DataSink *sink) {
  17609. unique_lock<mutex> lk(m_);
  17610. int id = id_;
  17611. // Wait with timeout to prevent hanging if client disconnects
  17612. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17613. [&] { return cid_ == id; })) {
  17614. return false; // Timeout occurred
  17615. }
  17616. sink->write(message_.data(), message_.size());
  17617. return true;
  17618. }
  17619. void send_event(const string &message) {
  17620. lock_guard<mutex> lk(m_);
  17621. cid_ = id_++;
  17622. message_ = message;
  17623. cv_.notify_all();
  17624. }
  17625. private:
  17626. mutex m_;
  17627. condition_variable cv_;
  17628. atomic_int id_{0};
  17629. atomic_int cid_{-1};
  17630. string message_;
  17631. };
  17632. TEST(ClientInThreadTest, Issue2068) {
  17633. EventDispatcher ed;
  17634. Server svr;
  17635. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17636. res.set_chunked_content_provider("text/event-stream",
  17637. [&](size_t /*offset*/, DataSink &sink) {
  17638. return ed.wait_event(&sink);
  17639. });
  17640. });
  17641. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17642. svr.wait_until_ready();
  17643. thread event_thread([&] {
  17644. int id = 0;
  17645. while (svr.is_running()) {
  17646. this_thread::sleep_for(chrono::milliseconds(500));
  17647. std::stringstream ss;
  17648. ss << "data: " << id << "\n\n";
  17649. ed.send_event(ss.str());
  17650. id++;
  17651. }
  17652. });
  17653. auto se = detail::scope_exit([&] {
  17654. svr.stop();
  17655. listen_thread.join();
  17656. event_thread.join();
  17657. ASSERT_FALSE(svr.is_running());
  17658. });
  17659. {
  17660. auto client = detail::make_unique<Client>(HOST, PORT);
  17661. client->set_read_timeout(std::chrono::minutes(10));
  17662. std::atomic<bool> stop{false};
  17663. std::thread t([&] {
  17664. client->Get("/event1",
  17665. [&](const char *, size_t) -> bool { return !stop; });
  17666. });
  17667. std::this_thread::sleep_for(std::chrono::seconds(2));
  17668. stop = true;
  17669. client->stop();
  17670. t.join();
  17671. // Reset client after thread has finished
  17672. client.reset();
  17673. }
  17674. }
  17675. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17676. auto handled = false;
  17677. Server svr;
  17678. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17679. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17680. auto se = detail::scope_exit([&] {
  17681. svr.stop();
  17682. t.join();
  17683. ASSERT_FALSE(svr.is_running());
  17684. ASSERT_FALSE(handled);
  17685. });
  17686. svr.wait_until_ready();
  17687. // Two Content-Length headers with different values — must be rejected
  17688. auto req = "POST /test HTTP/1.1\r\n"
  17689. "Content-Length: 5\r\n"
  17690. "Content-Length: 10\r\n"
  17691. "\r\n"
  17692. "hello";
  17693. std::string response;
  17694. ASSERT_TRUE(send_request(1, req, &response));
  17695. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17696. response.substr(0, response.find("\r\n")));
  17697. }
  17698. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17699. auto handled = false;
  17700. Server svr;
  17701. svr.Post("/test", [&](const Request &, Response &res) {
  17702. handled = true;
  17703. res.set_content("ok", "text/plain");
  17704. });
  17705. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17706. auto se = detail::scope_exit([&] {
  17707. svr.stop();
  17708. t.join();
  17709. ASSERT_FALSE(svr.is_running());
  17710. ASSERT_TRUE(handled);
  17711. });
  17712. svr.wait_until_ready();
  17713. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17714. auto req = "POST /test HTTP/1.1\r\n"
  17715. "Host: localhost\r\n"
  17716. "Content-Length: 5\r\n"
  17717. "Content-Length: 5\r\n"
  17718. "\r\n"
  17719. "hello";
  17720. std::string response;
  17721. ASSERT_TRUE(send_request(1, req, &response));
  17722. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17723. }
  17724. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17725. Server svr;
  17726. svr.Get("/test", [](const Request &, Response &res) {
  17727. res.set_content("ok", "text/plain");
  17728. });
  17729. auto port = svr.bind_to_any_port(HOST);
  17730. thread t = thread([&] { svr.listen_after_bind(); });
  17731. auto se = detail::scope_exit([&] {
  17732. svr.stop();
  17733. t.join();
  17734. ASSERT_FALSE(svr.is_running());
  17735. });
  17736. svr.wait_until_ready();
  17737. auto status_line = [&](const std::string &host_lines) {
  17738. std::string res;
  17739. send_request(
  17740. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17741. &res, port);
  17742. return res.substr(0, res.find("\r\n"));
  17743. };
  17744. const char *accepted[] = {
  17745. "Host: localhost\r\n",
  17746. "Host: a.example:8080\r\n",
  17747. "Host: my_service\r\n",
  17748. "Host: [::1]:8080\r\n",
  17749. "Host: [fe80::1%25eth0]\r\n",
  17750. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17751. };
  17752. for (auto host_lines : accepted) {
  17753. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17754. }
  17755. const char *rejected[] = {
  17756. "Host: a.example\r\nHost: b.example\r\n",
  17757. "Host: a.example\r\nHost: a.example\r\n",
  17758. "Host: a@b.example\r\n",
  17759. "Host: a.example/b\r\n",
  17760. "Host: a.example\\b\r\n",
  17761. "Host: a.example?b\r\n",
  17762. "Host: a.example#b\r\n",
  17763. "Host: a.example b.example\r\n",
  17764. };
  17765. for (auto host_lines : rejected) {
  17766. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17767. << host_lines;
  17768. }
  17769. }
  17770. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17771. Server svr;
  17772. svr.Get("/", [](const Request &req, Response &res) {
  17773. EXPECT_EQ(2U, req.trailers.size());
  17774. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17775. // Denied
  17776. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17777. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17778. // Accepted
  17779. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17780. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17781. EXPECT_TRUE(req.has_trailer("X-World"));
  17782. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17783. res.set_content("ok", "text/plain");
  17784. });
  17785. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17786. auto se = detail::scope_exit([&] {
  17787. svr.stop();
  17788. t.join();
  17789. ASSERT_FALSE(svr.is_running());
  17790. });
  17791. svr.wait_until_ready();
  17792. const std::string req = "GET / HTTP/1.1\r\n"
  17793. "Transfer-Encoding: chunked\r\n"
  17794. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17795. "\r\n"
  17796. "0\r\n"
  17797. "Content-Length: 10\r\n"
  17798. "Host: internal.local\r\n"
  17799. "Content-Type: malicious/content\r\n"
  17800. "Cookie: any\r\n"
  17801. "Set-Cookie: any\r\n"
  17802. "X-Forwarded-For: attacker.com\r\n"
  17803. "X-Real-Ip: 1.1.1.1\r\n"
  17804. "X-Hello: hello\r\n"
  17805. "X-World: world\r\n"
  17806. "\r\n";
  17807. std::string res;
  17808. ASSERT_TRUE(send_request(1, req, &res));
  17809. }
  17810. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17811. // several field lines, and the combined value is what has to be parsed. A
  17812. // Trailer field split across lines therefore declares every name it lists;
  17813. // reading only the first line silently drops the trailers the later lines
  17814. // declare. The prohibited-trailer filter still applies to every line.
  17815. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17816. Server svr;
  17817. size_t observed_trailer_count = 0;
  17818. std::string observed_hello;
  17819. std::string observed_world;
  17820. bool observed_content_length = true;
  17821. svr.Get("/", [&](const Request &req, Response &res) {
  17822. observed_trailer_count = req.trailers.size();
  17823. observed_hello = req.get_trailer_value("X-Hello");
  17824. observed_world = req.get_trailer_value("X-World");
  17825. observed_content_length = req.has_trailer("Content-Length");
  17826. res.set_content("ok", "text/plain");
  17827. });
  17828. auto port = svr.bind_to_any_port(HOST);
  17829. thread t = thread([&]() { svr.listen_after_bind(); });
  17830. auto se = detail::scope_exit([&] {
  17831. svr.stop();
  17832. t.join();
  17833. ASSERT_FALSE(svr.is_running());
  17834. });
  17835. svr.wait_until_ready();
  17836. const std::string req = "GET / HTTP/1.1\r\n"
  17837. "Host: localhost\r\n"
  17838. "Transfer-Encoding: chunked\r\n"
  17839. "Trailer: X-Hello\r\n"
  17840. "Trailer: X-World, Content-Length\r\n"
  17841. "\r\n"
  17842. "0\r\n"
  17843. "X-Hello: hello\r\n"
  17844. "X-World: world\r\n"
  17845. "Content-Length: 10\r\n"
  17846. "\r\n";
  17847. std::string res;
  17848. ASSERT_TRUE(send_request(1, req, &res, port));
  17849. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17850. // Accepted: both field lines contribute to the declared set
  17851. EXPECT_EQ(2U, observed_trailer_count);
  17852. EXPECT_EQ(observed_hello, "hello");
  17853. EXPECT_EQ(observed_world, "world");
  17854. // Denied: a prohibited name stays prohibited on a later field line
  17855. EXPECT_FALSE(observed_content_length);
  17856. }
  17857. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17858. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17859. // unbounded run of fields that are never declared, because the counter would
  17860. // only advance for declared fields.
  17861. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17862. Server svr;
  17863. bool handler_called = false;
  17864. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17865. handler_called = true;
  17866. res.set_content("ok", "text/plain");
  17867. });
  17868. auto port = svr.bind_to_any_port(HOST);
  17869. thread t = thread([&]() { svr.listen_after_bind(); });
  17870. auto se = detail::scope_exit([&] {
  17871. svr.stop();
  17872. t.join();
  17873. ASSERT_FALSE(svr.is_running());
  17874. });
  17875. svr.wait_until_ready();
  17876. // Declare nothing, then send far more undeclared trailer fields than the
  17877. // header-count limit. Parsing must stop and reject the request rather than
  17878. // read every line.
  17879. std::string req = "GET / HTTP/1.1\r\n"
  17880. "Transfer-Encoding: chunked\r\n"
  17881. "\r\n"
  17882. "0\r\n";
  17883. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17884. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17885. }
  17886. req += "\r\n";
  17887. std::string res;
  17888. ASSERT_TRUE(send_request(1, req, &res, port));
  17889. // The request is rejected before the handler runs.
  17890. EXPECT_FALSE(handler_called);
  17891. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17892. }
  17893. // The set of declared trailer names is capped so a peer cannot grow it without
  17894. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17895. // declared past the cap is not honored, even if the field is actually sent.
  17896. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17897. Server svr;
  17898. // One name inside the cap and one past it, so the test tracks the cap rather
  17899. // than a fixed count.
  17900. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17901. const std::string within_cap_name = "X-T-0";
  17902. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17903. bool observed_within_cap = false;
  17904. bool observed_past_cap = false;
  17905. svr.Get("/", [&](const Request &req, Response &res) {
  17906. observed_within_cap = req.has_trailer(within_cap_name);
  17907. observed_past_cap = req.has_trailer(past_cap_name);
  17908. res.set_content("ok", "text/plain");
  17909. });
  17910. auto port = svr.bind_to_any_port(HOST);
  17911. thread t = thread([&]() { svr.listen_after_bind(); });
  17912. auto se = detail::scope_exit([&] {
  17913. svr.stop();
  17914. t.join();
  17915. ASSERT_FALSE(svr.is_running());
  17916. });
  17917. svr.wait_until_ready();
  17918. // Declare more trailer names than the cap in a single Trailer field, then
  17919. // actually send the first (within the cap) and the last (past it).
  17920. std::string trailer_decl = "Trailer: ";
  17921. for (int i = 0; i < declared_count; i++) {
  17922. if (i != 0) { trailer_decl += ", "; }
  17923. trailer_decl += "X-T-" + std::to_string(i);
  17924. }
  17925. trailer_decl += "\r\n";
  17926. const std::string req = "GET / HTTP/1.1\r\n"
  17927. "Host: localhost\r\n"
  17928. "Transfer-Encoding: chunked\r\n" +
  17929. trailer_decl +
  17930. "\r\n"
  17931. "0\r\n" +
  17932. within_cap_name + ": a\r\n" + past_cap_name +
  17933. ": b\r\n"
  17934. "\r\n";
  17935. std::string res;
  17936. ASSERT_TRUE(send_request(1, req, &res, port));
  17937. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17938. // A name within the cap is honored; one declared past the cap is dropped.
  17939. EXPECT_TRUE(observed_within_cap);
  17940. EXPECT_FALSE(observed_past_cap);
  17941. }
  17942. // A direct client that is not listed in trusted_proxies must not be able to
  17943. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17944. // the peer address on the actual TCP connection determines whether the
  17945. // header is honored.
  17946. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17947. Server svr;
  17948. // Deliberately does NOT include the loopback address the test client
  17949. // actually connects from, so the direct connection is not a trusted proxy.
  17950. svr.set_trusted_proxies({"203.0.113.66"});
  17951. std::string observed_remote_addr;
  17952. svr.Get("/ip", [&](const Request &req, Response &res) {
  17953. observed_remote_addr = req.remote_addr;
  17954. res.set_content("ok", "text/plain");
  17955. });
  17956. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17957. auto se = detail::scope_exit([&] {
  17958. svr.stop();
  17959. t.join();
  17960. ASSERT_FALSE(svr.is_running());
  17961. });
  17962. svr.wait_until_ready();
  17963. Client cli(HOST, PORT);
  17964. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17966. EXPECT_EQ(StatusCode::OK_200, res->status);
  17967. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17968. // ignored entirely and the real connection-level address retained.
  17969. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17970. observed_remote_addr == "127.0.0.1");
  17971. }
  17972. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17973. Server svr;
  17974. std::string observed_remote_addr;
  17975. std::string observed_xff;
  17976. svr.Get("/ip", [&](const Request &req, Response &res) {
  17977. observed_remote_addr = req.remote_addr;
  17978. observed_xff = req.get_header_value("X-Forwarded-For");
  17979. res.set_content("ok", "text/plain");
  17980. });
  17981. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17982. auto se = detail::scope_exit([&] {
  17983. svr.stop();
  17984. t.join();
  17985. ASSERT_FALSE(svr.is_running());
  17986. });
  17987. svr.wait_until_ready();
  17988. Client cli(HOST, PORT);
  17989. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17991. EXPECT_EQ(StatusCode::OK_200, res->status);
  17992. EXPECT_EQ(observed_xff, "203.0.113.66");
  17993. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17994. observed_remote_addr == "127.0.0.1");
  17995. }
  17996. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17997. Server svr;
  17998. svr.set_trusted_proxies({"203.0.113.66"});
  17999. std::string observed_remote_addr;
  18000. std::string observed_xff;
  18001. svr.Get("/ip", [&](const Request &req, Response &res) {
  18002. observed_remote_addr = req.remote_addr;
  18003. observed_xff = req.get_header_value("X-Forwarded-For");
  18004. res.set_content("ok", "text/plain");
  18005. });
  18006. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18007. auto se = detail::scope_exit([&] {
  18008. svr.stop();
  18009. t.join();
  18010. ASSERT_FALSE(svr.is_running());
  18011. });
  18012. svr.wait_until_ready();
  18013. Client cli(HOST, PORT);
  18014. auto res = cli.Get("/ip");
  18015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18016. EXPECT_EQ(StatusCode::OK_200, res->status);
  18017. EXPECT_EQ(observed_xff, "");
  18018. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18019. observed_remote_addr == "127.0.0.1");
  18020. }
  18021. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18022. Server svr;
  18023. // Include the loopback address the test client actually connects from, so
  18024. // the direct connection itself is recognized as the trusted proxy hop.
  18025. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18026. std::string observed_remote_addr;
  18027. std::string observed_xff;
  18028. svr.Get("/ip", [&](const Request &req, Response &res) {
  18029. observed_remote_addr = req.remote_addr;
  18030. observed_xff = req.get_header_value("X-Forwarded-For");
  18031. res.set_content("ok", "text/plain");
  18032. });
  18033. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18034. auto se = detail::scope_exit([&] {
  18035. svr.stop();
  18036. t.join();
  18037. ASSERT_FALSE(svr.is_running());
  18038. });
  18039. svr.wait_until_ready();
  18040. Client cli(HOST, PORT);
  18041. auto res = cli.Get(
  18042. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18044. EXPECT_EQ(StatusCode::OK_200, res->status);
  18045. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18046. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18047. }
  18048. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18049. Server svr;
  18050. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18051. std::string observed_remote_addr;
  18052. std::string observed_xff;
  18053. svr.Get("/ip", [&](const Request &req, Response &res) {
  18054. observed_remote_addr = req.remote_addr;
  18055. observed_xff = req.get_header_value("X-Forwarded-For");
  18056. res.set_content("ok", "text/plain");
  18057. });
  18058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18059. auto se = detail::scope_exit([&] {
  18060. svr.stop();
  18061. t.join();
  18062. ASSERT_FALSE(svr.is_running());
  18063. });
  18064. svr.wait_until_ready();
  18065. Client cli(HOST, PORT);
  18066. auto res = cli.Get(
  18067. "/ip",
  18068. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18070. EXPECT_EQ(StatusCode::OK_200, res->status);
  18071. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18072. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18073. }
  18074. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18075. Server svr;
  18076. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18077. std::string observed_remote_addr;
  18078. std::string observed_xff;
  18079. svr.Get("/ip", [&](const Request &req, Response &res) {
  18080. observed_remote_addr = req.remote_addr;
  18081. observed_xff = req.get_header_value("X-Forwarded-For");
  18082. res.set_content("ok", "text/plain");
  18083. });
  18084. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18085. auto se = detail::scope_exit([&] {
  18086. svr.stop();
  18087. t.join();
  18088. ASSERT_FALSE(svr.is_running());
  18089. });
  18090. svr.wait_until_ready();
  18091. Client cli(HOST, PORT);
  18092. auto res = cli.Get(
  18093. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18095. EXPECT_EQ(StatusCode::OK_200, res->status);
  18096. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18097. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18098. // and must not be selected.
  18099. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18100. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18101. }
  18102. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18103. Server svr;
  18104. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18105. std::string observed_remote_addr;
  18106. svr.Get("/ip", [&](const Request &req, Response &res) {
  18107. observed_remote_addr = req.remote_addr;
  18108. res.set_content("ok", "text/plain");
  18109. });
  18110. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18111. auto se = detail::scope_exit([&] {
  18112. svr.stop();
  18113. t.join();
  18114. ASSERT_FALSE(svr.is_running());
  18115. });
  18116. svr.wait_until_ready();
  18117. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18118. // a forged address and the trusted proxy's own address; the forged value must
  18119. // not win over the address the trusted proxy actually recorded.
  18120. Client cli(HOST, PORT);
  18121. auto res = cli.Get(
  18122. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18124. EXPECT_EQ(StatusCode::OK_200, res->status);
  18125. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18126. }
  18127. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18128. Server svr;
  18129. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18130. std::string observed_remote_addr;
  18131. std::string observed_xff;
  18132. svr.Get("/ip", [&](const Request &req, Response &res) {
  18133. observed_remote_addr = req.remote_addr;
  18134. observed_xff = req.get_header_value("X-Forwarded-For");
  18135. res.set_content("ok", "text/plain");
  18136. });
  18137. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18138. auto se = detail::scope_exit([&] {
  18139. svr.stop();
  18140. t.join();
  18141. ASSERT_FALSE(svr.is_running());
  18142. });
  18143. svr.wait_until_ready();
  18144. Client cli(HOST, PORT);
  18145. auto res = cli.Get(
  18146. "/ip",
  18147. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18149. EXPECT_EQ(StatusCode::OK_200, res->status);
  18150. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18151. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18152. }
  18153. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18154. Server svr;
  18155. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18156. std::string observed_remote_addr;
  18157. std::string observed_xff;
  18158. svr.Get("/ip", [&](const Request &req, Response &res) {
  18159. observed_remote_addr = req.remote_addr;
  18160. observed_xff = req.get_header_value("X-Forwarded-For");
  18161. res.set_content("ok", "text/plain");
  18162. });
  18163. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18164. auto se = detail::scope_exit([&] {
  18165. svr.stop();
  18166. t.join();
  18167. ASSERT_FALSE(svr.is_running());
  18168. });
  18169. svr.wait_until_ready();
  18170. std::string raw_req =
  18171. "GET /ip HTTP/1.1\r\n"
  18172. "Host: localhost\r\n"
  18173. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18174. "Connection: close\r\n"
  18175. "\r\n";
  18176. std::string out;
  18177. ASSERT_TRUE(send_request(5, raw_req, &out));
  18178. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18179. // Header parser trims surrounding whitespace of the header value
  18180. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18181. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18182. }
  18183. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18184. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18185. // their own X-Forwarded-For as a separate field line rather than extending the
  18186. // one the client sent, so every occurrence has to be taken into account.
  18187. // Reading only the first one hands back the address the client chose.
  18188. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18189. Server svr;
  18190. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18191. std::string observed_remote_addr;
  18192. size_t observed_xff_count = 0;
  18193. svr.Get("/ip", [&](const Request &req, Response &res) {
  18194. observed_remote_addr = req.remote_addr;
  18195. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18196. res.set_content("ok", "text/plain");
  18197. });
  18198. auto port = svr.bind_to_any_port(HOST);
  18199. thread t = thread([&]() { svr.listen_after_bind(); });
  18200. auto se = detail::scope_exit([&] {
  18201. svr.stop();
  18202. t.join();
  18203. ASSERT_FALSE(svr.is_running());
  18204. });
  18205. svr.wait_until_ready();
  18206. // The client supplies the first field line; the trusted proxy appends the
  18207. // address it observed as a second one.
  18208. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18209. "Host: localhost\r\n"
  18210. "X-Forwarded-For: 1.2.3.4\r\n"
  18211. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18212. "Connection: close\r\n"
  18213. "\r\n";
  18214. std::string out;
  18215. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18216. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18217. EXPECT_EQ(observed_xff_count, 2U);
  18218. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18219. // The same chain spread over one field line per hop derives the same client
  18220. // address, i.e. the split and the comma-joined representations agree.
  18221. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18222. "Host: localhost\r\n"
  18223. "X-Forwarded-For: 1.2.3.4\r\n"
  18224. "X-Forwarded-For: 198.51.100.23\r\n"
  18225. "X-Forwarded-For: 192.0.2.45\r\n"
  18226. "Connection: close\r\n"
  18227. "\r\n";
  18228. out.clear();
  18229. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18230. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18231. EXPECT_EQ(observed_xff_count, 3U);
  18232. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18233. }
  18234. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18235. // crash the server (it used to call front() on an empty vector inside
  18236. // get_client_ip). The connection-level remote address must be retained instead.
  18237. static void run_malformed_xff_test(const std::string &xff_value) {
  18238. Server svr;
  18239. svr.set_trusted_proxies({"192.0.2.45"});
  18240. std::string observed_remote_addr;
  18241. svr.Get("/ip", [&](const Request &req, Response &res) {
  18242. observed_remote_addr = req.remote_addr;
  18243. res.set_content("ok", "text/plain");
  18244. });
  18245. int port = 0;
  18246. thread t = thread([&]() {
  18247. port = svr.bind_to_any_port(HOST);
  18248. svr.listen_after_bind();
  18249. });
  18250. auto se = detail::scope_exit([&] {
  18251. svr.stop();
  18252. t.join();
  18253. ASSERT_FALSE(svr.is_running());
  18254. });
  18255. svr.wait_until_ready();
  18256. Client cli(HOST, port);
  18257. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18259. EXPECT_EQ(StatusCode::OK_200, res->status);
  18260. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18261. observed_remote_addr == "127.0.0.1");
  18262. }
  18263. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18264. run_malformed_xff_test("");
  18265. }
  18266. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18267. run_malformed_xff_test(",");
  18268. }
  18269. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18270. run_malformed_xff_test(", , ,");
  18271. }
  18272. // The same rule applies to Accept: a request whose acceptable types are spread
  18273. // over several field lines must be negotiated against all of them.
  18274. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18275. // case-insensitive connection options. Comparing the whole field value against
  18276. // one option misses a client that sends several of them, and misses every
  18277. // casing but the one written in the comparison.
  18278. //
  18279. // Sends req, reads the response, then reuses the same socket for a second
  18280. // request to find out whether the server kept the connection.
  18281. static void probe_connection_reuse(int port, const std::string &req,
  18282. bool *announced_close, bool *reusable) {
  18283. auto error = Error::Success;
  18284. auto sock = detail::create_client_socket(
  18285. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18286. /*connection_timeout_sec=*/5, 0,
  18287. /*read_timeout_sec=*/1, 0,
  18288. /*write_timeout_sec=*/5, 0, std::string(), error);
  18289. ASSERT_NE(sock, INVALID_SOCKET);
  18290. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18291. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18292. "Host: localhost\r\n"
  18293. "Connection: close\r\n"
  18294. "\r\n";
  18295. std::string first_response;
  18296. std::string second_response;
  18297. detail::process_client_socket(
  18298. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18299. [&](Stream &strm) {
  18300. if (strm.write(req.data(), req.size()) !=
  18301. static_cast<ssize_t>(req.size())) {
  18302. return false;
  18303. }
  18304. char buf[512];
  18305. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18306. // Headers plus the two-byte body of the handler below
  18307. while (reader.getline()) {
  18308. first_response += reader.ptr();
  18309. if (first_response.find("ok") != std::string::npos) { break; }
  18310. }
  18311. if (strm.write(second.data(), second.size()) !=
  18312. static_cast<ssize_t>(second.size())) {
  18313. return true;
  18314. }
  18315. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18316. while (reader2.getline()) {
  18317. second_response += reader2.ptr();
  18318. if (second_response.find("ok") != std::string::npos) { break; }
  18319. }
  18320. return true;
  18321. });
  18322. *announced_close =
  18323. first_response.find("Connection: close") != std::string::npos;
  18324. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18325. }
  18326. class ConnectionTokenTest : public ::testing::Test {
  18327. protected:
  18328. void SetUp() override {
  18329. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18330. res.set_content("ok", "text/plain");
  18331. });
  18332. port_ = svr_.bind_to_any_port(HOST);
  18333. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18334. svr_.wait_until_ready();
  18335. }
  18336. void TearDown() override {
  18337. svr_.stop();
  18338. if (thread_.joinable()) { thread_.join(); }
  18339. }
  18340. Server svr_;
  18341. int port_ = 0;
  18342. thread thread_;
  18343. };
  18344. // "close" alongside another option still closes the connection, and the
  18345. // response says so rather than leaving the peer to discover it.
  18346. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18347. bool announced_close = false;
  18348. bool reusable = true;
  18349. probe_connection_reuse(port_,
  18350. "GET /keepalive HTTP/1.1\r\n"
  18351. "Host: localhost\r\n"
  18352. "Connection: keep-alive, close\r\n"
  18353. "\r\n",
  18354. &announced_close, &reusable);
  18355. EXPECT_TRUE(announced_close);
  18356. EXPECT_FALSE(reusable);
  18357. }
  18358. // "close" split over two field lines is the same list, so it is honored too.
  18359. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18360. bool announced_close = false;
  18361. bool reusable = true;
  18362. probe_connection_reuse(port_,
  18363. "GET /keepalive HTTP/1.1\r\n"
  18364. "Host: localhost\r\n"
  18365. "Connection: keep-alive\r\n"
  18366. "Connection: close\r\n"
  18367. "\r\n",
  18368. &announced_close, &reusable);
  18369. EXPECT_TRUE(announced_close);
  18370. EXPECT_FALSE(reusable);
  18371. }
  18372. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18373. // keep-alive in the spelling everyone actually sends keeps its connection.
  18374. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18375. bool announced_close = false;
  18376. bool reusable = false;
  18377. probe_connection_reuse(port_,
  18378. "GET /keepalive HTTP/1.0\r\n"
  18379. "Host: localhost\r\n"
  18380. "Connection: keep-alive\r\n"
  18381. "\r\n",
  18382. &announced_close, &reusable);
  18383. EXPECT_FALSE(announced_close);
  18384. EXPECT_TRUE(reusable);
  18385. }
  18386. // A token the value merely contains is not the token itself.
  18387. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18388. bool announced_close = false;
  18389. bool reusable = false;
  18390. probe_connection_reuse(port_,
  18391. "GET /keepalive HTTP/1.1\r\n"
  18392. "Host: localhost\r\n"
  18393. "Connection: notclose\r\n"
  18394. "\r\n",
  18395. &announced_close, &reusable);
  18396. EXPECT_FALSE(announced_close);
  18397. EXPECT_TRUE(reusable);
  18398. }
  18399. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18400. Server svr;
  18401. std::vector<std::string> observed_types;
  18402. svr.Get("/", [&](const Request &req, Response &res) {
  18403. observed_types = req.accept_content_types;
  18404. res.set_content("ok", "text/plain");
  18405. });
  18406. auto port = svr.bind_to_any_port(HOST);
  18407. thread t = thread([&]() { svr.listen_after_bind(); });
  18408. auto se = detail::scope_exit([&] {
  18409. svr.stop();
  18410. t.join();
  18411. ASSERT_FALSE(svr.is_running());
  18412. });
  18413. svr.wait_until_ready();
  18414. Client cli(HOST, port);
  18415. Headers headers;
  18416. headers.emplace("Accept", "text/plain;q=0.5");
  18417. headers.emplace("Accept", "application/json");
  18418. auto res = cli.Get("/", headers);
  18419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18420. EXPECT_EQ(StatusCode::OK_200, res->status);
  18421. // Sorted by q-value, so the second field line's type comes first
  18422. ASSERT_EQ(2U, observed_types.size());
  18423. EXPECT_EQ("application/json", observed_types[0]);
  18424. EXPECT_EQ("text/plain", observed_types[1]);
  18425. }
  18426. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18427. // empty field line must not contribute a bare comma to the combined value.
  18428. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18429. Server svr;
  18430. std::vector<std::string> observed_types;
  18431. svr.Get("/", [&](const Request &req, Response &res) {
  18432. observed_types = req.accept_content_types;
  18433. res.set_content("ok", "text/plain");
  18434. });
  18435. auto port = svr.bind_to_any_port(HOST);
  18436. thread t = thread([&]() { svr.listen_after_bind(); });
  18437. auto se = detail::scope_exit([&] {
  18438. svr.stop();
  18439. t.join();
  18440. ASSERT_FALSE(svr.is_running());
  18441. });
  18442. svr.wait_until_ready();
  18443. // Empty first field line, then a real one
  18444. std::string raw_req = "GET / HTTP/1.1\r\n"
  18445. "Host: localhost\r\n"
  18446. "Accept:\r\n"
  18447. "Accept: application/json\r\n"
  18448. "Connection: close\r\n"
  18449. "\r\n";
  18450. std::string out;
  18451. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18452. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18453. ASSERT_EQ(1U, observed_types.size());
  18454. EXPECT_EQ("application/json", observed_types[0]);
  18455. }
  18456. // The skip in get_combined_header_value() is what keeps an empty field line
  18457. // from contributing a bare comma. Only a trailing empty field line exercises
  18458. // it: a leading one is already covered by the "combined is still empty" check,
  18459. // and parse_accept_header() now ignores the empty element either way, so the
  18460. // request-level test above can no longer tell the two apart.
  18461. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18462. Headers headers;
  18463. headers.emplace("Accept", "text/html");
  18464. headers.emplace("Accept", "");
  18465. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18466. headers.clear();
  18467. headers.emplace("Accept", "");
  18468. headers.emplace("Accept", "application/json");
  18469. EXPECT_EQ("application/json",
  18470. detail::get_combined_header_value(headers, "Accept"));
  18471. }
  18472. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18473. // An encoding offered on a later Accept-Encoding field line is still offered.
  18474. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18475. Server svr;
  18476. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18477. res.set_content(std::string(1024, 'x'), "text/plain");
  18478. });
  18479. auto port = svr.bind_to_any_port(HOST);
  18480. thread t = thread([&]() { svr.listen_after_bind(); });
  18481. auto se = detail::scope_exit([&] {
  18482. svr.stop();
  18483. t.join();
  18484. ASSERT_FALSE(svr.is_running());
  18485. });
  18486. svr.wait_until_ready();
  18487. Client cli(HOST, port);
  18488. cli.set_decompress(false);
  18489. Headers headers;
  18490. headers.emplace("Accept-Encoding", "identity");
  18491. headers.emplace("Accept-Encoding", "gzip");
  18492. auto res = cli.Get("/", headers);
  18493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18494. EXPECT_EQ(StatusCode::OK_200, res->status);
  18495. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18496. }
  18497. #endif
  18498. #ifndef _WIN32
  18499. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18500. Server svr;
  18501. svr.Post("/post", [&](const Request &req, Response &res) {
  18502. res.set_content(req.body, "text/plain");
  18503. });
  18504. svr.Put("/put", [&](const Request &req, Response &res) {
  18505. res.set_content(req.body, "text/plain");
  18506. });
  18507. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18508. res.set_content(req.body, "text/plain");
  18509. });
  18510. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18511. res.set_content(req.body, "text/plain");
  18512. });
  18513. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18514. auto se = detail::scope_exit([&] {
  18515. svr.stop();
  18516. t.join();
  18517. ASSERT_FALSE(svr.is_running());
  18518. });
  18519. svr.wait_until_ready();
  18520. std::string resp;
  18521. // POST without Content-Length
  18522. ASSERT_TRUE(send_request(5,
  18523. "POST /post HTTP/1.1\r\n"
  18524. "Host: localhost\r\n"
  18525. "Connection: close\r\n"
  18526. "\r\n",
  18527. &resp));
  18528. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18529. // PUT without Content-Length
  18530. resp.clear();
  18531. ASSERT_TRUE(send_request(5,
  18532. "PUT /put HTTP/1.1\r\n"
  18533. "Host: localhost\r\n"
  18534. "Connection: close\r\n"
  18535. "\r\n",
  18536. &resp));
  18537. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18538. // PATCH without Content-Length
  18539. resp.clear();
  18540. ASSERT_TRUE(send_request(5,
  18541. "PATCH /patch HTTP/1.1\r\n"
  18542. "Host: localhost\r\n"
  18543. "Connection: close\r\n"
  18544. "\r\n",
  18545. &resp));
  18546. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18547. // DELETE without Content-Length
  18548. resp.clear();
  18549. ASSERT_TRUE(send_request(5,
  18550. "DELETE /delete HTTP/1.1\r\n"
  18551. "Host: localhost\r\n"
  18552. "Connection: close\r\n"
  18553. "\r\n",
  18554. &resp));
  18555. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18556. }
  18557. #endif
  18558. //==============================================================================
  18559. // open_stream() Tests
  18560. //==============================================================================
  18561. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18562. std::string result;
  18563. char buf[8192];
  18564. ssize_t n;
  18565. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18566. result.append(buf, static_cast<size_t>(n));
  18567. }
  18568. return result;
  18569. }
  18570. // Mock stream for unit tests
  18571. class MockStream : public Stream {
  18572. public:
  18573. std::string data;
  18574. size_t pos = 0;
  18575. ssize_t error_after = -1; // -1 = no error
  18576. explicit MockStream(const std::string &d, ssize_t err = -1)
  18577. : data(d), error_after(err) {}
  18578. bool is_readable() const override { return true; }
  18579. bool wait_readable() const override { return true; }
  18580. bool wait_writable() const override { return true; }
  18581. ssize_t read(char *ptr, size_t size) override {
  18582. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18583. if (pos >= data.size()) return 0;
  18584. size_t limit =
  18585. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18586. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18587. std::memcpy(ptr, data.data() + pos, to_read);
  18588. pos += to_read;
  18589. return static_cast<ssize_t>(to_read);
  18590. }
  18591. ssize_t write(const char *, size_t) override { return -1; }
  18592. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18593. ip = "127.0.0.1";
  18594. port = 0;
  18595. }
  18596. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18597. ip = "127.0.0.1";
  18598. port = 0;
  18599. }
  18600. socket_t socket() const override { return INVALID_SOCKET; }
  18601. time_t duration() const override { return 0; }
  18602. };
  18603. TEST(StreamHandleTest, Basic) {
  18604. ClientImpl::StreamHandle handle;
  18605. EXPECT_FALSE(handle.is_valid());
  18606. handle.response = detail::make_unique<Response>();
  18607. handle.error = Error::Connection;
  18608. EXPECT_FALSE(handle.is_valid());
  18609. handle.error = Error::Success;
  18610. EXPECT_TRUE(handle.is_valid());
  18611. }
  18612. TEST(BodyReaderTest, Basic) {
  18613. MockStream stream("Hello, World!");
  18614. detail::BodyReader reader;
  18615. reader.stream = &stream;
  18616. reader.content_length = 13;
  18617. char buf[32];
  18618. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18619. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18620. EXPECT_TRUE(reader.eof);
  18621. }
  18622. TEST(BodyReaderTest, NoStream) {
  18623. detail::BodyReader reader;
  18624. char buf[32];
  18625. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18626. EXPECT_EQ(Error::Connection, reader.last_error);
  18627. }
  18628. TEST(BodyReaderTest, Error) {
  18629. MockStream stream("Hello, World!", 5);
  18630. detail::BodyReader reader;
  18631. reader.stream = &stream;
  18632. reader.content_length = 13;
  18633. char buf[32];
  18634. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18635. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18636. EXPECT_EQ(Error::Read, reader.last_error);
  18637. }
  18638. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18639. // Mock-based StreamHandle tests relying on private internals are removed.
  18640. class OpenStreamTest : public ::testing::Test {
  18641. protected:
  18642. void SetUp() override {
  18643. svr_.Get("/hello", [](const Request &, Response &res) {
  18644. res.set_content("Hello World!", "text/plain");
  18645. });
  18646. svr_.Get("/large", [](const Request &, Response &res) {
  18647. res.set_content(std::string(10000, 'X'), "text/plain");
  18648. });
  18649. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18650. res.set_content("Hello World!", "image/jpeg");
  18651. res.set_header("Content-Encoding", "UTF-8");
  18652. });
  18653. svr_.Get("/chunked", [](const Request &, Response &res) {
  18654. res.set_chunked_content_provider("text/plain",
  18655. [](size_t offset, DataSink &sink) {
  18656. if (offset < 15) {
  18657. sink.write("chunk", 5);
  18658. return true;
  18659. }
  18660. sink.done();
  18661. return true;
  18662. });
  18663. });
  18664. svr_.Get("/compressible", [](const Request &, Response &res) {
  18665. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18666. DataSink &sink) {
  18667. if (offset < 100 * 1024) {
  18668. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18669. sink.write(chunk.data(), chunk.size());
  18670. return true;
  18671. }
  18672. sink.done();
  18673. return true;
  18674. });
  18675. });
  18676. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18677. [](const Request & /*req*/, Response &res) {
  18678. auto i = new int(0);
  18679. res.set_header("Trailer", "Content-Length, X-Allowed");
  18680. res.set_chunked_content_provider(
  18681. "text/plain",
  18682. [i](size_t /*offset*/, DataSink &sink) {
  18683. switch (*i) {
  18684. case 0: sink.os << "123"; break;
  18685. case 1: sink.os << "456"; break;
  18686. case 2: sink.os << "789"; break;
  18687. case 3: {
  18688. sink.done_with_trailer(
  18689. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18690. } break;
  18691. }
  18692. (*i)++;
  18693. return true;
  18694. },
  18695. [i](bool success) {
  18696. EXPECT_TRUE(success);
  18697. delete i;
  18698. });
  18699. });
  18700. // Echo headers endpoint for header-related tests
  18701. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18702. std::string body;
  18703. for (const auto &h : req.headers) {
  18704. body.append(h.first);
  18705. body.push_back(':');
  18706. body.append(h.second);
  18707. body.push_back('\n');
  18708. }
  18709. res.set_content(body, "text/plain");
  18710. });
  18711. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18712. std::string body;
  18713. for (const auto &h : req.headers) {
  18714. body.append(h.first);
  18715. body.push_back(':');
  18716. body.append(h.second);
  18717. body.push_back('\n');
  18718. }
  18719. res.set_content(body, "text/plain");
  18720. });
  18721. port_ = svr_.bind_to_any_port("127.0.0.1");
  18722. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18723. svr_.wait_until_ready();
  18724. }
  18725. void TearDown() override {
  18726. svr_.stop();
  18727. if (thread_.joinable()) thread_.join();
  18728. }
  18729. Server svr_;
  18730. std::thread thread_;
  18731. int port_ = 0;
  18732. };
  18733. TEST_F(OpenStreamTest, Basic) {
  18734. Client cli("127.0.0.1", port_);
  18735. auto handle = cli.open_stream("GET", "/hello");
  18736. EXPECT_TRUE(handle.is_valid());
  18737. EXPECT_EQ("Hello World!", read_all(handle));
  18738. }
  18739. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18740. Client cli("127.0.0.1", port_);
  18741. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18742. ASSERT_TRUE(handle.is_valid());
  18743. EXPECT_EQ("Hello World!", read_all(handle));
  18744. }
  18745. TEST_F(OpenStreamTest, SmallBuffer) {
  18746. Client cli("127.0.0.1", port_);
  18747. auto handle = cli.open_stream("GET", "/hello");
  18748. std::string result;
  18749. char buf[4];
  18750. ssize_t n;
  18751. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18752. result.append(buf, static_cast<size_t>(n));
  18753. EXPECT_EQ("Hello World!", result);
  18754. }
  18755. TEST_F(OpenStreamTest, DefaultHeaders) {
  18756. Client cli("127.0.0.1", port_);
  18757. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18758. {
  18759. auto handle = cli.open_stream("GET", "/echo-headers");
  18760. ASSERT_TRUE(handle.is_valid());
  18761. auto body = read_all(handle);
  18762. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18763. std::string::npos);
  18764. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18765. std::string::npos);
  18766. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18767. }
  18768. // open_stream POST with body and no explicit content_type should NOT add
  18769. // text/plain Content-Type (behavior differs from non-streaming path), but
  18770. // should include Content-Length
  18771. {
  18772. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18773. ASSERT_TRUE(handle.is_valid());
  18774. auto body = read_all(handle);
  18775. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18776. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18777. }
  18778. // open_stream POST with explicit Content-Type should preserve it
  18779. {
  18780. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18781. {{"Content-Type", "application/custom"}},
  18782. "{}", "application/custom");
  18783. ASSERT_TRUE(handle.is_valid());
  18784. auto body = read_all(handle);
  18785. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18786. }
  18787. // User-specified User-Agent must not be overwritten for stream API
  18788. {
  18789. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18790. {{"User-Agent", "MyAgent/1.2"}});
  18791. ASSERT_TRUE(handle.is_valid());
  18792. auto body = read_all(handle);
  18793. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18794. }
  18795. }
  18796. TEST_F(OpenStreamTest, Large) {
  18797. Client cli("127.0.0.1", port_);
  18798. auto handle = cli.open_stream("GET", "/large");
  18799. EXPECT_EQ(10000u, read_all(handle).size());
  18800. }
  18801. TEST_F(OpenStreamTest, ConnectionError) {
  18802. Client cli("127.0.0.1", 9999);
  18803. auto handle = cli.open_stream("GET", "/hello");
  18804. EXPECT_FALSE(handle.is_valid());
  18805. }
  18806. TEST_F(OpenStreamTest, Chunked) {
  18807. Client cli("127.0.0.1", port_);
  18808. auto handle = cli.open_stream("GET", "/chunked");
  18809. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18810. "Transfer-Encoding") == "chunked");
  18811. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18812. }
  18813. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18814. Client cli("127.0.0.1", port_);
  18815. auto handle =
  18816. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18817. ASSERT_TRUE(handle.is_valid());
  18818. // Consume body to allow trailers to be received/parsed
  18819. auto body = read_all(handle);
  18820. // Explicitly parse trailers (ensure trailers are available for assertion)
  18821. handle.parse_trailers_if_needed();
  18822. EXPECT_EQ(std::string("123456789"), body);
  18823. // The response should include a Trailer header declaring both names
  18824. ASSERT_TRUE(handle.response);
  18825. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18826. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18827. handle.response->get_header_value("Trailer"));
  18828. // Prohibited trailer must not be present
  18829. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18830. // Allowed trailer should be present
  18831. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18832. EXPECT_EQ(std::string("yes"),
  18833. handle.response->get_trailer_value("X-Allowed"));
  18834. // Verify trailers are NOT present as regular headers
  18835. EXPECT_EQ(std::string(""),
  18836. handle.response->get_header_value("Content-Length"));
  18837. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18838. }
  18839. // Accepts one connection on an OS-assigned port, which it hands over through
  18840. // port_promise, reads the request head and sends back response. after_send,
  18841. // if given, runs on the connection before it is closed.
  18842. static std::thread
  18843. serve_single_response(std::promise<int> &port_promise,
  18844. const std::string &response,
  18845. std::function<void(socket_t)> after_send = nullptr) {
  18846. return std::thread([&port_promise, response, after_send] {
  18847. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18848. default_socket_options(srv);
  18849. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18850. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18851. sockaddr_in addr{};
  18852. addr.sin_family = AF_INET;
  18853. addr.sin_port = htons(0); // Let OS assign a free port
  18854. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18855. int opt = 1;
  18856. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18857. #ifdef _WIN32
  18858. reinterpret_cast<const char *>(&opt),
  18859. #else
  18860. &opt,
  18861. #endif
  18862. sizeof(opt));
  18863. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18864. ::listen(srv, 1) != 0) {
  18865. port_promise.set_value(-1);
  18866. detail::close_socket(srv);
  18867. return;
  18868. }
  18869. socklen_t addr_len = sizeof(addr);
  18870. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18871. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18872. sockaddr_in cli_addr{};
  18873. socklen_t cli_len = sizeof(cli_addr);
  18874. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18875. if (cli != INVALID_SOCKET) {
  18876. // Read the complete HTTP request (until the blank line that terminates
  18877. // headers) before sending the response. If the server closes the socket
  18878. // while the client's request data is still unread in the kernel receive
  18879. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18880. // connection on both sides: it discards the client's receive buffer
  18881. // (which already holds our response) and causes any in-progress write on
  18882. // the client to fail with ECONNRESET. Reading all request data first
  18883. // ensures close() emits a graceful FIN.
  18884. {
  18885. char rbuf[256];
  18886. std::string req;
  18887. while (req.find("\r\n\r\n") == std::string::npos) {
  18888. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18889. if (n <= 0) { break; }
  18890. req.append(rbuf, static_cast<size_t>(n));
  18891. }
  18892. }
  18893. ::send(cli,
  18894. #ifdef _WIN32
  18895. static_cast<const char *>(response.c_str()),
  18896. static_cast<int>(response.size()),
  18897. #else
  18898. response.c_str(), response.size(),
  18899. #endif
  18900. 0);
  18901. if (after_send) { after_send(cli); }
  18902. detail::close_socket(cli);
  18903. }
  18904. detail::close_socket(srv);
  18905. });
  18906. }
  18907. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18908. #ifndef _WIN32
  18909. signal(SIGPIPE, SIG_IGN);
  18910. #endif
  18911. std::promise<int> port_promise;
  18912. auto port_future = port_promise.get_future();
  18913. auto server_thread =
  18914. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18915. "Content-Type: text/plain\r\n"
  18916. "Content-Length: not-a-number\r\n"
  18917. "Connection: close\r\n"
  18918. "\r\n"
  18919. "hello");
  18920. auto port = port_future.get();
  18921. ASSERT_GT(port, 0);
  18922. Client cli("127.0.0.1", port);
  18923. auto handle = cli.open_stream("GET", "/");
  18924. EXPECT_FALSE(handle.is_valid());
  18925. server_thread.join();
  18926. }
  18927. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18928. #ifndef _WIN32
  18929. signal(SIGPIPE, SIG_IGN);
  18930. #endif
  18931. std::promise<int> port_promise;
  18932. auto port_future = port_promise.get_future();
  18933. auto server_thread = serve_single_response(
  18934. port_promise, "HTTP/1.1 200 OK\r\n"
  18935. "Content-Type: text/plain\r\n"
  18936. "Content-Length: 99999999999999999999999999\r\n"
  18937. "Connection: close\r\n"
  18938. "\r\n"
  18939. "hello");
  18940. auto port = port_future.get();
  18941. ASSERT_GT(port, 0);
  18942. // Historically std::stoull would throw std::out_of_range here and crash
  18943. // the process, then parsing silently clamped to a bogus framing length and
  18944. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18945. // so the stream fails to open, matching the not-a-number case above. The
  18946. // process still must NOT terminate.
  18947. Client cli("127.0.0.1", port);
  18948. auto handle = cli.open_stream("GET", "/");
  18949. EXPECT_FALSE(handle.is_valid());
  18950. server_thread.join();
  18951. }
  18952. // Serves `response` to the single request `fn` makes with a fresh client.
  18953. template <typename Fn>
  18954. static void with_single_response(const std::string &response, Fn fn) {
  18955. #ifndef _WIN32
  18956. signal(SIGPIPE, SIG_IGN);
  18957. #endif
  18958. std::promise<int> port_promise;
  18959. auto port_future = port_promise.get_future();
  18960. auto server_thread = serve_single_response(port_promise, response);
  18961. auto se = detail::scope_exit([&] { server_thread.join(); });
  18962. auto port = port_future.get();
  18963. ASSERT_GT(port, 0);
  18964. Client cli("127.0.0.1", port);
  18965. fn(cli);
  18966. }
  18967. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  18968. const char *responses[] = {
  18969. "HTTP/1.1 103 Early Hints\r\n"
  18970. "Link: </style.css>; rel=preload\r\n"
  18971. "\r\n"
  18972. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18973. "HTTP/1.1 100 Continue\r\n"
  18974. "X-Note: interim\r\n"
  18975. "\r\n"
  18976. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18977. };
  18978. for (auto response : responses) {
  18979. with_single_response(response, [](Client &cli) {
  18980. auto res = cli.Get("/");
  18981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18982. EXPECT_EQ(StatusCode::OK_200, res->status);
  18983. EXPECT_EQ("ok", res->body);
  18984. });
  18985. }
  18986. }
  18987. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  18988. #ifndef _WIN32
  18989. signal(SIGPIPE, SIG_IGN);
  18990. #endif
  18991. // The server answers the head without asking for the body. Bytes it then
  18992. // reads on the connection would be taken for the body the request declared.
  18993. auto closed_by_client = false;
  18994. std::promise<int> port_promise;
  18995. auto server_thread = serve_single_response(
  18996. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  18997. [&](socket_t sock) {
  18998. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18999. char buf[256];
  19000. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19001. });
  19002. Client cli("127.0.0.1", port_promise.get_future().get());
  19003. cli.set_keep_alive(true);
  19004. cli.set_read_timeout(1, 0);
  19005. // Long enough for the client to send Expect: 100-continue.
  19006. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19008. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19009. cli.Get("/second");
  19010. server_thread.join();
  19011. EXPECT_TRUE(closed_by_client);
  19012. }
  19013. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19014. // Long enough for the client to send Expect: 100-continue
  19015. with_single_response(
  19016. "HTTP/1.1 103 Early Hints\r\n"
  19017. "Link: </style.css>; rel=preload\r\n"
  19018. "\r\n"
  19019. "HTTP/1.1 401 Unauthorized\r\n"
  19020. "Content-Length: 0\r\n\r\n",
  19021. [](Client &cli) {
  19022. cli.set_read_timeout(2, 0);
  19023. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19025. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19026. });
  19027. }
  19028. #ifdef CPPHTTPLIB_SSL_ENABLED
  19029. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19030. #ifndef _WIN32
  19031. signal(SIGPIPE, SIG_IGN);
  19032. #endif
  19033. auto reused = false;
  19034. std::promise<int> port_promise;
  19035. auto server_thread = serve_single_response(
  19036. port_promise,
  19037. "HTTP/1.1 401 Unauthorized\r\n"
  19038. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19039. "Content-Length: 0\r\n\r\n",
  19040. [&](socket_t sock) {
  19041. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19042. char buf[256];
  19043. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19044. });
  19045. Client cli("127.0.0.1", port_promise.get_future().get());
  19046. cli.set_keep_alive(true);
  19047. cli.set_digest_auth("user", "pass");
  19048. cli.set_read_timeout(1, 0);
  19049. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19050. server_thread.join();
  19051. EXPECT_FALSE(reused);
  19052. }
  19053. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19054. // Any other answer to CONNECT would read as the origin's response.
  19055. struct {
  19056. const char *response;
  19057. bool passed_on;
  19058. } cases[] = {
  19059. {"HTTP/1.1 201 Created\r\n"
  19060. "Set-Cookie: session=from-proxy\r\n"
  19061. "Content-Length: 0\r\n\r\n",
  19062. false},
  19063. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19064. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19065. "Content-Length: 0\r\n\r\n",
  19066. true},
  19067. };
  19068. for (const auto &c : cases) {
  19069. std::promise<int> port_promise;
  19070. auto server_thread = serve_single_response(port_promise, c.response);
  19071. SSLClient cli("example.com", 443);
  19072. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19073. auto res = cli.Get("/");
  19074. server_thread.join();
  19075. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19076. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19077. if (res) {
  19078. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19079. }
  19080. }
  19081. }
  19082. #endif
  19083. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19084. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19085. // the chunked coding and drop Content-Length, so a front-end that trusts
  19086. // Content-Length would disagree about where the body ends (response
  19087. // smuggling). The client must reject such a response.
  19088. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19089. for (const char *te : {"chunked", "gzip, chunked"}) {
  19090. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19091. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19092. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19093. "5\r\nhello\r\n0\r\n\r\n";
  19094. with_single_response(response, [&](Client &cli) {
  19095. auto res = cli.Get("/");
  19096. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19097. EXPECT_EQ(Error::Read, res.error()) << te;
  19098. });
  19099. with_single_response(response, [&](Client &cli) {
  19100. auto handle = cli.open_stream("GET", "/");
  19101. EXPECT_FALSE(handle.is_valid()) << te;
  19102. EXPECT_EQ(Error::Read, handle.error) << te;
  19103. });
  19104. }
  19105. }
  19106. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19107. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19108. // closing the connection (unlike a request, which must be rejected).
  19109. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19110. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19111. "Transfer-Encoding: chunked\r\n"
  19112. "Connection: close\r\n"
  19113. "\r\n"
  19114. "5\r\nhello\r\n0\r\n\r\n",
  19115. "HTTP/1.1 200 OK\r\n"
  19116. "Transfer-Encoding: gzip\r\n"
  19117. "Connection: close\r\n"
  19118. "\r\n"
  19119. "hello"}) {
  19120. with_single_response(response, [&](Client &cli) {
  19121. auto res = cli.Get("/");
  19122. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19123. EXPECT_EQ("hello", res->body);
  19124. });
  19125. with_single_response(response, [&](Client &cli) {
  19126. auto handle = cli.open_stream("GET", "/");
  19127. ASSERT_TRUE(handle.is_valid()) << response;
  19128. EXPECT_EQ("hello", read_all(handle));
  19129. });
  19130. }
  19131. }
  19132. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19133. // framing headers describe nothing to read and must not be rejected.
  19134. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19135. const std::string framing = "Content-Length: 5\r\n"
  19136. "Transfer-Encoding: chunked\r\n"
  19137. "Connection: close\r\n"
  19138. "\r\n";
  19139. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19140. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19141. });
  19142. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19143. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19144. });
  19145. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19146. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19147. with_single_response(response, [&](Client &cli) {
  19148. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19149. });
  19150. with_single_response(response, [&](Client &cli) {
  19151. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19152. });
  19153. }
  19154. }
  19155. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19156. // response, is faulty framing, so the connection is not reused after it.
  19157. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19158. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19159. "Content-Length: 0\r\n"
  19160. "Transfer-Encoding: chunked\r\n"
  19161. "\r\n"
  19162. "5\r\nhello\r\n0\r\n\r\n",
  19163. "HTTP/1.0 200 Connection established\r\n"
  19164. "Connection: keep-alive\r\n"
  19165. "Transfer-Encoding: chunked\r\n"
  19166. "\r\n"
  19167. "5\r\nhello\r\n0\r\n\r\n"}) {
  19168. with_single_response(response, [&](Client &cli) {
  19169. cli.set_keep_alive(true);
  19170. auto res = cli.Get("/");
  19171. ASSERT_TRUE(res) << response;
  19172. EXPECT_EQ("hello", res->body);
  19173. EXPECT_FALSE(cli.is_socket_open()) << response;
  19174. });
  19175. }
  19176. }
  19177. // A payload max length of 0 means no limit, however the body is framed.
  19178. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19179. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19180. "Transfer-Encoding: chunked\r\n"
  19181. "\r\n"
  19182. "5\r\nhello\r\n0\r\n\r\n",
  19183. "HTTP/1.1 200 OK\r\n"
  19184. "Connection: close\r\n"
  19185. "\r\n"
  19186. "hello"}) {
  19187. with_single_response(response, [&](Client &cli) {
  19188. cli.set_payload_max_length(0);
  19189. auto res = cli.Get("/");
  19190. ASSERT_TRUE(res) << response;
  19191. EXPECT_EQ("hello", res->body) << response;
  19192. });
  19193. }
  19194. }
  19195. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19196. Server svr;
  19197. svr.set_payload_max_length(0);
  19198. svr.Post("/echo", [](const Request &req, Response &res) {
  19199. res.set_content(req.body, "text/plain");
  19200. });
  19201. auto port = svr.bind_to_any_port(HOST);
  19202. thread t = thread([&] { svr.listen_after_bind(); });
  19203. auto se = detail::scope_exit([&] {
  19204. svr.stop();
  19205. t.join();
  19206. ASSERT_FALSE(svr.is_running());
  19207. });
  19208. svr.wait_until_ready();
  19209. Client cli(HOST, port);
  19210. auto res = cli.Post(
  19211. "/echo",
  19212. [](size_t /*offset*/, DataSink &sink) {
  19213. sink.write("hello", 5);
  19214. sink.done();
  19215. return true;
  19216. },
  19217. "text/plain");
  19218. ASSERT_TRUE(res);
  19219. EXPECT_EQ(StatusCode::OK_200, res->status);
  19220. EXPECT_EQ("hello", res->body);
  19221. }
  19222. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19223. TEST_F(OpenStreamTest, Gzip) {
  19224. Client cli("127.0.0.1", port_);
  19225. auto handle = cli.open_stream("GET", "/compressible", {},
  19226. {{"Accept-Encoding", "gzip"}});
  19227. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19228. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19229. }
  19230. #endif
  19231. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19232. TEST_F(OpenStreamTest, Brotli) {
  19233. Client cli("127.0.0.1", port_);
  19234. auto handle =
  19235. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19236. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19237. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19238. }
  19239. #endif
  19240. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19241. TEST_F(OpenStreamTest, Zstd) {
  19242. Client cli("127.0.0.1", port_);
  19243. auto handle = cli.open_stream("GET", "/compressible", {},
  19244. {{"Accept-Encoding", "zstd"}});
  19245. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19246. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19247. }
  19248. #endif
  19249. #ifdef CPPHTTPLIB_SSL_ENABLED
  19250. class SSLOpenStreamTest : public ::testing::Test {
  19251. protected:
  19252. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19253. void SetUp() override {
  19254. svr_.Get("/hello", [](const Request &, Response &res) {
  19255. res.set_content("Hello SSL World!", "text/plain");
  19256. });
  19257. svr_.Get("/chunked", [](const Request &, Response &res) {
  19258. res.set_chunked_content_provider("text/plain",
  19259. [](size_t offset, DataSink &sink) {
  19260. if (offset < 15) {
  19261. sink.write("chunk", 5);
  19262. return true;
  19263. }
  19264. sink.done();
  19265. return true;
  19266. });
  19267. });
  19268. svr_.Post("/echo", [](const Request &req, Response &res) {
  19269. res.set_content(req.body, req.get_header_value("Content-Type"));
  19270. });
  19271. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19272. std::string body = req.body;
  19273. res.set_chunked_content_provider(
  19274. "text/plain", [body](size_t offset, DataSink &sink) {
  19275. if (offset < body.size()) {
  19276. sink.write(body.data() + offset, body.size() - offset);
  19277. }
  19278. sink.done();
  19279. return true;
  19280. });
  19281. });
  19282. port_ = svr_.bind_to_any_port("127.0.0.1");
  19283. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19284. svr_.wait_until_ready();
  19285. }
  19286. void TearDown() override {
  19287. svr_.stop();
  19288. if (thread_.joinable()) thread_.join();
  19289. }
  19290. SSLServer svr_;
  19291. std::thread thread_;
  19292. int port_ = 0;
  19293. };
  19294. TEST_F(SSLOpenStreamTest, Basic) {
  19295. SSLClient cli("127.0.0.1", port_);
  19296. cli.enable_server_certificate_verification(false);
  19297. auto handle = cli.open_stream("GET", "/hello");
  19298. ASSERT_TRUE(handle.is_valid());
  19299. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19300. }
  19301. TEST_F(SSLOpenStreamTest, Chunked) {
  19302. SSLClient cli("127.0.0.1", port_);
  19303. cli.enable_server_certificate_verification(false);
  19304. auto handle = cli.open_stream("GET", "/chunked");
  19305. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19306. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19307. "Transfer-Encoding") == "chunked");
  19308. auto body = read_all(handle);
  19309. EXPECT_EQ("chunkchunkchunk", body);
  19310. }
  19311. TEST_F(SSLOpenStreamTest, Post) {
  19312. SSLClient cli("127.0.0.1", port_);
  19313. cli.enable_server_certificate_verification(false);
  19314. auto handle =
  19315. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19316. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19317. EXPECT_EQ(200, handle.response->status);
  19318. auto body = read_all(handle);
  19319. EXPECT_EQ("Hello SSL POST", body);
  19320. }
  19321. TEST_F(SSLOpenStreamTest, PostChunked) {
  19322. SSLClient cli("127.0.0.1", port_);
  19323. cli.enable_server_certificate_verification(false);
  19324. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19325. "Chunked SSL Data", "text/plain");
  19326. ASSERT_TRUE(handle.is_valid());
  19327. EXPECT_EQ(200, handle.response->status);
  19328. auto body = read_all(handle);
  19329. EXPECT_EQ("Chunked SSL Data", body);
  19330. }
  19331. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19332. // Content-Length is terminated by the server closing the connection. When the
  19333. // SSL peer sends a close_notify after the body, the client must treat it as a
  19334. // clean EOF and return a successful response rather than an error.
  19335. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19337. ASSERT_TRUE(svr.is_valid());
  19338. svr.set_keep_alive_max_count(1);
  19339. const std::string expected_body = "Hello from connection-close response!";
  19340. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19341. res.set_content_provider("text/plain",
  19342. [&](size_t offset, DataSink &sink) -> bool {
  19343. if (offset < expected_body.size()) {
  19344. sink.write(expected_body.data() + offset,
  19345. expected_body.size() - offset);
  19346. }
  19347. sink.done();
  19348. return true;
  19349. });
  19350. });
  19351. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19352. auto se = detail::scope_exit([&] {
  19353. svr.stop();
  19354. listen_thread.join();
  19355. ASSERT_FALSE(svr.is_running());
  19356. });
  19357. svr.wait_until_ready();
  19358. SSLClient cli(HOST, PORT);
  19359. cli.enable_server_certificate_verification(false);
  19360. auto res = cli.Get("/no-content-length");
  19361. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19362. EXPECT_EQ(StatusCode::OK_200, res->status);
  19363. EXPECT_EQ(expected_body, res->body);
  19364. }
  19365. #endif // CPPHTTPLIB_SSL_ENABLED
  19366. //==============================================================================
  19367. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19368. // results for various scenarios.
  19369. //==============================================================================
  19370. TEST(ParityTest, GetVsOpenStream) {
  19371. Server svr;
  19372. const std::string path = "/parity";
  19373. const std::string content = "Parity test content: hello world";
  19374. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19375. res.set_content(content, "text/plain");
  19376. });
  19377. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19378. auto se = detail::scope_exit([&] {
  19379. svr.stop();
  19380. t.join();
  19381. ASSERT_FALSE(svr.is_running());
  19382. });
  19383. svr.wait_until_ready();
  19384. Client cli(HOST, PORT);
  19385. // Non-stream path
  19386. auto r1 = cli.Get(path);
  19387. ASSERT_TRUE(r1);
  19388. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19389. // Stream path
  19390. auto h = cli.open_stream("GET", path);
  19391. ASSERT_TRUE(h.is_valid());
  19392. EXPECT_EQ(r1->body, read_all(h));
  19393. }
  19394. // Helper to compress data with provided compressor type T
  19395. template <typename Compressor>
  19396. static std::string compress_payload_for_parity(const std::string &in) {
  19397. std::string out;
  19398. Compressor compressor;
  19399. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19400. [&](const char *data, size_t n) {
  19401. out.append(data, n);
  19402. return true;
  19403. });
  19404. EXPECT_TRUE(ok);
  19405. return out;
  19406. }
  19407. // Helper function for compression parity tests
  19408. template <typename Compressor>
  19409. static void test_compression_parity(const std::string &original,
  19410. const std::string &path,
  19411. const std::string &encoding) {
  19412. const std::string compressed =
  19413. compress_payload_for_parity<Compressor>(original);
  19414. Server svr;
  19415. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19416. res.set_content(compressed, "application/octet-stream");
  19417. res.set_header("Content-Encoding", encoding);
  19418. });
  19419. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19420. auto se = detail::scope_exit([&] {
  19421. svr.stop();
  19422. t.join();
  19423. ASSERT_FALSE(svr.is_running());
  19424. });
  19425. svr.wait_until_ready();
  19426. Client cli(HOST, PORT);
  19427. // Non-streaming
  19428. {
  19429. auto res = cli.Get(path);
  19430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19431. EXPECT_EQ(StatusCode::OK_200, res->status);
  19432. EXPECT_EQ(original, res->body);
  19433. }
  19434. // Streaming
  19435. {
  19436. auto h = cli.open_stream("GET", path);
  19437. ASSERT_TRUE(h.is_valid());
  19438. EXPECT_EQ(original, read_all(h));
  19439. }
  19440. }
  19441. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19442. TEST(ParityTest, Gzip) {
  19443. test_compression_parity<detail::gzip_compressor>(
  19444. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19445. }
  19446. #endif
  19447. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19448. TEST(ParityTest, Brotli) {
  19449. test_compression_parity<detail::brotli_compressor>(
  19450. "Hello, brotli parity test payload", "/parity-br", "br");
  19451. }
  19452. #endif
  19453. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19454. TEST(ParityTest, Zstd) {
  19455. test_compression_parity<detail::zstd_compressor>(
  19456. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19457. }
  19458. #endif
  19459. //==============================================================================
  19460. // New Stream API Tests
  19461. //==============================================================================
  19462. inline std::string read_body(httplib::stream::Result &result) {
  19463. std::string body;
  19464. while (result.next()) {
  19465. body.append(result.data(), result.size());
  19466. }
  19467. return body;
  19468. }
  19469. TEST(ClientConnectionTest, Basic) {
  19470. httplib::ClientConnection conn;
  19471. EXPECT_FALSE(conn.is_open());
  19472. conn.sock = 1;
  19473. EXPECT_TRUE(conn.is_open());
  19474. httplib::ClientConnection conn2(std::move(conn));
  19475. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19476. conn2.sock = INVALID_SOCKET;
  19477. }
  19478. // Unified test server for all stream::* tests
  19479. class StreamApiTest : public ::testing::Test {
  19480. protected:
  19481. void SetUp() override {
  19482. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19483. res.set_content("Hello World!", "text/plain");
  19484. });
  19485. svr_.Get("/echo-params",
  19486. [](const httplib::Request &req, httplib::Response &res) {
  19487. std::string r;
  19488. for (const auto &p : req.params) {
  19489. if (!r.empty()) r += "&";
  19490. r += p.first + "=" + p.second;
  19491. }
  19492. res.set_content(r, "text/plain");
  19493. });
  19494. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19495. res.set_content(req.body, req.get_header_value("Content-Type"));
  19496. });
  19497. svr_.Post("/echo-headers",
  19498. [](const httplib::Request &req, httplib::Response &res) {
  19499. std::string r;
  19500. for (const auto &h : req.headers)
  19501. r += h.first + ": " + h.second + "\n";
  19502. res.set_content(r, "text/plain");
  19503. });
  19504. svr_.Post("/echo-params",
  19505. [](const httplib::Request &req, httplib::Response &res) {
  19506. std::string r = "params:";
  19507. for (const auto &p : req.params)
  19508. r += p.first + "=" + p.second + ";";
  19509. res.set_content(r + " body:" + req.body, "text/plain");
  19510. });
  19511. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19512. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19513. });
  19514. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19515. res.set_content("PUT:" + req.body, "text/plain");
  19516. });
  19517. svr_.Patch("/echo",
  19518. [](const httplib::Request &req, httplib::Response &res) {
  19519. res.set_content("PATCH:" + req.body, "text/plain");
  19520. });
  19521. svr_.Delete(
  19522. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19523. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19524. "text/plain");
  19525. });
  19526. svr_.Get("/head-test",
  19527. [](const httplib::Request &, httplib::Response &res) {
  19528. res.set_content("body for HEAD", "text/plain");
  19529. });
  19530. svr_.Options("/options",
  19531. [](const httplib::Request &, httplib::Response &res) {
  19532. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19533. });
  19534. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19535. svr_.wait_until_ready();
  19536. }
  19537. void TearDown() override {
  19538. svr_.stop();
  19539. if (thread_.joinable()) thread_.join();
  19540. }
  19541. httplib::Server svr_;
  19542. std::thread thread_;
  19543. };
  19544. // stream::Get tests
  19545. TEST_F(StreamApiTest, GetBasic) {
  19546. httplib::Client cli(HOST, PORT);
  19547. auto result = httplib::stream::Get(cli, "/hello");
  19548. ASSERT_TRUE(result.is_valid());
  19549. EXPECT_EQ(200, result.status());
  19550. EXPECT_EQ("Hello World!", read_body(result));
  19551. }
  19552. TEST_F(StreamApiTest, GetWithParams) {
  19553. httplib::Client cli(HOST, PORT);
  19554. httplib::Params params{{"foo", "bar"}};
  19555. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19556. ASSERT_TRUE(result.is_valid());
  19557. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19558. }
  19559. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19560. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19561. httplib::Client cli(HOST, PORT);
  19562. cli.set_payload_max_length(0);
  19563. auto result = httplib::stream::Get(cli, "/hello");
  19564. ASSERT_TRUE(result.is_valid());
  19565. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19566. EXPECT_EQ("Hello World!", read_body(result));
  19567. }
  19568. #endif
  19569. TEST_F(StreamApiTest, GetConnectionError) {
  19570. httplib::Client cli(HOST, 9999);
  19571. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19572. }
  19573. TEST_F(StreamApiTest, Get404) {
  19574. httplib::Client cli(HOST, PORT);
  19575. auto result = httplib::stream::Get(cli, "/nonexistent");
  19576. EXPECT_TRUE(result.is_valid());
  19577. EXPECT_EQ(404, result.status());
  19578. }
  19579. // stream::Post tests
  19580. TEST_F(StreamApiTest, PostBasic) {
  19581. httplib::Client cli(HOST, PORT);
  19582. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19583. "application/json");
  19584. ASSERT_TRUE(result.is_valid());
  19585. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19586. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19587. }
  19588. TEST_F(StreamApiTest, PostWithHeaders) {
  19589. httplib::Client cli(HOST, PORT);
  19590. httplib::Headers headers{{"X-Custom", "value"}};
  19591. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19592. "text/plain");
  19593. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19594. }
  19595. TEST_F(StreamApiTest, PostWithParams) {
  19596. httplib::Client cli(HOST, PORT);
  19597. httplib::Params params{{"k", "v"}};
  19598. auto result =
  19599. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19600. auto body = read_body(result);
  19601. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19602. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19603. }
  19604. TEST_F(StreamApiTest, PostLarge) {
  19605. httplib::Client cli(HOST, PORT);
  19606. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19607. size_t total = 0;
  19608. while (result.next()) {
  19609. total += result.size();
  19610. }
  19611. EXPECT_EQ(100u * 1024u, total);
  19612. }
  19613. // stream::Put/Patch tests
  19614. TEST_F(StreamApiTest, PutAndPatch) {
  19615. httplib::Client cli(HOST, PORT);
  19616. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19617. EXPECT_EQ("PUT:test", read_body(put));
  19618. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19619. EXPECT_EQ("PATCH:test", read_body(patch));
  19620. }
  19621. // stream::Delete tests
  19622. TEST_F(StreamApiTest, Delete) {
  19623. httplib::Client cli(HOST, PORT);
  19624. auto del1 = httplib::stream::Delete(cli, "/resource");
  19625. EXPECT_EQ("Deleted", read_body(del1));
  19626. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19627. EXPECT_EQ("Deleted:data", read_body(del2));
  19628. }
  19629. // stream::Head/Options tests
  19630. TEST_F(StreamApiTest, HeadAndOptions) {
  19631. httplib::Client cli(HOST, PORT);
  19632. auto head = httplib::stream::Head(cli, "/head-test");
  19633. EXPECT_TRUE(head.is_valid());
  19634. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19635. auto opts = httplib::stream::Options(cli, "/options");
  19636. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19637. }
  19638. // SSL stream::* tests
  19639. #ifdef CPPHTTPLIB_SSL_ENABLED
  19640. class SSLStreamApiTest : public ::testing::Test {
  19641. protected:
  19642. void SetUp() override {
  19643. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19644. res.set_content("Hello SSL!", "text/plain");
  19645. });
  19646. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19647. res.set_content(req.body, "text/plain");
  19648. });
  19649. port_ = svr_.bind_to_any_port("127.0.0.1");
  19650. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19651. svr_.wait_until_ready();
  19652. }
  19653. void TearDown() override {
  19654. svr_.stop();
  19655. if (thread_.joinable()) thread_.join();
  19656. }
  19657. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19658. std::thread thread_;
  19659. int port_ = 0;
  19660. };
  19661. TEST_F(SSLStreamApiTest, GetAndPost) {
  19662. httplib::SSLClient cli("127.0.0.1", port_);
  19663. cli.enable_server_certificate_verification(false);
  19664. auto get = httplib::stream::Get(cli, "/hello");
  19665. EXPECT_EQ("Hello SSL!", read_body(get));
  19666. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19667. EXPECT_EQ("test", read_body(post));
  19668. }
  19669. #endif
  19670. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19671. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19672. // BodyReader
  19673. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19674. // Test that read timeout during streaming is detected
  19675. // Use a large content-length response where server delays mid-stream
  19676. Server svr;
  19677. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19678. // Send a large response with delay in the middle
  19679. res.set_content_provider(
  19680. 1000, // content_length
  19681. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19682. if (offset < 100) {
  19683. // Send first 100 bytes immediately
  19684. std::string data(100, 'A');
  19685. sink.write(data.c_str(), data.size());
  19686. return true;
  19687. }
  19688. // Then delay longer than client timeout
  19689. std::this_thread::sleep_for(std::chrono::seconds(3));
  19690. std::string data(900, 'B');
  19691. sink.write(data.c_str(), data.size());
  19692. return true;
  19693. });
  19694. });
  19695. auto port = 8091;
  19696. std::thread t([&]() { svr.listen("localhost", port); });
  19697. svr.wait_until_ready();
  19698. Client cli("localhost", port);
  19699. cli.set_read_timeout(1, 0); // 1 second timeout
  19700. auto handle = cli.open_stream("GET", "/slow-stream");
  19701. ASSERT_TRUE(handle.is_valid());
  19702. char buf[256];
  19703. ssize_t total = 0;
  19704. ssize_t n;
  19705. bool got_error = false;
  19706. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19707. total += n;
  19708. }
  19709. if (n < 0) {
  19710. got_error = true;
  19711. // Should be timeout or read error
  19712. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19713. handle.get_read_error() == Error::Read)
  19714. << "Actual error: " << to_string(handle.get_read_error());
  19715. }
  19716. // Either we got an error, or we got less data than expected
  19717. EXPECT_TRUE(got_error || total < 1000)
  19718. << "Expected timeout but got all " << total << " bytes";
  19719. svr.stop();
  19720. t.join();
  19721. }
  19722. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19723. // Test connection closed detection via BodyReader
  19724. Server svr;
  19725. std::atomic<bool> close_now{false};
  19726. svr.Get("/will-close", [&](const Request &, Response &res) {
  19727. res.set_content_provider(
  19728. 10000, // Large content_length that we won't fully send
  19729. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19730. if (offset < 100) {
  19731. std::string data(100, 'X');
  19732. sink.write(data.c_str(), data.size());
  19733. return true;
  19734. }
  19735. // Wait for signal then abort
  19736. while (!close_now) {
  19737. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19738. }
  19739. return false; // Abort - server will close connection
  19740. });
  19741. });
  19742. auto port = 8092;
  19743. std::thread t([&]() { svr.listen("localhost", port); });
  19744. svr.wait_until_ready();
  19745. Client cli("localhost", port);
  19746. auto handle = cli.open_stream("GET", "/will-close");
  19747. ASSERT_TRUE(handle.is_valid());
  19748. char buf[256];
  19749. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19750. EXPECT_GT(n, 0) << "First read should succeed";
  19751. // Signal server to close
  19752. close_now = true;
  19753. // Keep reading until error or EOF
  19754. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19755. // Keep reading
  19756. }
  19757. // Should get an error since content_length wasn't satisfied
  19758. if (n < 0) {
  19759. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19760. handle.get_read_error() == Error::Read)
  19761. << "Actual error: " << to_string(handle.get_read_error());
  19762. }
  19763. svr.stop();
  19764. t.join();
  19765. }
  19766. #ifdef CPPHTTPLIB_SSL_ENABLED
  19767. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19768. // Test that read timeout during SSL streaming is detected
  19769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19770. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19771. res.set_content_provider(
  19772. 1000, "text/plain",
  19773. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19774. if (offset < 100) {
  19775. std::string data(100, 'A');
  19776. sink.write(data.c_str(), data.size());
  19777. return true;
  19778. }
  19779. std::this_thread::sleep_for(std::chrono::seconds(3));
  19780. std::string data(900, 'B');
  19781. sink.write(data.c_str(), data.size());
  19782. return true;
  19783. });
  19784. });
  19785. auto port = 8093;
  19786. std::thread t([&]() { svr.listen("localhost", port); });
  19787. svr.wait_until_ready();
  19788. SSLClient cli("localhost", port);
  19789. cli.enable_server_certificate_verification(false);
  19790. cli.set_read_timeout(1, 0); // 1 second timeout
  19791. auto handle = cli.open_stream("GET", "/slow-stream");
  19792. ASSERT_TRUE(handle.is_valid());
  19793. char buf[256];
  19794. ssize_t total = 0;
  19795. ssize_t n;
  19796. bool got_error = false;
  19797. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19798. total += n;
  19799. }
  19800. if (n < 0) {
  19801. got_error = true;
  19802. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19803. handle.get_read_error() == Error::Read)
  19804. << "Actual error: " << to_string(handle.get_read_error());
  19805. }
  19806. EXPECT_TRUE(got_error || total < 1000)
  19807. << "Expected timeout but got all " << total << " bytes";
  19808. svr.stop();
  19809. t.join();
  19810. }
  19811. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19812. // Test SSL connection closed detection
  19813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19814. std::atomic<bool> close_now{false};
  19815. svr.Get("/will-close", [&](const Request &, Response &res) {
  19816. res.set_content_provider(
  19817. 10000, "text/plain",
  19818. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19819. if (offset < 100) {
  19820. std::string data(100, 'X');
  19821. sink.write(data.c_str(), data.size());
  19822. return true;
  19823. }
  19824. while (!close_now) {
  19825. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19826. }
  19827. return false;
  19828. });
  19829. });
  19830. auto port = 8094;
  19831. std::thread t([&]() { svr.listen("localhost", port); });
  19832. svr.wait_until_ready();
  19833. SSLClient cli("localhost", port);
  19834. cli.enable_server_certificate_verification(false);
  19835. auto handle = cli.open_stream("GET", "/will-close");
  19836. ASSERT_TRUE(handle.is_valid());
  19837. char buf[256];
  19838. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19839. EXPECT_GT(n, 0);
  19840. // Signal server to close
  19841. close_now = true;
  19842. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19843. // Keep reading
  19844. }
  19845. if (n < 0) {
  19846. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19847. handle.get_read_error() == Error::Read)
  19848. << "Actual error: " << to_string(handle.get_read_error());
  19849. }
  19850. svr.stop();
  19851. t.join();
  19852. }
  19853. #endif
  19854. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19855. using namespace httplib;
  19856. // Create a test file
  19857. const char *fname = "etag_testfile.txt";
  19858. const char *content = "etag-content";
  19859. {
  19860. std::ofstream ofs(fname);
  19861. ofs << content;
  19862. ASSERT_TRUE(ofs.good());
  19863. }
  19864. Server svr;
  19865. svr.set_mount_point("/static", ".");
  19866. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19867. svr.wait_until_ready();
  19868. Client cli(HOST, PORT);
  19869. // First request: should get 200 with ETag header
  19870. auto res1 = cli.Get("/static/etag_testfile.txt");
  19871. ASSERT_TRUE(res1);
  19872. ASSERT_EQ(200, res1->status);
  19873. ASSERT_TRUE(res1->has_header("ETag"));
  19874. std::string etag = res1->get_header_value("ETag");
  19875. EXPECT_FALSE(etag.empty());
  19876. // Verify ETag format: W/"hex-hex"
  19877. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19878. EXPECT_EQ('W', etag[0]);
  19879. EXPECT_EQ('/', etag[1]);
  19880. EXPECT_EQ('"', etag[2]);
  19881. EXPECT_EQ('"', etag.back());
  19882. // Exact match: expect 304 Not Modified
  19883. Headers h2 = {{"If-None-Match", etag}};
  19884. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19885. ASSERT_TRUE(res2);
  19886. EXPECT_EQ(304, res2->status);
  19887. // Wildcard match: expect 304 Not Modified
  19888. Headers h3 = {{"If-None-Match", "*"}};
  19889. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19890. ASSERT_TRUE(res3);
  19891. EXPECT_EQ(304, res3->status);
  19892. // Non-matching ETag: expect 200
  19893. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19894. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19895. ASSERT_TRUE(res4);
  19896. EXPECT_EQ(200, res4->status);
  19897. // Multiple ETags with one matching: expect 304
  19898. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19899. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19900. ASSERT_TRUE(res5);
  19901. EXPECT_EQ(304, res5->status);
  19902. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19903. // that equivalent to the single comma-separated list above, so the match on
  19904. // the second line must still be found.
  19905. Headers h6;
  19906. h6.emplace("If-None-Match", "W/\"other\"");
  19907. h6.emplace("If-None-Match", etag);
  19908. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19909. ASSERT_TRUE(res6);
  19910. EXPECT_EQ(304, res6->status);
  19911. svr.stop();
  19912. t.join();
  19913. std::remove(fname);
  19914. }
  19915. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19916. using namespace httplib;
  19917. Server svr;
  19918. svr.set_mount_point("/static", ".");
  19919. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19920. svr.wait_until_ready();
  19921. Client cli(HOST, PORT);
  19922. // Send If-None-Match: * to a non-existent file
  19923. Headers h = {{"If-None-Match", "*"}};
  19924. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19926. EXPECT_EQ(404, res->status);
  19927. svr.stop();
  19928. t.join();
  19929. }
  19930. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19931. using namespace httplib;
  19932. // Create a test file
  19933. const char *fname = "etag_boundary_testfile.txt";
  19934. const char *content = "boundary-test";
  19935. {
  19936. std::ofstream ofs(fname);
  19937. ofs << content;
  19938. ASSERT_TRUE(ofs.good());
  19939. }
  19940. Server svr;
  19941. svr.set_mount_point("/static", ".");
  19942. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19943. svr.wait_until_ready();
  19944. Client cli(HOST, PORT);
  19945. // Get the actual ETag
  19946. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19947. ASSERT_TRUE(res1);
  19948. ASSERT_EQ(200, res1->status);
  19949. ASSERT_TRUE(res1->has_header("ETag"));
  19950. std::string etag = res1->get_header_value("ETag");
  19951. // Test 1: Very long ETag value (longer than actual ETag)
  19952. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19953. Headers h1 = {{"If-None-Match", "W/"
  19954. "\"very-long-etag-value-that-is-much-longer-"
  19955. "than-the-actual-etag-value\""}};
  19956. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19957. ASSERT_TRUE(res2);
  19958. EXPECT_EQ(200, res2->status); // Should not match
  19959. // Test 2: Long string followed by wildcard
  19960. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19961. // string)
  19962. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19963. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19964. ASSERT_TRUE(res3);
  19965. EXPECT_EQ(304, res3->status); // Should match on "*"
  19966. // Test 3: Wildcard followed by long string
  19967. // Should match on "*" immediately and return 304
  19968. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19969. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19970. ASSERT_TRUE(res4);
  19971. EXPECT_EQ(304, res4->status); // Should match on "*"
  19972. // Test 4: Multiple long non-matching values
  19973. // Should NOT match and return 200 (test that all comparisons are safe)
  19974. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19975. "W/\"second-long-non-matching-value\", "
  19976. "W/\"third-long-non-matching-value\""}};
  19977. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19978. ASSERT_TRUE(res5);
  19979. EXPECT_EQ(200, res5->status); // Should not match
  19980. // Test 5: Single character that is not "*" (edge case)
  19981. Headers h5 = {{"If-None-Match", "X"}};
  19982. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19983. ASSERT_TRUE(res6);
  19984. EXPECT_EQ(200, res6->status); // Should not match
  19985. svr.stop();
  19986. t.join();
  19987. std::remove(fname);
  19988. }
  19989. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19990. using namespace httplib;
  19991. // Create a test file
  19992. const char *fname = "ims_testfile.txt";
  19993. const char *content = "if-modified-since-test";
  19994. {
  19995. std::ofstream ofs(fname);
  19996. ofs << content;
  19997. ASSERT_TRUE(ofs.good());
  19998. }
  19999. Server svr;
  20000. svr.set_mount_point("/static", ".");
  20001. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20002. svr.wait_until_ready();
  20003. Client cli(HOST, PORT);
  20004. // First request: should get 200 with Last-Modified header
  20005. auto res1 = cli.Get("/static/ims_testfile.txt");
  20006. ASSERT_TRUE(res1);
  20007. ASSERT_EQ(200, res1->status);
  20008. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20009. std::string last_modified = res1->get_header_value("Last-Modified");
  20010. EXPECT_FALSE(last_modified.empty());
  20011. // If-Modified-Since with same time: expect 304
  20012. Headers h2 = {{"If-Modified-Since", last_modified}};
  20013. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20014. ASSERT_TRUE(res2);
  20015. EXPECT_EQ(304, res2->status);
  20016. // If-Modified-Since with future time: expect 304
  20017. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20018. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20019. ASSERT_TRUE(res3);
  20020. EXPECT_EQ(304, res3->status);
  20021. // If-Modified-Since with past time: expect 200
  20022. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20023. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20024. ASSERT_TRUE(res4);
  20025. EXPECT_EQ(200, res4->status);
  20026. // If-None-Match takes precedence over If-Modified-Since
  20027. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20028. ASSERT_TRUE(res1->has_header("ETag"));
  20029. std::string etag = res1->get_header_value("ETag");
  20030. Headers h5 = {{"If-None-Match", etag},
  20031. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20032. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20033. ASSERT_TRUE(res5);
  20034. EXPECT_EQ(304, res5->status);
  20035. svr.stop();
  20036. t.join();
  20037. std::remove(fname);
  20038. }
  20039. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20040. using namespace httplib;
  20041. Server svr;
  20042. // Endpoint that returns compressible content
  20043. svr.Get("/compressible", [](const Request &, Response &res) {
  20044. // Return a large enough body to trigger compression
  20045. std::string body(1000, 'a');
  20046. res.set_content(body, "text/plain");
  20047. });
  20048. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20049. svr.wait_until_ready();
  20050. Client cli(HOST, PORT);
  20051. // Request with gzip support: should get Vary header when compressed
  20052. cli.set_compress(true);
  20053. auto res1 = cli.Get("/compressible");
  20054. ASSERT_TRUE(res1);
  20055. EXPECT_EQ(200, res1->status);
  20056. // If Content-Encoding is set, Vary should also be set
  20057. if (res1->has_header("Content-Encoding")) {
  20058. EXPECT_TRUE(res1->has_header("Vary"));
  20059. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20060. }
  20061. // Request without Accept-Encoding header: should not have compression
  20062. Headers h_no_compress;
  20063. auto res2 = cli.Get("/compressible", h_no_compress);
  20064. ASSERT_TRUE(res2);
  20065. EXPECT_EQ(200, res2->status);
  20066. // Verify Vary header is present when compression is applied
  20067. // (the exact behavior depends on server configuration)
  20068. svr.stop();
  20069. t.join();
  20070. }
  20071. TEST(ETagTest, IfRangeWithETag) {
  20072. using namespace httplib;
  20073. // Create a test file with known content
  20074. const char *fname = "if_range_testfile.txt";
  20075. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20076. {
  20077. std::ofstream ofs(fname);
  20078. ofs << content;
  20079. ASSERT_TRUE(ofs.good());
  20080. }
  20081. Server svr;
  20082. svr.set_mount_point("/static", ".");
  20083. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20084. svr.wait_until_ready();
  20085. Client cli(HOST, PORT);
  20086. // First request: get ETag
  20087. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20088. ASSERT_TRUE(res1);
  20089. ASSERT_EQ(200, res1->status);
  20090. ASSERT_TRUE(res1->has_header("ETag"));
  20091. std::string etag = res1->get_header_value("ETag");
  20092. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20093. // Since our server generates weak ETags (W/"..."), If-Range with our
  20094. // ETag should NOT result in partial content - it should return full content.
  20095. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20096. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20097. ASSERT_TRUE(res2);
  20098. // Weak ETag in If-Range -> full content (200), not partial (206)
  20099. EXPECT_EQ(200, res2->status);
  20100. EXPECT_EQ(content, res2->body);
  20101. EXPECT_FALSE(res2->has_header("Content-Range"));
  20102. // Range request with non-matching If-Range (ETag): should get 200 (full
  20103. // content)
  20104. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20105. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20106. ASSERT_TRUE(res3);
  20107. EXPECT_EQ(200, res3->status);
  20108. EXPECT_EQ(content, res3->body);
  20109. EXPECT_FALSE(res3->has_header("Content-Range"));
  20110. // Range request with strong ETag (hypothetical - our server doesn't generate
  20111. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20112. // should return full content)
  20113. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20114. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20115. ASSERT_TRUE(res4);
  20116. EXPECT_EQ(200, res4->status);
  20117. EXPECT_EQ(content, res4->body);
  20118. EXPECT_FALSE(res4->has_header("Content-Range"));
  20119. svr.stop();
  20120. t.join();
  20121. std::remove(fname);
  20122. }
  20123. TEST(ETagTest, IfRangeWithDate) {
  20124. using namespace httplib;
  20125. // Create a test file
  20126. const char *fname = "if_range_date_testfile.txt";
  20127. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20128. {
  20129. std::ofstream ofs(fname);
  20130. ofs << content;
  20131. ASSERT_TRUE(ofs.good());
  20132. }
  20133. Server svr;
  20134. svr.set_mount_point("/static", ".");
  20135. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20136. svr.wait_until_ready();
  20137. Client cli(HOST, PORT);
  20138. // First request: get Last-Modified
  20139. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20140. ASSERT_TRUE(res1);
  20141. ASSERT_EQ(200, res1->status);
  20142. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20143. std::string last_modified = res1->get_header_value("Last-Modified");
  20144. // Range request with matching If-Range (date): should get 206
  20145. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20146. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20147. ASSERT_TRUE(res2);
  20148. EXPECT_EQ(206, res2->status);
  20149. EXPECT_EQ("FGHIJ", res2->body);
  20150. // Range request with old If-Range date: should get 200 (full content)
  20151. Headers h3 = {{"Range", "bytes=5-9"},
  20152. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20153. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20154. ASSERT_TRUE(res3);
  20155. EXPECT_EQ(200, res3->status);
  20156. EXPECT_EQ(content, res3->body);
  20157. // Range request with future If-Range date: should get 206
  20158. Headers h4 = {{"Range", "bytes=0-4"},
  20159. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20160. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20161. ASSERT_TRUE(res4);
  20162. EXPECT_EQ(206, res4->status);
  20163. EXPECT_EQ("ABCDE", res4->body);
  20164. svr.stop();
  20165. t.join();
  20166. std::remove(fname);
  20167. }
  20168. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20169. using namespace httplib;
  20170. const char *fname = "etag_malformed.txt";
  20171. const char *content = "malformed-etag";
  20172. {
  20173. std::ofstream ofs(fname);
  20174. ofs << content;
  20175. ASSERT_TRUE(ofs.good());
  20176. }
  20177. Server svr;
  20178. svr.set_mount_point("/static", ".");
  20179. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20180. svr.wait_until_ready();
  20181. Client cli(HOST, PORT);
  20182. // baseline: should get 200 and an ETag
  20183. auto res1 = cli.Get("/static/etag_malformed.txt");
  20184. ASSERT_TRUE(res1);
  20185. ASSERT_EQ(200, res1->status);
  20186. ASSERT_TRUE(res1->has_header("ETag"));
  20187. // Malformed ETag value (missing quotes) should be treated as non-matching
  20188. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20189. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20190. ASSERT_TRUE(res_bad);
  20191. EXPECT_EQ(200, res_bad->status);
  20192. // Whitespace-only header value should be considered invalid / non-matching
  20193. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20194. "Host: localhost\r\n"
  20195. "If-None-Match: \r\n"
  20196. "Connection: close\r\n"
  20197. "\r\n";
  20198. std::string out;
  20199. ASSERT_TRUE(send_request(5, raw_req, &out));
  20200. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20201. svr.stop();
  20202. t.join();
  20203. std::remove(fname);
  20204. }
  20205. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20206. using namespace httplib;
  20207. const char *fname = "ims_invalid_format.txt";
  20208. const char *content = "ims-bad-format";
  20209. {
  20210. std::ofstream ofs(fname);
  20211. ofs << content;
  20212. ASSERT_TRUE(ofs.good());
  20213. }
  20214. Server svr;
  20215. svr.set_mount_point("/static", ".");
  20216. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20217. svr.wait_until_ready();
  20218. Client cli(HOST, PORT);
  20219. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20220. ASSERT_TRUE(res1);
  20221. ASSERT_EQ(200, res1->status);
  20222. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20223. // If-Modified-Since with invalid format should not result in 304
  20224. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20225. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20226. ASSERT_TRUE(res_bad);
  20227. EXPECT_EQ(200, res_bad->status);
  20228. // If-Range with invalid date format should be treated as mismatch -> full
  20229. // content (200)
  20230. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20231. {"If-Range", "invalid-date"}};
  20232. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20233. ASSERT_TRUE(res_ifrange);
  20234. EXPECT_EQ(200, res_ifrange->status);
  20235. svr.stop();
  20236. t.join();
  20237. std::remove(fname);
  20238. }
  20239. TEST(ETagTest, IfRangeWithMalformedETag) {
  20240. using namespace httplib;
  20241. const char *fname = "ifrange_malformed.txt";
  20242. const std::string content = "0123456789";
  20243. {
  20244. std::ofstream ofs(fname);
  20245. ofs << content;
  20246. ASSERT_TRUE(ofs.good());
  20247. }
  20248. Server svr;
  20249. svr.set_mount_point("/static", ".");
  20250. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20251. svr.wait_until_ready();
  20252. Client cli(HOST, PORT);
  20253. // First request: get ETag
  20254. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20255. ASSERT_TRUE(res1);
  20256. ASSERT_EQ(200, res1->status);
  20257. ASSERT_TRUE(res1->has_header("ETag"));
  20258. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20259. // full content (200)
  20260. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20261. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20262. ASSERT_TRUE(res2);
  20263. EXPECT_EQ(200, res2->status);
  20264. EXPECT_EQ(content, res2->body);
  20265. svr.stop();
  20266. t.join();
  20267. std::remove(fname);
  20268. }
  20269. TEST(ETagTest, ExtremeLargeDateValues) {
  20270. using namespace httplib;
  20271. const char *fname = "ims_extreme_date.txt";
  20272. const char *content = "ims-extreme-date";
  20273. {
  20274. std::ofstream ofs(fname);
  20275. ofs << content;
  20276. ASSERT_TRUE(ofs.good());
  20277. }
  20278. Server svr;
  20279. svr.set_mount_point("/static", ".");
  20280. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20281. svr.wait_until_ready();
  20282. Client cli(HOST, PORT);
  20283. auto res1 = cli.Get(std::string("/static/") + fname);
  20284. ASSERT_TRUE(res1);
  20285. ASSERT_EQ(200, res1->status);
  20286. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20287. // Extremely large year that may overflow date parsing routines.
  20288. Headers h_large_date = {
  20289. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20290. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20291. ASSERT_TRUE(res_bad);
  20292. // Expect server to treat this as invalid/mismatch and return full content
  20293. EXPECT_EQ(200, res_bad->status);
  20294. // If-Range with extremely large date should be treated as mismatch -> full
  20295. // content (200)
  20296. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20297. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20298. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20299. ASSERT_TRUE(res_ifrange);
  20300. EXPECT_EQ(200, res_ifrange->status);
  20301. svr.stop();
  20302. t.join();
  20303. std::remove(fname);
  20304. }
  20305. TEST(ETagTest, NegativeFileModificationTime) {
  20306. using namespace httplib;
  20307. const char *fname = "ims_negative_mtime.txt";
  20308. const std::string content = "negative-mtime";
  20309. {
  20310. std::ofstream ofs(fname);
  20311. ofs << content;
  20312. ASSERT_TRUE(ofs.good());
  20313. }
  20314. // Try to set file mtime to a negative value. This may fail on some
  20315. // platforms/filesystems; if it fails, the test will still verify server
  20316. // behaves safely by performing a regular conditional request.
  20317. #if defined(__APPLE__) || defined(__linux__)
  20318. bool set_negative = false;
  20319. do {
  20320. struct timeval times[2];
  20321. // access time: now
  20322. times[0].tv_sec = time(nullptr);
  20323. times[0].tv_usec = 0;
  20324. // modification time: negative (e.g., -1)
  20325. times[1].tv_sec = -1;
  20326. times[1].tv_usec = 0;
  20327. if (utimes(fname, times) == 0) { set_negative = true; }
  20328. } while (0);
  20329. #else
  20330. bool set_negative = false;
  20331. #endif
  20332. Server svr;
  20333. svr.set_mount_point("/static", ".");
  20334. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20335. svr.wait_until_ready();
  20336. Client cli(HOST, PORT);
  20337. auto res1 = cli.Get(std::string("/static/") + fname);
  20338. ASSERT_TRUE(res1);
  20339. ASSERT_EQ(200, res1->status);
  20340. bool has_last_modified = res1->has_header("Last-Modified");
  20341. std::string last_modified;
  20342. if (has_last_modified) {
  20343. last_modified = res1->get_header_value("Last-Modified");
  20344. }
  20345. if (set_negative) {
  20346. // If we successfully set a negative mtime, ensure server returns a
  20347. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20348. // with an old date and ensure server handles it without crash.
  20349. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20350. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20351. ASSERT_TRUE(res2);
  20352. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20353. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20354. } else {
  20355. // Could not set negative mtime on this platform; fall back to verifying
  20356. // that normal invalid/malformed dates are treated safely (non-304).
  20357. Headers h_bad_date = {
  20358. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20359. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20360. ASSERT_TRUE(res_bad);
  20361. EXPECT_EQ(200, res_bad->status);
  20362. }
  20363. svr.stop();
  20364. t.join();
  20365. std::remove(fname);
  20366. }
  20367. //==============================================================================
  20368. // Integration Tests with Server
  20369. //==============================================================================
  20370. class SSEIntegrationTest : public ::testing::Test {
  20371. protected:
  20372. void SetUp() override {
  20373. stop_server_.store(false);
  20374. events_.clear();
  20375. server_ = httplib::detail::make_unique<Server>();
  20376. setup_server();
  20377. start_server();
  20378. }
  20379. void TearDown() override {
  20380. stop_server_.store(true);
  20381. event_cv_.notify_all();
  20382. server_->stop();
  20383. if (server_thread_.joinable()) { server_thread_.join(); }
  20384. }
  20385. void setup_server() {
  20386. // Simple SSE endpoint
  20387. server_->Get("/events", [this](const Request &req, Response &res) {
  20388. auto last_id = req.get_header_value("Last-Event-ID");
  20389. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20390. res.set_chunked_content_provider(
  20391. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20392. std::unique_lock<std::mutex> lock(event_mutex_);
  20393. if (event_cv_.wait_for(
  20394. lock, std::chrono::milliseconds(200), [this] {
  20395. return !events_.empty() || stop_server_.load();
  20396. })) {
  20397. if (stop_server_.load()) { return false; }
  20398. if (!events_.empty()) {
  20399. std::string event = events_.front();
  20400. events_.erase(events_.begin());
  20401. sink.write(event.data(), event.size());
  20402. return true;
  20403. }
  20404. }
  20405. return !stop_server_.load();
  20406. });
  20407. });
  20408. // Endpoint that returns error
  20409. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20410. res.status = 500;
  20411. res.set_content("Internal Server Error", "text/plain");
  20412. });
  20413. // Endpoint for custom event types
  20414. server_->Get("/custom-events", [](const Request &, Response &res) {
  20415. res.set_chunked_content_provider(
  20416. "text/event-stream", [](size_t offset, DataSink &sink) {
  20417. if (offset == 0) {
  20418. std::string event = "event: update\ndata: updated\n\n"
  20419. "event: delete\ndata: deleted\n\n";
  20420. sink.write(event.data(), event.size());
  20421. }
  20422. return false; // End stream after sending
  20423. });
  20424. });
  20425. }
  20426. void start_server() {
  20427. port_ = server_->bind_to_any_port(HOST);
  20428. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20429. // Wait for server to start
  20430. while (!server_->is_running()) {
  20431. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20432. }
  20433. }
  20434. int get_port() const { return port_; }
  20435. void send_event(const std::string &event) {
  20436. std::lock_guard<std::mutex> lock(event_mutex_);
  20437. events_.push_back(event);
  20438. event_cv_.notify_all();
  20439. }
  20440. std::unique_ptr<Server> server_;
  20441. std::thread server_thread_;
  20442. std::mutex event_mutex_;
  20443. std::condition_variable event_cv_;
  20444. std::vector<std::string> events_;
  20445. std::atomic<bool> stop_server_{false};
  20446. std::string last_received_event_id_;
  20447. int port_ = 0;
  20448. };
  20449. //==============================================================================
  20450. // SSE Parsing Tests
  20451. //==============================================================================
  20452. class SSEParsingTest : public SSEIntegrationTest {
  20453. protected:
  20454. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20455. // A trailing sentinel event tells when the whole stream has been parsed.
  20456. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20457. auto body = stream + "event: end\ndata: end\n\n";
  20458. server_->Get("/parse", [body](const Request &, Response &res) {
  20459. res.set_content(body, "text/event-stream");
  20460. });
  20461. return collect("/parse");
  20462. }
  20463. // Runs SSEClient against path until an "end" event arrives and returns the
  20464. // messages dispatched before it
  20465. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20466. Client client(HOST, get_port());
  20467. sse::SSEClient sse(client, path);
  20468. std::mutex mutex;
  20469. std::condition_variable cv;
  20470. std::vector<sse::SSEMessage> messages;
  20471. auto done = false;
  20472. sse.on_message([&](const sse::SSEMessage &msg) {
  20473. std::lock_guard<std::mutex> lock(mutex);
  20474. // Ignore a replay from a reconnect that races with stop()
  20475. if (!done) { messages.push_back(msg); }
  20476. });
  20477. sse.on_event("end", [&](const sse::SSEMessage &) {
  20478. std::lock_guard<std::mutex> lock(mutex);
  20479. done = true;
  20480. cv.notify_all();
  20481. });
  20482. sse.set_reconnect_interval(100);
  20483. sse.start_async();
  20484. {
  20485. std::unique_lock<std::mutex> lock(mutex);
  20486. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20487. }
  20488. sse.stop();
  20489. EXPECT_TRUE(done);
  20490. return messages;
  20491. }
  20492. };
  20493. TEST_F(SSEParsingTest, SingleLineData) {
  20494. auto msgs = parse("data: hello\n\n");
  20495. ASSERT_EQ(msgs.size(), 1u);
  20496. EXPECT_EQ(msgs[0].data, "hello");
  20497. EXPECT_EQ(msgs[0].event, "message");
  20498. }
  20499. TEST_F(SSEParsingTest, MultiLineData) {
  20500. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20501. ASSERT_EQ(msgs.size(), 1u);
  20502. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20503. }
  20504. TEST_F(SSEParsingTest, CustomEventType) {
  20505. auto msgs = parse("event: update\ndata: payload\n\n");
  20506. ASSERT_EQ(msgs.size(), 1u);
  20507. EXPECT_EQ(msgs[0].event, "update");
  20508. EXPECT_EQ(msgs[0].data, "payload");
  20509. }
  20510. TEST_F(SSEParsingTest, EventIdHandling) {
  20511. auto msgs = parse("id: 12345\ndata: test\n\n");
  20512. ASSERT_EQ(msgs.size(), 1u);
  20513. EXPECT_EQ(msgs[0].id, "12345");
  20514. }
  20515. TEST_F(SSEParsingTest, EmptyEventId) {
  20516. auto msgs = parse("id:\ndata: test\n\n");
  20517. ASSERT_EQ(msgs.size(), 1u);
  20518. EXPECT_EQ(msgs[0].id, "");
  20519. }
  20520. TEST_F(SSEParsingTest, CommentsIgnored) {
  20521. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20522. ASSERT_EQ(msgs.size(), 1u);
  20523. EXPECT_EQ(msgs[0].data, "hello");
  20524. EXPECT_EQ(msgs[0].event, "message");
  20525. }
  20526. TEST_F(SSEParsingTest, ColonInValue) {
  20527. auto msgs = parse("data: hello:world:test\n\n");
  20528. ASSERT_EQ(msgs.size(), 1u);
  20529. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20530. }
  20531. TEST_F(SSEParsingTest, FieldNameOnly) {
  20532. // A line without a colon is a field name with an empty value
  20533. auto msgs = parse("data\n\n");
  20534. ASSERT_EQ(msgs.size(), 1u);
  20535. EXPECT_EQ(msgs[0].data, "");
  20536. }
  20537. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20538. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20539. ASSERT_EQ(msgs.size(), 1u);
  20540. EXPECT_EQ(msgs[0].event, "update");
  20541. EXPECT_EQ(msgs[0].data, "hello");
  20542. }
  20543. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20544. auto msgs = parse("data\r\n\r\n");
  20545. ASSERT_EQ(msgs.size(), 1u);
  20546. EXPECT_EQ(msgs[0].data, "");
  20547. }
  20548. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20549. auto msgs = parse("event: update\rdata: hello\r\r");
  20550. ASSERT_EQ(msgs.size(), 1u);
  20551. EXPECT_EQ(msgs[0].event, "update");
  20552. EXPECT_EQ(msgs[0].data, "hello");
  20553. }
  20554. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20555. // Chunk boundaries fall inside every \r\n and right before the first one
  20556. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20557. "\n\r", "\nevent: end\ndata: end\n\n"};
  20558. server_->Get("/split", [chunks](const Request &, Response &res) {
  20559. auto i = std::make_shared<size_t>(0);
  20560. res.set_chunked_content_provider(
  20561. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20562. if (*i == chunks.size()) {
  20563. sink.done();
  20564. } else {
  20565. sink.write(chunks[*i].data(), chunks[*i].size());
  20566. (*i)++;
  20567. }
  20568. return true;
  20569. });
  20570. });
  20571. auto msgs = collect("/split");
  20572. ASSERT_EQ(msgs.size(), 1u);
  20573. EXPECT_EQ(msgs[0].event, "update");
  20574. EXPECT_EQ(msgs[0].data, "hello");
  20575. }
  20576. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20577. // Only a BOM at the start of the stream is ignored
  20578. auto msgs = parse("\xEF\xBB\xBF"
  20579. "data: first\n\n"
  20580. "\xEF\xBB\xBF"
  20581. "data: second\n\n");
  20582. ASSERT_EQ(msgs.size(), 1u);
  20583. EXPECT_EQ(msgs[0].data, "first");
  20584. }
  20585. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20586. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20587. ASSERT_EQ(msgs.size(), 1u);
  20588. EXPECT_EQ(msgs[0].data, "hello");
  20589. EXPECT_EQ(msgs[0].event, "message");
  20590. }
  20591. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20592. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20593. ASSERT_EQ(msgs.size(), 2u);
  20594. EXPECT_EQ(msgs[0].data, "hello");
  20595. EXPECT_EQ(msgs[1].data, "hello");
  20596. }
  20597. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20598. // An event without data is not dispatched, and its type must not leak
  20599. // into the next event
  20600. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20601. ASSERT_EQ(msgs.size(), 1u);
  20602. EXPECT_EQ(msgs[0].event, "message");
  20603. EXPECT_EQ(msgs[0].data, "hello");
  20604. }
  20605. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20606. // The first connection sends only an id; the second echoes back the
  20607. // Last-Event-ID it was reconnected with
  20608. std::atomic<int> connection_count{0};
  20609. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20610. if (connection_count++ == 0) {
  20611. res.set_content("id: 42\n\n", "text/event-stream");
  20612. } else {
  20613. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20614. "\n\nevent: end\ndata: end\n\n",
  20615. "text/event-stream");
  20616. }
  20617. });
  20618. auto msgs = collect("/id-only");
  20619. ASSERT_EQ(msgs.size(), 1u);
  20620. EXPECT_EQ(msgs[0].data, "42");
  20621. }
  20622. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20623. // The first connection sets an id and then clears it with an empty one; the
  20624. // second reports whether it was reconnected with a Last-Event-ID
  20625. std::atomic<int> connection_count{0};
  20626. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20627. if (connection_count++ == 0) {
  20628. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20629. "text/event-stream");
  20630. } else {
  20631. res.set_content(
  20632. std::string("data: ") +
  20633. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20634. "\n\nevent: end\ndata: end\n\n",
  20635. "text/event-stream");
  20636. }
  20637. });
  20638. auto msgs = collect("/id-clear");
  20639. ASSERT_EQ(msgs.size(), 3u);
  20640. EXPECT_EQ(msgs[0].id, "1");
  20641. EXPECT_EQ(msgs[1].id, "");
  20642. EXPECT_EQ(msgs[2].data, "not sent");
  20643. }
  20644. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20645. // The first connection sets an id and then sends ids that cannot be carried
  20646. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20647. // with
  20648. std::atomic<int> connection_count{0};
  20649. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20650. if (connection_count++ == 0) {
  20651. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20652. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20653. "text/event-stream");
  20654. } else {
  20655. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20656. "\n\nevent: end\ndata: end\n\n",
  20657. "text/event-stream");
  20658. }
  20659. });
  20660. auto msgs = collect("/id-unsendable");
  20661. ASSERT_EQ(msgs.size(), 1u);
  20662. EXPECT_EQ(msgs[0].data, "42");
  20663. }
  20664. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20665. auto msgs = parse("event: notification\nid: evt-42\n"
  20666. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20667. ASSERT_EQ(msgs.size(), 1u);
  20668. EXPECT_EQ(msgs[0].event, "notification");
  20669. EXPECT_EQ(msgs[0].id, "evt-42");
  20670. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20671. }
  20672. TEST(SSEMessageTest, Clear) {
  20673. sse::SSEMessage msg;
  20674. msg.event = "custom";
  20675. msg.data = "some data";
  20676. msg.id = "123";
  20677. msg.clear();
  20678. EXPECT_EQ(msg.event, "message");
  20679. EXPECT_EQ(msg.data, "");
  20680. EXPECT_EQ(msg.id, "");
  20681. }
  20682. //==============================================================================
  20683. // SSE Integration Tests
  20684. //==============================================================================
  20685. // Test: Successful connection and on_open callback
  20686. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20687. // Add a simple endpoint that sends one event and closes
  20688. server_->Get("/simple-event", [](const Request &, Response &res) {
  20689. res.set_chunked_content_provider(
  20690. "text/event-stream", [](size_t offset, DataSink &sink) {
  20691. if (offset == 0) {
  20692. std::string event = "data: hello\n\n";
  20693. sink.write(event.data(), event.size());
  20694. }
  20695. return false; // Close stream after sending
  20696. });
  20697. });
  20698. Client client("localhost", get_port());
  20699. sse::SSEClient sse(client, "/simple-event");
  20700. std::atomic<bool> open_called{false};
  20701. std::atomic<bool> message_received{false};
  20702. sse.on_open([&open_called]() { open_called.store(true); });
  20703. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20704. if (msg.data == "hello") { message_received.store(true); }
  20705. });
  20706. sse.set_reconnect_interval(100);
  20707. sse.set_max_reconnect_attempts(1);
  20708. // Start async
  20709. sse.start_async();
  20710. // Wait for message to be processed
  20711. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20712. sse.stop();
  20713. EXPECT_TRUE(open_called.load());
  20714. EXPECT_TRUE(message_received.load());
  20715. }
  20716. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20717. // A data line that never ends.
  20718. server_->Get("/endless-line", [](const Request &, Response &res) {
  20719. res.set_chunked_content_provider(
  20720. "text/event-stream", [](size_t offset, DataSink &sink) {
  20721. if (offset == 0) { sink.write("data: ", 6); }
  20722. std::string chunk(64 * 1024, 'A');
  20723. return sink.write(chunk.data(), chunk.size());
  20724. });
  20725. });
  20726. Client client("localhost", get_port());
  20727. sse::SSEClient sse(client, "/endless-line");
  20728. std::atomic<bool> too_long{false};
  20729. sse.on_error([&](Error err) {
  20730. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20731. });
  20732. sse.set_max_reconnect_attempts(1);
  20733. sse.start_async();
  20734. for (int i = 0; i < 500 && !too_long; i++) {
  20735. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20736. }
  20737. sse.stop();
  20738. EXPECT_TRUE(too_long);
  20739. }
  20740. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  20741. // Far more in all than the client's payload limit below.
  20742. server_->Get("/many-events", [](const Request &, Response &res) {
  20743. res.set_chunked_content_provider(
  20744. "text/event-stream", [](size_t offset, DataSink &sink) {
  20745. if (offset == 0) {
  20746. std::string events;
  20747. for (int i = 0; i < 1000; i++) {
  20748. events += "data: message\n\n";
  20749. }
  20750. sink.write(events.data(), events.size());
  20751. }
  20752. return false;
  20753. });
  20754. });
  20755. Client client("localhost", get_port());
  20756. client.set_payload_max_length(1024);
  20757. sse::SSEClient sse(client, "/many-events");
  20758. std::atomic<int> messages{0};
  20759. std::atomic<bool> too_large{false};
  20760. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  20761. sse.on_error([&](Error err) {
  20762. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  20763. });
  20764. sse.set_max_reconnect_attempts(1);
  20765. sse.start_async();
  20766. for (int i = 0; i < 500 && messages < 1000; i++) {
  20767. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20768. }
  20769. sse.stop();
  20770. EXPECT_GE(messages.load(), 1000);
  20771. EXPECT_FALSE(too_large);
  20772. }
  20773. // Test: on_message callback
  20774. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20775. // Endpoint that sends multiple events then closes
  20776. server_->Get("/multi-event", [](const Request &, Response &res) {
  20777. res.set_chunked_content_provider(
  20778. "text/event-stream", [](size_t offset, DataSink &sink) {
  20779. if (offset == 0) {
  20780. std::string events = "data: message1\n\ndata: message2\n\n";
  20781. sink.write(events.data(), events.size());
  20782. }
  20783. return false;
  20784. });
  20785. });
  20786. Client client("localhost", get_port());
  20787. sse::SSEClient sse(client, "/multi-event");
  20788. std::vector<std::string> received_messages;
  20789. std::mutex messages_mutex;
  20790. sse.on_message([&](const sse::SSEMessage &msg) {
  20791. std::lock_guard<std::mutex> lock(messages_mutex);
  20792. received_messages.push_back(msg.data);
  20793. });
  20794. sse.set_reconnect_interval(100);
  20795. sse.set_max_reconnect_attempts(1);
  20796. sse.start_async();
  20797. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20798. sse.stop();
  20799. std::lock_guard<std::mutex> lock(messages_mutex);
  20800. EXPECT_GE(received_messages.size(), 2u);
  20801. if (received_messages.size() >= 2) {
  20802. EXPECT_EQ(received_messages[0], "message1");
  20803. EXPECT_EQ(received_messages[1], "message2");
  20804. }
  20805. }
  20806. // Test: on_event for specific types
  20807. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20808. Client client("localhost", get_port());
  20809. sse::SSEClient sse(client, "/custom-events");
  20810. std::atomic<bool> update_received{false};
  20811. std::atomic<bool> delete_received{false};
  20812. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20813. if (msg.data == "updated") { update_received.store(true); }
  20814. });
  20815. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20816. if (msg.data == "deleted") { delete_received.store(true); }
  20817. });
  20818. sse.set_max_reconnect_attempts(1);
  20819. sse.start_async();
  20820. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20821. sse.stop();
  20822. EXPECT_TRUE(update_received.load());
  20823. EXPECT_TRUE(delete_received.load());
  20824. }
  20825. // Test: on_error callback on connection failure
  20826. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20827. // Connect to a non-existent port
  20828. Client client("localhost", 59999);
  20829. sse::SSEClient sse(client, "/events");
  20830. std::atomic<bool> error_called{false};
  20831. Error received_error = Error::Success;
  20832. sse.on_error([&](Error err) {
  20833. error_called.store(true);
  20834. received_error = err;
  20835. });
  20836. sse.set_reconnect_interval(50);
  20837. sse.set_max_reconnect_attempts(1);
  20838. sse.start_async();
  20839. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20840. sse.stop();
  20841. EXPECT_TRUE(error_called.load());
  20842. EXPECT_NE(received_error, Error::Success);
  20843. }
  20844. // Test: Last-Event-ID header sent on reconnect
  20845. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20846. // Endpoint that sends event with ID
  20847. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20848. res.set_chunked_content_provider(
  20849. "text/event-stream", [](size_t offset, DataSink &sink) {
  20850. if (offset == 0) {
  20851. std::string event = "id: evt-123\ndata: test\n\n";
  20852. sink.write(event.data(), event.size());
  20853. }
  20854. return false;
  20855. });
  20856. });
  20857. Client client("localhost", get_port());
  20858. sse::SSEClient sse(client, "/event-with-id");
  20859. std::atomic<bool> id_received{false};
  20860. sse.on_message([&](const sse::SSEMessage &msg) {
  20861. if (!msg.id.empty()) { id_received.store(true); }
  20862. });
  20863. sse.set_reconnect_interval(100);
  20864. sse.set_max_reconnect_attempts(1);
  20865. sse.start_async();
  20866. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20867. sse.stop();
  20868. EXPECT_TRUE(id_received.load());
  20869. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20870. }
  20871. // Test: Manual stop
  20872. TEST_F(SSEIntegrationTest, ManualStop) {
  20873. // Endpoint that sends one event and stays open briefly
  20874. std::atomic<bool> handler_running{true};
  20875. server_->Get("/stay-open", [&handler_running](const Request &,
  20876. Response &res) {
  20877. res.set_chunked_content_provider(
  20878. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20879. if (offset == 0) {
  20880. std::string event = "data: connected\n\n";
  20881. sink.write(event.data(), event.size());
  20882. }
  20883. // Keep connection open while handler_running is true
  20884. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20885. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20886. }
  20887. return false;
  20888. });
  20889. });
  20890. Client client("localhost", get_port());
  20891. sse::SSEClient sse(client, "/stay-open");
  20892. std::atomic<bool> connected{false};
  20893. sse.on_open([&connected]() { connected.store(true); });
  20894. sse.set_reconnect_interval(100);
  20895. sse.set_max_reconnect_attempts(1);
  20896. sse.start_async();
  20897. // Wait for connection to establish
  20898. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20899. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20900. }
  20901. EXPECT_TRUE(connected.load());
  20902. EXPECT_TRUE(sse.is_connected());
  20903. // Signal handler to stop
  20904. handler_running.store(false);
  20905. // Stop SSE client
  20906. sse.stop();
  20907. EXPECT_FALSE(sse.is_connected());
  20908. }
  20909. // Test: SSEClient with custom headers
  20910. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20911. // Setup a server endpoint that checks for custom header
  20912. std::atomic<bool> header_received{false};
  20913. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20914. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20915. header_received.store(true);
  20916. }
  20917. res.set_chunked_content_provider("text/event-stream",
  20918. [](size_t, DataSink &) { return false; });
  20919. });
  20920. Client client("localhost", get_port());
  20921. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20922. sse::SSEClient sse(client, "/header-check", headers);
  20923. sse.set_max_reconnect_attempts(1);
  20924. sse.start_async();
  20925. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20926. sse.stop();
  20927. EXPECT_TRUE(header_received.load());
  20928. }
  20929. // Test: Reconnect interval configuration
  20930. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20931. Client client("localhost", get_port());
  20932. sse::SSEClient sse(client, "/events");
  20933. auto &result = sse.set_reconnect_interval(500);
  20934. // Builder pattern should return reference to self
  20935. EXPECT_EQ(&result, &sse);
  20936. }
  20937. // Test: Max reconnect attempts
  20938. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20939. // Connect to non-existent port to force reconnects
  20940. Client client("localhost", 59998);
  20941. sse::SSEClient sse(client, "/events");
  20942. std::atomic<int> error_count{0};
  20943. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20944. sse.set_reconnect_interval(50);
  20945. sse.set_max_reconnect_attempts(2);
  20946. auto start = std::chrono::steady_clock::now();
  20947. sse.start(); // Blocking call
  20948. auto end = std::chrono::steady_clock::now();
  20949. // Should have stopped after 2 failed attempts
  20950. EXPECT_GE(error_count.load(), 2);
  20951. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20952. auto duration =
  20953. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20954. #ifdef _WIN32
  20955. // Windows is much slower for socket connection failures
  20956. EXPECT_LT(duration.count(), 7000);
  20957. #else
  20958. EXPECT_LT(duration.count(), 1000);
  20959. #endif
  20960. }
  20961. // Test: Multi-line data in integration
  20962. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20963. // Endpoint with multi-line data
  20964. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20965. res.set_chunked_content_provider(
  20966. "text/event-stream", [](size_t offset, DataSink &sink) {
  20967. if (offset == 0) {
  20968. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20969. sink.write(event.data(), event.size());
  20970. }
  20971. return false;
  20972. });
  20973. });
  20974. Client client("localhost", get_port());
  20975. sse::SSEClient sse(client, "/multiline-data");
  20976. std::string received_data;
  20977. std::mutex data_mutex;
  20978. sse.on_message([&](const sse::SSEMessage &msg) {
  20979. std::lock_guard<std::mutex> lock(data_mutex);
  20980. received_data = msg.data;
  20981. });
  20982. sse.set_reconnect_interval(100);
  20983. sse.set_max_reconnect_attempts(1);
  20984. sse.start_async();
  20985. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20986. sse.stop();
  20987. std::lock_guard<std::mutex> lock(data_mutex);
  20988. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20989. }
  20990. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20991. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20992. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20993. DataSink &sink) {
  20994. if (offset == 0) {
  20995. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20996. sink.write(events.data(), events.size());
  20997. }
  20998. return false;
  20999. });
  21000. });
  21001. Client client("localhost", get_port());
  21002. sse::SSEClient sse(client, "/empty-data-lines");
  21003. std::mutex mutex;
  21004. std::condition_variable cv;
  21005. std::vector<std::string> received;
  21006. sse.on_message([&](const sse::SSEMessage &msg) {
  21007. std::lock_guard<std::mutex> lock(mutex);
  21008. received.push_back(msg.data);
  21009. cv.notify_all();
  21010. });
  21011. sse.set_max_reconnect_attempts(1);
  21012. sse.start_async();
  21013. {
  21014. std::unique_lock<std::mutex> lock(mutex);
  21015. cv.wait_for(lock, std::chrono::seconds(2),
  21016. [&] { return received.size() >= 3; });
  21017. }
  21018. sse.stop();
  21019. ASSERT_GE(received.size(), 3u);
  21020. EXPECT_EQ(received[0], "");
  21021. EXPECT_EQ(received[1], "\nhello");
  21022. EXPECT_EQ(received[2], "");
  21023. }
  21024. // Test: Auto-reconnect after server disconnection
  21025. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21026. std::atomic<int> connection_count{0};
  21027. std::atomic<int> message_count{0};
  21028. // Endpoint that sends one event and closes, forcing reconnect
  21029. server_->Get("/reconnect-test",
  21030. [&connection_count](const Request &, Response &res) {
  21031. connection_count.fetch_add(1);
  21032. res.set_chunked_content_provider(
  21033. "text/event-stream", [](size_t offset, DataSink &sink) {
  21034. if (offset == 0) {
  21035. std::string event = "data: hello\n\n";
  21036. sink.write(event.data(), event.size());
  21037. }
  21038. return false; // Close connection after sending
  21039. });
  21040. });
  21041. Client client("localhost", get_port());
  21042. sse::SSEClient sse(client, "/reconnect-test");
  21043. sse.on_message([&message_count](const sse::SSEMessage &) {
  21044. message_count.fetch_add(1);
  21045. });
  21046. sse.set_reconnect_interval(100);
  21047. sse.set_max_reconnect_attempts(3);
  21048. sse.start_async();
  21049. // Wait long enough for multiple reconnects
  21050. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21051. sse.stop();
  21052. // Should have connected multiple times (initial + reconnects)
  21053. EXPECT_GE(connection_count.load(), 2);
  21054. // Should have received messages from multiple connections
  21055. EXPECT_GE(message_count.load(), 2);
  21056. }
  21057. // Test: A retry field that is not all ASCII digits is ignored
  21058. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21059. std::atomic<int> connection_count{0};
  21060. server_->Get("/bad-retry",
  21061. [&connection_count](const Request &, Response &res) {
  21062. connection_count.fetch_add(1);
  21063. res.set_chunked_content_provider(
  21064. "text/event-stream", [](size_t offset, DataSink &sink) {
  21065. if (offset == 0) {
  21066. std::string event = "retry: -1\ndata: hello\n\n";
  21067. sink.write(event.data(), event.size());
  21068. }
  21069. return false;
  21070. });
  21071. });
  21072. Client client("localhost", get_port());
  21073. sse::SSEClient sse(client, "/bad-retry");
  21074. sse.set_reconnect_interval(10000);
  21075. sse.start_async();
  21076. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21077. sse.stop();
  21078. EXPECT_EQ(connection_count.load(), 1);
  21079. }
  21080. // Test: A retry field of all ASCII digits sets the reconnection time
  21081. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21082. std::mutex mutex;
  21083. std::condition_variable cv;
  21084. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21085. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21086. {
  21087. std::lock_guard<std::mutex> lock(mutex);
  21088. connected_at.push_back(std::chrono::steady_clock::now());
  21089. cv.notify_all();
  21090. }
  21091. res.set_chunked_content_provider(
  21092. "text/event-stream", [](size_t offset, DataSink &sink) {
  21093. if (offset == 0) {
  21094. std::string event = "retry: 0\ndata: hello\n\n";
  21095. sink.write(event.data(), event.size());
  21096. }
  21097. return false;
  21098. });
  21099. });
  21100. Client client("localhost", get_port());
  21101. sse::SSEClient sse(client, "/zero-retry");
  21102. sse.set_reconnect_interval(10000);
  21103. sse.start_async();
  21104. {
  21105. std::unique_lock<std::mutex> lock(mutex);
  21106. cv.wait_for(lock, std::chrono::seconds(5),
  21107. [&] { return connected_at.size() >= 2; });
  21108. }
  21109. sse.stop();
  21110. // The server-supplied interval is applied, but never below 100ms, so
  21111. // "retry: 0" does not cause a busy reconnect loop
  21112. std::lock_guard<std::mutex> lock(mutex);
  21113. ASSERT_GE(connected_at.size(), 2u);
  21114. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21115. connected_at[1] - connected_at[0])
  21116. .count();
  21117. EXPECT_GE(interval_ms, 100);
  21118. }
  21119. // Test: Last-Event-ID sent on reconnect
  21120. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21121. std::atomic<int> connection_count{0};
  21122. std::vector<std::string> received_last_event_ids;
  21123. std::mutex id_mutex;
  21124. // Endpoint that checks Last-Event-ID header and sends event with ID
  21125. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21126. int conn = connection_count.fetch_add(1);
  21127. // Capture the Last-Event-ID header from each connection
  21128. {
  21129. std::lock_guard<std::mutex> lock(id_mutex);
  21130. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21131. }
  21132. res.set_chunked_content_provider(
  21133. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21134. if (offset == 0) {
  21135. std::string event =
  21136. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21137. sink.write(event.data(), event.size());
  21138. }
  21139. return false;
  21140. });
  21141. });
  21142. Client client("localhost", get_port());
  21143. sse::SSEClient sse(client, "/reconnect-with-id");
  21144. sse.set_reconnect_interval(100);
  21145. sse.set_max_reconnect_attempts(3);
  21146. sse.start_async();
  21147. // Wait for at least 2 connections
  21148. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21149. sse.stop();
  21150. // Verify behavior
  21151. std::lock_guard<std::mutex> lock(id_mutex);
  21152. EXPECT_GE(received_last_event_ids.size(), 2u);
  21153. // First connection should have no Last-Event-ID
  21154. if (!received_last_event_ids.empty()) {
  21155. EXPECT_EQ(received_last_event_ids[0], "");
  21156. }
  21157. // Second connection should have Last-Event-ID from first connection
  21158. if (received_last_event_ids.size() >= 2) {
  21159. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21160. }
  21161. }
  21162. // Test: set_headers updates headers used on reconnect
  21163. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21164. std::vector<std::string> received_tokens;
  21165. std::mutex token_mutex;
  21166. // Endpoint that captures Authorization header
  21167. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21168. {
  21169. std::lock_guard<std::mutex> lock(token_mutex);
  21170. received_tokens.push_back(req.get_header_value("Authorization"));
  21171. }
  21172. res.set_chunked_content_provider(
  21173. "text/event-stream", [](size_t offset, DataSink &sink) {
  21174. if (offset == 0) {
  21175. std::string event = "data: hello\n\n";
  21176. sink.write(event.data(), event.size());
  21177. }
  21178. return false; // Close connection to trigger reconnect
  21179. });
  21180. });
  21181. Client client("localhost", get_port());
  21182. Headers headers = {{"Authorization", "Bearer old-token"}};
  21183. sse::SSEClient sse(client, "/auth-check", headers);
  21184. // Update headers on each successful connection
  21185. sse.on_open(
  21186. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21187. sse.set_reconnect_interval(100);
  21188. sse.set_max_reconnect_attempts(3);
  21189. sse.start_async();
  21190. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21191. sse.stop();
  21192. std::lock_guard<std::mutex> lock(token_mutex);
  21193. ASSERT_GE(received_tokens.size(), 2u);
  21194. // First connection uses original header
  21195. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21196. // Second connection uses updated header from set_headers
  21197. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21198. }
  21199. // Test: 401 allows reconnection (so on_error can refresh headers)
  21200. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21201. std::atomic<int> connection_count{0};
  21202. // Endpoint: returns 401 on first attempt, 200 on second
  21203. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21204. int conn = connection_count.fetch_add(1);
  21205. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21206. res.status = StatusCode::Unauthorized_401;
  21207. res.set_content("Unauthorized", "text/plain");
  21208. return;
  21209. }
  21210. res.set_chunked_content_provider(
  21211. "text/event-stream", [](size_t offset, DataSink &sink) {
  21212. if (offset == 0) {
  21213. std::string event = "data: authenticated\n\n";
  21214. sink.write(event.data(), event.size());
  21215. }
  21216. return false;
  21217. });
  21218. });
  21219. Client client("localhost", get_port());
  21220. Headers headers = {{"Authorization", "Bearer expired"}};
  21221. sse::SSEClient sse(client, "/auth-retry", headers);
  21222. std::atomic<bool> message_received{false};
  21223. // Refresh token on error
  21224. sse.on_error(
  21225. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21226. sse.on_message([&](const sse::SSEMessage &msg) {
  21227. if (msg.data == "authenticated") { message_received.store(true); }
  21228. });
  21229. sse.set_reconnect_interval(100);
  21230. sse.set_max_reconnect_attempts(3);
  21231. sse.start_async();
  21232. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21233. sse.stop();
  21234. // Should have reconnected after 401 and succeeded with new token
  21235. EXPECT_GE(connection_count.load(), 2);
  21236. EXPECT_TRUE(message_received.load());
  21237. }
  21238. TEST(Issue2318Test, EmptyHostString) {
  21239. {
  21240. httplib::Client cli_empty("", PORT);
  21241. auto res = cli_empty.Get("/");
  21242. ASSERT_FALSE(res);
  21243. EXPECT_EQ(httplib::Error::Connection, res.error());
  21244. }
  21245. {
  21246. httplib::Client cli(" ", PORT);
  21247. auto res = cli.Get("/");
  21248. ASSERT_FALSE(res);
  21249. EXPECT_EQ(httplib::Error::Connection, res.error());
  21250. }
  21251. }
  21252. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21253. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21254. Server svr;
  21255. // Set a small payload limit (1KB)
  21256. svr.set_payload_max_length(1024);
  21257. svr.Post("/test", [&](const Request &req, Response &res) {
  21258. res.set_content("Body size: " + std::to_string(req.body.size()),
  21259. "text/plain");
  21260. });
  21261. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21262. auto se = detail::scope_exit([&] {
  21263. svr.stop();
  21264. listen_thread.join();
  21265. });
  21266. svr.wait_until_ready();
  21267. // Create data that compresses well but exceeds limit when decompressed
  21268. // 8KB of repeated null bytes compresses to a very small size
  21269. std::string original_data(8 * 1024, '\0');
  21270. // Compress the data using gzip
  21271. std::string compressed_data;
  21272. detail::gzip_compressor compressor;
  21273. compressor.compress(original_data.data(), original_data.size(), true,
  21274. [&](const char *data, size_t size) {
  21275. compressed_data.append(data, size);
  21276. return true;
  21277. });
  21278. // Verify compression worked (compressed should be much smaller)
  21279. ASSERT_LT(compressed_data.size(), original_data.size());
  21280. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21281. // Send compressed data with Content-Encoding: gzip
  21282. Client cli(HOST, PORT);
  21283. Headers headers = {{"Content-Encoding", "gzip"}};
  21284. auto res =
  21285. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21286. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21288. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21289. }
  21290. #endif
  21291. // ============================================================================
  21292. // OpenSSL-Specific Tests
  21293. // ============================================================================
  21294. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21295. X509 *readCertificate(const std::string &strFileName) {
  21296. std::ifstream inStream(strFileName);
  21297. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21298. std::istreambuf_iterator<char>());
  21299. if (strCertPEM.empty()) return (nullptr);
  21300. BIO *pbCert = BIO_new(BIO_s_mem());
  21301. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21302. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21303. BIO_free(pbCert);
  21304. return (pCert);
  21305. }
  21306. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21307. std::ifstream inStream(strFileName);
  21308. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21309. std::istreambuf_iterator<char>());
  21310. if (strPrivateKeyPEM.empty()) return (nullptr);
  21311. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21312. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21313. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21314. BIO_free(pbPrivKey);
  21315. return (pPrivateKey);
  21316. }
  21317. TEST(BindServerTest, UpdateCerts) {
  21318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21319. int port = svr.bind_to_any_port("0.0.0.0");
  21320. ASSERT_TRUE(svr.is_valid());
  21321. ASSERT_TRUE(port > 0);
  21322. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21323. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21324. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21325. ASSERT_TRUE(cert != nullptr);
  21326. ASSERT_TRUE(ca_cert != nullptr);
  21327. ASSERT_TRUE(key != nullptr);
  21328. X509_STORE *cert_store = X509_STORE_new();
  21329. X509_STORE_add_cert(cert_store, ca_cert);
  21330. // svr.update_certs(cert, key, cert_store); // deprecated
  21331. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21332. CLIENT_CA_CERT_FILE);
  21333. ASSERT_TRUE(svr.is_valid());
  21334. svr.stop();
  21335. X509_STORE_free(cert_store);
  21336. X509_free(cert);
  21337. X509_free(ca_cert);
  21338. EVP_PKEY_free(key);
  21339. }
  21340. // Test that update_certs() updates client CA list correctly
  21341. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21342. // Start with file-based constructor
  21343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21344. ASSERT_TRUE(svr.is_valid());
  21345. // Initially no client CA list should be set
  21346. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21347. ASSERT_TRUE(ssl_ctx != nullptr);
  21348. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21349. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21350. EXPECT_EQ(0, count_before);
  21351. // Now update with client CA (PEM string)
  21352. std::string cert_pem, key_pem, ca_pem;
  21353. read_file(SERVER_CERT_FILE, cert_pem);
  21354. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21355. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21356. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21357. ASSERT_TRUE(svr.is_valid());
  21358. // Now client CA list should be set
  21359. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21360. ASSERT_TRUE(ca_list_after != nullptr);
  21361. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21362. }
  21363. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21364. // Test that the file-path SSLServer constructor properly sets the client CA
  21365. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21366. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21367. ASSERT_TRUE(svr.is_valid());
  21368. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21369. ASSERT_TRUE(ssl_ctx != nullptr);
  21370. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21371. ASSERT_TRUE(ca_list != nullptr);
  21372. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21373. }
  21374. #endif
  21375. // ============================================================================
  21376. // MbedTLS-Specific Tests
  21377. // ============================================================================
  21378. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21379. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21380. using namespace httplib::tls;
  21381. // Track if callback was invoked
  21382. bool callback_invoked = false;
  21383. // The callback receives void* ctx which is actually MbedTlsContext*
  21384. // We can access the mbedtls_ssl_config via the context
  21385. auto setup_callback = [&callback_invoked](void *ctx) {
  21386. callback_invoked = true;
  21387. // Cast to MbedTlsContext* to access the ssl config
  21388. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21389. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21390. // Use static variables to hold certificate data (simplified for test)
  21391. static mbedtls_x509_crt own_cert;
  21392. static mbedtls_pk_context own_key;
  21393. static mbedtls_x509_crt ca_chain;
  21394. static bool initialized = false;
  21395. if (!initialized) {
  21396. mbedtls_x509_crt_init(&own_cert);
  21397. mbedtls_pk_init(&own_key);
  21398. mbedtls_x509_crt_init(&ca_chain);
  21399. // Load server certificate
  21400. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21401. return false;
  21402. }
  21403. // Load server private key.
  21404. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21405. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21406. #if MBEDTLS_VERSION_MAJOR == 3
  21407. ,
  21408. mbedtls_ctr_drbg_random, nullptr
  21409. #endif
  21410. ) != 0) {
  21411. return false;
  21412. }
  21413. // Load CA chain for client verification
  21414. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21415. return false;
  21416. }
  21417. initialized = true;
  21418. }
  21419. // Configure the SSL config
  21420. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21421. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21422. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21423. // Set minimum TLS version using mbedTLS native API
  21424. #if MBEDTLS_VERSION_MAJOR >= 3
  21425. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21426. #else
  21427. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21428. MBEDTLS_SSL_MINOR_VERSION_3);
  21429. #endif
  21430. return true;
  21431. };
  21432. SSLServer svr(setup_callback);
  21433. ASSERT_TRUE(svr.is_valid());
  21434. ASSERT_TRUE(callback_invoked);
  21435. svr.Get("/test", [&](const Request &req, Response &res) {
  21436. res.set_content("test", "text/plain");
  21437. auto cert = req.peer_cert();
  21438. ASSERT_TRUE(static_cast<bool>(cert));
  21439. auto common_name = cert.subject_cn();
  21440. EXPECT_EQ("Common Name", common_name);
  21441. });
  21442. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21443. auto se = detail::scope_exit([&] {
  21444. svr.stop();
  21445. t.join();
  21446. ASSERT_FALSE(svr.is_running());
  21447. });
  21448. svr.wait_until_ready();
  21449. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21450. cli.enable_server_certificate_verification(false);
  21451. cli.set_connection_timeout(30);
  21452. auto res = cli.Get("/test");
  21453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21454. ASSERT_EQ(StatusCode::OK_200, res->status);
  21455. }
  21456. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21457. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21458. // keep-alive SSL session, which reads through that config in
  21459. // mbedtls_ssl_close_notify.
  21460. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21462. ASSERT_TRUE(svr.is_valid());
  21463. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21464. res.set_content("test", "text/plain");
  21465. });
  21466. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21467. auto se = detail::scope_exit([&] {
  21468. svr.stop();
  21469. t.join();
  21470. ASSERT_FALSE(svr.is_running());
  21471. });
  21472. svr.wait_until_ready();
  21473. {
  21474. SSLClient cli(HOST, PORT);
  21475. cli.enable_server_certificate_verification(false);
  21476. cli.set_keep_alive(true);
  21477. auto res = cli.Get("/test");
  21478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21479. ASSERT_EQ(StatusCode::OK_200, res->status);
  21480. // cli is destructed here with the keep-alive SSL session still open.
  21481. }
  21482. }
  21483. #endif
  21484. // WebSocket Tests
  21485. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21486. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21487. // defining the meaning of these bits has been negotiated.
  21488. auto make_frame = [](uint8_t first_byte) {
  21489. std::string frame;
  21490. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21491. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21492. frame += "Hello";
  21493. return frame;
  21494. };
  21495. // RSV1 set (0x40)
  21496. {
  21497. detail::BufferStream strm;
  21498. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21499. ws::Opcode opcode;
  21500. std::string payload;
  21501. bool fin;
  21502. EXPECT_EQ(
  21503. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21504. ws::impl::FrameRead::Fail);
  21505. }
  21506. // RSV2 set (0x20)
  21507. {
  21508. detail::BufferStream strm;
  21509. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21510. ws::Opcode opcode;
  21511. std::string payload;
  21512. bool fin;
  21513. EXPECT_EQ(
  21514. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21515. ws::impl::FrameRead::Fail);
  21516. }
  21517. // RSV3 set (0x10)
  21518. {
  21519. detail::BufferStream strm;
  21520. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21521. ws::Opcode opcode;
  21522. std::string payload;
  21523. bool fin;
  21524. EXPECT_EQ(
  21525. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21526. ws::impl::FrameRead::Fail);
  21527. }
  21528. // No RSV bits set - should succeed
  21529. {
  21530. detail::BufferStream strm;
  21531. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21532. ws::Opcode opcode;
  21533. std::string payload;
  21534. bool fin;
  21535. EXPECT_EQ(
  21536. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21537. ws::impl::FrameRead::Ok);
  21538. EXPECT_EQ(ws::Opcode::Text, opcode);
  21539. EXPECT_EQ("Hello", payload);
  21540. EXPECT_TRUE(fin);
  21541. }
  21542. }
  21543. TEST(WebSocketTest, ControlFrameValidation) {
  21544. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21545. // payload length <= 125.
  21546. // Ping with FIN=0 - must be rejected
  21547. {
  21548. detail::BufferStream strm;
  21549. std::string frame;
  21550. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21551. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21552. strm.write(frame.data(), frame.size());
  21553. ws::Opcode opcode;
  21554. std::string payload;
  21555. bool fin;
  21556. EXPECT_EQ(
  21557. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21558. ws::impl::FrameRead::Fail);
  21559. }
  21560. // Close with FIN=0 - must be rejected
  21561. {
  21562. detail::BufferStream strm;
  21563. std::string frame;
  21564. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21565. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21566. strm.write(frame.data(), frame.size());
  21567. ws::Opcode opcode;
  21568. std::string payload;
  21569. bool fin;
  21570. EXPECT_EQ(
  21571. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21572. ws::impl::FrameRead::Fail);
  21573. }
  21574. // Ping with payload_len=126 (extended length) - must be rejected
  21575. {
  21576. detail::BufferStream strm;
  21577. std::string frame;
  21578. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21579. frame += static_cast<char>(126); // payload_len=126 (>125)
  21580. frame += static_cast<char>(0x00); // extended length high byte
  21581. frame += static_cast<char>(126); // extended length low byte
  21582. frame += std::string(126, 'x');
  21583. strm.write(frame.data(), frame.size());
  21584. ws::Opcode opcode;
  21585. std::string payload;
  21586. bool fin;
  21587. EXPECT_EQ(
  21588. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21589. ws::impl::FrameRead::Fail);
  21590. }
  21591. // Ping with FIN=1 and payload_len=125 - should succeed
  21592. {
  21593. detail::BufferStream strm;
  21594. std::string frame;
  21595. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21596. frame += static_cast<char>(125); // payload_len=125
  21597. frame += std::string(125, 'x');
  21598. strm.write(frame.data(), frame.size());
  21599. ws::Opcode opcode;
  21600. std::string payload;
  21601. bool fin;
  21602. EXPECT_EQ(
  21603. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21604. ws::impl::FrameRead::Ok);
  21605. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21606. EXPECT_EQ(125u, payload.size());
  21607. EXPECT_TRUE(fin);
  21608. }
  21609. }
  21610. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21611. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21612. // length MUST be 0.
  21613. // MSB set - must be rejected
  21614. {
  21615. detail::BufferStream strm;
  21616. std::string frame;
  21617. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21618. frame += static_cast<char>(127); // 64-bit extended length
  21619. frame += static_cast<char>(0x80); // MSB set (invalid)
  21620. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21621. strm.write(frame.data(), frame.size());
  21622. ws::Opcode opcode;
  21623. std::string payload;
  21624. bool fin;
  21625. EXPECT_EQ(
  21626. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21627. ws::impl::FrameRead::Fail);
  21628. }
  21629. // MSB clear - should pass length parsing (will be rejected by max_len,
  21630. // but that's a different check; use a small length to verify)
  21631. {
  21632. detail::BufferStream strm;
  21633. std::string frame;
  21634. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21635. frame += static_cast<char>(127); // 64-bit extended length
  21636. frame += std::string(7, '\0'); // high bytes = 0
  21637. frame += static_cast<char>(0x03); // length = 3
  21638. frame += "abc";
  21639. strm.write(frame.data(), frame.size());
  21640. ws::Opcode opcode;
  21641. std::string payload;
  21642. bool fin;
  21643. EXPECT_EQ(
  21644. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21645. ws::impl::FrameRead::Ok);
  21646. EXPECT_EQ(ws::Opcode::Text, opcode);
  21647. EXPECT_EQ("abc", payload);
  21648. }
  21649. }
  21650. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21651. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21652. // Valid UTF-8
  21653. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21654. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21655. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21656. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21657. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21658. // Invalid UTF-8
  21659. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21660. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21661. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21662. EXPECT_FALSE(
  21663. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21664. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21665. }
  21666. TEST(WebSocketTest, ConnectAndDisconnect) {
  21667. Server svr;
  21668. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21669. std::string msg;
  21670. while (ws.read(msg)) {}
  21671. });
  21672. auto port = svr.bind_to_any_port(HOST);
  21673. std::thread t([&]() { svr.listen_after_bind(); });
  21674. svr.wait_until_ready();
  21675. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21676. auto res = client.connect();
  21677. ASSERT_TRUE(res);
  21678. EXPECT_EQ(Error::Success, res.error());
  21679. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21680. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21681. EXPECT_TRUE(client.is_open());
  21682. client.close();
  21683. EXPECT_FALSE(client.is_open());
  21684. svr.stop();
  21685. t.join();
  21686. }
  21687. TEST(WebSocketTest, ValidURL) {
  21688. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21689. EXPECT_TRUE(ws1.is_valid());
  21690. ws::WebSocketClient ws2("ws://example.com/path");
  21691. EXPECT_TRUE(ws2.is_valid());
  21692. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21693. EXPECT_TRUE(ws3.is_valid());
  21694. #ifdef CPPHTTPLIB_SSL_ENABLED
  21695. ws::WebSocketClient wss1("wss://example.com/path");
  21696. EXPECT_TRUE(wss1.is_valid());
  21697. ws::WebSocketClient wss2("wss://example.com:443/path");
  21698. EXPECT_TRUE(wss2.is_valid());
  21699. #endif
  21700. }
  21701. TEST(WebSocketTest, InvalidURL) {
  21702. // No scheme
  21703. ws::WebSocketClient ws1("localhost:8080/path");
  21704. EXPECT_FALSE(ws1.is_valid());
  21705. // No path
  21706. ws::WebSocketClient ws2("ws://localhost:8080");
  21707. EXPECT_FALSE(ws2.is_valid());
  21708. // Empty string
  21709. ws::WebSocketClient ws3("");
  21710. EXPECT_FALSE(ws3.is_valid());
  21711. // Missing host
  21712. ws::WebSocketClient ws4("ws://:8080/path");
  21713. EXPECT_FALSE(ws4.is_valid());
  21714. // Port number overflow — should not crash
  21715. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21716. EXPECT_FALSE(ws5.is_valid());
  21717. // Port out of range
  21718. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21719. EXPECT_FALSE(ws6.is_valid());
  21720. }
  21721. TEST(WebSocketTest, UnsupportedScheme) {
  21722. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21723. ws::WebSocketClient ws1("http://localhost:8080/path");
  21724. EXPECT_FALSE(ws1.is_valid());
  21725. ws::WebSocketClient ws2("https://localhost:8080/path");
  21726. EXPECT_FALSE(ws2.is_valid());
  21727. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21728. EXPECT_FALSE(ws3.is_valid());
  21729. #else
  21730. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21731. std::invalid_argument);
  21732. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21733. std::invalid_argument);
  21734. #endif
  21735. }
  21736. TEST(WebSocketTest, ConnectWhenInvalid) {
  21737. ws::WebSocketClient ws("not a valid url");
  21738. EXPECT_FALSE(ws.is_valid());
  21739. auto res = ws.connect();
  21740. EXPECT_FALSE(res);
  21741. EXPECT_EQ(Error::Connection, res.error());
  21742. EXPECT_EQ(-1, res.status());
  21743. }
  21744. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21745. // Grab a port that is free, then close it again so nothing listens there
  21746. Server svr;
  21747. auto port = svr.bind_to_any_port(HOST);
  21748. svr.stop();
  21749. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21750. auto res = client.connect();
  21751. ASSERT_FALSE(res);
  21752. EXPECT_EQ(Error::Connection, res.error());
  21753. EXPECT_EQ(-1, res.status());
  21754. }
  21755. TEST(WebSocketTest, DefaultPort) {
  21756. ws::WebSocketClient ws1("ws://example.com/path");
  21757. EXPECT_TRUE(ws1.is_valid());
  21758. // ws:// defaults to port 80 (verified by successful parse)
  21759. #ifdef CPPHTTPLIB_SSL_ENABLED
  21760. ws::WebSocketClient ws2("wss://example.com/path");
  21761. EXPECT_TRUE(ws2.is_valid());
  21762. // wss:// defaults to port 443 (verified by successful parse)
  21763. #endif
  21764. }
  21765. TEST(WebSocketTest, IPv6LiteralAddress) {
  21766. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21767. EXPECT_TRUE(ws1.is_valid());
  21768. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21769. EXPECT_TRUE(ws2.is_valid());
  21770. }
  21771. TEST(WebSocketTest, ComplexPath) {
  21772. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21773. EXPECT_TRUE(ws1.is_valid());
  21774. ws::WebSocketClient ws2("ws://localhost:8080/");
  21775. EXPECT_TRUE(ws2.is_valid());
  21776. }
  21777. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21778. Server svr;
  21779. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21780. std::string msg;
  21781. while (ws.read(msg)) {}
  21782. });
  21783. auto port = svr.bind_to_any_port(HOST);
  21784. std::thread t([&]() { svr.listen_after_bind(); });
  21785. svr.wait_until_ready();
  21786. auto another_host = "example.com";
  21787. auto wrong_ip = "192.0.2.1";
  21788. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21789. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21790. ASSERT_TRUE(client.connect());
  21791. EXPECT_TRUE(client.is_open());
  21792. client.close();
  21793. svr.stop();
  21794. t.join();
  21795. }
  21796. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21797. Server svr;
  21798. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21799. std::string msg;
  21800. while (ws.read(msg)) {}
  21801. });
  21802. auto port = svr.bind_to_any_port(HOST);
  21803. std::thread t([&]() { svr.listen_after_bind(); });
  21804. svr.wait_until_ready();
  21805. auto wrong_ip = "192.0.2.1";
  21806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21807. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21808. client.set_connection_timeout(1);
  21809. client.set_read_timeout(1);
  21810. client.set_write_timeout(1);
  21811. EXPECT_FALSE(client.connect());
  21812. EXPECT_FALSE(client.is_open());
  21813. svr.stop();
  21814. t.join();
  21815. }
  21816. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21817. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21818. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21819. // (RFC 6761) is only a map key and the Host header value.
  21820. auto host = "target.invalid";
  21821. Server svr;
  21822. std::string received_host;
  21823. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21824. received_host = req.get_header_value("Host");
  21825. std::string msg;
  21826. while (ws.read(msg)) {}
  21827. });
  21828. auto port = svr.bind_to_any_port(HOST);
  21829. std::thread t([&]() { svr.listen_after_bind(); });
  21830. // ASSERT_* below returns from the test body, which would leave t joinable
  21831. // and make ~thread call std::terminate.
  21832. auto se = detail::scope_exit([&] {
  21833. svr.stop();
  21834. if (t.joinable()) { t.join(); }
  21835. });
  21836. svr.wait_until_ready();
  21837. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21838. std::to_string(port) + "/ws");
  21839. client.set_hostname_addr_map({{host, HOST}});
  21840. ASSERT_TRUE(client.connect());
  21841. EXPECT_TRUE(client.is_open());
  21842. client.close();
  21843. svr.stop();
  21844. t.join();
  21845. // The mapping only redirects the connection; the identity stays host_.
  21846. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21847. }
  21848. class WebSocketIntegrationTest : public ::testing::Test {
  21849. protected:
  21850. void SetUp() override {
  21851. server_ = httplib::detail::make_unique<Server>();
  21852. setup_server();
  21853. start_server();
  21854. }
  21855. void TearDown() override {
  21856. server_->stop();
  21857. if (server_thread_.joinable()) { server_thread_.join(); }
  21858. }
  21859. void setup_server() {
  21860. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21861. std::string msg;
  21862. ws::ReadResult ret;
  21863. while ((ret = ws.read(msg))) {
  21864. if (ret == ws::Binary) {
  21865. ws.send(msg.data(), msg.size());
  21866. } else {
  21867. ws.send(msg);
  21868. }
  21869. }
  21870. });
  21871. server_->WebSocket("/ws-echo-string",
  21872. [](const Request &, ws::WebSocket &ws) {
  21873. std::string msg;
  21874. while (ws.read(msg)) {
  21875. ws.send("echo: " + msg);
  21876. }
  21877. });
  21878. server_->WebSocket(
  21879. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21880. // Echo back request metadata
  21881. ws.send("path:" + req.path);
  21882. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21883. std::string msg;
  21884. while (ws.read(msg)) {}
  21885. });
  21886. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21887. std::string msg;
  21888. ws.read(msg); // wait for a message
  21889. ws.close();
  21890. });
  21891. server_->WebSocket("/ws-close-status",
  21892. [](const Request &, ws::WebSocket &ws) {
  21893. std::string msg;
  21894. ws.read(msg); // wait for a message
  21895. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21896. });
  21897. server_->WebSocket(
  21898. "/ws-subprotocol",
  21899. [](const Request &, ws::WebSocket &ws) {
  21900. std::string msg;
  21901. while (ws.read(msg)) {
  21902. ws.send(msg);
  21903. }
  21904. },
  21905. [](const std::vector<std::string> &protocols) -> std::string {
  21906. for (const auto &p : protocols) {
  21907. if (p == "graphql-ws") { return p; }
  21908. }
  21909. return "";
  21910. });
  21911. server_->WebSocket(
  21912. "/ws-subprotocol-unoffered",
  21913. [](const Request &, ws::WebSocket &ws) {
  21914. std::string msg;
  21915. while (ws.read(msg)) {
  21916. ws.send(msg);
  21917. }
  21918. },
  21919. [](const std::vector<std::string> &) -> std::string {
  21920. return "admin";
  21921. });
  21922. }
  21923. void start_server() {
  21924. port_ = server_->bind_to_any_port(HOST);
  21925. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21926. server_->wait_until_ready();
  21927. }
  21928. std::unique_ptr<Server> server_;
  21929. std::thread server_thread_;
  21930. int port_ = 0;
  21931. };
  21932. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21933. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21934. "/ws-echo");
  21935. ASSERT_TRUE(client.connect());
  21936. ASSERT_TRUE(client.is_open());
  21937. ASSERT_TRUE(client.send("Hello WebSocket"));
  21938. std::string msg;
  21939. EXPECT_EQ(ws::Text, client.read(msg));
  21940. EXPECT_EQ("Hello WebSocket", msg);
  21941. client.close();
  21942. }
  21943. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21945. "/ws-echo");
  21946. ASSERT_TRUE(client.connect());
  21947. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21948. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21949. std::string msg;
  21950. EXPECT_EQ(ws::Binary, client.read(msg));
  21951. EXPECT_EQ(binary_data, msg);
  21952. client.close();
  21953. }
  21954. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21955. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21956. "/ws-echo");
  21957. ASSERT_TRUE(client.connect());
  21958. for (int i = 0; i < 10; i++) {
  21959. auto text = "message " + std::to_string(i);
  21960. ASSERT_TRUE(client.send(text));
  21961. std::string msg;
  21962. ASSERT_TRUE(client.read(msg));
  21963. EXPECT_EQ(text, msg);
  21964. }
  21965. client.close();
  21966. }
  21967. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21968. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21969. "/ws-close");
  21970. ASSERT_TRUE(client.connect());
  21971. // Send a message to trigger the server to close
  21972. ASSERT_TRUE(client.send("trigger close"));
  21973. // The server will close, so read should return false
  21974. std::string msg;
  21975. EXPECT_FALSE(client.read(msg));
  21976. EXPECT_FALSE(client.is_open());
  21977. }
  21978. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21979. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21980. "/ws-echo");
  21981. ASSERT_TRUE(client.connect());
  21982. // 128KB message
  21983. std::string large_data(128 * 1024, 'X');
  21984. ASSERT_TRUE(client.send(large_data));
  21985. std::string msg;
  21986. ASSERT_TRUE(client.read(msg));
  21987. EXPECT_EQ(large_data, msg);
  21988. client.close();
  21989. }
  21990. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21991. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21992. "/ws-echo");
  21993. ASSERT_TRUE(client.connect());
  21994. const int num_threads = 4;
  21995. std::vector<std::thread> threads;
  21996. std::atomic<int> send_count{0};
  21997. for (int t = 0; t < num_threads; t++) {
  21998. threads.emplace_back([&client, &send_count, t]() {
  21999. for (int i = 0; i < 5; i++) {
  22000. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22001. if (client.send(text)) { send_count++; }
  22002. }
  22003. });
  22004. }
  22005. for (auto &th : threads) {
  22006. th.join();
  22007. }
  22008. int received = 0;
  22009. std::string msg;
  22010. while (received < send_count.load()) {
  22011. if (!client.read(msg)) { break; }
  22012. received++;
  22013. }
  22014. EXPECT_EQ(send_count.load(), received);
  22015. client.close();
  22016. }
  22017. TEST_F(WebSocketIntegrationTest, ReadString) {
  22018. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22019. "/ws-echo-string");
  22020. ASSERT_TRUE(client.connect());
  22021. ASSERT_TRUE(client.send("hello"));
  22022. std::string msg;
  22023. ASSERT_TRUE(client.read(msg));
  22024. EXPECT_EQ("echo: hello", msg);
  22025. ASSERT_TRUE(client.send("world"));
  22026. ASSERT_TRUE(client.read(msg));
  22027. EXPECT_EQ("echo: world", msg);
  22028. client.close();
  22029. }
  22030. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22031. Headers headers = {{"X-Test-Header", "test-value"}};
  22032. ws::WebSocketClient client(
  22033. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22034. ASSERT_TRUE(client.connect());
  22035. std::string msg;
  22036. ASSERT_TRUE(client.read(msg));
  22037. EXPECT_EQ("path:/ws-request-info", msg);
  22038. ASSERT_TRUE(client.read(msg));
  22039. EXPECT_EQ("header:test-value", msg);
  22040. client.close();
  22041. }
  22042. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22043. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22044. "/ws-echo");
  22045. client.set_read_timeout(1, 0); // 1 second
  22046. ASSERT_TRUE(client.connect());
  22047. // Don't send anything — server echo handler waits for a message, so read()
  22048. // should time out. The connection survives it: nothing was consumed.
  22049. std::string msg;
  22050. EXPECT_EQ(client.read(msg), ws::Timeout);
  22051. EXPECT_TRUE(client.is_open());
  22052. // And it is still usable afterwards.
  22053. EXPECT_TRUE(client.send("after timeout"));
  22054. EXPECT_EQ(client.read(msg), ws::Text);
  22055. EXPECT_EQ(msg, "after timeout");
  22056. }
  22057. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22058. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22059. "/ws-echo");
  22060. client.set_read_timeout(1, 0);
  22061. ASSERT_TRUE(client.connect());
  22062. ASSERT_TRUE(client.send("first"));
  22063. std::string msg;
  22064. ASSERT_EQ(client.read(msg), ws::Text);
  22065. ASSERT_EQ(msg, "first");
  22066. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22067. // not be used with a read timeout: it would reprocess the previous message.
  22068. EXPECT_EQ(client.read(msg), ws::Timeout);
  22069. EXPECT_EQ(msg, "first");
  22070. }
  22071. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22072. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22073. "/ws-echo");
  22074. ASSERT_TRUE(client.connect());
  22075. // Setting it once the connection is open reaches the live stream, not just
  22076. // the seed for the next connect().
  22077. client.set_read_timeout(1, 0);
  22078. std::string msg;
  22079. EXPECT_EQ(client.read(msg), ws::Timeout);
  22080. EXPECT_TRUE(client.is_open());
  22081. }
  22082. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22083. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22084. "/ws-echo");
  22085. client.set_read_timeout(5, 0);
  22086. ASSERT_TRUE(client.connect());
  22087. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22088. // The server should reject it and close the connection.
  22089. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22090. client.send(oversized);
  22091. // The server's read() should have failed due to payload limit,
  22092. // so our read() should return false (connection closed).
  22093. std::string msg;
  22094. EXPECT_FALSE(client.read(msg));
  22095. }
  22096. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22097. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22098. "/ws-echo");
  22099. client.set_read_timeout(10, 0);
  22100. ASSERT_TRUE(client.connect());
  22101. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22102. // This should succeed.
  22103. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22104. ASSERT_TRUE(client.send(at_limit));
  22105. std::string msg;
  22106. ASSERT_TRUE(client.read(msg));
  22107. EXPECT_EQ(at_limit.size(), msg.size());
  22108. client.close();
  22109. }
  22110. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22111. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22112. "/nonexistent");
  22113. auto res = client.connect();
  22114. EXPECT_FALSE(res);
  22115. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22116. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22117. EXPECT_FALSE(client.is_open());
  22118. }
  22119. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22120. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22121. "/ws-echo");
  22122. ASSERT_TRUE(client.connect());
  22123. ASSERT_TRUE(client.send(""));
  22124. std::string msg;
  22125. EXPECT_EQ(ws::Text, client.read(msg));
  22126. EXPECT_EQ("", msg);
  22127. client.close();
  22128. }
  22129. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22130. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22131. "/ws-echo");
  22132. // First connection
  22133. ASSERT_TRUE(client.connect());
  22134. ASSERT_TRUE(client.send("first"));
  22135. std::string msg;
  22136. ASSERT_TRUE(client.read(msg));
  22137. EXPECT_EQ("first", msg);
  22138. client.close();
  22139. EXPECT_FALSE(client.is_open());
  22140. // Reconnect using the same client object
  22141. ASSERT_TRUE(client.connect());
  22142. ASSERT_TRUE(client.is_open());
  22143. ASSERT_TRUE(client.send("second"));
  22144. ASSERT_TRUE(client.read(msg));
  22145. EXPECT_EQ("second", msg);
  22146. client.close();
  22147. }
  22148. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22149. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22150. "/ws-close-status");
  22151. ASSERT_TRUE(client.connect());
  22152. // Trigger the server to close with GoingAway status
  22153. ASSERT_TRUE(client.send("trigger"));
  22154. // read() should return false after receiving the close frame
  22155. std::string msg;
  22156. EXPECT_FALSE(client.read(msg));
  22157. EXPECT_FALSE(client.is_open());
  22158. }
  22159. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22160. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22161. "/ws-echo");
  22162. ASSERT_TRUE(client.connect());
  22163. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22164. EXPECT_FALSE(client.is_open());
  22165. }
  22166. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22167. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22168. ws::WebSocketClient client(
  22169. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22170. ASSERT_TRUE(client.connect());
  22171. // Server should have selected graphql-ws
  22172. EXPECT_EQ("graphql-ws", client.subprotocol());
  22173. client.close();
  22174. }
  22175. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22176. Headers headers;
  22177. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22178. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22179. ws::WebSocketClient client(
  22180. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22181. ASSERT_TRUE(client.connect());
  22182. // The offer on the second field line counts too, so graphql-ws is selected
  22183. EXPECT_EQ("graphql-ws", client.subprotocol());
  22184. client.close();
  22185. }
  22186. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22187. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22188. ws::WebSocketClient client(
  22189. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22190. ASSERT_TRUE(client.connect());
  22191. // Server should not have selected any subprotocol
  22192. EXPECT_TRUE(client.subprotocol().empty());
  22193. client.close();
  22194. }
  22195. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22196. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22197. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22198. "/ws-subprotocol-unoffered",
  22199. headers);
  22200. ASSERT_TRUE(client.connect());
  22201. EXPECT_TRUE(client.subprotocol().empty());
  22202. client.close();
  22203. }
  22204. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22205. // Connect without requesting any subprotocol
  22206. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22207. "/ws-subprotocol");
  22208. ASSERT_TRUE(client.connect());
  22209. EXPECT_TRUE(client.subprotocol().empty());
  22210. client.close();
  22211. }
  22212. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22213. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22214. "/ws-echo");
  22215. client.set_tcp_nodelay(true);
  22216. client.set_connection_timeout(3, 0);
  22217. bool socket_options_called = false;
  22218. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22219. ASSERT_TRUE(client.connect());
  22220. ASSERT_TRUE(client.is_open());
  22221. EXPECT_TRUE(socket_options_called);
  22222. ASSERT_TRUE(client.send("hello"));
  22223. std::string msg;
  22224. auto result = client.read(msg);
  22225. EXPECT_EQ(result, ws::ReadResult::Text);
  22226. EXPECT_EQ(msg, "hello");
  22227. client.close();
  22228. }
  22229. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22230. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22231. "/ws-echo");
  22232. client.set_connection_timeout(std::chrono::seconds(3));
  22233. client.set_write_timeout(std::chrono::seconds(3));
  22234. // A sub-second remainder exercises the seconds/microseconds split.
  22235. client.set_read_timeout(std::chrono::milliseconds(1500));
  22236. ASSERT_TRUE(client.connect());
  22237. auto start = std::chrono::steady_clock::now();
  22238. std::string msg;
  22239. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22240. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22241. std::chrono::steady_clock::now() - start)
  22242. .count();
  22243. // Above 1s so that dropping the microseconds half of the split fails here.
  22244. // Ignoring the setter altogether would not reach this line at all: a client
  22245. // waits forever by default.
  22246. EXPECT_GE(elapsed, 1400);
  22247. EXPECT_LT(elapsed, 30000);
  22248. }
  22249. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22250. Server svr;
  22251. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22252. if (!req.has_header("Authorization")) {
  22253. res.status = StatusCode::Unauthorized_401;
  22254. res.set_content("Unauthorized", "text/plain");
  22255. return Server::HandlerResponse::Handled;
  22256. }
  22257. return Server::HandlerResponse::Unhandled;
  22258. });
  22259. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22260. std::string msg;
  22261. while (ws.read(msg)) {
  22262. ws.send(msg);
  22263. }
  22264. });
  22265. auto port = svr.bind_to_any_port("localhost");
  22266. std::thread t([&]() { svr.listen_after_bind(); });
  22267. svr.wait_until_ready();
  22268. // Without Authorization header - should be rejected before upgrade
  22269. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22270. EXPECT_FALSE(client1.connect());
  22271. // The rejection is framed like any other HTTP response
  22272. {
  22273. Client cli("localhost", port);
  22274. Headers headers = {{"Upgrade", "websocket"},
  22275. {"Connection", "Upgrade"},
  22276. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22277. {"Sec-WebSocket-Version", "13"}};
  22278. auto res = cli.Get("/ws", headers);
  22279. ASSERT_TRUE(res);
  22280. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22281. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22282. EXPECT_EQ("Unauthorized", res->body);
  22283. }
  22284. // With Authorization header - should succeed
  22285. Headers headers = {{"Authorization", "Bearer token123"}};
  22286. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22287. headers);
  22288. ASSERT_TRUE(client2.connect());
  22289. ASSERT_TRUE(client2.send("hello"));
  22290. std::string msg;
  22291. ASSERT_TRUE(client2.read(msg));
  22292. EXPECT_EQ("hello", msg);
  22293. client2.close();
  22294. svr.stop();
  22295. t.join();
  22296. }
  22297. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22298. Server svr;
  22299. std::atomic<int> pre_request_calls{0};
  22300. std::atomic<bool> route_matched{false};
  22301. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22302. pre_request_calls++;
  22303. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22304. if (req.get_header_value("Authorization") != "Bearer token123") {
  22305. res.status = StatusCode::Unauthorized_401;
  22306. res.set_content("Unauthorized", "text/plain");
  22307. return Server::HandlerResponse::Handled;
  22308. }
  22309. return Server::HandlerResponse::Unhandled;
  22310. });
  22311. std::atomic<bool> handler_called{false};
  22312. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22313. handler_called = true;
  22314. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22315. });
  22316. auto port = svr.bind_to_any_port("localhost");
  22317. std::thread t([&]() { svr.listen_after_bind(); });
  22318. svr.wait_until_ready();
  22319. // Without Authorization header - should be rejected before upgrade
  22320. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22321. "/ws/1");
  22322. EXPECT_FALSE(client1.connect());
  22323. EXPECT_FALSE(handler_called);
  22324. EXPECT_EQ(1, pre_request_calls);
  22325. EXPECT_TRUE(route_matched);
  22326. // The rejection is an ordinary HTTP response, not a protocol switch
  22327. {
  22328. Client cli("localhost", port);
  22329. Headers headers = {{"Upgrade", "websocket"},
  22330. {"Connection", "Upgrade"},
  22331. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22332. {"Sec-WebSocket-Version", "13"}};
  22333. auto res = cli.Get("/ws/1", headers);
  22334. ASSERT_TRUE(res);
  22335. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22336. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22337. EXPECT_EQ("Unauthorized", res->body);
  22338. }
  22339. EXPECT_FALSE(handler_called);
  22340. // With Authorization header - should succeed
  22341. Headers headers = {{"Authorization", "Bearer token123"}};
  22342. ws::WebSocketClient client2(
  22343. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22344. ASSERT_TRUE(client2.connect());
  22345. std::string msg;
  22346. ASSERT_TRUE(client2.read(msg));
  22347. EXPECT_EQ("/ws/:id 2", msg);
  22348. EXPECT_TRUE(handler_called);
  22349. client2.close();
  22350. svr.stop();
  22351. t.join();
  22352. }
  22353. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22354. Server svr;
  22355. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22356. // A read timeout is how a handler gets control back. Without it, a handler
  22357. // parked in read() can never write on the connection it is reading.
  22358. ws.set_read_timeout(std::chrono::milliseconds(100));
  22359. std::string msg;
  22360. while (ws.is_open()) {
  22361. auto r = ws.read(msg);
  22362. if (r == httplib::ws::Timeout) {
  22363. ws.send("tick");
  22364. continue;
  22365. }
  22366. if (r == httplib::ws::Fail) { break; }
  22367. ws.send(msg);
  22368. }
  22369. });
  22370. auto port = svr.bind_to_any_port("localhost");
  22371. std::thread t([&]() { svr.listen_after_bind(); });
  22372. svr.wait_until_ready();
  22373. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22374. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22375. ASSERT_TRUE(client.connect());
  22376. // The client sends nothing, so anything it receives came out of the
  22377. // handler's timeout path.
  22378. std::string msg;
  22379. ASSERT_EQ(client.read(msg), ws::Text);
  22380. EXPECT_EQ("tick", msg);
  22381. client.close();
  22382. svr.stop();
  22383. t.join();
  22384. }
  22385. // Stream::read may return fewer bytes than asked for. This is that contract at
  22386. // its worst -- one byte per call -- which is what a frame header straddling a
  22387. // read buffer's boundary looks like to the frame parser.
  22388. class WsByteAtATimeStream : public Stream {
  22389. public:
  22390. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22391. bool is_readable() const override { return true; }
  22392. bool wait_readable() const override { return true; }
  22393. bool wait_writable() const override { return true; }
  22394. ssize_t read(char *ptr, size_t size) override {
  22395. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22396. *ptr = data_[pos_++];
  22397. return 1;
  22398. }
  22399. ssize_t write(const char *, size_t size) override {
  22400. return static_cast<ssize_t>(size);
  22401. }
  22402. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22403. ip = "127.0.0.1";
  22404. port = 0;
  22405. }
  22406. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22407. ip = "127.0.0.1";
  22408. port = 0;
  22409. }
  22410. socket_t socket() const override { return INVALID_SOCKET; }
  22411. time_t duration() const override { return 0; }
  22412. private:
  22413. std::string data_;
  22414. size_t pos_ = 0;
  22415. };
  22416. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22417. // The payload uses the 16-bit extended length, so the header, the length
  22418. // and the mask key are all multi-byte fields here. Each used to be read
  22419. // with a single read() call, which fails as soon as one is split. The
  22420. // payload is also a little over one read chunk, so it is read in two.
  22421. std::string body;
  22422. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22423. body += static_cast<char>(i % 251);
  22424. }
  22425. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22426. std::string frame;
  22427. frame += static_cast<char>(0x81); // FIN + Text
  22428. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22429. frame += static_cast<char>(body.size() >> 8);
  22430. frame += static_cast<char>(body.size() & 0xff);
  22431. for (size_t i = 0; i < 4; i++) {
  22432. frame += static_cast<char>(mask[i]);
  22433. }
  22434. for (size_t i = 0; i < body.size(); i++) {
  22435. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22436. }
  22437. WsByteAtATimeStream strm(frame);
  22438. ws::Opcode opcode;
  22439. std::string payload;
  22440. bool fin = false;
  22441. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22442. /*expect_masked=*/true, body.size()),
  22443. ws::impl::FrameRead::Ok);
  22444. EXPECT_TRUE(fin);
  22445. EXPECT_EQ(opcode, ws::Opcode::Text);
  22446. EXPECT_EQ(payload, body);
  22447. }
  22448. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22449. std::string body(2000, 'x');
  22450. std::string frame;
  22451. frame += static_cast<char>(0x82); // FIN + Binary
  22452. frame += static_cast<char>(126); // 16-bit length follows
  22453. frame += static_cast<char>(body.size() >> 8);
  22454. frame += static_cast<char>(body.size() & 0xff);
  22455. frame += body;
  22456. detail::BufferStream strm;
  22457. strm.write(frame.data(), frame.size());
  22458. ws::Opcode opcode;
  22459. std::string payload;
  22460. bool fin;
  22461. EXPECT_EQ(
  22462. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22463. ws::impl::FrameRead::Ok);
  22464. EXPECT_EQ(body, payload);
  22465. }
  22466. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22467. // The header announces the largest payload allowed, and only 3 bytes of it
  22468. // ever arrive.
  22469. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22470. std::string frame;
  22471. frame += static_cast<char>(0x82); // FIN + Binary
  22472. frame += static_cast<char>(127); // 64-bit length follows
  22473. for (int shift = 56; shift >= 0; shift -= 8) {
  22474. frame += static_cast<char>((len >> shift) & 0xff);
  22475. }
  22476. frame += "abc";
  22477. detail::BufferStream strm;
  22478. strm.write(frame.data(), frame.size());
  22479. ws::Opcode opcode;
  22480. std::string payload;
  22481. bool fin;
  22482. EXPECT_EQ(
  22483. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22484. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22485. ws::impl::FrameRead::Fail);
  22486. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22487. }
  22488. TEST(WebSocketTest, QueryStringInHandshake) {
  22489. Server svr;
  22490. std::mutex mtx;
  22491. std::string received_target;
  22492. std::string received_token;
  22493. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22494. {
  22495. std::lock_guard<std::mutex> lock(mtx);
  22496. received_target = req.target;
  22497. if (req.has_param("token")) {
  22498. received_token = req.get_param_value("token");
  22499. }
  22500. }
  22501. std::string msg;
  22502. while (ws.read(msg)) {
  22503. ws.send(msg);
  22504. }
  22505. });
  22506. auto port = svr.bind_to_any_port("localhost");
  22507. std::thread t([&]() { svr.listen_after_bind(); });
  22508. svr.wait_until_ready();
  22509. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22510. "/ws?token=ABC&session=123");
  22511. ASSERT_TRUE(client.connect());
  22512. // Round-trip ensures the handler has run and captured the request.
  22513. ASSERT_TRUE(client.send("hello"));
  22514. std::string msg;
  22515. ASSERT_TRUE(client.read(msg));
  22516. EXPECT_EQ("hello", msg);
  22517. client.close();
  22518. {
  22519. std::lock_guard<std::mutex> lock(mtx);
  22520. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22521. EXPECT_EQ("ABC", received_token);
  22522. }
  22523. svr.stop();
  22524. t.join();
  22525. }
  22526. // Run a handshake against a throwaway server and hand the request the server
  22527. // received back to the caller, so tests can assert on the headers the client
  22528. // actually put on the wire.
  22529. static void capture_websocket_handshake_request(
  22530. const Headers &client_headers,
  22531. std::function<void(const Request &, int port)> verify) {
  22532. Server svr;
  22533. std::mutex mtx;
  22534. Request received;
  22535. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22536. {
  22537. std::lock_guard<std::mutex> lock(mtx);
  22538. received = req;
  22539. }
  22540. std::string msg;
  22541. while (ws.read(msg)) {
  22542. ws.send(msg);
  22543. }
  22544. });
  22545. auto port = svr.bind_to_any_port("localhost");
  22546. std::thread t([&]() { svr.listen_after_bind(); });
  22547. auto se = detail::scope_exit([&] {
  22548. svr.stop();
  22549. t.join();
  22550. });
  22551. svr.wait_until_ready();
  22552. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22553. client_headers);
  22554. ASSERT_TRUE(client.connect());
  22555. ASSERT_TRUE(client.send("hello"));
  22556. std::string msg;
  22557. ASSERT_TRUE(client.read(msg));
  22558. client.close();
  22559. {
  22560. std::lock_guard<std::mutex> lock(mtx);
  22561. verify(received, port);
  22562. }
  22563. }
  22564. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22565. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22566. // Non-default port must be present in the Host header. Default ports
  22567. // (80/443) are omitted; that logic is covered by
  22568. // MakeHostAndPortStringTest.
  22569. EXPECT_EQ("localhost:" + std::to_string(port),
  22570. req.get_header_value("Host"));
  22571. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22572. req.get_header_value("User-Agent"));
  22573. EXPECT_FALSE(req.has_header("Accept"));
  22574. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22575. EXPECT_FALSE(req.has_header("Content-Length"));
  22576. });
  22577. }
  22578. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22579. capture_websocket_handshake_request(
  22580. {{"Host", "example.com"},
  22581. {"User-Agent", "custom-agent"},
  22582. {"X-Custom", "value"}},
  22583. [](const Request &req, int) {
  22584. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22585. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22586. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22587. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22588. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22589. });
  22590. }
  22591. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22592. capture_websocket_handshake_request(
  22593. {{"Upgrade", "bogus"},
  22594. {"Connection", "close"},
  22595. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22596. {"Sec-WebSocket-Version", "8"}},
  22597. [](const Request &req, int) {
  22598. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22599. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22600. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22601. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22602. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22603. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22604. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22605. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22606. req.get_header_value("Sec-WebSocket-Key"));
  22607. });
  22608. }
  22609. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22610. // A header the client refuses to send must abort the handshake before any
  22611. // part of it reaches the wire; a lone request line would otherwise sit in
  22612. // the peer's buffer as a truncated request.
  22613. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22614. ASSERT_NE(INVALID_SOCKET, srv);
  22615. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22616. sockaddr_in addr{};
  22617. addr.sin_family = AF_INET;
  22618. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22619. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22620. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22621. ASSERT_EQ(0, ::listen(srv, 1));
  22622. sockaddr_in bound{};
  22623. socklen_t bound_len = sizeof(bound);
  22624. ASSERT_EQ(
  22625. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22626. auto port = ntohs(bound.sin_port);
  22627. ssize_t received = -1;
  22628. std::thread t([&] {
  22629. // Bound every blocking call so a regression fails the test with a bad
  22630. // value instead of hanging the suite.
  22631. fd_set rfds;
  22632. FD_ZERO(&rfds);
  22633. FD_SET(srv, &rfds);
  22634. timeval tv{5, 0};
  22635. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22636. 0) {
  22637. return;
  22638. }
  22639. sockaddr_in cli_addr{};
  22640. socklen_t cli_len = sizeof(cli_addr);
  22641. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22642. if (cli == INVALID_SOCKET) { return; }
  22643. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22644. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22645. char buf[4096];
  22646. received = ::recv(cli, buf, sizeof(buf), 0);
  22647. });
  22648. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22649. // connect() has already shut the socket down by the time it returns false,
  22650. // so the peer sees EOF without waiting for the client to be destroyed.
  22651. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22652. {{"X-Bad", "a\r\nInjected: 1"}});
  22653. EXPECT_FALSE(client.connect());
  22654. t.join();
  22655. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22656. EXPECT_EQ(0, received);
  22657. }
  22658. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22659. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22660. // contains "upgrade" as a substring is a different token and must not
  22661. // start a WebSocket handshake.
  22662. auto make_request = [](const std::vector<std::string> &connection_values) {
  22663. Request req;
  22664. req.method = "GET";
  22665. req.headers.emplace("Upgrade", "websocket");
  22666. for (const auto &value : connection_values) {
  22667. req.headers.emplace("Connection", value);
  22668. }
  22669. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22670. req.headers.emplace("Sec-WebSocket-Version", "13");
  22671. return req;
  22672. };
  22673. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22674. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22675. EXPECT_TRUE(
  22676. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22677. EXPECT_TRUE(
  22678. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22679. EXPECT_TRUE(
  22680. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22681. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22682. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22683. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22684. EXPECT_FALSE(
  22685. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22686. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22687. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22688. }
  22689. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22690. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22691. // asks recipients to match each protocol-name case-insensitively, and RFC
  22692. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22693. // client naming websocket alongside another protocol, or on a second field
  22694. // line, is offering websocket; a value that merely contains "websocket" as a
  22695. // substring is a different protocol name and is not.
  22696. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22697. Request req;
  22698. req.method = "GET";
  22699. for (const auto &value : upgrade_values) {
  22700. req.headers.emplace("Upgrade", value);
  22701. }
  22702. req.headers.emplace("Connection", "Upgrade");
  22703. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22704. req.headers.emplace("Sec-WebSocket-Version", "13");
  22705. return req;
  22706. };
  22707. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22708. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22709. EXPECT_TRUE(
  22710. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22711. EXPECT_TRUE(
  22712. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22713. EXPECT_TRUE(
  22714. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22715. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22716. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22717. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22718. EXPECT_FALSE(
  22719. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22720. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22721. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22722. }
  22723. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22724. Server svr;
  22725. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22726. auto port = svr.bind_to_any_port("localhost");
  22727. std::thread t([&]() { svr.listen_after_bind(); });
  22728. auto se = detail::scope_exit([&] {
  22729. svr.stop();
  22730. t.join();
  22731. });
  22732. svr.wait_until_ready();
  22733. Headers headers = {{"Upgrade", "websocket"},
  22734. {"Connection", "notupgrade"},
  22735. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22736. {"Sec-WebSocket-Version", "13"}};
  22737. Client cli("localhost", port);
  22738. auto res = cli.Get("/ws", headers);
  22739. // The route exists only as a WebSocket route, so a request that fails the
  22740. // handshake check falls through to ordinary routing.
  22741. ASSERT_TRUE(res);
  22742. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22743. }
  22744. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22745. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22746. // Connection value is the only thing left for the client to reject.
  22747. Server svr;
  22748. svr.Get("/ws", [](const Request &req, Response &res) {
  22749. res.status = StatusCode::SwitchingProtocol_101;
  22750. res.set_header("Upgrade", "websocket");
  22751. res.set_header("Connection", "notupgrade");
  22752. res.set_header("Sec-WebSocket-Accept",
  22753. detail::websocket_accept_key(
  22754. req.get_header_value("Sec-WebSocket-Key")));
  22755. });
  22756. auto port = svr.bind_to_any_port("localhost");
  22757. std::thread t([&]() { svr.listen_after_bind(); });
  22758. auto se = detail::scope_exit([&] {
  22759. svr.stop();
  22760. t.join();
  22761. });
  22762. svr.wait_until_ready();
  22763. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22764. auto res = client.connect();
  22765. EXPECT_FALSE(res);
  22766. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22767. EXPECT_FALSE(client.is_open());
  22768. }
  22769. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22770. Server svr;
  22771. svr.Get("/ws", [](const Request &req, Response &res) {
  22772. res.status = StatusCode::SwitchingProtocol_101;
  22773. res.set_header("Upgrade", "websocket");
  22774. res.set_header("Connection", "Upgrade");
  22775. res.set_header("Sec-WebSocket-Accept",
  22776. detail::websocket_accept_key(
  22777. req.get_header_value("Sec-WebSocket-Key")));
  22778. res.set_header("Sec-WebSocket-Protocol", "admin");
  22779. });
  22780. auto port = svr.bind_to_any_port("localhost");
  22781. std::thread t([&]() { svr.listen_after_bind(); });
  22782. auto se = detail::scope_exit([&] {
  22783. svr.stop();
  22784. t.join();
  22785. });
  22786. svr.wait_until_ready();
  22787. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22788. // Server selects a subprotocol the client never offered
  22789. {
  22790. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22791. ws::WebSocketClient client(url, headers);
  22792. auto res = client.connect();
  22793. EXPECT_FALSE(res);
  22794. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22795. EXPECT_FALSE(client.is_open());
  22796. EXPECT_TRUE(client.subprotocol().empty());
  22797. }
  22798. // Client offered none but the server named one anyway
  22799. {
  22800. ws::WebSocketClient client(url);
  22801. auto res = client.connect();
  22802. EXPECT_FALSE(res);
  22803. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22804. EXPECT_FALSE(client.is_open());
  22805. EXPECT_TRUE(client.subprotocol().empty());
  22806. }
  22807. }
  22808. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22809. // The socket path doubles as the URL host, so it must not contain '/'.
  22810. const char *shard = getenv("GTEST_SHARD_INDEX");
  22811. const std::string sock_path =
  22812. shard ? std::string("httplib-ws-") + shard + ".sock"
  22813. : std::string("httplib-ws.sock");
  22814. std::remove(sock_path.c_str());
  22815. Server svr;
  22816. std::mutex mtx;
  22817. std::string received_host;
  22818. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22819. {
  22820. std::lock_guard<std::mutex> lock(mtx);
  22821. received_host = req.get_header_value("Host");
  22822. }
  22823. std::string msg;
  22824. while (ws.read(msg)) {
  22825. ws.send(msg);
  22826. }
  22827. });
  22828. svr.set_address_family(AF_UNIX);
  22829. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22830. auto se = detail::scope_exit([&] {
  22831. svr.stop();
  22832. t.join();
  22833. std::remove(sock_path.c_str());
  22834. });
  22835. svr.wait_until_ready();
  22836. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22837. client.set_address_family(AF_UNIX);
  22838. ASSERT_TRUE(client.connect());
  22839. ASSERT_TRUE(client.send("hello"));
  22840. std::string msg;
  22841. ASSERT_TRUE(client.read(msg));
  22842. client.close();
  22843. {
  22844. std::lock_guard<std::mutex> lock(mtx);
  22845. // There is no host:port for a Unix socket, so the same "localhost"
  22846. // placeholder the HTTP client uses is expected.
  22847. EXPECT_EQ("localhost", received_host);
  22848. }
  22849. }
  22850. // Two threads must never parse WebSocket frames from the same stream.
  22851. // close() used to read the peer's Close reply with its own frame read, so it
  22852. // raced a reader thread that was in the middle of a payload: the payload loop
  22853. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22854. // so bytes taken by close() were replaced with bytes from further along the
  22855. // stream. The message kept its length and silently changed content.
  22856. //
  22857. // The raw peer below sends a frame header plus part of the payload, waits for
  22858. // the handler to call close(), and only then sends the rest. Whichever thread
  22859. // would win the race for those bytes, the message must arrive intact, because
  22860. // close() must not touch the stream while read() owns it.
  22861. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22862. #ifndef _WIN32
  22863. signal(SIGPIPE, SIG_IGN);
  22864. #endif
  22865. const size_t payload_len = 120; // fits the 7-bit length field
  22866. const size_t prefix_len = 8;
  22867. const int attempts = 8;
  22868. std::string expected(payload_len, '\0');
  22869. for (size_t i = 0; i < payload_len; i++) {
  22870. expected[i] = static_cast<char>('a' + i % 26);
  22871. }
  22872. std::atomic<bool> peer_stalled{false};
  22873. std::atomic<bool> handler_done{false};
  22874. std::mutex received_mutex;
  22875. std::vector<std::string> received;
  22876. // Bound every wait, so a regression fails the test instead of hanging the
  22877. // suite.
  22878. auto wait_for = [](const std::atomic<bool> &flag) {
  22879. for (int i = 0; i < 500 && !flag; i++) {
  22880. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22881. }
  22882. };
  22883. Server svr;
  22884. svr.set_websocket_ping_interval(0);
  22885. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22886. std::thread reader([&]() {
  22887. std::string msg;
  22888. while (ws.read(msg)) {
  22889. std::lock_guard<std::mutex> guard(received_mutex);
  22890. received.push_back(msg);
  22891. }
  22892. });
  22893. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22894. // inside read_websocket_frame() when close() runs.
  22895. wait_for(peer_stalled);
  22896. ws.close();
  22897. reader.join();
  22898. handler_done = true;
  22899. });
  22900. auto port = svr.bind_to_any_port("127.0.0.1");
  22901. std::thread t([&]() { svr.listen_after_bind(); });
  22902. auto se = detail::scope_exit([&] {
  22903. svr.stop();
  22904. t.join();
  22905. });
  22906. svr.wait_until_ready();
  22907. auto send_bytes = [](socket_t s, const std::string &data) {
  22908. #ifdef _WIN32
  22909. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22910. #else
  22911. auto n = ::send(s, data.data(), data.size(), 0);
  22912. #endif
  22913. return n == static_cast<decltype(n)>(data.size());
  22914. };
  22915. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22916. // Every length used here fits the 7-bit length field.
  22917. auto masked_header = [](uint8_t first_byte, size_t len) {
  22918. std::string h;
  22919. h += static_cast<char>(first_byte);
  22920. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22921. h.append(4, '\0'); // mask key
  22922. return h;
  22923. };
  22924. for (int attempt = 0; attempt < attempts; attempt++) {
  22925. peer_stalled = false;
  22926. handler_done = false;
  22927. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22928. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22929. auto se_sock = detail::scope_exit([&] {
  22930. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22931. });
  22932. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22933. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22934. sockaddr_in addr{};
  22935. addr.sin_family = AF_INET;
  22936. addr.sin_port = htons(static_cast<uint16_t>(port));
  22937. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22938. ASSERT_EQ(
  22939. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22940. << "attempt " << attempt;
  22941. ASSERT_TRUE(send_bytes(sock,
  22942. "GET /ws HTTP/1.1\r\n"
  22943. "Host: 127.0.0.1\r\n"
  22944. "Upgrade: websocket\r\n"
  22945. "Connection: Upgrade\r\n"
  22946. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22947. "Sec-WebSocket-Version: 13\r\n"
  22948. "\r\n"))
  22949. << "attempt " << attempt;
  22950. std::string response;
  22951. while (response.find("\r\n\r\n") == std::string::npos) {
  22952. char buf[512];
  22953. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22954. if (n <= 0) { break; }
  22955. response.append(buf, static_cast<size_t>(n));
  22956. }
  22957. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22958. << "attempt " << attempt;
  22959. // Send the header of a Binary message but only the first prefix_len bytes
  22960. // of its payload, leaving the reader thread stalled inside the payload.
  22961. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22962. expected.substr(0, prefix_len)))
  22963. << "attempt " << attempt;
  22964. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22965. peer_stalled = true;
  22966. // Let close() send its Close frame and park in its own read before the
  22967. // rest of the payload arrives, so both threads are waiting for it.
  22968. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22969. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22970. close_frame += static_cast<char>(0x03); // status 1000
  22971. close_frame += static_cast<char>(0xE8);
  22972. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22973. << "attempt " << attempt;
  22974. // Closing the peer releases the reader thread even on the buggy path,
  22975. // where it waits for bytes another thread already consumed.
  22976. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22977. detail::close_socket(sock);
  22978. sock = INVALID_SOCKET;
  22979. wait_for(handler_done);
  22980. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22981. }
  22982. std::lock_guard<std::mutex> guard(received_mutex);
  22983. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22984. << "a message in flight when close() ran was dropped";
  22985. for (size_t i = 0; i < received.size(); i++) {
  22986. EXPECT_EQ(expected, received[i]) << "message " << i;
  22987. }
  22988. }
  22989. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22990. // returning the socket, or INVALID_SOCKET.
  22991. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22992. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22993. if (sock == INVALID_SOCKET) { return sock; }
  22994. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22995. sockaddr_in addr{};
  22996. addr.sin_family = AF_INET;
  22997. addr.sin_port = htons(static_cast<uint16_t>(port));
  22998. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22999. std::string req = "GET " + path +
  23000. " HTTP/1.1\r\n"
  23001. "Host: 127.0.0.1\r\n"
  23002. "Upgrade: websocket\r\n"
  23003. "Connection: Upgrade\r\n"
  23004. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23005. "Sec-WebSocket-Version: 13\r\n"
  23006. "\r\n";
  23007. std::string res;
  23008. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23009. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23010. static_cast<int>(req.size())) {
  23011. char c;
  23012. while (res.find("\r\n\r\n") == std::string::npos &&
  23013. ::recv(sock, &c, 1, 0) == 1) {
  23014. res += c;
  23015. }
  23016. }
  23017. if (res.find(" 101 ") == std::string::npos) {
  23018. detail::close_socket(sock);
  23019. return INVALID_SOCKET;
  23020. }
  23021. return sock;
  23022. }
  23023. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23024. // The payload must fit the 7-bit length field.
  23025. static std::string masked_frame(uint8_t first_byte,
  23026. const std::string &payload) {
  23027. std::string f;
  23028. f += static_cast<char>(first_byte);
  23029. f += static_cast<char>(0x80 | payload.size());
  23030. f.append(4, '\0');
  23031. return f + payload;
  23032. }
  23033. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23034. std::atomic<bool> done{false};
  23035. std::string received;
  23036. Server svr;
  23037. svr.set_websocket_ping_interval(0);
  23038. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23039. std::string msg;
  23040. if (ws.read(msg) == ws::Binary) { received = msg; }
  23041. done = true;
  23042. });
  23043. auto port = svr.bind_to_any_port("127.0.0.1");
  23044. std::thread t([&]() { svr.listen_after_bind(); });
  23045. auto se = detail::scope_exit([&] {
  23046. svr.stop();
  23047. t.join();
  23048. });
  23049. svr.wait_until_ready();
  23050. auto sock = connect_raw_websocket(port, "/ws");
  23051. ASSERT_NE(INVALID_SOCKET, sock);
  23052. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23053. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23054. masked_frame(0x89, "p") + // FIN + Ping
  23055. masked_frame(0x80, "lo"); // FIN + Continuation
  23056. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23057. for (int i = 0; i < 500 && !done; i++) {
  23058. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23059. }
  23060. ASSERT_TRUE(done);
  23061. EXPECT_EQ("Hello", received);
  23062. // The Ping between the fragments is answered with a Pong.
  23063. char pong[3];
  23064. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23065. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23066. }
  23067. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23068. Server svr;
  23069. svr.set_websocket_ping_interval(-1);
  23070. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23071. std::string msg;
  23072. while (ws.read(msg)) {}
  23073. });
  23074. auto port = svr.bind_to_any_port("127.0.0.1");
  23075. std::thread t([&]() { svr.listen_after_bind(); });
  23076. auto se = detail::scope_exit([&] {
  23077. svr.stop();
  23078. t.join();
  23079. });
  23080. svr.wait_until_ready();
  23081. auto sock = connect_raw_websocket(port, "/ws");
  23082. ASSERT_NE(INVALID_SOCKET, sock);
  23083. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23084. // Nothing comes while the client stays quiet.
  23085. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23086. char c;
  23087. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23088. }
  23089. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23090. Server svr;
  23091. svr.set_websocket_ping_interval(0);
  23092. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23093. std::string msg;
  23094. while (ws.read(msg)) {}
  23095. });
  23096. auto port = svr.bind_to_any_port("127.0.0.1");
  23097. std::thread t([&]() { svr.listen_after_bind(); });
  23098. auto se = detail::scope_exit([&] {
  23099. svr.stop();
  23100. t.join();
  23101. });
  23102. svr.wait_until_ready();
  23103. // Each Close payload and the reply it should get: an echo when valid, 1002
  23104. // otherwise.
  23105. std::vector<std::pair<std::string, std::string>> cases = {
  23106. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23107. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23108. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23109. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23110. };
  23111. // Also between the fragments of a message.
  23112. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23113. for (const auto &c : cases) {
  23114. auto sock = connect_raw_websocket(port, "/ws");
  23115. ASSERT_NE(INVALID_SOCKET, sock);
  23116. auto frames = prefix + masked_frame(0x88, c.first);
  23117. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23118. std::string reply;
  23119. char buf[256];
  23120. while (reply.size() < 2 + c.second.size()) {
  23121. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23122. if (n <= 0) { break; }
  23123. reply.append(buf, static_cast<size_t>(n));
  23124. }
  23125. detail::close_socket(sock);
  23126. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23127. c.second,
  23128. reply);
  23129. }
  23130. }
  23131. }
  23132. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23133. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23134. protected:
  23135. void SetUp() override {
  23136. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23137. SERVER_PRIVATE_KEY_FILE);
  23138. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23139. std::string msg;
  23140. ws::ReadResult ret;
  23141. while ((ret = ws.read(msg))) {
  23142. if (ret == ws::Binary) {
  23143. ws.send(msg.data(), msg.size());
  23144. } else {
  23145. ws.send(msg);
  23146. }
  23147. }
  23148. });
  23149. port_ = server_->bind_to_any_port(HOST);
  23150. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23151. server_->wait_until_ready();
  23152. }
  23153. void TearDown() override {
  23154. server_->stop();
  23155. if (server_thread_.joinable()) { server_thread_.join(); }
  23156. }
  23157. std::unique_ptr<SSLServer> server_;
  23158. std::thread server_thread_;
  23159. int port_ = 0;
  23160. };
  23161. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23162. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23163. {
  23164. ws::WebSocketClient client(url);
  23165. client.enable_server_certificate_verification(false);
  23166. auto calls = 0;
  23167. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23168. calls++;
  23169. return false;
  23170. });
  23171. EXPECT_FALSE(client.connect());
  23172. EXPECT_GT(calls, 0);
  23173. }
  23174. {
  23175. ws::WebSocketClient client(url);
  23176. client.enable_server_certificate_verification(false);
  23177. client.set_session_verifier([](tls::session_t) {
  23178. return SSLVerifierResponse::CertificateRejected;
  23179. });
  23180. EXPECT_FALSE(client.connect());
  23181. }
  23182. {
  23183. ws::WebSocketClient client(url);
  23184. client.enable_server_certificate_verification(false);
  23185. client.set_session_verifier([](tls::session_t) {
  23186. return SSLVerifierResponse::CertificateAccepted;
  23187. });
  23188. EXPECT_TRUE(client.connect());
  23189. }
  23190. }
  23191. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23192. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23193. "/ws-echo");
  23194. client.enable_server_certificate_verification(false);
  23195. ASSERT_TRUE(client.connect());
  23196. ASSERT_TRUE(client.is_open());
  23197. ASSERT_TRUE(client.send("Hello WSS"));
  23198. std::string msg;
  23199. EXPECT_EQ(ws::Text, client.read(msg));
  23200. EXPECT_EQ("Hello WSS", msg);
  23201. client.close();
  23202. }
  23203. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23204. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23205. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23206. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23207. // client (without calling close() first) is the only path that runs
  23208. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23209. // bug exactly.
  23210. //
  23211. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23212. // when linked against an instrumented libssl; run under Valgrind to catch it
  23213. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23214. // suite (the freed session otherwise stalls on the close handshake) — this test
  23215. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23216. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23217. {
  23218. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23219. "/ws-echo");
  23220. client.enable_server_certificate_verification(false);
  23221. client.set_read_timeout(2, 0);
  23222. client.set_write_timeout(2, 0);
  23223. ASSERT_TRUE(client.connect());
  23224. ASSERT_TRUE(client.is_open());
  23225. ASSERT_TRUE(client.send("still open"));
  23226. // Intentionally do NOT call client.close(): leaving scope runs
  23227. // shutdown_and_close() with the WebSocket still open, which must send the
  23228. // close frame while the TLS session is still alive.
  23229. }
  23230. }
  23231. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23232. // shutdown_and_close() at the start of connect(), reproducing the same
  23233. // use-after-free within the test body rather than at scope exit. The second
  23234. // connect must succeed and echo, proving the close handshake ran over a live
  23235. // session. See the note above about memory-tool requirements.
  23236. TEST_F(WebSocketSSLIntegrationTest,
  23237. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23238. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23239. "/ws-echo");
  23240. client.enable_server_certificate_verification(false);
  23241. client.set_read_timeout(2, 0);
  23242. client.set_write_timeout(2, 0);
  23243. ASSERT_TRUE(client.connect());
  23244. ASSERT_TRUE(client.is_open());
  23245. ASSERT_TRUE(client.send("still open"));
  23246. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23247. // the still-open connection, which must not touch a freed TLS session.
  23248. ASSERT_TRUE(client.connect());
  23249. ASSERT_TRUE(client.is_open());
  23250. ASSERT_TRUE(client.send("after reconnect"));
  23251. std::string msg;
  23252. EXPECT_EQ(ws::Text, client.read(msg));
  23253. EXPECT_EQ("after reconnect", msg);
  23254. client.close();
  23255. }
  23256. #endif
  23257. #ifdef CPPHTTPLIB_SSL_ENABLED
  23258. class WebSocketSSLCATest : public ::testing::Test {
  23259. protected:
  23260. void SetUp() override {
  23261. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23262. SERVER_PRIVATE_KEY_FILE);
  23263. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23264. std::string msg;
  23265. while (ws.read(msg)) {
  23266. ws.send(msg);
  23267. }
  23268. });
  23269. port_ = server_->bind_to_any_port("127.0.0.1");
  23270. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23271. server_->wait_until_ready();
  23272. }
  23273. void TearDown() override {
  23274. server_->stop();
  23275. if (server_thread_.joinable()) { server_thread_.join(); }
  23276. }
  23277. std::string url() const {
  23278. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23279. }
  23280. std::unique_ptr<SSLServer> server_;
  23281. std::thread server_thread_;
  23282. int port_ = 0;
  23283. };
  23284. // A custom CA loaded as PEM verifies the server with full certificate
  23285. // verification enabled
  23286. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23287. ws::WebSocketClient client(url());
  23288. std::string cert;
  23289. read_file(SERVER_CERT2_FILE, cert);
  23290. client.load_ca_cert_store(cert.c_str(), cert.size());
  23291. ASSERT_TRUE(client.connect());
  23292. ASSERT_TRUE(client.send("hello"));
  23293. std::string msg;
  23294. EXPECT_EQ(ws::Text, client.read(msg));
  23295. EXPECT_EQ("hello", msg);
  23296. client.close();
  23297. }
  23298. // A custom CA that does not cover the server must fail verification (the
  23299. // custom CA is exclusive; system certs are not loaded alongside it)
  23300. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23301. ws::WebSocketClient client(url());
  23302. std::string cert;
  23303. read_file(CLIENT_CA_CERT_FILE, cert);
  23304. client.load_ca_cert_store(cert.c_str(), cert.size());
  23305. auto res = client.connect();
  23306. ASSERT_FALSE(res);
  23307. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23308. EXPECT_EQ(-1, res.status());
  23309. EXPECT_NE(0u, res.ssl_backend_error());
  23310. }
  23311. // The same CA as a file path rather than PEM in memory
  23312. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23313. ws::WebSocketClient client(url());
  23314. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23315. ASSERT_TRUE(client.connect());
  23316. ASSERT_TRUE(client.send("hello"));
  23317. std::string msg;
  23318. EXPECT_EQ(ws::Text, client.read(msg));
  23319. EXPECT_EQ("hello", msg);
  23320. client.close();
  23321. }
  23322. // ...and a CA file that does not cover the server still fails, so it is the
  23323. // path above that decides the outcome
  23324. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23325. ws::WebSocketClient client(url());
  23326. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23327. ASSERT_FALSE(client.connect());
  23328. }
  23329. // Regression test: reconnecting with a native custom CA store used to reuse
  23330. // a store handle the previous TLS context had already freed (use-after-free
  23331. // under the OpenSSL backend). The context now lives as long as the client.
  23332. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23333. ws::WebSocketClient client(url());
  23334. std::string cert;
  23335. read_file(SERVER_CERT2_FILE, cert);
  23336. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23337. ASSERT_TRUE(client.connect());
  23338. client.close();
  23339. ASSERT_TRUE(client.connect());
  23340. ASSERT_TRUE(client.send("again"));
  23341. std::string msg;
  23342. EXPECT_EQ(ws::Text, client.read(msg));
  23343. EXPECT_EQ("again", msg);
  23344. client.close();
  23345. }
  23346. // Regression test: a certificate with a trusted chain but no identity match
  23347. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23348. // verification entirely for IP hosts, so this connection succeeded there.
  23349. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23350. // chain verification while the identity check must still fail.
  23351. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23352. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23353. ASSERT_TRUE(svr.is_valid());
  23354. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23355. std::string msg;
  23356. while (ws.read(msg)) {
  23357. ws.send(msg);
  23358. }
  23359. });
  23360. auto port = svr.bind_to_any_port("127.0.0.1");
  23361. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23362. auto se = detail::scope_exit([&] {
  23363. svr.stop();
  23364. t.join();
  23365. });
  23366. svr.wait_until_ready();
  23367. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23368. "/echo");
  23369. std::string cert;
  23370. read_file(SERVER_CERT_FILE, cert);
  23371. client.load_ca_cert_store(cert.c_str(), cert.size());
  23372. ASSERT_FALSE(client.connect());
  23373. }
  23374. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23375. // SNI, so nothing binds the host name to the TLS session. These bind the
  23376. // server to "localhost" instead, the only shape that exercises the SNI and
  23377. // hostname-verification path with certificate verification left enabled.
  23378. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23379. protected:
  23380. void Start(const char *cert_file) {
  23381. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23382. SERVER_PRIVATE_KEY_FILE);
  23383. ASSERT_TRUE(server_->is_valid());
  23384. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23385. std::string msg;
  23386. while (ws.read(msg)) {
  23387. ws.send(msg);
  23388. }
  23389. });
  23390. port_ = server_->bind_to_any_port("localhost");
  23391. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23392. server_->wait_until_ready();
  23393. }
  23394. void TearDown() override {
  23395. if (server_) { server_->stop(); }
  23396. if (server_thread_.joinable()) { server_thread_.join(); }
  23397. }
  23398. std::string url() const {
  23399. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23400. }
  23401. std::unique_ptr<SSLServer> server_;
  23402. std::thread server_thread_;
  23403. int port_ = 0;
  23404. };
  23405. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23406. // out and the connection is usable
  23407. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23408. Start(SERVER_CERT2_FILE);
  23409. ws::WebSocketClient client(url());
  23410. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23411. ASSERT_TRUE(client.connect());
  23412. ASSERT_TRUE(client.send("hello"));
  23413. std::string msg;
  23414. EXPECT_EQ(ws::Text, client.read(msg));
  23415. EXPECT_EQ("hello", msg);
  23416. client.close();
  23417. }
  23418. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23419. // while the identity check must still reject "localhost"
  23420. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23421. Start(SERVER_CERT_FILE);
  23422. ws::WebSocketClient client(url());
  23423. client.set_ca_cert_path(SERVER_CERT_FILE);
  23424. auto res = client.connect();
  23425. ASSERT_FALSE(res);
  23426. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23427. EXPECT_EQ(-1, res.status());
  23428. }
  23429. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23430. // disabled: the chain is still checked, only the identity check is skipped
  23431. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23432. Start(SERVER_CERT_FILE);
  23433. ws::WebSocketClient client(url());
  23434. client.set_ca_cert_path(SERVER_CERT_FILE);
  23435. client.enable_server_hostname_verification(false);
  23436. ASSERT_TRUE(client.connect());
  23437. ASSERT_TRUE(client.send("hello"));
  23438. std::string msg;
  23439. EXPECT_EQ(ws::Text, client.read(msg));
  23440. EXPECT_EQ("hello", msg);
  23441. client.close();
  23442. }
  23443. // A CA that did not sign the server certificate fails the chain, even though
  23444. // the name would match
  23445. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23446. Start(SERVER_CERT2_FILE);
  23447. ws::WebSocketClient client(url());
  23448. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23449. ASSERT_FALSE(client.connect());
  23450. }
  23451. // With verification disabled, neither the chain nor the name is checked
  23452. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23453. Start(SERVER_CERT_FILE);
  23454. ws::WebSocketClient client(url());
  23455. client.enable_server_certificate_verification(false);
  23456. ASSERT_TRUE(client.connect());
  23457. ASSERT_TRUE(client.send("hello"));
  23458. std::string msg;
  23459. EXPECT_EQ(ws::Text, client.read(msg));
  23460. EXPECT_EQ("hello", msg);
  23461. client.close();
  23462. }
  23463. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23464. protected:
  23465. void SetUp() override {
  23466. server_ = httplib::detail::make_unique<SSLServer>(
  23467. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23468. ASSERT_TRUE(server_->is_valid());
  23469. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23470. std::string msg;
  23471. while (ws.read(msg)) {
  23472. ws.send(msg);
  23473. }
  23474. });
  23475. port_ = server_->bind_to_any_port("localhost");
  23476. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23477. server_->wait_until_ready();
  23478. }
  23479. void TearDown() override {
  23480. server_->stop();
  23481. if (server_thread_.joinable()) { server_thread_.join(); }
  23482. }
  23483. std::string url() const {
  23484. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23485. }
  23486. void ConnectWithClientCert(const std::string &client_cert_file,
  23487. const std::string &client_private_key_file,
  23488. const char *private_key_password) {
  23489. std::string cert_pem, key_pem;
  23490. read_file(client_cert_file, cert_pem);
  23491. read_file(client_private_key_file, key_pem);
  23492. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23493. key_pem.c_str(), key_pem.size(),
  23494. private_key_password};
  23495. ws::WebSocketClient client(url(), pem);
  23496. ASSERT_TRUE(client.is_valid());
  23497. client.enable_server_certificate_verification(false);
  23498. ASSERT_TRUE(client.connect());
  23499. ASSERT_TRUE(client.send("hello"));
  23500. std::string msg;
  23501. EXPECT_EQ(ws::Text, client.read(msg));
  23502. EXPECT_EQ("hello", msg);
  23503. client.close();
  23504. }
  23505. std::unique_ptr<SSLServer> server_;
  23506. std::thread server_thread_;
  23507. int port_ = 0;
  23508. };
  23509. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23510. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23511. }
  23512. // Control for the tests above: the fixture's server really does require a
  23513. // client certificate, so it is the PEM the constructor installed that decides
  23514. // the outcome.
  23515. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23516. ws::WebSocketClient client(url());
  23517. ASSERT_TRUE(client.is_valid());
  23518. client.enable_server_certificate_verification(false);
  23519. EXPECT_FALSE(client.connect());
  23520. }
  23521. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23522. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23523. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23524. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23525. }
  23526. #endif
  23527. #if !defined(_WIN32)
  23528. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23529. auto secret_dir = std::string("./symlink_test_secret");
  23530. auto served_dir = std::string("./symlink_test_served");
  23531. auto secret_file = secret_dir + "/secret.txt";
  23532. auto symlink_path = served_dir + "/escape";
  23533. // Setup: create directories and files
  23534. mkdir(secret_dir.c_str(), 0755);
  23535. mkdir(served_dir.c_str(), 0755);
  23536. {
  23537. std::ofstream ofs(secret_file);
  23538. ofs << "SECRET_DATA";
  23539. }
  23540. // Create symlink using absolute path so it resolves correctly
  23541. #ifdef PATH_MAX
  23542. char abs_secret[PATH_MAX];
  23543. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23544. #else
  23545. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23546. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23547. ASSERT_NE(nullptr, abs_secret);
  23548. #endif
  23549. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23550. auto se = detail::scope_exit([&] {
  23551. unlink(symlink_path.c_str());
  23552. unlink(secret_file.c_str());
  23553. rmdir(served_dir.c_str());
  23554. rmdir(secret_dir.c_str());
  23555. });
  23556. Server svr;
  23557. svr.set_mount_point("/", served_dir);
  23558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23559. auto se2 = detail::scope_exit([&] {
  23560. svr.stop();
  23561. listen_thread.join();
  23562. });
  23563. svr.wait_until_ready();
  23564. Client cli("localhost", PORT);
  23565. // Symlink pointing outside base dir should be blocked
  23566. auto res = cli.Get("/escape/secret.txt");
  23567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23568. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23569. }
  23570. #endif
  23571. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23572. // "GET /smuggled" request), reads the first response, and only then sends the
  23573. // embedded request as the body. Returns how many times /smuggled ran.
  23574. //
  23575. // The body is sent AFTER receiving the first response (as in the original
  23576. // PoC) so that the stream_line_reader cannot buffer it together with the
  23577. // headers of the first request.
  23578. static int count_smuggled_requests(const std::string &outer_head,
  23579. std::string &first_response) {
  23580. Server svr;
  23581. svr.set_mount_point("/", "./www");
  23582. std::atomic<int> smuggled_count(0);
  23583. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23584. smuggled_count++;
  23585. res.set_content("oops", "text/plain");
  23586. });
  23587. svr.Post("/post", [&](const Request &req, Response &res) {
  23588. res.set_content(req.body, "text/plain");
  23589. });
  23590. auto port = svr.bind_to_any_port("localhost");
  23591. thread t = thread([&] { svr.listen_after_bind(); });
  23592. auto se = detail::scope_exit([&] {
  23593. svr.stop();
  23594. t.join();
  23595. });
  23596. svr.wait_until_ready();
  23597. auto error = Error::Success;
  23598. auto sock = detail::create_client_socket(
  23599. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23600. /*connection_timeout_sec=*/2, 0,
  23601. /*read_timeout_sec=*/2, 0,
  23602. /*write_timeout_sec=*/2, 0, std::string(), error);
  23603. EXPECT_NE(INVALID_SOCKET, sock);
  23604. if (sock == INVALID_SOCKET) { return -1; }
  23605. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23606. // The "smuggled" request will be sent as the body of the outer request
  23607. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23608. "Host: localhost\r\n"
  23609. "Connection: close\r\n"
  23610. "\r\n";
  23611. auto head = outer_head;
  23612. auto len = std::to_string(smuggled.size());
  23613. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23614. pos = head.find("{len}", pos + len.size())) {
  23615. head.replace(pos, 5, len);
  23616. }
  23617. // Step 1: Send only the outer request headers (no body yet)
  23618. auto sent = send(sock, head.data(), head.size(), 0);
  23619. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23620. // Step 2: Read the first response
  23621. char buf[4096];
  23622. for (;;) {
  23623. auto n = recv(sock, buf, sizeof(buf), 0);
  23624. if (n <= 0) break;
  23625. first_response.append(buf, static_cast<size_t>(n));
  23626. // Stop once we have a complete response (headers + body)
  23627. auto hdr_end = first_response.find("\r\n\r\n");
  23628. if (hdr_end != std::string::npos) {
  23629. // Check for Content-Length to know when the body is complete
  23630. auto cl_pos = first_response.find("Content-Length:");
  23631. if (cl_pos != std::string::npos) {
  23632. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23633. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23634. auto cl = std::stoul(
  23635. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23636. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23637. } else {
  23638. break; // No Content-Length, assume headers-only response
  23639. }
  23640. }
  23641. }
  23642. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23643. // vulnerable server the keep-alive loop reads this as a second request. The
  23644. // server may already have closed the connection, so the result is ignored.
  23645. send(sock, smuggled.data(), smuggled.size(), 0);
  23646. // Half-close so that a server which drained the body sees EOF and closes,
  23647. // instead of the read below waiting for the read timeout.
  23648. #ifdef _WIN32
  23649. ::shutdown(sock, SD_SEND);
  23650. #else
  23651. ::shutdown(sock, SHUT_WR);
  23652. #endif
  23653. // Step 4: Read until the server closes the connection
  23654. for (;;) {
  23655. auto n = recv(sock, buf, sizeof(buf), 0);
  23656. if (n <= 0) break;
  23657. }
  23658. return smuggled_count.load();
  23659. }
  23660. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23661. // A GET request with Content-Length to a static file handler must have its
  23662. // body drained before the keep-alive connection is reused. Otherwise the
  23663. // unread body bytes are interpreted as the next HTTP request.
  23664. std::string first_response;
  23665. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23666. "Host: localhost\r\n"
  23667. "Content-Length: {len}\r\n"
  23668. "\r\n",
  23669. first_response));
  23670. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23671. }
  23672. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23673. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23674. // be answered with 400 and the connection closed. Treating it as "no body"
  23675. // leaves the body to be parsed as the next request.
  23676. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23677. const char *targets[] = {
  23678. "GET /file", // handler that never reads the body
  23679. "GET /not-found", // no handler matches (404)
  23680. "POST /post", // handler that reads the body
  23681. };
  23682. for (auto target : targets) {
  23683. for (auto value : values) {
  23684. std::string first_response;
  23685. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23686. " HTTP/1.1\r\n"
  23687. "Host: localhost\r\n"
  23688. "Content-Length: " +
  23689. value + "\r\n\r\n",
  23690. first_response))
  23691. << target << " with Content-Length: " << value;
  23692. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23693. << target << " with Content-Length: " << value;
  23694. }
  23695. }
  23696. }
  23697. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23698. // A 400 for an unparseable request line leaves the rest of the message
  23699. // unread, so the connection must be closed rather than reused.
  23700. std::string first_response;
  23701. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23702. "Host: localhost\r\n"
  23703. "Content-Length: {len}\r\n"
  23704. "\r\n",
  23705. first_response));
  23706. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23707. }
  23708. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23709. // Same as above for a header block that fails to parse.
  23710. std::string first_response;
  23711. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23712. "Host: localhost\r\n"
  23713. "Bad Header\r\n"
  23714. "Content-Length: {len}\r\n"
  23715. "\r\n",
  23716. first_response));
  23717. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23718. }
  23719. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23720. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23721. // server must not read another request on that connection, even when the
  23722. // request had no body to drain.
  23723. std::string first_response;
  23724. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23725. "Host: localhost\r\n"
  23726. "\r\n",
  23727. first_response));
  23728. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23729. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23730. }
  23731. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23732. // A content reader that stops early leaves the stream inside the body.
  23733. // Draining the whole Content-Length from there, or reading the body again,
  23734. // reads into the next request, and whatever follows is parsed as a request
  23735. // of its own.
  23736. Server svr;
  23737. std::atomic<int> smuggled_count(0);
  23738. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23739. svr.Post("/upload", [](const Request &req, Response &res,
  23740. const ContentReader &content_reader) {
  23741. // Stop at the last chunk, so the whole body has been read however it
  23742. // arrives.
  23743. auto length = req.get_header_value_u64("Content-Length");
  23744. size_t total = 0;
  23745. auto consumed = content_reader([&](const char *, size_t n) {
  23746. total += n;
  23747. return total < length;
  23748. });
  23749. EXPECT_FALSE(consumed);
  23750. if (req.has_param("retry")) {
  23751. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23752. }
  23753. // Replace the 400 the aborted read set, which would close the connection.
  23754. res.set_redirect("/done");
  23755. });
  23756. auto port = svr.bind_to_any_port(HOST);
  23757. thread t = thread([&] { svr.listen_after_bind(); });
  23758. auto se = detail::scope_exit([&] {
  23759. svr.stop();
  23760. t.join();
  23761. });
  23762. svr.wait_until_ready();
  23763. // A front end sees the second request as a POST whose body is the GET. The
  23764. // first body is as long as the POST's headers, so draining it again reads
  23765. // exactly those and leaves the GET to be parsed next.
  23766. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23767. "Host: localhost\r\n"
  23768. "\r\n";
  23769. std::string second_head = "POST /post HTTP/1.1\r\n"
  23770. "Host: localhost\r\n"
  23771. "Content-Length: " +
  23772. std::to_string(inner.size()) +
  23773. "\r\n"
  23774. "\r\n";
  23775. for (auto target : {"/upload", "/upload?retry"}) {
  23776. smuggled_count = 0;
  23777. std::string request = "POST " + std::string(target) +
  23778. " HTTP/1.1\r\n"
  23779. "Host: localhost\r\n"
  23780. "Content-Length: " +
  23781. std::to_string(second_head.size()) +
  23782. "\r\n"
  23783. "\r\n" +
  23784. std::string(second_head.size(), 'A') + second_head +
  23785. inner;
  23786. std::string response;
  23787. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23788. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23789. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23790. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23791. EXPECT_EQ(0, smuggled_count.load()) << target;
  23792. }
  23793. }
  23794. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23795. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23796. // must be rejected with 400 Bad Request.
  23797. Server svr;
  23798. svr.Post("/test", [&](const Request &, Response &res) {
  23799. res.set_content("ok", "text/plain");
  23800. });
  23801. thread t = thread([&] { svr.listen(HOST, PORT); });
  23802. auto se = detail::scope_exit([&] {
  23803. svr.stop();
  23804. t.join();
  23805. ASSERT_FALSE(svr.is_running());
  23806. });
  23807. svr.wait_until_ready();
  23808. // Exact "chunked"
  23809. {
  23810. auto req = "POST /test HTTP/1.1\r\n"
  23811. "Host: localhost\r\n"
  23812. "Content-Length: 5\r\n"
  23813. "Transfer-Encoding: chunked\r\n"
  23814. "Connection: close\r\n"
  23815. "\r\n"
  23816. "hello";
  23817. std::string response;
  23818. ASSERT_TRUE(send_request(1, req, &response));
  23819. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23820. response.substr(0, response.find("\r\n")));
  23821. }
  23822. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23823. {
  23824. auto req = "POST /test HTTP/1.1\r\n"
  23825. "Host: localhost\r\n"
  23826. "Content-Length: 5\r\n"
  23827. "Transfer-Encoding: gzip, chunked\r\n"
  23828. "Connection: close\r\n"
  23829. "\r\n"
  23830. "hello";
  23831. std::string response;
  23832. ASSERT_TRUE(send_request(1, req, &response));
  23833. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23834. response.substr(0, response.find("\r\n")));
  23835. }
  23836. }
  23837. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23838. Server svr;
  23839. svr.Post("/test", [&](const Request &, Response &res) {
  23840. res.set_content("ok", "text/plain");
  23841. });
  23842. thread t = thread([&] { svr.listen(HOST, PORT); });
  23843. auto se = detail::scope_exit([&] {
  23844. svr.stop();
  23845. t.join();
  23846. ASSERT_FALSE(svr.is_running());
  23847. });
  23848. svr.wait_until_ready();
  23849. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23850. // length cannot be determined, so the server must answer 400 and close
  23851. // rather than treat the request as bodyless and leave the body in the
  23852. // socket for the next request to pick up.
  23853. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23854. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23855. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23856. std::string response;
  23857. ASSERT_TRUE(send_request(1, req, &response));
  23858. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23859. response.substr(0, response.find("\r\n")))
  23860. << transfer_encoding;
  23861. }
  23862. // RFC 9110 5.3: the codings may also be split across several
  23863. // Transfer-Encoding lines, which combine in the order they were received.
  23864. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23865. // just like the single-line "chunked, gzip" above.
  23866. {
  23867. auto req = "POST /test HTTP/1.1\r\n"
  23868. "Host: localhost\r\n"
  23869. "Transfer-Encoding: chunked\r\n"
  23870. "Transfer-Encoding: gzip\r\n"
  23871. "\r\n"
  23872. "0\r\n\r\n";
  23873. std::string response;
  23874. ASSERT_TRUE(send_request(1, req, &response));
  23875. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23876. response.substr(0, response.find("\r\n")));
  23877. }
  23878. // A sequence ending in chunked stays valid.
  23879. auto req = "POST /test HTTP/1.1\r\n"
  23880. "Host: localhost\r\n"
  23881. "Transfer-Encoding: gzip, chunked\r\n"
  23882. "Connection: close\r\n"
  23883. "\r\n"
  23884. "0\r\n\r\n";
  23885. std::string response;
  23886. ASSERT_TRUE(send_request(1, req, &response));
  23887. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23888. // ...including when it is spread over several lines.
  23889. auto split_req = "POST /test HTTP/1.1\r\n"
  23890. "Host: localhost\r\n"
  23891. "Transfer-Encoding: gzip\r\n"
  23892. "Transfer-Encoding: chunked\r\n"
  23893. "Connection: close\r\n"
  23894. "\r\n"
  23895. "0\r\n\r\n";
  23896. std::string split_response;
  23897. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23898. EXPECT_EQ("HTTP/1.1 200 OK",
  23899. split_response.substr(0, split_response.find("\r\n")));
  23900. }
  23901. // Regression for issue #2450: a DELETE without Content-Length on a
  23902. // keep-alive connection must not let the post-response drain consume the
  23903. // next request's bytes.
  23904. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23905. Server svr;
  23906. std::atomic<int> delete_count(0);
  23907. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23908. delete_count++;
  23909. res.status = StatusCode::NoContent_204;
  23910. });
  23911. auto port = svr.bind_to_any_port(HOST);
  23912. thread t = thread([&] { svr.listen_after_bind(); });
  23913. auto se = detail::scope_exit([&] {
  23914. svr.stop();
  23915. t.join();
  23916. });
  23917. svr.wait_until_ready();
  23918. auto error = Error::Success;
  23919. auto sock = detail::create_client_socket(
  23920. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23921. /*connection_timeout_sec=*/2, 0,
  23922. /*read_timeout_sec=*/2, 0,
  23923. /*write_timeout_sec=*/2, 0, std::string(), error);
  23924. ASSERT_NE(INVALID_SOCKET, sock);
  23925. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23926. auto send_request_and_read_response = [&](const std::string &req,
  23927. std::string &out) -> bool {
  23928. auto sent = send(sock, req.data(), req.size(), 0);
  23929. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23930. char buf[4096];
  23931. for (;;) {
  23932. auto n = recv(sock, buf, sizeof(buf), 0);
  23933. if (n <= 0) { return !out.empty(); }
  23934. out.append(buf, static_cast<size_t>(n));
  23935. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23936. }
  23937. };
  23938. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23939. "Host: localhost\r\n"
  23940. "\r\n";
  23941. std::string resp1;
  23942. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23943. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23944. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23945. "Host: localhost\r\n"
  23946. "Connection: close\r\n"
  23947. "\r\n";
  23948. std::string resp2;
  23949. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23950. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23951. EXPECT_EQ(2, delete_count.load());
  23952. }
  23953. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23954. Server svr;
  23955. svr.Post("/ingest", [&](const Request &, Response &res,
  23956. const ContentReader &content_reader) {
  23957. auto consumed = content_reader([](const char *, size_t) { return false; });
  23958. EXPECT_FALSE(consumed);
  23959. res.status = StatusCode::Conflict_409;
  23960. res.set_header("Connection", "close");
  23961. });
  23962. auto port = svr.bind_to_any_port(HOST);
  23963. thread t = thread([&] { svr.listen_after_bind(); });
  23964. auto se = detail::scope_exit([&] {
  23965. svr.stop();
  23966. t.join();
  23967. });
  23968. svr.wait_until_ready();
  23969. auto error = Error::Success;
  23970. auto sock = detail::create_client_socket(
  23971. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23972. /*connection_timeout_sec=*/2, 0,
  23973. /*read_timeout_sec=*/1, 0,
  23974. /*write_timeout_sec=*/2, 0, std::string(), error);
  23975. ASSERT_NE(INVALID_SOCKET, sock);
  23976. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23977. std::string request = "POST /ingest HTTP/1.1\r\n"
  23978. "Host: localhost\r\n"
  23979. "Transfer-Encoding: chunked\r\n"
  23980. "\r\n"
  23981. "4\r\n"
  23982. "data\r\n";
  23983. auto sent = send(sock, request.data(), request.size(), 0);
  23984. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23985. std::string response;
  23986. ssize_t received = 0;
  23987. do {
  23988. char buf[4096];
  23989. received = recv(sock, buf, sizeof(buf), 0);
  23990. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23991. } while (received > 0);
  23992. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23993. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23994. EXPECT_EQ(0, received);
  23995. }
  23996. namespace no_proxy_test {
  23997. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23998. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23999. // calling listen().
  24000. class ScopedServer {
  24001. public:
  24002. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24003. ~ScopedServer() {
  24004. svr_.stop();
  24005. if (th_.joinable()) { th_.join(); }
  24006. }
  24007. Server &svr() { return svr_; }
  24008. int port() const { return port_; }
  24009. void listen() {
  24010. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24011. svr_.wait_until_ready();
  24012. }
  24013. private:
  24014. Server svr_;
  24015. std::thread th_;
  24016. int port_ = 0;
  24017. };
  24018. class ProxyAndTargetServers {
  24019. public:
  24020. ProxyAndTargetServers() {
  24021. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24022. proxy_hits_++;
  24023. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24024. res.set_content("via-proxy", "text/plain");
  24025. });
  24026. target_.Get(".*", [this](const Request &req, Response &res) {
  24027. target_hits_++;
  24028. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24029. res.set_content("direct", "text/plain");
  24030. });
  24031. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24032. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24033. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24034. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24035. proxy_mock_.wait_until_ready();
  24036. target_.wait_until_ready();
  24037. }
  24038. ~ProxyAndTargetServers() {
  24039. proxy_mock_.stop();
  24040. target_.stop();
  24041. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24042. if (target_thread_.joinable()) { target_thread_.join(); }
  24043. }
  24044. Server &proxy_mock() { return proxy_mock_; }
  24045. Server &target() { return target_; }
  24046. int proxy_port() const { return proxy_port_; }
  24047. int target_port() const { return target_port_; }
  24048. int proxy_hits() const { return proxy_hits_.load(); }
  24049. int target_hits() const { return target_hits_.load(); }
  24050. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24051. void reset_counters() {
  24052. proxy_hits_ = 0;
  24053. target_hits_ = 0;
  24054. last_had_proxy_authz_ = false;
  24055. }
  24056. private:
  24057. Server proxy_mock_;
  24058. Server target_;
  24059. std::thread proxy_thread_;
  24060. std::thread target_thread_;
  24061. int proxy_port_ = 0;
  24062. int target_port_ = 0;
  24063. std::atomic<int> proxy_hits_{0};
  24064. std::atomic<int> target_hits_{0};
  24065. std::atomic<bool> last_had_proxy_authz_{false};
  24066. };
  24067. inline std::unique_ptr<Client> make_client(const std::string &host,
  24068. ProxyAndTargetServers &s) {
  24069. auto cli = detail::make_unique<Client>(host, s.target_port());
  24070. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24071. cli->set_proxy("127.0.0.1", s.proxy_port());
  24072. return cli;
  24073. }
  24074. } // namespace no_proxy_test
  24075. using no_proxy_test::make_client;
  24076. using no_proxy_test::ProxyAndTargetServers;
  24077. TEST(NoProxyTest, ExactHostnameBypasses) {
  24078. ProxyAndTargetServers s;
  24079. auto cli = make_client("example.com", s);
  24080. cli->set_no_proxy({"example.com"});
  24081. auto res = cli->Get("/");
  24082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24083. EXPECT_EQ(0, s.proxy_hits());
  24084. EXPECT_EQ(1, s.target_hits());
  24085. }
  24086. TEST(NoProxyTest, SubdomainBypasses) {
  24087. ProxyAndTargetServers s;
  24088. auto cli = make_client("foo.example.com", s);
  24089. cli->set_no_proxy({"example.com"});
  24090. auto res = cli->Get("/");
  24091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24092. EXPECT_EQ(0, s.proxy_hits());
  24093. EXPECT_EQ(1, s.target_hits());
  24094. }
  24095. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24096. // Regression guard: "evilexample.com" must not be considered a subdomain
  24097. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24098. // check would let traffic bypass the proxy and leak credentials direct
  24099. // to the attacker host.
  24100. ProxyAndTargetServers s;
  24101. auto cli = make_client("evilexample.com", s);
  24102. cli->set_no_proxy({"example.com"});
  24103. auto res = cli->Get("/");
  24104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24105. EXPECT_GE(s.proxy_hits(), 1);
  24106. EXPECT_EQ(0, s.target_hits());
  24107. }
  24108. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24109. ProxyAndTargetServers s;
  24110. auto cli = make_client("example.com.evil.com", s);
  24111. cli->set_no_proxy({"example.com"});
  24112. auto res = cli->Get("/");
  24113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24114. EXPECT_GE(s.proxy_hits(), 1);
  24115. EXPECT_EQ(0, s.target_hits());
  24116. }
  24117. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24118. ProxyAndTargetServers s;
  24119. auto cli = make_client("example.com", s);
  24120. cli->set_no_proxy({".example.com"});
  24121. auto res = cli->Get("/");
  24122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24123. EXPECT_EQ(0, s.proxy_hits());
  24124. EXPECT_EQ(1, s.target_hits());
  24125. }
  24126. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24127. ProxyAndTargetServers s;
  24128. auto cli = make_client("Example.COM", s);
  24129. cli->set_no_proxy({"EXAMPLE.com"});
  24130. auto res = cli->Get("/");
  24131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24132. EXPECT_EQ(0, s.proxy_hits());
  24133. EXPECT_EQ(1, s.target_hits());
  24134. }
  24135. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24136. ProxyAndTargetServers s;
  24137. auto cli = make_client("example.com.", s);
  24138. cli->set_no_proxy({"example.com"});
  24139. auto res = cli->Get("/");
  24140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24141. EXPECT_EQ(0, s.proxy_hits());
  24142. EXPECT_EQ(1, s.target_hits());
  24143. }
  24144. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24145. // Trailing dots must be normalized on BOTH sides — host and entry.
  24146. // An implementation that only strips the host-side trailing dot would
  24147. // fail to match host "example.com" against entry "example.com." because
  24148. // a literal substring search would compare 11 chars against 12.
  24149. ProxyAndTargetServers s;
  24150. auto cli = make_client("example.com", s);
  24151. cli->set_no_proxy({"example.com."});
  24152. auto res = cli->Get("/");
  24153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24154. EXPECT_EQ(0, s.proxy_hits());
  24155. EXPECT_EQ(1, s.target_hits());
  24156. }
  24157. TEST(NoProxyTest, WildcardBypassesEverything) {
  24158. ProxyAndTargetServers s;
  24159. auto cli = make_client("anything.invalid.test", s);
  24160. cli->set_no_proxy({"*"});
  24161. auto res = cli->Get("/");
  24162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24163. EXPECT_EQ(0, s.proxy_hits());
  24164. EXPECT_EQ(1, s.target_hits());
  24165. }
  24166. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24167. ProxyAndTargetServers s;
  24168. Client cli("127.0.0.1", s.target_port());
  24169. cli.set_proxy("127.0.0.1", s.proxy_port());
  24170. cli.set_no_proxy({"127.0.0.1"});
  24171. auto res = cli.Get("/");
  24172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24173. EXPECT_EQ(0, s.proxy_hits());
  24174. EXPECT_EQ(1, s.target_hits());
  24175. }
  24176. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24177. ProxyAndTargetServers s;
  24178. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24179. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24180. cli.set_proxy("127.0.0.1", s.proxy_port());
  24181. cli.set_no_proxy({"::1"});
  24182. auto res = cli.Get("/");
  24183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24184. EXPECT_EQ(0, s.proxy_hits());
  24185. EXPECT_EQ(1, s.target_hits());
  24186. }
  24187. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24188. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24189. // must still be recognized as IPv6 for CIDR matching. Implementations
  24190. // that detect IPv6 only when the host begins with '[' would parse the
  24191. // host as a hostname and miss the match.
  24192. ProxyAndTargetServers s;
  24193. Client cli("fe80::1", s.target_port());
  24194. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24195. cli.set_proxy("127.0.0.1", s.proxy_port());
  24196. cli.set_no_proxy({"fe80::/10"});
  24197. auto res = cli.Get("/");
  24198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24199. EXPECT_EQ(0, s.proxy_hits());
  24200. EXPECT_EQ(1, s.target_hits());
  24201. }
  24202. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24203. ProxyAndTargetServers s;
  24204. Client cli("::1", s.target_port());
  24205. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24206. cli.set_proxy("127.0.0.1", s.proxy_port());
  24207. cli.set_no_proxy({"[::1]"});
  24208. auto res = cli.Get("/");
  24209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24210. EXPECT_EQ(0, s.proxy_hits());
  24211. EXPECT_EQ(1, s.target_hits());
  24212. }
  24213. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24214. ProxyAndTargetServers s;
  24215. Client cli("fe80::1", s.target_port());
  24216. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24217. cli.set_proxy("127.0.0.1", s.proxy_port());
  24218. cli.set_no_proxy({"[fe80::]/10"});
  24219. auto res = cli.Get("/");
  24220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24221. EXPECT_EQ(0, s.proxy_hits());
  24222. EXPECT_EQ(1, s.target_hits());
  24223. }
  24224. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24225. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24226. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24227. // tricks via address-family conversion.
  24228. ProxyAndTargetServers s;
  24229. Client cli("::ffff:127.0.0.1", s.target_port());
  24230. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24231. cli.set_proxy("127.0.0.1", s.proxy_port());
  24232. cli.set_no_proxy({"127.0.0.1"});
  24233. auto res = cli.Get("/");
  24234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24235. EXPECT_GE(s.proxy_hits(), 1);
  24236. EXPECT_EQ(0, s.target_hits());
  24237. }
  24238. TEST(NoProxyTest, IPv4CidrMatch) {
  24239. ProxyAndTargetServers s;
  24240. Client cli("127.0.0.1", s.target_port());
  24241. cli.set_proxy("127.0.0.1", s.proxy_port());
  24242. cli.set_no_proxy({"127.0.0.0/8"});
  24243. auto res = cli.Get("/");
  24244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24245. EXPECT_EQ(0, s.proxy_hits());
  24246. EXPECT_EQ(1, s.target_hits());
  24247. }
  24248. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24249. ProxyAndTargetServers s;
  24250. Client cli("127.0.0.1", s.target_port());
  24251. cli.set_proxy("127.0.0.1", s.proxy_port());
  24252. cli.set_no_proxy({"10.0.0.0/8"});
  24253. auto res = cli.Get("/");
  24254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24255. EXPECT_GE(s.proxy_hits(), 1);
  24256. EXPECT_EQ(0, s.target_hits());
  24257. }
  24258. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24259. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24260. // IPv4 target matches.
  24261. ProxyAndTargetServers s;
  24262. Client cli("127.0.0.1", s.target_port());
  24263. cli.set_proxy("127.0.0.1", s.proxy_port());
  24264. cli.set_no_proxy({"0.0.0.0/0"});
  24265. auto res = cli.Get("/");
  24266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24267. EXPECT_EQ(0, s.proxy_hits());
  24268. EXPECT_EQ(1, s.target_hits());
  24269. }
  24270. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24271. ProxyAndTargetServers s;
  24272. Client cli("127.0.0.1", s.target_port());
  24273. cli.set_proxy("127.0.0.1", s.proxy_port());
  24274. cli.set_no_proxy({"127.0.0.1"});
  24275. auto res = cli.Get("/");
  24276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24277. EXPECT_EQ(0, s.proxy_hits());
  24278. EXPECT_EQ(1, s.target_hits());
  24279. }
  24280. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24281. ProxyAndTargetServers s;
  24282. Client cli("127.0.0.1", s.target_port());
  24283. cli.set_proxy("127.0.0.1", s.proxy_port());
  24284. cli.set_no_proxy({"127.0.0.0/33"});
  24285. auto res = cli.Get("/");
  24286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24287. EXPECT_GE(s.proxy_hits(), 1);
  24288. EXPECT_EQ(0, s.target_hits());
  24289. }
  24290. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24291. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24292. ProxyAndTargetServers s;
  24293. Client cli("127.0.0.1", s.target_port());
  24294. cli.set_proxy("127.0.0.1", s.proxy_port());
  24295. cli.set_no_proxy({"127.0.0.1/"});
  24296. auto res = cli.Get("/");
  24297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24298. EXPECT_GE(s.proxy_hits(), 1);
  24299. EXPECT_EQ(0, s.target_hits());
  24300. }
  24301. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24302. ProxyAndTargetServers s;
  24303. auto cli = make_client("internal.corp", s);
  24304. cli->set_proxy_basic_auth("u", "p");
  24305. cli->set_no_proxy({"internal.corp"});
  24306. auto res = cli->Get("/");
  24307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24308. EXPECT_EQ(1, s.target_hits());
  24309. EXPECT_EQ(0, s.proxy_hits());
  24310. EXPECT_FALSE(s.last_had_proxy_authz())
  24311. << "Proxy-Authorization must not be sent direct to the target";
  24312. }
  24313. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24314. ProxyAndTargetServers s;
  24315. auto cli = make_client("public.example", s);
  24316. cli->set_proxy_basic_auth("u", "p");
  24317. cli->set_no_proxy({"internal.corp"}); // does not match
  24318. auto res = cli->Get("/");
  24319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24320. EXPECT_GE(s.proxy_hits(), 1);
  24321. EXPECT_TRUE(s.last_had_proxy_authz());
  24322. }
  24323. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24324. std::atomic<int> hits{0};
  24325. std::atomic<int> hits_with_authz{0};
  24326. no_proxy_test::ScopedServer proxy_mock;
  24327. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24328. hits++;
  24329. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24330. if (req.target.find("/redir") != std::string::npos) {
  24331. res.set_redirect("http://other.example/landed");
  24332. } else {
  24333. res.set_content("via-proxy", "text/plain");
  24334. }
  24335. });
  24336. proxy_mock.listen();
  24337. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24338. hits = 0;
  24339. hits_with_authz = 0;
  24340. Client cli("public.example", 80);
  24341. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24342. cli.set_proxy_basic_auth(c.first, c.second);
  24343. cli.set_follow_location(true);
  24344. // The redirect to another host goes through the proxy as well
  24345. auto res = cli.Get("/redir");
  24346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24347. EXPECT_EQ(2, hits.load());
  24348. EXPECT_EQ(2, hits_with_authz.load());
  24349. }
  24350. }
  24351. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24352. ProxyAndTargetServers s;
  24353. auto cli = make_client("anything.test", s);
  24354. auto res = cli->Get("/");
  24355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24356. EXPECT_GE(s.proxy_hits(), 1);
  24357. EXPECT_EQ(0, s.target_hits());
  24358. }
  24359. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24360. ProxyAndTargetServers s;
  24361. auto cli = make_client("example.com", s);
  24362. cli->set_no_proxy({"example.com:8080"});
  24363. auto res = cli->Get("/");
  24364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24365. EXPECT_GE(s.proxy_hits(), 1);
  24366. EXPECT_EQ(0, s.target_hits());
  24367. }
  24368. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24369. ProxyAndTargetServers s;
  24370. auto cli = make_client("anything.test", s);
  24371. cli->set_no_proxy({"", " ", "\t"});
  24372. auto res = cli->Get("/");
  24373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24374. EXPECT_GE(s.proxy_hits(), 1);
  24375. EXPECT_EQ(0, s.target_hits());
  24376. }
  24377. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24378. // An entry with leading/trailing whitespace must still match — env-style
  24379. // values are commonly pasted with stray spaces and an implementation
  24380. // that feeds the raw token directly to inet_pton would fail to match
  24381. // valid CIDRs because of the spaces.
  24382. ProxyAndTargetServers s;
  24383. Client cli("127.0.0.1", s.target_port());
  24384. cli.set_proxy("127.0.0.1", s.proxy_port());
  24385. cli.set_no_proxy({" 127.0.0.0/8 "});
  24386. auto res = cli.Get("/");
  24387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24388. EXPECT_EQ(0, s.proxy_hits());
  24389. EXPECT_EQ(1, s.target_hits());
  24390. }
  24391. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24392. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24393. // go direct and must NOT carry Proxy-Authorization.
  24394. std::atomic<int> proxy_hits{0};
  24395. std::atomic<int> target_hits{0};
  24396. std::atomic<bool> target_saw_authz{false};
  24397. no_proxy_test::ScopedServer proxy_mock, target;
  24398. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24399. proxy_hits++;
  24400. res.status = 302;
  24401. res.set_header("Location", "http://127.0.0.1:" +
  24402. std::to_string(target.port()) + "/landed");
  24403. });
  24404. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24405. target_hits++;
  24406. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24407. res.set_content("direct", "text/plain");
  24408. });
  24409. proxy_mock.listen();
  24410. target.listen();
  24411. Client cli("public.example", target.port());
  24412. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24413. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24414. cli.set_proxy_basic_auth("u", "p");
  24415. cli.set_no_proxy({"127.0.0.1"});
  24416. cli.set_follow_location(true);
  24417. auto res = cli.Get("/redir");
  24418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24419. EXPECT_GE(proxy_hits.load(), 1);
  24420. EXPECT_GE(target_hits.load(), 1);
  24421. EXPECT_FALSE(target_saw_authz.load());
  24422. }
  24423. #ifdef CPPHTTPLIB_SSL_ENABLED
  24424. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24425. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24426. // proxy creds would be sent to the (possibly hostile) origin.
  24427. std::atomic<int> target_hits{0};
  24428. std::atomic<bool> target_saw_proxy_authz{false};
  24429. no_proxy_test::ScopedServer target;
  24430. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24431. target_hits++;
  24432. if (req.has_header("Proxy-Authorization")) {
  24433. target_saw_proxy_authz = true;
  24434. }
  24435. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24436. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24437. "nonce=\"abc\", algorithm=MD5");
  24438. });
  24439. target.listen();
  24440. // The proxy address is set to the target's port: the bypass MUST kick in;
  24441. // if it doesn't, the test still routes "via proxy" to the same server and
  24442. // the Proxy-Authorization assertion below catches the leak.
  24443. Client cli("evil.example", target.port());
  24444. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24445. cli.set_proxy("127.0.0.1", target.port());
  24446. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24447. cli.set_no_proxy({"evil.example"});
  24448. auto res = cli.Get("/x");
  24449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24450. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24451. EXPECT_EQ(1, target_hits.load());
  24452. EXPECT_FALSE(target_saw_proxy_authz.load());
  24453. }
  24454. #endif
  24455. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24456. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24457. std::atomic<int> proxy_hits{0};
  24458. std::atomic<int> bypass_hits{0};
  24459. std::atomic<bool> proxy_saw_c_url{false};
  24460. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24461. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24462. proxy_hits++;
  24463. if (req.path.find("/start") != std::string::npos) {
  24464. res.status = 302;
  24465. res.set_header("Location", "http://127.0.0.1:" +
  24466. std::to_string(bypass_server.port()) +
  24467. "/middle");
  24468. return;
  24469. }
  24470. if (req.path.find("/end") != std::string::npos) {
  24471. proxy_saw_c_url = true;
  24472. res.set_content("c-via-proxy", "text/plain");
  24473. return;
  24474. }
  24475. res.set_content("unexpected", "text/plain");
  24476. });
  24477. // public.example's "advertised" port is arbitrary (the request never lands
  24478. // there — it goes through the proxy), but use a dynamic value to stay
  24479. // friendly with sharded parallel runs.
  24480. int public_port = bypass_server.port();
  24481. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24482. bypass_hits++;
  24483. res.status = 302;
  24484. res.set_header("Location", "http://public.example:" +
  24485. std::to_string(public_port) + "/end");
  24486. });
  24487. proxy_mock.listen();
  24488. bypass_server.listen();
  24489. Client cli("public.example", public_port);
  24490. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24491. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24492. cli.set_no_proxy({"127.0.0.1"});
  24493. cli.set_follow_location(true);
  24494. auto res = cli.Get("/start");
  24495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24496. EXPECT_EQ(StatusCode::OK_200, res->status);
  24497. EXPECT_EQ("c-via-proxy", res->body);
  24498. EXPECT_GE(proxy_hits.load(), 2);
  24499. EXPECT_GE(bypass_hits.load(), 1);
  24500. EXPECT_TRUE(proxy_saw_c_url.load());
  24501. }
  24502. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24503. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24504. // request reconnects to the correct endpoint.
  24505. std::atomic<int> proxy_hits{0};
  24506. std::atomic<int> target_hits{0};
  24507. no_proxy_test::ScopedServer proxy_mock, target;
  24508. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24509. proxy_hits++;
  24510. res.set_content("via-proxy", "text/plain");
  24511. });
  24512. target.svr().Get(".*", [&](const Request &, Response &res) {
  24513. target_hits++;
  24514. res.set_content("direct", "text/plain");
  24515. });
  24516. proxy_mock.listen();
  24517. target.listen();
  24518. Client cli("public.example", target.port());
  24519. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24520. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24521. cli.set_keep_alive(true);
  24522. auto res1 = cli.Get("/a");
  24523. ASSERT_TRUE(res1);
  24524. EXPECT_EQ("via-proxy", res1->body);
  24525. EXPECT_EQ(1, proxy_hits.load());
  24526. EXPECT_EQ(0, target_hits.load());
  24527. cli.set_no_proxy({"public.example"});
  24528. auto res2 = cli.Get("/b");
  24529. ASSERT_TRUE(res2);
  24530. EXPECT_EQ("direct", res2->body);
  24531. EXPECT_EQ(1, proxy_hits.load());
  24532. EXPECT_EQ(1, target_hits.load());
  24533. }
  24534. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24535. namespace proxy_tunnel_test {
  24536. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24537. class ScopedSSLServer {
  24538. public:
  24539. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24540. port_ = svr_.bind_to_any_port("127.0.0.1");
  24541. }
  24542. ~ScopedSSLServer() {
  24543. svr_.stop();
  24544. if (th_.joinable()) { th_.join(); }
  24545. }
  24546. SSLServer &svr() { return svr_; }
  24547. int port() const { return port_; }
  24548. void listen() {
  24549. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24550. svr_.wait_until_ready();
  24551. }
  24552. private:
  24553. SSLServer svr_;
  24554. std::thread th_;
  24555. int port_ = 0;
  24556. };
  24557. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24558. class ScopedConnectProxy {
  24559. public:
  24560. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24561. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24562. if (listen_fd_ < 0) { return; }
  24563. int yes = 1;
  24564. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24565. sockaddr_in a{};
  24566. a.sin_family = AF_INET;
  24567. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24568. a.sin_port = 0;
  24569. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24570. return;
  24571. }
  24572. socklen_t alen = sizeof(a);
  24573. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24574. 0) {
  24575. return;
  24576. }
  24577. port_ = ntohs(a.sin_port);
  24578. if (::listen(listen_fd_, 1) != 0) { return; }
  24579. th_ = std::thread([this] { run(); });
  24580. }
  24581. ~ScopedConnectProxy() {
  24582. stop_ = true;
  24583. if (listen_fd_ >= 0) {
  24584. ::shutdown(listen_fd_, SHUT_RDWR);
  24585. ::close(listen_fd_);
  24586. }
  24587. if (th_.joinable()) { th_.join(); }
  24588. }
  24589. int port() const { return port_; }
  24590. int connect_hits() const { return connect_hits_.load(); }
  24591. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24592. std::string connect_request() const {
  24593. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24594. return connect_request_;
  24595. }
  24596. private:
  24597. void run() {
  24598. while (!stop_.load()) {
  24599. fd_set rfds;
  24600. FD_ZERO(&rfds);
  24601. FD_SET(listen_fd_, &rfds);
  24602. timeval tv{0, 100 * 1000};
  24603. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24604. if (sel <= 0) { continue; }
  24605. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24606. if (client_fd < 0) { continue; }
  24607. std::string req;
  24608. char buf[2048];
  24609. while (req.find("\r\n\r\n") == std::string::npos) {
  24610. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24611. if (n <= 0) { break; }
  24612. req.append(buf, static_cast<size_t>(n));
  24613. }
  24614. if (req.compare(0, 7, "CONNECT") != 0) {
  24615. ::close(client_fd);
  24616. continue;
  24617. }
  24618. connect_hits_++;
  24619. {
  24620. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24621. connect_request_ = req;
  24622. }
  24623. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24624. ::send(client_fd, ok, std::strlen(ok), 0);
  24625. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24626. sockaddr_in o{};
  24627. o.sin_family = AF_INET;
  24628. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24629. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24630. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24631. 0) {
  24632. ::close(client_fd);
  24633. ::close(origin_fd);
  24634. continue;
  24635. }
  24636. auto forward = [](int from, int to) {
  24637. char b[8192];
  24638. for (;;) {
  24639. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24640. if (n <= 0) { break; }
  24641. ssize_t off = 0;
  24642. while (off < n) {
  24643. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24644. if (s <= 0) {
  24645. off = n;
  24646. break;
  24647. }
  24648. off += s;
  24649. }
  24650. }
  24651. ::shutdown(to, SHUT_WR);
  24652. };
  24653. std::thread t1([&] { forward(client_fd, origin_fd); });
  24654. std::thread t2([&] { forward(origin_fd, client_fd); });
  24655. t1.join();
  24656. t2.join();
  24657. ::close(client_fd);
  24658. ::close(origin_fd);
  24659. }
  24660. }
  24661. int forward_port_ = -1;
  24662. int listen_fd_ = -1;
  24663. int port_ = 0;
  24664. std::thread th_;
  24665. std::atomic<bool> stop_{false};
  24666. std::atomic<int> connect_hits_{0};
  24667. mutable std::mutex connect_request_mutex_;
  24668. std::string connect_request_;
  24669. };
  24670. // Sends one request through the CONNECT proxy to the TLS origin with a
  24671. // credential configured for each hop, and checks that each credential reaches
  24672. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24673. // origin's (every header in origin_headers) on the tunnelled request.
  24674. void CredentialsStayWithTheirHop(
  24675. const std::function<void(SSLClient &)> &set_credentials,
  24676. const std::string &scheme,
  24677. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24678. std::atomic<int> origin_hits{0};
  24679. std::atomic<bool> origin_saw_proxy_authz{false};
  24680. std::atomic<bool> origin_saw_headers{false};
  24681. ScopedSSLServer origin;
  24682. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24683. origin_hits++;
  24684. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24685. origin_saw_headers =
  24686. std::all_of(origin_headers.begin(), origin_headers.end(),
  24687. [&](const std::string &h) { return req.has_header(h); });
  24688. res.set_content("ok", "text/plain");
  24689. });
  24690. origin.listen();
  24691. ScopedConnectProxy proxy(origin.port());
  24692. ASSERT_NE(0, proxy.port());
  24693. // Pinned to 127.0.0.1 for the same reason as the test below.
  24694. SSLClient cli("127.0.0.1", origin.port());
  24695. cli.enable_server_certificate_verification(false);
  24696. cli.set_proxy("127.0.0.1", proxy.port());
  24697. set_credentials(cli);
  24698. auto res = cli.Get("/x");
  24699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24700. EXPECT_EQ(StatusCode::OK_200, res->status);
  24701. EXPECT_EQ(1, origin_hits.load());
  24702. EXPECT_EQ(1, proxy.connect_hits());
  24703. EXPECT_TRUE(origin_saw_headers.load());
  24704. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24705. << "Proxy-Authorization must not be sent inside the tunnel";
  24706. auto connect_req = proxy.connect_request();
  24707. EXPECT_NE(std::string::npos,
  24708. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24709. for (const auto &h : origin_headers) {
  24710. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24711. << h << " must not be sent to the proxy on CONNECT";
  24712. }
  24713. }
  24714. } // namespace proxy_tunnel_test
  24715. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24716. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24717. [](SSLClient &cli) {
  24718. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24719. cli.set_basic_auth("origin-user", "origin-pass");
  24720. },
  24721. "Basic");
  24722. }
  24723. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24724. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24725. [](SSLClient &cli) {
  24726. cli.set_proxy_bearer_token_auth("proxy-token");
  24727. cli.set_bearer_token_auth("origin-token");
  24728. },
  24729. "Bearer");
  24730. }
  24731. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24732. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24733. [](SSLClient &cli) {
  24734. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24735. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24736. {"Cookie", "sid=origin-session"},
  24737. {"X-Api-Key", "origin-key"}});
  24738. },
  24739. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24740. }
  24741. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24742. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24743. // retry; otherwise proxy creds would be sent to the origin.
  24744. std::atomic<int> origin_hits{0};
  24745. std::atomic<bool> origin_saw_proxy_authz{false};
  24746. proxy_tunnel_test::ScopedSSLServer origin;
  24747. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24748. origin_hits++;
  24749. if (req.has_header("Proxy-Authorization")) {
  24750. origin_saw_proxy_authz = true;
  24751. }
  24752. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24753. res.set_header("Proxy-Authenticate",
  24754. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24755. "algorithm=MD5");
  24756. });
  24757. origin.listen();
  24758. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24759. ASSERT_NE(0, proxy.port());
  24760. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24761. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24762. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24763. // and answer with its own status, making this test flaky.
  24764. SSLClient cli("127.0.0.1", origin.port());
  24765. cli.enable_server_certificate_verification(false);
  24766. cli.set_proxy("127.0.0.1", proxy.port());
  24767. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24768. auto res = cli.Get("/x");
  24769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24770. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24771. EXPECT_EQ(1, origin_hits.load());
  24772. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24773. EXPECT_EQ(1, proxy.connect_hits());
  24774. }
  24775. #endif