test.cc 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899
  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_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. ctx_t create_client_context();
  75. void set_verify_client(ctx_t ctx, bool require);
  76. session_t create_session(ctx_t ctx, socket_t sock);
  77. void free_session(session_t session);
  78. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  79. time_t timeout_usec, TlsError *err,
  80. const std::function<bool()> &interrupted);
  81. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  82. time_t timeout_usec, TlsError *err,
  83. const std::function<bool()> &interrupted);
  84. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  85. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  86. void shutdown(session_t session, bool graceful);
  87. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  88. namespace impl {
  89. SecTrustSettingsResult
  90. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  91. } // namespace impl
  92. #endif
  93. } // namespace tls
  94. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  95. namespace detail {
  96. bool ssl_free_buffers_is_safe(unsigned long version);
  97. } // namespace detail
  98. #endif
  99. } // namespace httplib
  100. #endif
  101. using namespace std;
  102. using namespace httplib;
  103. const char *HOST = "localhost";
  104. static int get_base_port() {
  105. const char *shard = getenv("GTEST_SHARD_INDEX");
  106. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  107. }
  108. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  109. // New standalone tests MUST use svr.bind_to_any_port() instead.
  110. const int PORT = get_base_port();
  111. const string LONG_QUERY_VALUE = string(25000, '@');
  112. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  113. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  114. const string TOO_LONG_QUERY_URL =
  115. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  116. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  117. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  118. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  119. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  120. return file.name == key;
  121. });
  122. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  123. return *it;
  124. #else
  125. if (it != items.end()) { return *it; }
  126. throw std::runtime_error("invalid multipart form data name error");
  127. #endif
  128. }
  129. static void read_file(const std::string &path, std::string &out) {
  130. std::ifstream fs(path, std::ios_base::binary);
  131. if (!fs) {
  132. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  133. return;
  134. #else
  135. throw std::runtime_error("File not found: " + path);
  136. #endif
  137. }
  138. fs.seekg(0, std::ios_base::end);
  139. auto size = fs.tellg();
  140. fs.seekg(0);
  141. out.resize(static_cast<size_t>(size));
  142. fs.read(&out[0], static_cast<std::streamsize>(size));
  143. }
  144. // Failures of the services that the *_Online tests reach, unrelated to the
  145. // client under test: httpbingo.org intermittently answers with gateway errors,
  146. // and badssl.com drops connections from CI runners before it sends its
  147. // certificate. A handshake that fails before any verdict on the certificate is
  148. // left to the tests against local servers.
  149. static bool is_service_failure(const Result &res) {
  150. if (res) {
  151. return res->status == StatusCode::BadGateway_502 ||
  152. res->status == StatusCode::ServiceUnavailable_503 ||
  153. res->status == StatusCode::GatewayTimeout_504;
  154. }
  155. return res.error() == Error::SSLConnection;
  156. }
  157. template <typename F> static Result retry_service_failures(F &&send) {
  158. auto res = send();
  159. for (auto wait : {1, 2}) {
  160. if (!is_service_failure(res)) { break; }
  161. std::this_thread::sleep_for(std::chrono::seconds(wait));
  162. res = send();
  163. }
  164. return res;
  165. }
  166. #define SKIP_ON_SERVICE_FAILURE(res) \
  167. do { \
  168. if (is_service_failure(res)) { \
  169. if (res) { \
  170. GTEST_SKIP() << "service failure: status " << (res)->status; \
  171. } else { \
  172. GTEST_SKIP() << "service failure: " << to_string((res).error()); \
  173. } \
  174. } \
  175. } while (0)
  176. class UnixSocketTest : public ::testing::Test {
  177. protected:
  178. void TearDown() override { std::remove(pathname_.c_str()); }
  179. void client_GET(const std::string &addr) {
  180. httplib::Client cli{addr};
  181. cli.set_address_family(AF_UNIX);
  182. ASSERT_TRUE(cli.is_valid());
  183. const auto &result = cli.Get(pattern_);
  184. ASSERT_TRUE(result) << "error: " << result.error();
  185. const auto &resp = result.value();
  186. EXPECT_EQ(resp.status, StatusCode::OK_200);
  187. EXPECT_EQ(resp.body, content_);
  188. }
  189. static std::string make_sock_path() {
  190. const char *shard = getenv("GTEST_SHARD_INDEX");
  191. return shard ? std::string("./httplib-server-") + shard + ".sock"
  192. : "./httplib-server.sock";
  193. }
  194. const std::string pathname_{make_sock_path()};
  195. const std::string pattern_{"/hi"};
  196. const std::string content_{"Hello World!"};
  197. };
  198. TEST_F(UnixSocketTest, pathname) {
  199. httplib::Server svr;
  200. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  201. res.set_content(content_, "text/plain");
  202. });
  203. std::thread t{[&] {
  204. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  205. }};
  206. auto se = detail::scope_exit([&] {
  207. svr.stop();
  208. t.join();
  209. ASSERT_FALSE(svr.is_running());
  210. });
  211. svr.wait_until_ready();
  212. ASSERT_TRUE(svr.is_running());
  213. client_GET(pathname_);
  214. // ".//x.sock", which is not taken for a URL
  215. client_GET("./" + pathname_.substr(1));
  216. }
  217. #if defined(__linux__) || \
  218. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  219. TEST_F(UnixSocketTest, PeerPid) {
  220. httplib::Server svr;
  221. std::string remote_port_val;
  222. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  223. res.set_content(content_, "text/plain");
  224. remote_port_val = std::to_string(req.remote_port);
  225. });
  226. std::thread t{[&] {
  227. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  228. }};
  229. auto se = detail::scope_exit([&] {
  230. svr.stop();
  231. t.join();
  232. ASSERT_FALSE(svr.is_running());
  233. });
  234. svr.wait_until_ready();
  235. ASSERT_TRUE(svr.is_running());
  236. client_GET(pathname_);
  237. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  238. }
  239. #endif
  240. #ifdef __linux__
  241. TEST_F(UnixSocketTest, abstract) {
  242. constexpr char svr_path[]{"\x00httplib-server.sock"};
  243. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  244. httplib::Server svr;
  245. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  246. res.set_content(content_, "text/plain");
  247. });
  248. std::thread t{[&] {
  249. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  250. }};
  251. auto se = detail::scope_exit([&] {
  252. svr.stop();
  253. t.join();
  254. ASSERT_FALSE(svr.is_running());
  255. });
  256. svr.wait_until_ready();
  257. ASSERT_TRUE(svr.is_running());
  258. client_GET(abstract_addr);
  259. }
  260. #endif
  261. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  262. httplib::Server svr;
  263. std::string received_host_header;
  264. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  265. // Capture the Host header sent by the client
  266. auto host_iter = req.headers.find("Host");
  267. if (host_iter != req.headers.end()) {
  268. received_host_header = host_iter->second;
  269. }
  270. res.set_content(content_, "text/plain");
  271. });
  272. std::thread t{[&] {
  273. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  274. }};
  275. auto se = detail::scope_exit([&] {
  276. svr.stop();
  277. t.join();
  278. ASSERT_FALSE(svr.is_running());
  279. });
  280. svr.wait_until_ready();
  281. ASSERT_TRUE(svr.is_running());
  282. // Test that Host header is automatically set to "localhost" for Unix socket
  283. // connections
  284. httplib::Client cli{pathname_};
  285. cli.set_address_family(AF_UNIX);
  286. ASSERT_TRUE(cli.is_valid());
  287. const auto &result = cli.Get(pattern_);
  288. ASSERT_TRUE(result) << "error: " << result.error();
  289. const auto &resp = result.value();
  290. EXPECT_EQ(resp.status, StatusCode::OK_200);
  291. EXPECT_EQ(resp.body, content_);
  292. // Verify that Host header was automatically set to "localhost"
  293. EXPECT_EQ(received_host_header, "localhost");
  294. }
  295. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  296. // Another socket in the working directory, which a Location can name as
  297. // its host
  298. const auto other_path = "other-" + pathname_.substr(2);
  299. httplib::Server svr;
  300. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  301. // An absolute Location naming the Host this client sends
  302. res.set_redirect("http://localhost" + pattern_);
  303. });
  304. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  305. res.set_redirect("http://" + other_path + pattern_);
  306. });
  307. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  308. res.set_redirect("http://mapped.test" + pattern_);
  309. });
  310. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  311. res.set_header("X-Auth", req.get_header_value("Authorization"));
  312. res.set_content(content_, "text/plain");
  313. });
  314. httplib::Server other;
  315. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  316. res.set_content("other", "text/plain");
  317. });
  318. std::thread t{[&] {
  319. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  320. }};
  321. std::thread t2{[&] {
  322. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  323. }};
  324. auto se = detail::scope_exit([&] {
  325. svr.stop();
  326. other.stop();
  327. t.join();
  328. t2.join();
  329. std::remove(other_path.c_str());
  330. });
  331. svr.wait_until_ready();
  332. other.wait_until_ready();
  333. httplib::Client cli{pathname_};
  334. cli.set_address_family(AF_UNIX);
  335. cli.set_follow_location(true);
  336. cli.set_bearer_token_auth("token");
  337. // Another host: the same socket, without the credentials
  338. auto res = cli.Get("/cross");
  339. ASSERT_TRUE(res) << "error: " << res.error();
  340. EXPECT_EQ(StatusCode::OK_200, res->status);
  341. EXPECT_EQ(content_, res->body);
  342. EXPECT_EQ("", res->get_header_value("X-Auth"));
  343. // localhost is this client's own host
  344. res = cli.Get("/redirect");
  345. ASSERT_TRUE(res) << "error: " << res.error();
  346. EXPECT_EQ(StatusCode::OK_200, res->status);
  347. EXPECT_EQ(content_, res->body);
  348. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  349. // A host the caller mapped to a socket goes there
  350. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  351. res = cli.Get("/mapped");
  352. ASSERT_TRUE(res) << "error: " << res.error();
  353. EXPECT_EQ(StatusCode::OK_200, res->status);
  354. EXPECT_EQ("other", res->body);
  355. }
  356. #ifndef _WIN32
  357. TEST(SocketStream, wait_writable_UNIX) {
  358. int fds[2];
  359. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  360. const auto asSocketStream = [&](socket_t fd,
  361. std::function<bool(Stream &)> func) {
  362. return detail::process_client_socket(
  363. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  364. };
  365. asSocketStream(fds[0], [&](Stream &s0) {
  366. EXPECT_EQ(s0.socket(), fds[0]);
  367. EXPECT_TRUE(s0.wait_writable());
  368. EXPECT_TRUE(s0.is_peer_alive());
  369. EXPECT_EQ(0, close(fds[1]));
  370. EXPECT_FALSE(s0.is_peer_alive());
  371. return true;
  372. });
  373. EXPECT_EQ(0, close(fds[0]));
  374. }
  375. TEST(SocketStream, wait_writable_INET) {
  376. sockaddr_in addr;
  377. memset(&addr, 0, sizeof(addr));
  378. addr.sin_family = AF_INET;
  379. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  380. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  381. int disconnected_svr_sock = -1;
  382. std::thread svr{[&] {
  383. const int s = socket(AF_INET, SOCK_STREAM, 0);
  384. ASSERT_LE(0, s);
  385. // PORT + 1 is shared with the SSL redirect tests and with
  386. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  387. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  388. // because that happens on a worker thread the ASSERT does not stop the
  389. // test: it runs on and fails at the disconnected_svr_sock check instead.
  390. default_socket_options(s);
  391. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  392. ASSERT_EQ(0, listen(s, 1));
  393. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  394. ASSERT_EQ(0, close(s));
  395. }};
  396. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  397. std::thread cli{[&] {
  398. const int s = socket(AF_INET, SOCK_STREAM, 0);
  399. ASSERT_LE(0, s);
  400. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  401. ASSERT_EQ(0, close(s));
  402. }};
  403. cli.join();
  404. svr.join();
  405. ASSERT_NE(disconnected_svr_sock, -1);
  406. const auto asSocketStream = [&](socket_t fd,
  407. std::function<bool(Stream &)> func) {
  408. return detail::process_client_socket(
  409. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  410. };
  411. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  412. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  413. // wait_writable() returns true because select_write() only checks if the
  414. // send buffer has space. Peer disconnection is detected later by send().
  415. EXPECT_TRUE(ss.wait_writable());
  416. return true;
  417. });
  418. ASSERT_EQ(0, close(disconnected_svr_sock));
  419. }
  420. #endif // #ifndef _WIN32
  421. TEST(SetSocketOptTest, TcpNoDelay) {
  422. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  423. ASSERT_NE(sock, INVALID_SOCKET);
  424. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  425. int val = 0;
  426. socklen_t len = sizeof(val);
  427. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  428. reinterpret_cast<char *>(&val), &len));
  429. EXPECT_NE(val, 0);
  430. detail::close_socket(sock);
  431. }
  432. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  433. // accept() reports failures through WSAGetLastError() on Windows and through
  434. // errno everywhere else. Asking the wrong one is what made the accept loop
  435. // treat every recoverable failure as fatal on Windows.
  436. struct Classification {
  437. bool resource;
  438. bool transient;
  439. };
  440. auto classify = [](int err) {
  441. #ifdef _WIN32
  442. WSASetLastError(err);
  443. #else
  444. errno = err;
  445. #endif
  446. // Read both before asserting: an assertion may clobber the error slot.
  447. Classification c;
  448. c.resource = detail::is_accept_resource_error();
  449. c.transient = detail::is_accept_transient_error();
  450. return c;
  451. };
  452. #ifdef _WIN32
  453. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  454. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  455. WSAECONNRESET, WSAECONNABORTED};
  456. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  457. #else
  458. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  459. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  460. ECONNABORTED};
  461. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  462. #endif
  463. for (auto err : resource_errors) {
  464. const auto c = classify(err);
  465. EXPECT_TRUE(c.resource) << "error " << err;
  466. EXPECT_FALSE(c.transient) << "error " << err;
  467. }
  468. for (auto err : transient_errors) {
  469. const auto c = classify(err);
  470. EXPECT_TRUE(c.transient) << "error " << err;
  471. EXPECT_FALSE(c.resource) << "error " << err;
  472. }
  473. for (auto err : fatal_errors) {
  474. const auto c = classify(err);
  475. EXPECT_FALSE(c.resource) << "error " << err;
  476. EXPECT_FALSE(c.transient) << "error " << err;
  477. }
  478. #ifdef _WIN32
  479. WSASetLastError(0);
  480. #else
  481. errno = 0;
  482. #endif
  483. }
  484. TEST(ClientTest, MoveConstructible) {
  485. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  486. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  487. }
  488. TEST(ClientTest, MoveAssignable) {
  489. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  490. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  491. }
  492. #ifdef _WIN32
  493. TEST(StartupTest, WSAStartup) {
  494. WSADATA wsaData;
  495. int ret = WSAStartup(0x0002, &wsaData);
  496. ASSERT_EQ(0, ret);
  497. }
  498. #endif
  499. TEST(DecodePathTest, PercentCharacter) {
  500. EXPECT_EQ(
  501. decode_path_component(
  502. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  503. U8("descrip=Gastos áéíóúñÑ 6"));
  504. }
  505. TEST(DecodePathTest, PercentCharacterNUL) {
  506. string expected;
  507. expected.push_back('x');
  508. expected.push_back('\0');
  509. expected.push_back('x');
  510. EXPECT_EQ(decode_path_component("x%00x"), expected);
  511. }
  512. TEST(DecodePathTest, UnicodeEncoding) {
  513. // %u0041 = 'A' (1-byte UTF-8)
  514. EXPECT_EQ("A", decode_path_component("%u0041"));
  515. // %u00E9 = 'é' (2-byte UTF-8)
  516. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  517. // %u3042 = 'あ' (3-byte UTF-8)
  518. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  519. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  520. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  521. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  522. // neighbours)
  523. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  524. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  525. }
  526. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  527. // A sign or whitespace inside the two-character escape window must not be
  528. // accepted as a valid percent-encoding; the sequence is passed through
  529. // literally, matching decode_uri_component / decode_path_component.
  530. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  531. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  532. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  533. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  534. // Well-formed escapes still decode.
  535. EXPECT_EQ("-", decode_query_component("%2D", false));
  536. EXPECT_EQ("A", decode_query_component("%41", false));
  537. }
  538. TEST(SanitizeFilenameTest, VariousPatterns) {
  539. // Path traversal
  540. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  541. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  542. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  543. // Normal and edge cases
  544. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  545. EXPECT_EQ("filename.txt",
  546. httplib::sanitize_filename("/path/to/filename.txt"));
  547. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  548. EXPECT_EQ("", httplib::sanitize_filename(".."));
  549. EXPECT_EQ("", httplib::sanitize_filename(""));
  550. // Null bytes stripped
  551. EXPECT_EQ("safe.txt",
  552. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  553. // Whitespace-only rejected
  554. EXPECT_EQ("", httplib::sanitize_filename(" "));
  555. }
  556. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  557. // before it is dropped; anywhere else it is an ordinary file name character.
  558. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  559. #ifdef _WIN32
  560. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  561. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  562. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  563. #else
  564. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  565. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  566. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  567. #endif
  568. }
  569. // Forward declaration (see the base64_encode note below): split builds move the
  570. // definition into httplib.cc, so re-declaring it here lets the test link.
  571. namespace httplib {
  572. namespace detail {
  573. bool is_chunked_transfer_encoding(const Headers &headers);
  574. } // namespace detail
  575. } // namespace httplib
  576. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  577. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  578. auto make = [](std::initializer_list<const char *> lines) {
  579. Headers h;
  580. for (auto te : lines) {
  581. if (te) { h.emplace("Transfer-Encoding", te); }
  582. }
  583. return h;
  584. };
  585. // Sole coding, matched case-insensitively.
  586. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  587. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  588. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  589. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  590. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  591. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  592. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  593. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  594. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  595. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  596. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  597. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  598. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  599. // were received, into one list. Headers preserves that order, so the answer
  600. // is decided by the last coding of the last line and the order the lines
  601. // arrived in is significant.
  602. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  603. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  604. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  605. // The split can fall anywhere in the list.
  606. EXPECT_TRUE(
  607. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  608. EXPECT_FALSE(
  609. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  610. // A trailing line naming no coding leaves the list ending in nothing, so it
  611. // must not inherit the chunked from the line before it.
  612. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  613. }
  614. // Forward declarations (see the base64_encode note below).
  615. namespace httplib {
  616. namespace detail {
  617. bool parse_status_line(const char *line, std::string &version, int &status,
  618. std::string &reason);
  619. std::string file_extension(const std::string &path);
  620. std::string
  621. find_content_type(const std::string &path,
  622. const std::map<std::string, std::string> &user_data,
  623. const std::string &default_content_type);
  624. bool can_compress_content_type(const std::string &content_type);
  625. bool is_prohibited_header_name(const std::string &name);
  626. bool is_valid_path(const std::string &path);
  627. #ifdef CPPHTTPLIB_SSL_ENABLED
  628. bool match_hostname(const std::string &pattern, const std::string &hostname);
  629. #endif
  630. } // namespace detail
  631. } // namespace httplib
  632. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  633. struct {
  634. const char *line;
  635. const char *version;
  636. int status;
  637. const char *reason;
  638. } cases[] = {
  639. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  640. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  641. // The reason phrase may be empty, or left out along with its space.
  642. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  643. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  644. };
  645. for (const auto &c : cases) {
  646. std::string version;
  647. int status = 0;
  648. std::string reason = "unset";
  649. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  650. << c.line;
  651. EXPECT_EQ(c.version, version);
  652. EXPECT_EQ(c.status, status);
  653. EXPECT_EQ(c.reason, reason);
  654. }
  655. }
  656. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  657. const char *lines[] = {
  658. "HTTP/2 200 OK\r\n",
  659. "HTTP/1.2 200 OK\r\n",
  660. "HTTP/1.1 20 OK\r\n",
  661. "HTTP/1.1 2000 OK\r\n",
  662. "HTTP/1.1 2x0 OK\r\n",
  663. "HTTP/1.1 200 OK\r\n",
  664. "HTTP/1.1 200OK\r\n",
  665. "HTTP/1.1 200 O\rK\r\n",
  666. "HTTP/1.1 200 OK",
  667. "HTTP/1.1 200 OK\r\nX",
  668. "",
  669. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  670. "HTTP/1.1 200 OK\n",
  671. #endif
  672. };
  673. for (auto line : lines) {
  674. std::string version;
  675. int status = 0;
  676. std::string reason;
  677. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  678. << line;
  679. }
  680. }
  681. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  682. // Long enough to overflow the stack when matched with std::regex.
  683. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  684. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  685. std::string version;
  686. int status = 0;
  687. std::string reason;
  688. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  689. EXPECT_EQ(200, status);
  690. EXPECT_EQ(long_reason, reason);
  691. }
  692. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  693. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  694. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  695. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  696. EXPECT_EQ("", detail::file_extension("noext"));
  697. EXPECT_EQ("", detail::file_extension("a."));
  698. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  699. EXPECT_EQ("", detail::file_extension("a.b-c"));
  700. // Long enough to overflow the stack when matched with std::regex.
  701. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  702. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  703. }
  704. #ifdef CPPHTTPLIB_SSL_ENABLED
  705. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  706. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  707. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  708. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  709. // A wildcard needs two labels after it, in the leftmost label only
  710. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  711. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  712. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  713. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  714. EXPECT_FALSE(
  715. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  716. // No name may have an empty label
  717. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  718. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  719. }
  720. #endif
  721. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  722. detail::case_ignore::hash hash;
  723. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  724. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  725. // Long enough to overflow the stack if hashed one call per character.
  726. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  727. }
  728. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  729. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  730. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  731. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  732. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  733. // Same 26-bit hash as html, svg and js.
  734. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  735. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  736. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  737. }
  738. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  739. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  740. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  741. }
  742. }
  743. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  744. // name anywhere else.
  745. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  746. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  747. #ifdef _WIN32
  748. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  749. #else
  750. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  751. #endif
  752. }
  753. }
  754. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  755. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  756. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  757. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  758. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  759. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  760. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  761. // Same 26-bit hash as application/json.
  762. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  763. }
  764. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  765. Request req;
  766. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  767. EXPECT_TRUE(req.is_multipart_form_data());
  768. std::string boundary;
  769. EXPECT_TRUE(detail::parse_multipart_boundary(
  770. req.get_header_value("Content-Type"), boundary));
  771. EXPECT_EQ("x", boundary);
  772. }
  773. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  774. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  775. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  776. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  777. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  778. // Same 26-bit hash as REMOTE_ADDR.
  779. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  780. }
  781. // Forward declaration: in split builds split.py strips `inline` and moves the
  782. // definition into httplib.cc, so detail::base64_encode is not visible from the
  783. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  784. // in both header-only and split builds.
  785. namespace httplib {
  786. namespace detail {
  787. std::string base64_encode(const std::string &in);
  788. } // namespace detail
  789. } // namespace httplib
  790. TEST(Base64EncodeTest, KnownAnswers) {
  791. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  792. // where the accumulator's top bit is already set before the next shift.
  793. EXPECT_EQ("", detail::base64_encode(""));
  794. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  795. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  796. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  797. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  798. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  799. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  800. // High bytes keep the top bit set across several rounds.
  801. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  802. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  803. }
  804. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  805. string unescapedCharacters = "-_.!~*'()";
  806. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  807. }
  808. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  809. string reservedCharacters = ";,/?:@&=+$";
  810. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  811. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  812. }
  813. TEST(ClientQueryOrder, PreserveOrder) {
  814. // This test reproduces Issue #2259: client may reorder query parameters
  815. // when sending a GET request. The expected behavior is that the client
  816. // preserves the original query string order when the caller supplied it
  817. // as part of the path.
  818. Server svr;
  819. svr.Get("/", [&](const Request &req, Response &res) {
  820. // Echo back the raw target so the test can assert ordering
  821. res.set_content(req.target, "text/plain");
  822. });
  823. std::thread t{[&] { svr.listen(HOST, PORT); }};
  824. auto se = detail::scope_exit([&] {
  825. svr.stop();
  826. t.join();
  827. ASSERT_FALSE(svr.is_running());
  828. });
  829. svr.wait_until_ready();
  830. Client cli(HOST, PORT);
  831. ASSERT_TRUE(cli.is_valid());
  832. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  833. auto res = cli.Get(original);
  834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  835. // Expect the echoed target to exactly match the original path (order
  836. // preserved)
  837. EXPECT_EQ(res->body, original);
  838. }
  839. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  840. string chineseCharacters = U8("中国語");
  841. string russianCharacters = U8("дом");
  842. string brazilianCharacters = U8("óculos");
  843. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  844. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  845. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  846. "%D0%B4%D0%BE%D0%BC");
  847. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  848. }
  849. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  850. string unescapedCharacters = "-_.!~*'()";
  851. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  852. }
  853. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  854. string reservedCharacters = ";,/?:@&=+$";
  855. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  856. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  857. }
  858. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  859. string chineseCharacters = U8("中国語");
  860. string russianCharacters = U8("дом");
  861. string brazilianCharacters = U8("óculos");
  862. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  863. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  864. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  865. "%D0%B4%D0%BE%D0%BC");
  866. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  867. }
  868. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  869. // Issue #2082 use case: encoding path component with ampersand
  870. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  871. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  872. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  873. }
  874. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  875. string unescapedCharacters = "-_.!~*'()";
  876. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  877. }
  878. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  879. string reservedCharacters = ";,/?:@&=+$#";
  880. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  881. }
  882. TEST(EncodeUriTest, TestUTF8Characters) {
  883. string chineseCharacters = U8("中国語");
  884. string russianCharacters = U8("дом");
  885. string brazilianCharacters = U8("óculos");
  886. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  887. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  888. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  889. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  890. }
  891. TEST(EncodeUriTest, TestCompleteUri) {
  892. string uri =
  893. "https://example.com/path/to/resource?query=value&param=test#fragment";
  894. EXPECT_EQ(
  895. httplib::encode_uri(uri),
  896. "https://example.com/path/to/resource?query=value&param=test#fragment");
  897. }
  898. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  899. string uri =
  900. "https://example.com/path with spaces/file name.html?q=hello world";
  901. EXPECT_EQ(httplib::encode_uri(uri),
  902. "https://example.com/path%20with%20spaces/"
  903. "file%20name.html?q=hello%20world");
  904. }
  905. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  906. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  907. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  908. }
  909. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  910. string unescapedCharacters = "-_.!~*'()";
  911. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  912. }
  913. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  914. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  915. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  916. string encodedBrazilian = "%C3%B3culos";
  917. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  918. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  919. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  920. }
  921. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  922. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  923. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  924. "Piri Tommy Villiers - on & on");
  925. }
  926. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  927. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  928. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  929. }
  930. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  931. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  932. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  933. }
  934. TEST(DecodeUriTest, TestUTF8Characters) {
  935. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  936. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  937. string encodedBrazilian = "%C3%B3culos";
  938. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  939. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  940. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  941. }
  942. TEST(DecodeUriTest, TestCompleteUri) {
  943. string encodedUri = "https://example.com/path%20with%20spaces/"
  944. "file%20name.html?q=hello%20world";
  945. EXPECT_EQ(
  946. httplib::decode_uri(encodedUri),
  947. "https://example.com/path with spaces/file name.html?q=hello world");
  948. }
  949. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  950. string original =
  951. "https://example.com/path with spaces/file name.html?q=hello world";
  952. string encoded = httplib::encode_uri(original);
  953. string decoded = httplib::decode_uri(encoded);
  954. EXPECT_EQ(decoded, original);
  955. }
  956. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  957. // decode_uri is the inverse of encode_uri: an escaped reserved character
  958. // stays encoded so it is not promoted into a real delimiter, while
  959. // non-reserved escapes still decode (like JS decodeURI).
  960. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  961. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  962. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  963. "%3F%3A%40%26%3D%2B%24%2C%3B");
  964. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  965. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  966. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  967. "http://example.com/a%2Fb");
  968. // decode_uri_component still decodes the reserved character.
  969. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  970. }
  971. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  972. string original = "Piri Tommy Villiers - on & on";
  973. string encoded = httplib::encode_uri_component(original);
  974. string decoded = httplib::decode_uri_component(encoded);
  975. EXPECT_EQ(decoded, original);
  976. }
  977. TEST(TrimTests, TrimStringTests) {
  978. EXPECT_EQ("abc", detail::trim_copy("abc"));
  979. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  980. EXPECT_TRUE(detail::trim_copy("").empty());
  981. }
  982. TEST(AsciiTest, LocaleIndependentClassification) {
  983. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  984. // which consult the global C locale: std::isalnum(0xC5) can return true
  985. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  986. // helpers must classify every byte by the ASCII grammar alone.
  987. for (int i = 0; i < 256; i++) {
  988. auto c = static_cast<char>(i);
  989. auto is_digit = i >= '0' && i <= '9';
  990. auto is_upper = i >= 'A' && i <= 'Z';
  991. auto is_lower = i >= 'a' && i <= 'z';
  992. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  993. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  994. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  995. << "byte " << i;
  996. }
  997. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  998. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  999. // Non-ASCII bytes must be percent-encoded, never passed through as
  1000. // alphanumeric.
  1001. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  1002. }
  1003. TEST(FromCharsTest, Double) {
  1004. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  1005. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  1006. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  1007. auto parse = [](const std::string &s, double &v) {
  1008. return detail::from_chars(s.data(), s.data() + s.size(), v);
  1009. };
  1010. double v = -1.0;
  1011. // Representative quality values.
  1012. EXPECT_EQ(parse("0", v).ec, std::errc{});
  1013. EXPECT_DOUBLE_EQ(v, 0.0);
  1014. EXPECT_EQ(parse("1", v).ec, std::errc{});
  1015. EXPECT_DOUBLE_EQ(v, 1.0);
  1016. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  1017. EXPECT_DOUBLE_EQ(v, 0.8);
  1018. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  1019. EXPECT_DOUBLE_EQ(v, 0.001);
  1020. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  1021. EXPECT_DOUBLE_EQ(v, 1.0);
  1022. // A missing integer or fractional part is tolerated.
  1023. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  1024. EXPECT_DOUBLE_EQ(v, 0.5);
  1025. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  1026. EXPECT_DOUBLE_EQ(v, 5.0);
  1027. // Values outside [0, 1] still parse; the caller range-checks them.
  1028. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  1029. EXPECT_DOUBLE_EQ(v, 123.456);
  1030. // Stops at the first byte that is not part of the number and reports where.
  1031. std::string trailing = "0.9, text/html";
  1032. auto r = parse(trailing, v);
  1033. EXPECT_EQ(r.ec, std::errc{});
  1034. EXPECT_DOUBLE_EQ(v, 0.9);
  1035. EXPECT_EQ(*r.ptr, ',');
  1036. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1037. // outright, and an 'e'/'E' simply ends the number.
  1038. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1039. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1040. std::string exp_input = "1.5e3";
  1041. r = parse(exp_input, v);
  1042. EXPECT_EQ(r.ec, std::errc{});
  1043. EXPECT_DOUBLE_EQ(v, 1.5);
  1044. EXPECT_EQ(*r.ptr, 'e');
  1045. // Invalid inputs.
  1046. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1047. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1048. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1049. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1050. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1051. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1052. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1053. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1054. std::errc{});
  1055. EXPECT_DOUBLE_EQ(v, 0.0);
  1056. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1057. std::errc{});
  1058. EXPECT_GE(v, 0.0);
  1059. EXPECT_LE(v, 1.0);
  1060. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1061. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1062. }
  1063. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1064. // Simple case without quality values
  1065. std::vector<std::string> result1;
  1066. EXPECT_TRUE(detail::parse_accept_header(
  1067. "text/html,application/json,text/plain", result1));
  1068. EXPECT_EQ(result1.size(), 3U);
  1069. EXPECT_EQ(result1[0], "text/html");
  1070. EXPECT_EQ(result1[1], "application/json");
  1071. EXPECT_EQ(result1[2], "text/plain");
  1072. // With quality values
  1073. std::vector<std::string> result2;
  1074. EXPECT_TRUE(detail::parse_accept_header(
  1075. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1076. EXPECT_EQ(result2.size(), 3U);
  1077. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1078. EXPECT_EQ(result2[1], "text/html");
  1079. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1080. }
  1081. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1082. // Mixed with and without quality values
  1083. std::vector<std::string> result;
  1084. EXPECT_TRUE(detail::parse_accept_header(
  1085. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1086. EXPECT_EQ(result.size(), 3U);
  1087. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1088. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1089. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1090. }
  1091. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1092. // Empty header
  1093. std::vector<std::string> empty_result;
  1094. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1095. EXPECT_TRUE(empty_result.empty());
  1096. // Single type
  1097. std::vector<std::string> single_result;
  1098. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1099. EXPECT_EQ(single_result.size(), 1U);
  1100. EXPECT_EQ(single_result[0], "application/json");
  1101. // Wildcard types
  1102. std::vector<std::string> wildcard_result;
  1103. EXPECT_TRUE(detail::parse_accept_header(
  1104. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1105. EXPECT_EQ(wildcard_result.size(), 3U);
  1106. EXPECT_EQ(wildcard_result[0], "application/json");
  1107. EXPECT_EQ(wildcard_result[1], "text/*");
  1108. EXPECT_EQ(wildcard_result[2], "*/*");
  1109. }
  1110. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1111. // Common browser Accept header
  1112. std::vector<std::string> browser_result;
  1113. EXPECT_TRUE(
  1114. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1115. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1116. browser_result));
  1117. EXPECT_EQ(browser_result.size(), 6U);
  1118. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1119. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1120. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1121. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1122. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1123. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1124. // API client header
  1125. std::vector<std::string> api_result;
  1126. EXPECT_TRUE(detail::parse_accept_header(
  1127. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1128. api_result));
  1129. EXPECT_EQ(api_result.size(), 3U);
  1130. EXPECT_EQ(api_result[0], "application/json");
  1131. EXPECT_EQ(api_result[1], "application/xml");
  1132. EXPECT_EQ(api_result[2], "text/plain");
  1133. }
  1134. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1135. // Quality value with 3 decimal places
  1136. std::vector<std::string> decimal_result;
  1137. EXPECT_TRUE(detail::parse_accept_header(
  1138. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1139. EXPECT_EQ(decimal_result.size(), 2U);
  1140. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1141. EXPECT_EQ(decimal_result[1], "text/html");
  1142. // Zero quality (should still be included but with lowest priority)
  1143. std::vector<std::string> zero_q_result;
  1144. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1145. zero_q_result));
  1146. EXPECT_EQ(zero_q_result.size(), 2U);
  1147. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1148. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1149. // No spaces around commas
  1150. std::vector<std::string> no_space_result;
  1151. EXPECT_TRUE(detail::parse_accept_header(
  1152. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1153. no_space_result));
  1154. EXPECT_EQ(no_space_result.size(), 3U);
  1155. EXPECT_EQ(no_space_result[0], "text/html");
  1156. EXPECT_EQ(no_space_result[1], "application/json");
  1157. EXPECT_EQ(no_space_result[2], "text/plain");
  1158. }
  1159. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1160. // Quality values always use '.' as the decimal separator, so parsing must
  1161. // not depend on the process locale. An embedding application may have
  1162. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1163. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1164. std::string saved = cur ? cur : "C";
  1165. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1166. "fr_FR.UTF-8"};
  1167. bool switched = false;
  1168. for (const auto loc : comma_locales) {
  1169. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1170. std::localeconv()->decimal_point[0] == ',') {
  1171. switched = true;
  1172. break;
  1173. }
  1174. }
  1175. if (!switched) {
  1176. std::setlocale(LC_NUMERIC, saved.c_str());
  1177. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1178. }
  1179. // The higher-weighted type appears later in the list, so a correct parse
  1180. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1181. // sensitive parse reads both weights as 0 and leaves the original order.
  1182. std::vector<std::string> result;
  1183. EXPECT_TRUE(detail::parse_accept_header(
  1184. "application/json;q=0.1,text/html;q=0.9", result));
  1185. ASSERT_EQ(result.size(), 2U);
  1186. EXPECT_EQ(result[0], "text/html");
  1187. EXPECT_EQ(result[1], "application/json");
  1188. std::setlocale(LC_NUMERIC, saved.c_str());
  1189. }
  1190. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1191. std::vector<std::string> result;
  1192. // Invalid quality value (> 1.0)
  1193. EXPECT_FALSE(
  1194. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1195. // Invalid quality value (< 0.0)
  1196. EXPECT_FALSE(
  1197. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1198. // Invalid quality value (not a number)
  1199. EXPECT_FALSE(detail::parse_accept_header(
  1200. "text/html;q=invalid,application/json", result));
  1201. // A valid numeric prefix does not make the entire quality value valid.
  1202. EXPECT_FALSE(detail::parse_accept_header(
  1203. "text/html;q=0.5junk,application/json", result));
  1204. // Empty quality value
  1205. EXPECT_FALSE(
  1206. detail::parse_accept_header("text/html;q=,application/json", result));
  1207. // Invalid media type format (no slash and not wildcard)
  1208. EXPECT_FALSE(
  1209. detail::parse_accept_header("invalidtype,application/json", result));
  1210. // Valid cases should still work
  1211. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1212. EXPECT_EQ(result.size(), 1U);
  1213. EXPECT_EQ(result[0], "*/*");
  1214. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1215. EXPECT_EQ(result.size(), 1U);
  1216. EXPECT_EQ(result[0], "*");
  1217. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1218. EXPECT_EQ(result.size(), 1U);
  1219. EXPECT_EQ(result[0], "text/*");
  1220. }
  1221. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1222. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1223. // and must not be answered with 400 Bad Request.
  1224. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1225. struct {
  1226. const char *value;
  1227. std::vector<std::string> expected;
  1228. } cases[] = {
  1229. {",application/json", {"application/json"}},
  1230. {"text/html,", {"text/html"}},
  1231. {"text/html,,*/*", {"text/html", "*/*"}},
  1232. // An empty element may be spelled with whitespace in it
  1233. {"text/html, , application/json", {"text/html", "application/json"}},
  1234. // Nothing but empty elements is an empty list, which means the same
  1235. // thing as no Accept header at all
  1236. {",,,", {}},
  1237. // Quality values still apply across ignored empty elements
  1238. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1239. };
  1240. for (const auto &c : cases) {
  1241. std::vector<std::string> result;
  1242. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1243. << "value: " << c.value;
  1244. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1245. }
  1246. // An invalid entry is still rejected when empty elements surround it
  1247. std::vector<std::string> result;
  1248. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1249. }
  1250. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1251. // or ';' inside one does not end the list element or the parameter. Section
  1252. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1253. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1254. struct {
  1255. const char *value;
  1256. std::vector<std::string> expected;
  1257. } cases[] = {
  1258. {"text/html;profile=\"a,b\",application/json",
  1259. {"text/html", "application/json"}},
  1260. // A "q=" inside a quoted value is not the weight
  1261. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1262. {"text/html", "application/json"}},
  1263. // The weight after a quoted value still applies
  1264. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1265. {"application/json", "text/html"}},
  1266. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1267. {"application/json", "text/html"}},
  1268. {"text/html;profile=\"a\\\"b\",application/json",
  1269. {"text/html", "application/json"}},
  1270. // An escaped backslash does not escape the '"' after it
  1271. {"text/html;profile=\"a\\\\\",application/json",
  1272. {"text/html", "application/json"}},
  1273. };
  1274. for (const auto &c : cases) {
  1275. std::vector<std::string> result;
  1276. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1277. << "value: " << c.value;
  1278. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1279. }
  1280. }
  1281. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1282. Server svr;
  1283. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1284. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1285. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1286. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1287. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1291. EXPECT_TRUE(false);
  1292. res.set_content("bad request", "text/plain");
  1293. });
  1294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. listen_thread.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. Client cli("localhost", PORT);
  1302. {
  1303. auto res = cli.Get(
  1304. "/accept_ok",
  1305. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1307. EXPECT_EQ(StatusCode::OK_200, res->status);
  1308. }
  1309. {
  1310. auto res = cli.Get("/accept_bad_request",
  1311. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1313. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1314. }
  1315. }
  1316. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1317. Server svr;
  1318. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1319. res.set_content("ok", "text/plain");
  1320. });
  1321. std::atomic<int> start_count{0};
  1322. std::atomic<bool> running_when_called{false};
  1323. svr.set_start_handler([&]() {
  1324. running_when_called = svr.is_running();
  1325. start_count++;
  1326. });
  1327. auto port = svr.bind_to_any_port(HOST);
  1328. std::thread t([&]() { svr.listen_after_bind(); });
  1329. auto se = detail::scope_exit([&] {
  1330. svr.stop();
  1331. t.join();
  1332. ASSERT_FALSE(svr.is_running());
  1333. });
  1334. svr.wait_until_ready();
  1335. // A successful request proves the accept loop is running, which the start
  1336. // handler precedes; so by now the handler must have run exactly once.
  1337. Client cli(HOST, port);
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. auto res = cli.Get("/");
  1340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1341. EXPECT_EQ(StatusCode::OK_200, res->status);
  1342. EXPECT_EQ(1, start_count.load());
  1343. EXPECT_TRUE(running_when_called.load());
  1344. }
  1345. TEST(DivideTest, DivideStringTests) {
  1346. auto divide = [](const std::string &str, char d) {
  1347. std::string lhs;
  1348. std::string rhs;
  1349. detail::divide(str, d,
  1350. [&](const char *lhs_data, std::size_t lhs_size,
  1351. const char *rhs_data, std::size_t rhs_size) {
  1352. lhs.assign(lhs_data, lhs_size);
  1353. rhs.assign(rhs_data, rhs_size);
  1354. });
  1355. return std::make_pair(std::move(lhs), std::move(rhs));
  1356. };
  1357. {
  1358. const auto res = divide("", '=');
  1359. EXPECT_EQ(res.first, "");
  1360. EXPECT_EQ(res.second, "");
  1361. }
  1362. {
  1363. const auto res = divide("=", '=');
  1364. EXPECT_EQ(res.first, "");
  1365. EXPECT_EQ(res.second, "");
  1366. }
  1367. {
  1368. const auto res = divide(" ", '=');
  1369. EXPECT_EQ(res.first, " ");
  1370. EXPECT_EQ(res.second, "");
  1371. }
  1372. {
  1373. const auto res = divide("a", '=');
  1374. EXPECT_EQ(res.first, "a");
  1375. EXPECT_EQ(res.second, "");
  1376. }
  1377. {
  1378. const auto res = divide("a=", '=');
  1379. EXPECT_EQ(res.first, "a");
  1380. EXPECT_EQ(res.second, "");
  1381. }
  1382. {
  1383. const auto res = divide("=b", '=');
  1384. EXPECT_EQ(res.first, "");
  1385. EXPECT_EQ(res.second, "b");
  1386. }
  1387. {
  1388. const auto res = divide("a=b", '=');
  1389. EXPECT_EQ(res.first, "a");
  1390. EXPECT_EQ(res.second, "b");
  1391. }
  1392. {
  1393. const auto res = divide("a=b=", '=');
  1394. EXPECT_EQ(res.first, "a");
  1395. EXPECT_EQ(res.second, "b=");
  1396. }
  1397. {
  1398. const auto res = divide("a=b=c", '=');
  1399. EXPECT_EQ(res.first, "a");
  1400. EXPECT_EQ(res.second, "b=c");
  1401. }
  1402. }
  1403. TEST(SplitTest, ParseQueryString) {
  1404. string s = "key1=val1&key2=val2&key3=val3";
  1405. Params dic;
  1406. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1407. [&](const char *b, const char *e) {
  1408. string key, val;
  1409. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1410. if (key.empty()) {
  1411. key.assign(b2, e2);
  1412. } else {
  1413. val.assign(b2, e2);
  1414. }
  1415. });
  1416. dic.emplace(key, val);
  1417. });
  1418. EXPECT_EQ("val1", dic.find("key1")->second);
  1419. EXPECT_EQ("val2", dic.find("key2")->second);
  1420. EXPECT_EQ("val3", dic.find("key3")->second);
  1421. }
  1422. TEST(SplitTest, ParseInvalidQueryTests) {
  1423. {
  1424. string s = " ";
  1425. Params dict;
  1426. detail::parse_query_text(s, dict);
  1427. EXPECT_TRUE(dict.empty());
  1428. }
  1429. {
  1430. string s = " = =";
  1431. Params dict;
  1432. detail::parse_query_text(s, dict);
  1433. EXPECT_TRUE(dict.empty());
  1434. }
  1435. }
  1436. TEST(ParseQueryTest, ParseQueryString) {
  1437. {
  1438. std::string s = "key1=val1&key2=val2&key3=val3";
  1439. Params dic;
  1440. detail::parse_query_text(s, dic);
  1441. EXPECT_EQ("val1", dic.find("key1")->second);
  1442. EXPECT_EQ("val2", dic.find("key2")->second);
  1443. EXPECT_EQ("val3", dic.find("key3")->second);
  1444. }
  1445. {
  1446. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1447. Params dic;
  1448. detail::parse_query_text(s, dic);
  1449. EXPECT_EQ("", dic.find("key1")->second);
  1450. EXPECT_EQ("val1", dic.find("key2")->second);
  1451. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1452. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1453. }
  1454. }
  1455. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1456. Params dic;
  1457. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1458. dic.emplace("key1", "val1");
  1459. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1460. dic.emplace("key2", "val2");
  1461. dic.emplace("key3", "val3");
  1462. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1463. }
  1464. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1465. Params params;
  1466. params.emplace("a", "1");
  1467. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1468. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1469. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1470. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1471. // Long enough to overflow the stack when matched with std::regex.
  1472. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1473. EXPECT_EQ("/p?" + long_query + "&a=1",
  1474. append_query_params("/p?" + long_query, params));
  1475. }
  1476. // Joins every entry of a Headers or Params into "key=value " so a whole
  1477. // traversal can be compared in one assertion. Both are instantiations of the
  1478. // same insertion-ordered container, so one helper serves both.
  1479. template <typename Map> static std::string entries_to_string(const Map &m) {
  1480. std::string s;
  1481. for (const auto &entry : m) {
  1482. s += entry.first + "=" + entry.second + " ";
  1483. }
  1484. return s;
  1485. }
  1486. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1487. // Params used to be a std::multimap, which sorted by name and handed the
  1488. // caller's query back alphabetised. A client signing its query string could
  1489. // not reproduce the order it asked for.
  1490. Params dic;
  1491. dic.emplace("zulu", "1");
  1492. dic.emplace("alpha", "2");
  1493. dic.emplace("mike", "3");
  1494. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1495. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1496. }
  1497. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1498. Params dic;
  1499. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1500. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1501. }
  1502. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1503. Request req;
  1504. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1505. req.params);
  1506. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1507. EXPECT_EQ("first", req.get_param_value("tag"));
  1508. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1509. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1510. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1511. EXPECT_EQ("", req.get_param_value("tag", 3));
  1512. }
  1513. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1514. // Params shares its container with Headers, which matches field names
  1515. // case-insensitively. Parameter names must not pick that up.
  1516. Params dic;
  1517. dic.emplace("Key", "upper");
  1518. dic.emplace("key", "lower");
  1519. EXPECT_EQ(2U, dic.size());
  1520. EXPECT_EQ(1U, dic.count("Key"));
  1521. EXPECT_EQ(1U, dic.count("key"));
  1522. EXPECT_EQ("upper", dic.find("Key")->second);
  1523. EXPECT_EQ("lower", dic.find("key")->second);
  1524. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1525. }
  1526. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1527. Server svr;
  1528. std::string order;
  1529. svr.Get("/order", [&](const Request &req, Response &res) {
  1530. order = entries_to_string(req.params);
  1531. res.set_content("ok", "text/plain");
  1532. });
  1533. auto port = svr.bind_to_any_port(HOST);
  1534. thread t = thread([&] { svr.listen_after_bind(); });
  1535. auto se = detail::scope_exit([&] {
  1536. svr.stop();
  1537. t.join();
  1538. ASSERT_FALSE(svr.is_running());
  1539. });
  1540. svr.wait_until_ready();
  1541. Client cli(HOST, port);
  1542. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1543. ASSERT_TRUE(res);
  1544. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1545. }
  1546. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1547. Server svr;
  1548. std::string field_order, file_order;
  1549. svr.Post("/order", [&](const Request &req, Response &res) {
  1550. for (const auto &field : req.form.fields) {
  1551. field_order += field.first + "=" + field.second.content + " ";
  1552. }
  1553. for (const auto &file : req.form.files) {
  1554. file_order += file.first + "=" + file.second.filename + " ";
  1555. }
  1556. res.set_content("ok", "text/plain");
  1557. });
  1558. auto port = svr.bind_to_any_port(HOST);
  1559. thread t = thread([&] { svr.listen_after_bind(); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. t.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. UploadFormDataItems items = {
  1567. {"zulu", "1", "", ""},
  1568. {"alpha", "2", "", ""},
  1569. {"mike", "3", "", ""},
  1570. {"zebra", "z", "z.txt", "text/plain"},
  1571. {"apple", "a", "a.txt", "text/plain"},
  1572. };
  1573. Client cli(HOST, port);
  1574. auto res = cli.Post("/order", items);
  1575. ASSERT_TRUE(res);
  1576. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1577. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1578. }
  1579. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1580. Server svr;
  1581. std::vector<std::string> values;
  1582. std::string first, second, out_of_range, order;
  1583. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1584. values = req.form.get_fields("tag");
  1585. first = req.form.get_field("tag", 0);
  1586. second = req.form.get_field("tag", 1);
  1587. out_of_range = req.form.get_field("tag", 2);
  1588. for (const auto &field : req.form.fields) {
  1589. order += field.first + "=" + field.second.content + " ";
  1590. }
  1591. res.set_content("ok", "text/plain");
  1592. });
  1593. auto port = svr.bind_to_any_port(HOST);
  1594. thread t = thread([&] { svr.listen_after_bind(); });
  1595. auto se = detail::scope_exit([&] {
  1596. svr.stop();
  1597. t.join();
  1598. ASSERT_FALSE(svr.is_running());
  1599. });
  1600. svr.wait_until_ready();
  1601. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1602. // not adjacent in the container.
  1603. UploadFormDataItems items = {
  1604. {"tag", "first", "", ""},
  1605. {"other", "x", "", ""},
  1606. {"tag", "second", "", ""},
  1607. };
  1608. Client cli(HOST, port);
  1609. auto res = cli.Post("/repeated", items);
  1610. ASSERT_TRUE(res);
  1611. ASSERT_EQ(2U, values.size());
  1612. EXPECT_EQ("first", values[0]);
  1613. EXPECT_EQ("second", values[1]);
  1614. EXPECT_EQ("first", first);
  1615. EXPECT_EQ("second", second);
  1616. // std::multimap already kept entries sharing a name in insertion order, so
  1617. // everything above passes without this change too. The whole traversal is
  1618. // what tells the two apart: sorting by name would hoist "other" to the front
  1619. // and the two "tag" parts would end up adjacent.
  1620. EXPECT_EQ("tag=first other=x tag=second ", order);
  1621. // Advancing past the last entry of a name used to run off the container;
  1622. // the container's saturating increment makes it return the default instead.
  1623. EXPECT_EQ("", out_of_range);
  1624. }
  1625. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1626. Server svr;
  1627. std::string file_names;
  1628. svr.Post("/upload", [&](const Request &req, Response &res) {
  1629. for (const auto &file : req.form.files) {
  1630. file_names += file.first + "|" + file.second.filename + " ";
  1631. }
  1632. res.set_content("ok", "text/plain");
  1633. });
  1634. auto port = svr.bind_to_any_port(HOST);
  1635. thread t = thread([&] { svr.listen_after_bind(); });
  1636. auto se = detail::scope_exit([&] {
  1637. svr.stop();
  1638. t.join();
  1639. ASSERT_FALSE(svr.is_running());
  1640. });
  1641. svr.wait_until_ready();
  1642. // A trailing backslash would otherwise escape the closing quote.
  1643. UploadFormDataItems items = {
  1644. {"dir\\", "x", "a.txt", "text/plain"},
  1645. {"b", "y", "a\\\\b.txt", "text/plain"},
  1646. };
  1647. Client cli(HOST, port);
  1648. auto res = cli.Post("/upload", items);
  1649. ASSERT_TRUE(res);
  1650. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1651. }
  1652. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1653. // Server::read_content() keeps a FormFields::iterator alive across the
  1654. // content callbacks that fill the part it points at. The container is
  1655. // vector-backed, so a later emplace can reallocate and invalidate an older
  1656. // iterator; 64 parts grow the vector through seven reallocations, which
  1657. // checks that every part's content still lands in its own entry.
  1658. const size_t part_count = 64;
  1659. // One formula for both the parts sent and the values expected back, so the
  1660. // two cannot drift apart.
  1661. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1662. auto content_of = [](size_t i) {
  1663. return std::string(64, static_cast<char>('a' + (i % 26)));
  1664. };
  1665. Server svr;
  1666. std::vector<std::pair<std::string, std::string>> received;
  1667. svr.Post("/many", [&](const Request &req, Response &res) {
  1668. for (const auto &field : req.form.fields) {
  1669. received.emplace_back(field.first, field.second.content);
  1670. }
  1671. res.set_content("ok", "text/plain");
  1672. });
  1673. auto port = svr.bind_to_any_port(HOST);
  1674. thread t = thread([&] { svr.listen_after_bind(); });
  1675. auto se = detail::scope_exit([&] {
  1676. svr.stop();
  1677. t.join();
  1678. ASSERT_FALSE(svr.is_running());
  1679. });
  1680. svr.wait_until_ready();
  1681. UploadFormDataItems items;
  1682. for (size_t i = 0; i < part_count; i++) {
  1683. items.push_back({name_of(i), content_of(i), "", ""});
  1684. }
  1685. Client cli(HOST, port);
  1686. auto res = cli.Post("/many", items);
  1687. ASSERT_TRUE(res);
  1688. ASSERT_EQ(part_count, received.size());
  1689. for (size_t i = 0; i < part_count; i++) {
  1690. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1691. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1692. }
  1693. }
  1694. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1695. string content_type = "multipart/form-data; boundary=something";
  1696. string boundary;
  1697. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1698. EXPECT_TRUE(ret);
  1699. EXPECT_EQ(boundary, "something");
  1700. }
  1701. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1702. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1703. string boundary;
  1704. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1705. EXPECT_TRUE(ret);
  1706. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1707. }
  1708. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1709. string content_type =
  1710. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1711. string boundary;
  1712. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1713. EXPECT_TRUE(ret);
  1714. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1715. }
  1716. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1717. string content_type =
  1718. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1719. string boundary;
  1720. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1721. EXPECT_TRUE(ret);
  1722. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1723. }
  1724. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1725. const string boundary(70, 'a');
  1726. string content_type = "multipart/form-data; boundary=" + boundary;
  1727. string parsed;
  1728. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1729. EXPECT_TRUE(ret);
  1730. EXPECT_EQ(parsed, boundary);
  1731. }
  1732. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1733. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1734. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1735. string parsed;
  1736. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1737. EXPECT_FALSE(ret);
  1738. }
  1739. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1740. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1741. // is 72 characters on the wire and still valid.
  1742. const string boundary(70, 'a');
  1743. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1744. string parsed;
  1745. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1746. EXPECT_EQ(parsed, boundary);
  1747. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1748. parsed.clear();
  1749. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1750. }
  1751. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1752. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1753. // The parameter parser must not treat that '=' as the key/value separator.
  1754. string content_type =
  1755. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1756. "charset=UTF-8";
  1757. string parsed;
  1758. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1759. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1760. }
  1761. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1762. // A ';' inside the quoted-string is part of the value, not a parameter
  1763. // separator, so it must not truncate the boundary.
  1764. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1765. string parsed;
  1766. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1767. EXPECT_EQ(parsed, "a;b");
  1768. }
  1769. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1770. string parsed;
  1771. EXPECT_TRUE(detail::parse_multipart_boundary(
  1772. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1773. EXPECT_EQ("a\\b", parsed);
  1774. EXPECT_TRUE(detail::parse_multipart_boundary(
  1775. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1776. EXPECT_EQ("a\"b", parsed);
  1777. }
  1778. TEST(ParseDispositionParamsTest, QuotedValues) {
  1779. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1780. // ';' and '=' are ordinary characters inside one.
  1781. struct {
  1782. const char *value;
  1783. std::vector<std::pair<const char *, const char *>> expected;
  1784. } cases[] = {
  1785. {"name=\"file1\"; filename=\"a.txt\"",
  1786. {{"name", "file1"}, {"filename", "a.txt"}}},
  1787. // Whitespace around '=' and ';' is still trimmed
  1788. {"name=\"file2\" ;filename = \"a.html\"",
  1789. {{"name", "file2"}, {"filename", "a.html"}}},
  1790. // '=' inside the value used to leave only the text after the last one
  1791. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1792. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1793. {"name=\"x=y\"", {{"name", "x=y"}}},
  1794. // ';' inside the value used to truncate the pair and leave a bogus one
  1795. {"name=\"file3\"; filename=\"a;b.txt\"",
  1796. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1797. // An unquoted value keeps working, and so does filename*
  1798. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1799. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1800. // A parameter with no key is dropped rather than turned into one whose
  1801. // key is the value
  1802. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1803. // An escaped quote does not end the value
  1804. {"name=\"a\\\"; filename=evil.php\"",
  1805. {{"name", "a\"; filename=evil.php"}}},
  1806. // Other backslashes, as in a Windows path, are kept
  1807. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1808. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1809. };
  1810. for (const auto &c : cases) {
  1811. Params params;
  1812. detail::parse_disposition_params(c.value, params);
  1813. for (const auto &kv : c.expected) {
  1814. auto it = params.find(kv.first);
  1815. ASSERT_NE(it, params.end())
  1816. << "value: " << c.value << ", key: " << kv.first;
  1817. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1818. }
  1819. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1820. }
  1821. }
  1822. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1823. Server svr;
  1824. std::string filename;
  1825. std::string content;
  1826. svr.Post("/upload", [&](const Request &req, Response &) {
  1827. const auto &file = req.form.get_file("file");
  1828. filename = file.filename;
  1829. content = file.content;
  1830. });
  1831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1832. auto se = detail::scope_exit([&] {
  1833. svr.stop();
  1834. thread.join();
  1835. ASSERT_FALSE(svr.is_running());
  1836. });
  1837. svr.wait_until_ready();
  1838. std::string body = "--B\r\n"
  1839. "Content-Disposition: form-data; name=\"file\"; "
  1840. "filename=\"a.txt\"\r\n"
  1841. "Content-Type: text/plain\r\n"
  1842. "\r\n"
  1843. "hello\r\n"
  1844. "--B--\r\n";
  1845. Client cli(HOST, PORT);
  1846. auto res = cli.Post(
  1847. "/upload",
  1848. [&](size_t offset, DataSink &sink) {
  1849. if (offset < body.size()) {
  1850. sink.write(&body[offset], 1);
  1851. } else {
  1852. sink.done();
  1853. }
  1854. return true;
  1855. },
  1856. "multipart/form-data; boundary=B");
  1857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1858. EXPECT_EQ(StatusCode::OK_200, res->status);
  1859. EXPECT_EQ("a.txt", filename);
  1860. EXPECT_EQ("hello", content);
  1861. }
  1862. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1863. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1864. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1865. Server svr;
  1866. std::string field_value, file_name, file_filename;
  1867. bool has_field = false, has_file = false;
  1868. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1869. has_field = req.form.has_field("x=y");
  1870. field_value = req.form.get_field("x=y");
  1871. has_file = req.form.has_file("file1");
  1872. const auto &file = req.form.get_file("file1");
  1873. file_name = file.name;
  1874. file_filename = file.filename;
  1875. res.set_content("ok", "text/plain");
  1876. });
  1877. auto port = svr.bind_to_any_port(HOST);
  1878. thread t = thread([&] { svr.listen_after_bind(); });
  1879. auto se = detail::scope_exit([&] {
  1880. svr.stop();
  1881. t.join();
  1882. ASSERT_FALSE(svr.is_running());
  1883. });
  1884. svr.wait_until_ready();
  1885. UploadFormDataItems items = {
  1886. {"x=y", "field-value", "", ""},
  1887. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1888. };
  1889. Client cli(HOST, port);
  1890. auto res = cli.Post("/quoted", items);
  1891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1892. ASSERT_EQ(StatusCode::OK_200, res->status);
  1893. EXPECT_TRUE(has_field);
  1894. EXPECT_EQ("field-value", field_value);
  1895. EXPECT_TRUE(has_file);
  1896. EXPECT_EQ("file1", file_name);
  1897. EXPECT_EQ("a;b=report.pdf", file_filename);
  1898. }
  1899. TEST(GetHeaderValueTest, DefaultValue) {
  1900. Headers headers = {{"Dummy", "Dummy"}};
  1901. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1902. EXPECT_STREQ("text/plain", val);
  1903. }
  1904. TEST(GetHeaderValueTest, DefaultValueInt) {
  1905. Headers headers = {{"Dummy", "Dummy"}};
  1906. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1907. EXPECT_EQ(100ull, val);
  1908. }
  1909. TEST(GetHeaderValueTest, RegularValue) {
  1910. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1911. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1912. EXPECT_STREQ("text/html", val);
  1913. }
  1914. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1915. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1916. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1917. EXPECT_STREQ("text/html", val);
  1918. }
  1919. TEST(GetHeaderValueTest, SetContent) {
  1920. Response res;
  1921. res.set_content("html", "text/html");
  1922. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1923. res.set_content("text", "text/plain");
  1924. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1925. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1926. }
  1927. TEST(GetHeaderValueTest, RegularValueInt) {
  1928. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1929. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1930. EXPECT_EQ(100ull, val);
  1931. }
  1932. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1933. Headers headers = {{"Content-Length", "x"}};
  1934. auto is_invalid_value = false;
  1935. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1936. is_invalid_value);
  1937. EXPECT_EQ(0ull, val);
  1938. EXPECT_TRUE(is_invalid_value);
  1939. }
  1940. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1941. // An all-digit value that overflows size_t must be reported as invalid, not
  1942. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1943. // a large length to a small one on 32-bit builds, leaving the framing length
  1944. // wrong while is_invalid_value stayed false.
  1945. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1946. auto is_invalid_value = false;
  1947. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1948. is_invalid_value);
  1949. EXPECT_TRUE(is_invalid_value);
  1950. // A well-formed length is unaffected.
  1951. Headers ok = {{"Content-Length", "1234"}};
  1952. is_invalid_value = false;
  1953. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1954. is_invalid_value);
  1955. EXPECT_EQ(1234ull, val);
  1956. EXPECT_FALSE(is_invalid_value);
  1957. }
  1958. TEST(GetHeaderValueTest, Range) {
  1959. {
  1960. Headers headers = {make_range_header({{1, -1}})};
  1961. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1962. EXPECT_STREQ("bytes=1-", val);
  1963. }
  1964. {
  1965. Headers headers = {make_range_header({{-1, 1}})};
  1966. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1967. EXPECT_STREQ("bytes=-1", val);
  1968. }
  1969. {
  1970. Headers headers = {make_range_header({{1, 10}})};
  1971. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1972. EXPECT_STREQ("bytes=1-10", val);
  1973. }
  1974. {
  1975. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1976. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1977. EXPECT_STREQ("bytes=1-10, 100-", val);
  1978. }
  1979. {
  1980. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1981. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1982. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1983. }
  1984. {
  1985. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1986. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1987. EXPECT_STREQ("bytes=0-0, -1", val);
  1988. }
  1989. }
  1990. TEST(BearerTokenAuthTest, SchemeValidation) {
  1991. // A value shorter than "Bearer " must not throw from the fixed-length
  1992. // substr, and a non-Bearer scheme must not be reported as a token.
  1993. struct {
  1994. const char *value;
  1995. const char *expected;
  1996. } cases[] = {
  1997. {"x", ""},
  1998. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1999. {"Bearer abc123", "abc123"},
  2000. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  2001. };
  2002. for (const auto &c : cases) {
  2003. Request req;
  2004. req.set_header("Authorization", c.value);
  2005. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  2006. }
  2007. }
  2008. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  2009. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  2010. // to depend on the standard library (libstdc++ handed back duplicates in
  2011. // reverse insertion order, libc++ in insertion order).
  2012. Request req;
  2013. req.set_header("Accept-Encoding", "gzip");
  2014. req.set_header("Accept-Encoding", "deflate");
  2015. req.set_header("Accept-Encoding", "br");
  2016. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  2017. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  2018. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  2019. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  2020. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  2021. }
  2022. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  2023. Request req;
  2024. req.set_header("X-Test", "only");
  2025. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  2026. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  2027. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  2028. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  2029. }
  2030. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  2031. Request req;
  2032. req.set_header("X-First", "1");
  2033. req.set_header("X-Test", "2");
  2034. req.params.emplace("first", "1");
  2035. req.params.emplace("test", "2");
  2036. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2037. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2038. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2039. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2040. // The second one is negative when read as a signed value
  2041. const auto max_id = (std::numeric_limits<size_t>::max)();
  2042. for (auto id : {max_id / 2, max_id}) {
  2043. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2044. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2045. EXPECT_EQ("", req.get_param_value("test", id));
  2046. EXPECT_EQ("", req.form.get_field("test", id));
  2047. EXPECT_EQ("", req.form.get_file("test", id).content);
  2048. }
  2049. }
  2050. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2051. Headers headers;
  2052. headers.emplace("Host", "example.com");
  2053. headers.emplace("Accept-Encoding", "gzip");
  2054. headers.emplace("User-Agent", "test");
  2055. headers.emplace("Accept-Encoding", "deflate");
  2056. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2057. "Accept-Encoding=deflate ",
  2058. entries_to_string(headers));
  2059. }
  2060. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2061. Headers headers = {{"Content-Type", "text/html"},
  2062. {"CONTENT-TYPE", "text/xml"}};
  2063. EXPECT_EQ(2U, headers.count("content-type"));
  2064. auto it = headers.find("content-type");
  2065. ASSERT_TRUE(it != headers.end());
  2066. EXPECT_EQ("text/html", it->second);
  2067. }
  2068. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2069. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2070. // drop only those fields and leave everything positioned between them.
  2071. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2072. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2073. auto rng = headers.equal_range("a");
  2074. headers.erase(rng.first, rng.second);
  2075. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2076. }
  2077. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2078. Headers headers = {
  2079. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2080. EXPECT_EQ(3U, headers.erase("A"));
  2081. EXPECT_EQ(0U, headers.count("A"));
  2082. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2083. }
  2084. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2085. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2086. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2087. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2088. }
  2089. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2090. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2091. headers.emplace_front("Host", "example.com");
  2092. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2093. entries_to_string(headers));
  2094. }
  2095. TEST(ParseHeaderValueTest, Range) {
  2096. {
  2097. Ranges ranges;
  2098. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2099. EXPECT_TRUE(ret);
  2100. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2101. }
  2102. {
  2103. Ranges ranges;
  2104. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2105. EXPECT_TRUE(ret);
  2106. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2107. }
  2108. {
  2109. Ranges ranges;
  2110. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2111. EXPECT_TRUE(ret);
  2112. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2113. }
  2114. {
  2115. Ranges ranges;
  2116. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2117. EXPECT_FALSE(ret);
  2118. }
  2119. {
  2120. Ranges ranges;
  2121. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2122. EXPECT_TRUE(ret);
  2123. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2124. }
  2125. {
  2126. Ranges ranges;
  2127. auto ret =
  2128. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2129. EXPECT_TRUE(ret);
  2130. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2131. }
  2132. {
  2133. Ranges ranges;
  2134. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2135. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2136. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2137. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2138. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2139. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2140. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2141. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2142. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2143. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2144. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2145. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2146. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2147. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2148. EXPECT_FALSE(
  2149. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2150. EXPECT_TRUE(ranges.empty());
  2151. }
  2152. {
  2153. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2154. // remainder of the representation, so it stays accepted.
  2155. Ranges ranges;
  2156. auto ret =
  2157. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2158. EXPECT_TRUE(ret);
  2159. ASSERT_EQ(1u, ranges.size());
  2160. EXPECT_EQ(0, ranges[0].first);
  2161. EXPECT_EQ(-1, ranges[0].second);
  2162. }
  2163. // RFC 9110 14.1: range unit names are case-insensitive.
  2164. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2165. Ranges ranges;
  2166. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2167. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2168. }
  2169. }
  2170. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2171. Request req;
  2172. req.set_header("Accept-Encoding", "gzip");
  2173. Response res;
  2174. res.set_header("Content-Type", "text/plain");
  2175. auto ret = detail::encoding_type(req, res);
  2176. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2177. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2178. #else
  2179. EXPECT_TRUE(ret == detail::EncodingType::None);
  2180. #endif
  2181. }
  2182. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2183. Request req;
  2184. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2185. Response res;
  2186. res.set_header("Content-Type", "text/plain");
  2187. auto ret = detail::encoding_type(req, res);
  2188. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2189. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2190. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2191. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2192. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2193. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2194. #else
  2195. EXPECT_TRUE(ret == detail::EncodingType::None);
  2196. #endif
  2197. }
  2198. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2199. Request req;
  2200. req.set_header("Accept-Encoding",
  2201. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2202. Response res;
  2203. res.set_header("Content-Type", "text/plain");
  2204. auto ret = detail::encoding_type(req, res);
  2205. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2206. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2207. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2208. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2209. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2210. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2211. #else
  2212. EXPECT_TRUE(ret == detail::EncodingType::None);
  2213. #endif
  2214. }
  2215. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2216. // All supported encodings rejected with q=0 should return None
  2217. Request req;
  2218. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2219. Response res;
  2220. res.set_header("Content-Type", "text/plain");
  2221. auto ret = detail::encoding_type(req, res);
  2222. EXPECT_TRUE(ret == detail::EncodingType::None);
  2223. }
  2224. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2225. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2226. Request req;
  2227. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2228. Response res;
  2229. res.set_header("Content-Type", "text/plain");
  2230. auto ret = detail::encoding_type(req, res);
  2231. EXPECT_TRUE(ret == detail::EncodingType::None);
  2232. }
  2233. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2234. Request req;
  2235. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2236. Response res;
  2237. res.set_header("Content-Type", "text/plain");
  2238. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2239. }
  2240. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2241. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2242. Request req;
  2243. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2244. Response res;
  2245. res.set_header("Content-Type", "text/plain");
  2246. auto ret = detail::encoding_type(req, res);
  2247. EXPECT_TRUE(ret == detail::EncodingType::None);
  2248. }
  2249. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2250. // RFC 7231: Accept-Encoding values are case-insensitive
  2251. Request req;
  2252. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2253. Response res;
  2254. res.set_header("Content-Type", "text/plain");
  2255. auto ret = detail::encoding_type(req, res);
  2256. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2257. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2258. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2259. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2260. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2261. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2262. #else
  2263. EXPECT_TRUE(ret == detail::EncodingType::None);
  2264. #endif
  2265. }
  2266. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2267. // q value should determine priority, not hardcoded order
  2268. Request req;
  2269. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2270. Response res;
  2271. res.set_header("Content-Type", "text/plain");
  2272. auto ret = detail::encoding_type(req, res);
  2273. // gzip has highest q=1.0, so it should be selected even though
  2274. // br and zstd are also supported
  2275. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2276. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2277. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2278. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2279. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2280. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2281. #else
  2282. EXPECT_TRUE(ret == detail::EncodingType::None);
  2283. #endif
  2284. }
  2285. TEST(BufferStreamTest, read) {
  2286. detail::BufferStream strm1;
  2287. Stream &strm = strm1;
  2288. EXPECT_EQ(5, strm.write("hello"));
  2289. char buf[512];
  2290. EXPECT_EQ(2, strm.read(buf, 2));
  2291. EXPECT_EQ('h', buf[0]);
  2292. EXPECT_EQ('e', buf[1]);
  2293. EXPECT_EQ(2, strm.read(buf, 2));
  2294. EXPECT_EQ('l', buf[0]);
  2295. EXPECT_EQ('l', buf[1]);
  2296. EXPECT_EQ(1, strm.read(buf, 1));
  2297. EXPECT_EQ('o', buf[0]);
  2298. EXPECT_EQ(0, strm.read(buf, 1));
  2299. }
  2300. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2301. auto host = "www.httpwatch.com";
  2302. auto ip = hosted_at(host);
  2303. EXPECT_EQ("23.96.13.243", ip);
  2304. std::vector<std::string> addrs;
  2305. hosted_at(host, addrs);
  2306. EXPECT_EQ(1u, addrs.size());
  2307. }
  2308. #if 0 // It depends on each test environment...
  2309. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2310. auto host = "www.youtube.com";
  2311. std::vector<std::string> addrs;
  2312. hosted_at(host, addrs);
  2313. EXPECT_EQ(20u, addrs.size());
  2314. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2315. EXPECT_TRUE(it != addrs.end());
  2316. }
  2317. #endif
  2318. class ChunkedEncodingTest : public ::testing::Test {
  2319. protected:
  2320. ChunkedEncodingTest()
  2321. : cli_(HOST, PORT)
  2322. #ifdef CPPHTTPLIB_SSL_ENABLED
  2323. ,
  2324. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2325. #endif
  2326. {
  2327. cli_.set_connection_timeout(2);
  2328. #ifdef CPPHTTPLIB_SSL_ENABLED
  2329. cli_.enable_server_certificate_verification(false);
  2330. #endif
  2331. }
  2332. virtual void SetUp() {
  2333. read_file("./image.jpg", image_data_);
  2334. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2335. res.set_content("Hello World!", "text/plain");
  2336. });
  2337. svr_.Get(
  2338. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2339. res.set_chunked_content_provider(
  2340. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2341. size_t remaining = image_data_.size() - offset;
  2342. if (remaining == 0) {
  2343. sink.done();
  2344. } else {
  2345. constexpr size_t CHUNK_SIZE = 1024;
  2346. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2347. sink.write(&image_data_[offset], send_size);
  2348. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2349. }
  2350. return true;
  2351. });
  2352. });
  2353. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2354. svr_.wait_until_ready();
  2355. }
  2356. virtual void TearDown() {
  2357. svr_.stop();
  2358. if (!request_threads_.empty()) {
  2359. std::this_thread::sleep_for(std::chrono::seconds(1));
  2360. for (auto &t : request_threads_) {
  2361. t.join();
  2362. }
  2363. }
  2364. t_.join();
  2365. }
  2366. #ifdef CPPHTTPLIB_SSL_ENABLED
  2367. SSLClient cli_;
  2368. SSLServer svr_;
  2369. #else
  2370. Client cli_;
  2371. Server svr_;
  2372. #endif
  2373. thread t_;
  2374. std::vector<thread> request_threads_;
  2375. std::string image_data_;
  2376. };
  2377. TEST_F(ChunkedEncodingTest, NormalGet) {
  2378. auto res = cli_.Get("/chunked");
  2379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2380. std::string out;
  2381. read_file("./image.jpg", out);
  2382. EXPECT_EQ(StatusCode::OK_200, res->status);
  2383. EXPECT_EQ(out, res->body);
  2384. }
  2385. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2386. std::string body;
  2387. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2388. body.append(data, data_length);
  2389. return true;
  2390. });
  2391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2392. std::string out;
  2393. read_file("./image.jpg", out);
  2394. EXPECT_EQ(StatusCode::OK_200, res->status);
  2395. EXPECT_EQ(out, body);
  2396. }
  2397. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2398. std::string body;
  2399. auto res = cli_.Get(
  2400. "/chunked",
  2401. [&](const Response &response) {
  2402. EXPECT_EQ(StatusCode::OK_200, response.status);
  2403. return true;
  2404. },
  2405. [&](const char *data, size_t data_length) {
  2406. body.append(data, data_length);
  2407. return true;
  2408. });
  2409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2410. std::string out;
  2411. read_file("./image.jpg", out);
  2412. EXPECT_EQ(StatusCode::OK_200, res->status);
  2413. EXPECT_EQ(out, body);
  2414. }
  2415. TEST(RangeTest, FromHTTPBin_Online) {
  2416. auto host = "httpbingo.org";
  2417. auto path = std::string{"/range/32"};
  2418. #ifdef CPPHTTPLIB_SSL_ENABLED
  2419. auto port = 443;
  2420. SSLClient cli(host, port);
  2421. #else
  2422. auto port = 80;
  2423. Client cli(host, port);
  2424. #endif
  2425. cli.set_connection_timeout(5);
  2426. {
  2427. auto res = retry_service_failures([&] { return cli.Get(path); });
  2428. SKIP_ON_SERVICE_FAILURE(res);
  2429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2430. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2431. EXPECT_EQ(StatusCode::OK_200, res->status);
  2432. }
  2433. {
  2434. Headers headers = {make_range_header({{1, -1}})};
  2435. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2436. SKIP_ON_SERVICE_FAILURE(res);
  2437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2438. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2439. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2440. }
  2441. {
  2442. Headers headers = {make_range_header({{1, 10}})};
  2443. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2444. SKIP_ON_SERVICE_FAILURE(res);
  2445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2446. EXPECT_EQ("bcdefghijk", res->body);
  2447. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2448. }
  2449. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2450. // entire resource, while the original httpbin returned 200. Both are
  2451. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2452. {
  2453. Headers headers = {make_range_header({{0, 31}})};
  2454. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2455. SKIP_ON_SERVICE_FAILURE(res);
  2456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2457. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2458. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2459. res->status == StatusCode::PartialContent_206);
  2460. }
  2461. {
  2462. Headers headers = {make_range_header({{0, -1}})};
  2463. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2464. SKIP_ON_SERVICE_FAILURE(res);
  2465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2466. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2467. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2468. res->status == StatusCode::PartialContent_206);
  2469. }
  2470. // go-httpbin returns 206 with clamped range for over-range requests,
  2471. // while the original httpbin returned 416. Both behaviors are observed
  2472. // in real servers, so we only verify the request succeeds.
  2473. {
  2474. Headers headers = {make_range_header({{0, 32}})};
  2475. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2476. SKIP_ON_SERVICE_FAILURE(res);
  2477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2478. }
  2479. }
  2480. TEST(RangeTest, IgnoredForPost) {
  2481. Server svr;
  2482. svr.Post("/", [](const Request &, Response &res) {
  2483. res.set_content("abcdefg", "text/plain");
  2484. });
  2485. auto port = svr.bind_to_any_port(HOST);
  2486. ASSERT_GT(port, 0);
  2487. thread t = thread([&] { svr.listen_after_bind(); });
  2488. auto se = detail::scope_exit([&] {
  2489. svr.stop();
  2490. t.join();
  2491. ASSERT_FALSE(svr.is_running());
  2492. });
  2493. svr.wait_until_ready();
  2494. Client cli(HOST, port);
  2495. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2496. auto res = cli.Post("/", Headers{{"Range", range}});
  2497. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2498. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2499. EXPECT_EQ("abcdefg", res->body) << range;
  2500. }
  2501. }
  2502. TEST(RangeTest, IgnoredForUnknownUnit) {
  2503. Server svr;
  2504. svr.Get("/", [](const Request &, Response &res) {
  2505. res.set_content("abcdefg", "text/plain");
  2506. });
  2507. auto port = svr.bind_to_any_port(HOST);
  2508. ASSERT_GT(port, 0);
  2509. thread t = thread([&] { svr.listen_after_bind(); });
  2510. auto se = detail::scope_exit([&] {
  2511. svr.stop();
  2512. t.join();
  2513. ASSERT_FALSE(svr.is_running());
  2514. });
  2515. svr.wait_until_ready();
  2516. Client cli(HOST, port);
  2517. for (auto range : {"items=1-2", "none=x"}) {
  2518. auto res = cli.Get("/", Headers{{"Range", range}});
  2519. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2520. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2521. EXPECT_EQ("abcdefg", res->body) << range;
  2522. }
  2523. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2524. ASSERT_TRUE(res) << to_string(res.error());
  2525. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2526. }
  2527. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2528. auto host = "unresolvableaddress.local";
  2529. auto path = std::string{"/"};
  2530. #ifdef CPPHTTPLIB_SSL_ENABLED
  2531. auto port = 443;
  2532. SSLClient cli(host, port);
  2533. #else
  2534. auto port = 80;
  2535. Client cli(host, port);
  2536. #endif
  2537. cli.set_connection_timeout(1);
  2538. {
  2539. auto res = cli.Get(path);
  2540. ASSERT_FALSE(res);
  2541. }
  2542. std::this_thread::sleep_for(std::chrono::seconds(8));
  2543. }
  2544. #if defined(__linux__) && defined(__GLIBC__) && \
  2545. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2546. // Forward declaration: in split builds split.py strips `inline` and moves the
  2547. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2548. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2549. // against the symbol in both header-only and split builds.
  2550. namespace httplib {
  2551. namespace detail {
  2552. int getaddrinfo_with_timeout(const char *node, const char *service,
  2553. const struct addrinfo *hints,
  2554. struct addrinfo **res, time_t timeout_sec);
  2555. } // namespace detail
  2556. } // namespace httplib
  2557. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2558. //
  2559. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2560. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2561. // gai_suspend() call hits the connection timeout the function calls
  2562. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2563. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2564. // still alive and still references the now-destroyed stack frame.
  2565. //
  2566. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2567. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2568. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2569. // and runs them in a container.
  2570. namespace {
  2571. bool should_run_issue_2431_tests() {
  2572. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2573. return v && *v && std::string(v) != "0";
  2574. }
  2575. std::string unique_unresolvable_host(int n) {
  2576. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2577. // glibc still asks the configured nameserver — which is exactly the path
  2578. // we want to exercise. A unique label per call avoids the resolver cache.
  2579. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2580. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2581. std::to_string(n) + ".invalid";
  2582. }
  2583. } // namespace
  2584. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2585. if (!should_run_issue_2431_tests()) {
  2586. GTEST_SKIP()
  2587. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2588. }
  2589. for (int i = 0; i < 8; ++i) {
  2590. struct addrinfo hints;
  2591. memset(&hints, 0, sizeof(hints));
  2592. hints.ai_family = AF_UNSPEC;
  2593. hints.ai_socktype = SOCK_STREAM;
  2594. auto host = unique_unresolvable_host(i);
  2595. struct addrinfo *result = nullptr;
  2596. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2597. &result, /*timeout_sec=*/1);
  2598. if (rc == 0 && result) { freeaddrinfo(result); }
  2599. }
  2600. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2601. // stack region they still believe holds their gaicb.
  2602. std::this_thread::sleep_for(std::chrono::seconds(3));
  2603. }
  2604. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2605. if (!should_run_issue_2431_tests()) {
  2606. GTEST_SKIP()
  2607. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2608. }
  2609. std::atomic<bool> stop{false};
  2610. std::vector<std::thread> threads;
  2611. for (int t = 0; t < 8; ++t) {
  2612. threads.emplace_back([t, &stop] {
  2613. int i = 0;
  2614. while (!stop.load(std::memory_order_relaxed)) {
  2615. struct addrinfo hints;
  2616. memset(&hints, 0, sizeof(hints));
  2617. hints.ai_family = AF_UNSPEC;
  2618. hints.ai_socktype = SOCK_STREAM;
  2619. auto host = unique_unresolvable_host(t * 100000 + i++);
  2620. struct addrinfo *result = nullptr;
  2621. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2622. &result, /*timeout_sec=*/1);
  2623. if (rc == 0 && result) { freeaddrinfo(result); }
  2624. }
  2625. });
  2626. }
  2627. std::this_thread::sleep_for(std::chrono::seconds(8));
  2628. stop.store(true, std::memory_order_relaxed);
  2629. for (auto &th : threads) {
  2630. th.join();
  2631. }
  2632. std::this_thread::sleep_for(std::chrono::seconds(3));
  2633. }
  2634. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2635. if (!should_run_issue_2431_tests()) {
  2636. GTEST_SKIP()
  2637. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2638. }
  2639. std::atomic<bool> stop{false};
  2640. std::vector<std::thread> threads;
  2641. for (int t = 0; t < 8; ++t) {
  2642. threads.emplace_back([t, &stop] {
  2643. int i = 0;
  2644. while (!stop.load(std::memory_order_relaxed)) {
  2645. auto host = unique_unresolvable_host(t * 100000 + i++);
  2646. Client cli(host, 80);
  2647. cli.set_connection_timeout(1, 0);
  2648. cli.set_read_timeout(1, 0);
  2649. cli.set_write_timeout(1, 0);
  2650. (void)cli.Get("/");
  2651. }
  2652. });
  2653. }
  2654. std::this_thread::sleep_for(std::chrono::seconds(8));
  2655. stop.store(true, std::memory_order_relaxed);
  2656. for (auto &th : threads) {
  2657. th.join();
  2658. }
  2659. std::this_thread::sleep_for(std::chrono::seconds(3));
  2660. }
  2661. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2662. TEST(ConnectionErrorTest, InvalidHost) {
  2663. auto host = "-abcde.com";
  2664. #ifdef CPPHTTPLIB_SSL_ENABLED
  2665. auto port = 443;
  2666. SSLClient cli(host, port);
  2667. #else
  2668. auto port = 80;
  2669. Client cli(host, port);
  2670. #endif
  2671. cli.set_connection_timeout(std::chrono::seconds(2));
  2672. auto res = cli.Get("/");
  2673. ASSERT_TRUE(!res);
  2674. EXPECT_EQ(Error::Connection, res.error());
  2675. }
  2676. TEST(ConnectionErrorTest, InvalidHost2) {
  2677. auto host = "httpcan.org/";
  2678. #ifdef CPPHTTPLIB_SSL_ENABLED
  2679. SSLClient cli(host);
  2680. #else
  2681. Client cli(host);
  2682. #endif
  2683. cli.set_connection_timeout(std::chrono::seconds(2));
  2684. auto res = cli.Get("/");
  2685. ASSERT_TRUE(!res);
  2686. EXPECT_EQ(Error::Connection, res.error());
  2687. }
  2688. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2689. auto host = "httpcan.org/";
  2690. #ifdef CPPHTTPLIB_SSL_ENABLED
  2691. SSLClient cli(host);
  2692. #else
  2693. Client cli(host);
  2694. #endif
  2695. cli.set_connection_timeout(std::chrono::seconds(2));
  2696. auto res = cli.Get("/");
  2697. ASSERT_TRUE(!res);
  2698. stringstream s;
  2699. s << "error code: " << res.error();
  2700. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2701. }
  2702. TEST(ConnectionErrorTest, InvalidPort) {
  2703. auto host = "localhost";
  2704. auto port = 44380;
  2705. #ifdef CPPHTTPLIB_SSL_ENABLED
  2706. SSLClient cli(host, port);
  2707. #else
  2708. Client cli(host, port);
  2709. #endif
  2710. cli.set_connection_timeout(std::chrono::seconds(2));
  2711. auto res = cli.Get("/");
  2712. ASSERT_TRUE(!res);
  2713. EXPECT_TRUE(Error::Connection == res.error() ||
  2714. Error::ConnectionTimeout == res.error());
  2715. }
  2716. TEST(ConnectionErrorTest, Timeout_Online) {
  2717. auto host = "google.com";
  2718. #ifdef CPPHTTPLIB_SSL_ENABLED
  2719. auto port = 44380;
  2720. SSLClient cli(host, port);
  2721. #else
  2722. auto port = 8080;
  2723. Client cli(host, port);
  2724. #endif
  2725. cli.set_connection_timeout(std::chrono::seconds(2));
  2726. // only probe one address type so that the error reason
  2727. // correlates to the timed-out IPv4, not the unsupported
  2728. // IPv6 connection attempt
  2729. cli.set_address_family(AF_INET);
  2730. auto res = cli.Get("/");
  2731. ASSERT_TRUE(!res);
  2732. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2733. }
  2734. TEST(CancelTest, NoCancel_Online) {
  2735. auto host = "httpbingo.org";
  2736. auto path = std::string{"/range/32"};
  2737. #ifdef CPPHTTPLIB_SSL_ENABLED
  2738. auto port = 443;
  2739. SSLClient cli(host, port);
  2740. #else
  2741. auto port = 80;
  2742. Client cli(host, port);
  2743. #endif
  2744. cli.set_connection_timeout(std::chrono::seconds(5));
  2745. auto res = retry_service_failures(
  2746. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
  2747. SKIP_ON_SERVICE_FAILURE(res);
  2748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2749. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2750. EXPECT_EQ(StatusCode::OK_200, res->status);
  2751. }
  2752. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2753. // Use /bytes with a large payload so that the DownloadProgress callback
  2754. // (which only fires for Content-Length responses) is invoked before the
  2755. // entire body is received, giving cancellation a chance to fire.
  2756. auto host = "httpbingo.org";
  2757. auto path = std::string{"/bytes/524288"};
  2758. #ifdef CPPHTTPLIB_SSL_ENABLED
  2759. auto port = 443;
  2760. SSLClient cli(host, port);
  2761. #else
  2762. auto port = 80;
  2763. Client cli(host, port);
  2764. #endif
  2765. auto res = retry_service_failures(
  2766. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
  2767. SKIP_ON_SERVICE_FAILURE(res);
  2768. cli.set_connection_timeout(std::chrono::seconds(5));
  2769. ASSERT_TRUE(!res);
  2770. EXPECT_EQ(Error::Canceled, res.error());
  2771. }
  2772. TEST(CancelTest, WithCancelLargePayload_Online) {
  2773. auto host = "httpbingo.org";
  2774. auto path = std::string{"/bytes/524288"};
  2775. #ifdef CPPHTTPLIB_SSL_ENABLED
  2776. auto port = 443;
  2777. SSLClient cli(host, port);
  2778. #else
  2779. auto port = 80;
  2780. Client cli(host, port);
  2781. #endif
  2782. cli.set_connection_timeout(std::chrono::seconds(5));
  2783. auto res = retry_service_failures([&] {
  2784. auto count = 0;
  2785. return cli.Get(path,
  2786. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2787. });
  2788. SKIP_ON_SERVICE_FAILURE(res);
  2789. ASSERT_TRUE(!res);
  2790. EXPECT_EQ(Error::Canceled, res.error());
  2791. }
  2792. TEST(CancelTest, NoCancelPost) {
  2793. Server svr;
  2794. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2795. res.set_content("Hello World!", "text/plain");
  2796. });
  2797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. thread.join();
  2801. ASSERT_FALSE(svr.is_running());
  2802. });
  2803. svr.wait_until_ready();
  2804. Client cli(HOST, PORT);
  2805. cli.set_connection_timeout(std::chrono::seconds(5));
  2806. auto res =
  2807. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2808. "application/json", [](uint64_t, uint64_t) { return true; });
  2809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2810. EXPECT_EQ("Hello World!", res->body);
  2811. EXPECT_EQ(StatusCode::OK_200, res->status);
  2812. }
  2813. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2814. Server svr;
  2815. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2816. res.set_content("Hello World!", "text/plain");
  2817. });
  2818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2819. auto se = detail::scope_exit([&] {
  2820. svr.stop();
  2821. thread.join();
  2822. ASSERT_FALSE(svr.is_running());
  2823. });
  2824. svr.wait_until_ready();
  2825. Client cli(HOST, PORT);
  2826. cli.set_connection_timeout(std::chrono::seconds(5));
  2827. auto res =
  2828. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2829. "application/json", [](uint64_t, uint64_t) { return false; });
  2830. ASSERT_TRUE(!res);
  2831. EXPECT_EQ(Error::Canceled, res.error());
  2832. }
  2833. TEST(CancelTest, WithCancelLargePayloadPost) {
  2834. Server svr;
  2835. svr.set_payload_max_length(200 * 1024 * 1024);
  2836. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2837. res.set_content(LARGE_DATA, "text/plain");
  2838. });
  2839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2840. auto se = detail::scope_exit([&] {
  2841. svr.stop();
  2842. thread.join();
  2843. ASSERT_FALSE(svr.is_running());
  2844. });
  2845. svr.wait_until_ready();
  2846. Client cli(HOST, PORT);
  2847. cli.set_payload_max_length(200 * 1024 * 1024);
  2848. cli.set_connection_timeout(std::chrono::seconds(5));
  2849. auto res =
  2850. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2851. "application/json", [](uint64_t, uint64_t) { return false; });
  2852. ASSERT_TRUE(!res);
  2853. EXPECT_EQ(Error::Canceled, res.error());
  2854. }
  2855. TEST(CancelTest, NoCancelPut) {
  2856. Server svr;
  2857. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2858. res.set_content("Hello World!", "text/plain");
  2859. });
  2860. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2861. auto se = detail::scope_exit([&] {
  2862. svr.stop();
  2863. thread.join();
  2864. ASSERT_FALSE(svr.is_running());
  2865. });
  2866. svr.wait_until_ready();
  2867. Client cli(HOST, PORT);
  2868. cli.set_connection_timeout(std::chrono::seconds(5));
  2869. auto res =
  2870. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2871. "application/json", [](uint64_t, uint64_t) { return true; });
  2872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2873. EXPECT_EQ("Hello World!", res->body);
  2874. EXPECT_EQ(StatusCode::OK_200, res->status);
  2875. }
  2876. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2877. Server svr;
  2878. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2879. res.set_content("Hello World!", "text/plain");
  2880. });
  2881. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2882. auto se = detail::scope_exit([&] {
  2883. svr.stop();
  2884. thread.join();
  2885. ASSERT_FALSE(svr.is_running());
  2886. });
  2887. svr.wait_until_ready();
  2888. Client cli(HOST, PORT);
  2889. cli.set_connection_timeout(std::chrono::seconds(5));
  2890. auto res =
  2891. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2892. "application/json", [](uint64_t, uint64_t) { return false; });
  2893. ASSERT_TRUE(!res);
  2894. EXPECT_EQ(Error::Canceled, res.error());
  2895. }
  2896. TEST(CancelTest, WithCancelLargePayloadPut) {
  2897. Server svr;
  2898. svr.set_payload_max_length(200 * 1024 * 1024);
  2899. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2900. res.set_content(LARGE_DATA, "text/plain");
  2901. });
  2902. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2903. auto se = detail::scope_exit([&] {
  2904. svr.stop();
  2905. thread.join();
  2906. ASSERT_FALSE(svr.is_running());
  2907. });
  2908. svr.wait_until_ready();
  2909. Client cli(HOST, PORT);
  2910. cli.set_payload_max_length(200 * 1024 * 1024);
  2911. cli.set_connection_timeout(std::chrono::seconds(5));
  2912. auto res =
  2913. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2914. "application/json", [](uint64_t, uint64_t) { return false; });
  2915. ASSERT_TRUE(!res);
  2916. EXPECT_EQ(Error::Canceled, res.error());
  2917. }
  2918. TEST(CancelTest, NoCancelPatch) {
  2919. Server svr;
  2920. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2921. res.set_content("Hello World!", "text/plain");
  2922. });
  2923. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2924. auto se = detail::scope_exit([&] {
  2925. svr.stop();
  2926. thread.join();
  2927. ASSERT_FALSE(svr.is_running());
  2928. });
  2929. svr.wait_until_ready();
  2930. Client cli(HOST, PORT);
  2931. cli.set_connection_timeout(std::chrono::seconds(5));
  2932. auto res =
  2933. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2934. "application/json", [](uint64_t, uint64_t) { return true; });
  2935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2936. EXPECT_EQ("Hello World!", res->body);
  2937. EXPECT_EQ(StatusCode::OK_200, res->status);
  2938. }
  2939. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2940. Server svr;
  2941. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2942. res.set_content("Hello World!", "text/plain");
  2943. });
  2944. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2945. auto se = detail::scope_exit([&] {
  2946. svr.stop();
  2947. thread.join();
  2948. ASSERT_FALSE(svr.is_running());
  2949. });
  2950. svr.wait_until_ready();
  2951. Client cli(HOST, PORT);
  2952. cli.set_connection_timeout(std::chrono::seconds(5));
  2953. auto res =
  2954. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2955. "application/json", [](uint64_t, uint64_t) { return false; });
  2956. ASSERT_TRUE(!res);
  2957. EXPECT_EQ(Error::Canceled, res.error());
  2958. }
  2959. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2960. Server svr;
  2961. svr.set_payload_max_length(200 * 1024 * 1024);
  2962. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2963. res.set_content(LARGE_DATA, "text/plain");
  2964. });
  2965. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2966. auto se = detail::scope_exit([&] {
  2967. svr.stop();
  2968. thread.join();
  2969. ASSERT_FALSE(svr.is_running());
  2970. });
  2971. svr.wait_until_ready();
  2972. Client cli(HOST, PORT);
  2973. cli.set_payload_max_length(200 * 1024 * 1024);
  2974. cli.set_connection_timeout(std::chrono::seconds(5));
  2975. auto res =
  2976. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2977. "application/json", [](uint64_t, uint64_t) { return false; });
  2978. ASSERT_TRUE(!res);
  2979. EXPECT_EQ(Error::Canceled, res.error());
  2980. }
  2981. TEST(CancelTest, NoCancelDelete) {
  2982. Server svr;
  2983. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2984. res.set_content("Hello World!", "text/plain");
  2985. });
  2986. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2987. auto se = detail::scope_exit([&] {
  2988. svr.stop();
  2989. thread.join();
  2990. ASSERT_FALSE(svr.is_running());
  2991. });
  2992. svr.wait_until_ready();
  2993. Client cli(HOST, PORT);
  2994. cli.set_connection_timeout(std::chrono::seconds(5));
  2995. auto res =
  2996. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2997. "application/json", [](uint64_t, uint64_t) { return true; });
  2998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2999. EXPECT_EQ("Hello World!", res->body);
  3000. EXPECT_EQ(StatusCode::OK_200, res->status);
  3001. }
  3002. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  3003. Server svr;
  3004. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3005. res.set_content("Hello World!", "text/plain");
  3006. });
  3007. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3008. auto se = detail::scope_exit([&] {
  3009. svr.stop();
  3010. thread.join();
  3011. ASSERT_FALSE(svr.is_running());
  3012. });
  3013. svr.wait_until_ready();
  3014. Client cli(HOST, PORT);
  3015. cli.set_connection_timeout(std::chrono::seconds(5));
  3016. auto res =
  3017. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3018. "application/json", [](uint64_t, uint64_t) { return false; });
  3019. ASSERT_TRUE(!res);
  3020. EXPECT_EQ(Error::Canceled, res.error());
  3021. }
  3022. TEST(CancelTest, WithCancelLargePayloadDelete) {
  3023. Server svr;
  3024. svr.set_payload_max_length(200 * 1024 * 1024);
  3025. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3026. res.set_content(LARGE_DATA, "text/plain");
  3027. });
  3028. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3029. auto se = detail::scope_exit([&] {
  3030. svr.stop();
  3031. thread.join();
  3032. ASSERT_FALSE(svr.is_running());
  3033. });
  3034. svr.wait_until_ready();
  3035. Client cli(HOST, PORT);
  3036. cli.set_payload_max_length(200 * 1024 * 1024);
  3037. cli.set_connection_timeout(std::chrono::seconds(5));
  3038. auto res =
  3039. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3040. "application/json", [](uint64_t, uint64_t) { return false; });
  3041. ASSERT_TRUE(!res);
  3042. EXPECT_EQ(Error::Canceled, res.error());
  3043. }
  3044. // One stop() from another thread ends a request that waits for the response
  3045. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3046. Server svr;
  3047. std::atomic<bool> received{false};
  3048. std::atomic<bool> done{false};
  3049. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3050. received.store(true);
  3051. while (!done.load()) {
  3052. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3053. }
  3054. res.set_content("Hello World!", "text/plain");
  3055. });
  3056. auto port = svr.bind_to_any_port(HOST);
  3057. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3058. Client cli(HOST, port);
  3059. cli.set_read_timeout(std::chrono::seconds(30));
  3060. std::future<Result> request;
  3061. auto se = detail::scope_exit([&] {
  3062. done.store(true);
  3063. svr.stop();
  3064. thread.join();
  3065. ASSERT_FALSE(svr.is_running());
  3066. });
  3067. svr.wait_until_ready();
  3068. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3069. for (int i = 0; i < 500 && !received.load(); ++i) {
  3070. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3071. }
  3072. ASSERT_TRUE(received.load());
  3073. // Let the client block in the wait for the response
  3074. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3075. auto start = std::chrono::steady_clock::now();
  3076. cli.stop();
  3077. ASSERT_EQ(std::future_status::ready,
  3078. request.wait_for(std::chrono::seconds(5)));
  3079. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3080. auto res = request.get();
  3081. ASSERT_TRUE(!res);
  3082. EXPECT_EQ(Error::Read, res.error());
  3083. }
  3084. // A listener whose backlog completes the TCP connections of clients, and that
  3085. // never answers them
  3086. struct SilentListener {
  3087. socket_t sock = INVALID_SOCKET;
  3088. sockaddr_in addr{};
  3089. int port = 0;
  3090. explicit SilentListener(int backlog = 1) {
  3091. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3092. addr.sin_family = AF_INET;
  3093. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3094. socklen_t len = sizeof(addr);
  3095. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3096. ::listen(sock, backlog) != 0 ||
  3097. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3098. detail::close_socket(sock);
  3099. sock = INVALID_SOCKET;
  3100. }
  3101. port = ntohs(addr.sin_port);
  3102. }
  3103. ~SilentListener() { detail::close_socket(sock); }
  3104. // The next connection, whose reads give up after 5 seconds
  3105. socket_t accept() const {
  3106. auto peer = ::accept(sock, nullptr, nullptr);
  3107. if (peer != INVALID_SOCKET) {
  3108. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3109. }
  3110. return peer;
  3111. }
  3112. };
  3113. static bool receives_a_byte(socket_t peer) {
  3114. char c = 0;
  3115. return detail::read_socket(peer, &c, 1, 0) == 1;
  3116. }
  3117. // Runs op, stops cli once the listener receives the first byte op sends, and
  3118. // expects op to end with error soon after
  3119. template <typename ClientType, typename Op>
  3120. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3121. Op op, Error error = Error::Canceled) {
  3122. auto ended = std::async(std::launch::async, op);
  3123. auto peer = listener.accept();
  3124. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3125. ASSERT_NE(INVALID_SOCKET, peer);
  3126. ASSERT_TRUE(receives_a_byte(peer));
  3127. cli.stop();
  3128. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3129. EXPECT_EQ(error, ended.get());
  3130. }
  3131. // Stops itself from another thread as the connection opens, the last moment a
  3132. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3133. // waits for the connection fails the test instead of hanging it.
  3134. class StoppedAsConnectedClient : public ClientImpl {
  3135. public:
  3136. using ClientImpl::ClientImpl;
  3137. protected:
  3138. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3139. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3140. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3141. stopper_.wait_for(std::chrono::seconds(1));
  3142. return true;
  3143. }
  3144. private:
  3145. std::future<void> stopper_;
  3146. };
  3147. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3148. SilentListener listener;
  3149. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3150. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3151. cli.set_read_timeout(std::chrono::seconds(3));
  3152. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3153. auto peer = listener.accept();
  3154. EXPECT_FALSE(receives_a_byte(peer));
  3155. detail::close_socket(peer);
  3156. auto handle = cli.open_stream("GET", "/");
  3157. EXPECT_FALSE(handle.is_valid());
  3158. EXPECT_EQ(Error::Canceled, handle.error);
  3159. peer = listener.accept();
  3160. EXPECT_FALSE(receives_a_byte(peer));
  3161. detail::close_socket(peer);
  3162. }
  3163. #ifdef __linux__
  3164. // A connect that a listener with a full backlog never completes
  3165. TEST(ClientStopTest, StopEndsAConnect) {
  3166. SilentListener listener(0);
  3167. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3168. std::vector<socket_t> backlog;
  3169. auto close_backlog = detail::scope_exit([&] {
  3170. for (auto sock : backlog) {
  3171. detail::close_socket(sock);
  3172. }
  3173. });
  3174. for (int i = 0; i < 8; i++) {
  3175. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3176. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3177. sizeof(listener.addr));
  3178. backlog.push_back(sock);
  3179. }
  3180. Client cli("127.0.0.1", listener.port);
  3181. cli.set_connection_timeout(std::chrono::seconds(3));
  3182. auto ended =
  3183. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3184. // A stop() before the request starts does not apply to it, so it repeats
  3185. auto status = std::future_status::timeout;
  3186. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3187. cli.stop();
  3188. status = ended.wait_for(std::chrono::milliseconds(10));
  3189. }
  3190. EXPECT_EQ(std::future_status::ready, status);
  3191. EXPECT_EQ(Error::Canceled, ended.get());
  3192. }
  3193. #endif
  3194. // The stream holds the socket while it waits for the head, out of the reach
  3195. // of shutdown()
  3196. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3197. SilentListener listener;
  3198. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3199. Client cli("127.0.0.1", listener.port);
  3200. cli.set_read_timeout(std::chrono::seconds(3));
  3201. expect_stop_ends(
  3202. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3203. Error::Read);
  3204. }
  3205. #ifdef CPPHTTPLIB_SSL_ENABLED
  3206. // A server that never answers the ClientHello
  3207. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3208. SilentListener listener;
  3209. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3210. SSLClient cli("127.0.0.1", listener.port);
  3211. cli.enable_server_certificate_verification(false);
  3212. cli.set_connection_timeout(std::chrono::seconds(3));
  3213. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3214. expect_stop_ends(cli, listener,
  3215. [&] { return cli.open_stream("GET", "/").error; });
  3216. }
  3217. // A proxy that takes the CONNECT and never answers it
  3218. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3219. SilentListener listener;
  3220. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3221. SSLClient cli("example.com", 443);
  3222. cli.set_proxy("127.0.0.1", listener.port);
  3223. cli.set_read_timeout(std::chrono::seconds(3));
  3224. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3225. }
  3226. #endif
  3227. // A read timeout past what the clock reaches waits for the response
  3228. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3229. SilentListener listener;
  3230. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3231. Client cli("127.0.0.1", listener.port);
  3232. cli.set_read_timeout(
  3233. static_cast<time_t>((std::min)(static_cast<long long>(
  3234. (std::numeric_limits<time_t>::max)()),
  3235. 10000000000LL)),
  3236. 0);
  3237. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3238. auto peer = listener.accept();
  3239. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3240. ASSERT_NE(INVALID_SOCKET, peer);
  3241. ASSERT_TRUE(receives_a_byte(peer));
  3242. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3243. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3244. "Connection: close\r\n\r\nok";
  3245. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3246. auto result = res.get();
  3247. ASSERT_TRUE(result);
  3248. EXPECT_EQ("ok", result->body);
  3249. }
  3250. static std::string remove_whitespace(const std::string &input) {
  3251. std::string output;
  3252. output.reserve(input.size());
  3253. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3254. [](unsigned char c) { return !std::isspace(c); });
  3255. return output;
  3256. }
  3257. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3258. auto host = "httpbingo.org";
  3259. auto path = std::string{"/basic-auth/hello/world"};
  3260. #ifdef CPPHTTPLIB_SSL_ENABLED
  3261. auto port = 443;
  3262. SSLClient cli(host, port);
  3263. #else
  3264. auto port = 80;
  3265. Client cli(host, port);
  3266. #endif
  3267. {
  3268. auto res = retry_service_failures([&] { return cli.Get(path); });
  3269. SKIP_ON_SERVICE_FAILURE(res);
  3270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3271. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3272. }
  3273. {
  3274. auto res = retry_service_failures([&] {
  3275. return cli.Get(
  3276. path, Headers{make_basic_authentication_header("hello", "world")});
  3277. });
  3278. SKIP_ON_SERVICE_FAILURE(res);
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. auto body = remove_whitespace(res->body);
  3281. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3282. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. }
  3285. {
  3286. cli.set_basic_auth("hello", "world");
  3287. auto res = retry_service_failures([&] { return cli.Get(path); });
  3288. SKIP_ON_SERVICE_FAILURE(res);
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. auto body = remove_whitespace(res->body);
  3291. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3292. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. }
  3295. {
  3296. cli.set_basic_auth("hello", "bad");
  3297. auto res = retry_service_failures([&] { return cli.Get(path); });
  3298. SKIP_ON_SERVICE_FAILURE(res);
  3299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3300. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3301. }
  3302. {
  3303. cli.set_basic_auth("bad", "world");
  3304. auto res = retry_service_failures([&] { return cli.Get(path); });
  3305. SKIP_ON_SERVICE_FAILURE(res);
  3306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3307. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3308. }
  3309. }
  3310. #ifdef CPPHTTPLIB_SSL_ENABLED
  3311. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3312. auto host = "httpbingo.org";
  3313. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3314. auto paths = std::vector<std::string>{
  3315. "/digest-auth/auth/hello/world/MD5",
  3316. "/digest-auth/auth/hello/world/SHA-256",
  3317. };
  3318. auto port = 443;
  3319. SSLClient cli(host, port);
  3320. {
  3321. auto res = retry_service_failures([&] { return cli.Get(unauth_path); });
  3322. SKIP_ON_SERVICE_FAILURE(res);
  3323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3324. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3325. }
  3326. {
  3327. cli.set_digest_auth("hello", "world");
  3328. for (const auto &path : paths) {
  3329. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3330. SKIP_ON_SERVICE_FAILURE(res);
  3331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3332. auto body = remove_whitespace(res->body);
  3333. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3334. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3335. EXPECT_EQ(StatusCode::OK_200, res->status);
  3336. }
  3337. cli.set_digest_auth("hello", "bad");
  3338. for (const auto &path : paths) {
  3339. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3340. SKIP_ON_SERVICE_FAILURE(res);
  3341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3342. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3343. }
  3344. }
  3345. }
  3346. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3347. // comma-separated list of challenges, and each challenge may itself carry a
  3348. // comma-separated auth-param list, so a server can legally offer Basic
  3349. // before Digest, either as two field lines or packed into one. Runs one 401
  3350. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3351. // value() joins them in receipt order) and checks that the retry carries a
  3352. // well-formed Digest Authorization header naming expected_realm.
  3353. static void
  3354. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3355. const std::string &expected_realm) {
  3356. std::atomic<int> hits{0};
  3357. Server svr;
  3358. svr.Get("/x", [&](const Request &req, Response &res) {
  3359. if (++hits == 1) {
  3360. res.status = StatusCode::Unauthorized_401;
  3361. for (const auto &challenge : challenges) {
  3362. res.set_header("WWW-Authenticate", challenge);
  3363. }
  3364. } else {
  3365. auto authorization = req.get_header_value("Authorization");
  3366. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3367. EXPECT_NE(std::string::npos,
  3368. authorization.find("realm=\"" + expected_realm + "\""));
  3369. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3370. res.set_content("ok", "text/plain");
  3371. }
  3372. });
  3373. auto port = svr.bind_to_any_port(HOST);
  3374. std::thread t([&]() { svr.listen_after_bind(); });
  3375. auto se = detail::scope_exit([&] {
  3376. svr.stop();
  3377. t.join();
  3378. });
  3379. svr.wait_until_ready();
  3380. Client cli(HOST, port);
  3381. cli.set_digest_auth("hello", "world");
  3382. auto res = cli.Get("/x");
  3383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3384. EXPECT_EQ(2, hits.load());
  3385. }
  3386. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3387. static const char *kDigestChallenge =
  3388. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3389. "algorithm=MD5";
  3390. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3391. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3392. "testrealm");
  3393. }
  3394. // Same challenge list with the schemes in the opposite order, to make sure
  3395. // the fix above didn't just special-case "Basic first".
  3396. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3397. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3398. "testrealm");
  3399. }
  3400. // A comma inside a quoted auth-param value must not be mistaken for the
  3401. // separator between two challenges (or two auth-params).
  3402. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3403. run_digest_challenge_list_test(
  3404. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3405. "algorithm=MD5"},
  3406. "test,realm");
  3407. }
  3408. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3409. // the params and leaves out the fragment.
  3410. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3411. Server svr;
  3412. std::string uri, target;
  3413. svr.Get("/a b", [&](const Request &req, Response &res) {
  3414. auto auth = req.get_header_value("Authorization");
  3415. if (auth.empty()) {
  3416. res.status = StatusCode::Unauthorized_401;
  3417. res.set_header("WWW-Authenticate",
  3418. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3419. return;
  3420. }
  3421. auto b = auth.find("uri=\"") + 5;
  3422. uri = auth.substr(b, auth.find('"', b) - b);
  3423. target = req.target;
  3424. });
  3425. auto port = svr.bind_to_any_port(HOST);
  3426. std::thread t([&]() { svr.listen_after_bind(); });
  3427. auto se = detail::scope_exit([&] {
  3428. svr.stop();
  3429. t.join();
  3430. });
  3431. svr.wait_until_ready();
  3432. Client cli(HOST, port);
  3433. cli.set_digest_auth("hello", "world");
  3434. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3436. EXPECT_EQ("/a%20b?x=1", target);
  3437. EXPECT_EQ(target, uri);
  3438. }
  3439. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3440. // make_digest_authentication_header() dereferences both unconditionally, so
  3441. // a server sending a challenge missing either one must not be treated as
  3442. // usable -- doing so used to crash the client with std::out_of_range.
  3443. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3444. Server svr;
  3445. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3446. res.status = StatusCode::Unauthorized_401;
  3447. res.set_header("WWW-Authenticate", challenge);
  3448. });
  3449. auto port = svr.bind_to_any_port(HOST);
  3450. std::thread t([&]() { svr.listen_after_bind(); });
  3451. auto se = detail::scope_exit([&] {
  3452. svr.stop();
  3453. t.join();
  3454. });
  3455. svr.wait_until_ready();
  3456. Client cli(HOST, port);
  3457. cli.set_digest_auth("hello", "world");
  3458. auto res = cli.Get("/x");
  3459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3460. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3461. }
  3462. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3463. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3464. }
  3465. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3466. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3467. }
  3468. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3469. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3470. }
  3471. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3472. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3473. // when storing the values, so the header builder has to re-escape them (and
  3474. // keep algorithm a bare token); otherwise the value breaks out of its
  3475. // quoted-string and injects extra auth-params into the client's Authorization.
  3476. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3477. std::atomic<int> hits{0};
  3478. std::string authorization;
  3479. Server svr;
  3480. svr.Get("/x", [&](const Request &req, Response &res) {
  3481. if (++hits == 1) {
  3482. res.status = StatusCode::Unauthorized_401;
  3483. // On the wire the quotes embedded in the values are backslash-escaped.
  3484. res.set_header("WWW-Authenticate",
  3485. "Digest realm=\"testrealm\", "
  3486. "nonce=\"n\\\"; injected=\\\"x\", "
  3487. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3488. } else {
  3489. authorization = req.get_header_value("Authorization");
  3490. res.set_content("ok", "text/plain");
  3491. }
  3492. });
  3493. auto port = svr.bind_to_any_port(HOST);
  3494. std::thread t([&]() { svr.listen_after_bind(); });
  3495. auto se = detail::scope_exit([&] {
  3496. svr.stop();
  3497. t.join();
  3498. });
  3499. svr.wait_until_ready();
  3500. Client cli(HOST, port);
  3501. cli.set_digest_auth("hello", "world");
  3502. auto res = cli.Get("/x");
  3503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3504. EXPECT_EQ(2, hits.load());
  3505. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3506. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3507. // inside its quoted-string rather than starting an "injected" auth-param.
  3508. EXPECT_NE(std::string::npos,
  3509. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3510. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3511. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3512. }
  3513. #endif
  3514. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3515. auto host = "google.com";
  3516. auto another_host = "example.com";
  3517. auto wrong_ip = "0.0.0.0";
  3518. #ifdef CPPHTTPLIB_SSL_ENABLED
  3519. SSLClient cli(host);
  3520. #else
  3521. Client cli(host);
  3522. #endif
  3523. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3524. auto res = cli.Get("/");
  3525. // Any status: Google may redirect or rate-limit CI runners.
  3526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3527. }
  3528. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3529. auto host = "google.com";
  3530. auto wrong_ip = "0.0.0.0";
  3531. #ifdef CPPHTTPLIB_SSL_ENABLED
  3532. SSLClient cli(host);
  3533. #else
  3534. Client cli(host);
  3535. #endif
  3536. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3537. auto res = cli.Get("/");
  3538. ASSERT_TRUE(!res);
  3539. EXPECT_EQ(Error::Connection, res.error());
  3540. }
  3541. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3542. // A mapped value that is not an IP literal must be resolved. "localhost"
  3543. // resolves from the hosts file, so this test needs no external DNS.
  3544. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3545. auto host = "target.invalid";
  3546. Server svr;
  3547. std::string received_host;
  3548. svr.Get("/hi", [&](const Request &req, Response &res) {
  3549. received_host = req.get_header_value("Host");
  3550. res.set_content("Hello World!", "text/plain");
  3551. });
  3552. auto port = svr.bind_to_any_port(HOST);
  3553. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3554. auto se = detail::scope_exit([&] {
  3555. svr.stop();
  3556. thread.join();
  3557. ASSERT_FALSE(svr.is_running());
  3558. });
  3559. svr.wait_until_ready();
  3560. Client cli(host, port);
  3561. cli.set_direct_hostname_addr_map({{host, HOST}});
  3562. auto res = cli.Get("/hi");
  3563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3564. EXPECT_EQ(StatusCode::OK_200, res->status);
  3565. // The mapping only redirects the connection; the identity stays host_.
  3566. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3567. }
  3568. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3569. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3570. auto host = "target.invalid";
  3571. Server svr;
  3572. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3573. res.set_content("Hello World!", "text/plain");
  3574. });
  3575. auto port = svr.bind_to_any_port("127.0.0.1");
  3576. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3577. auto se = detail::scope_exit([&] {
  3578. svr.stop();
  3579. thread.join();
  3580. ASSERT_FALSE(svr.is_running());
  3581. });
  3582. svr.wait_until_ready();
  3583. Client cli(host, port);
  3584. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3585. auto res = cli.Get("/hi");
  3586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3587. EXPECT_EQ(StatusCode::OK_200, res->status);
  3588. }
  3589. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3590. // An empty mapped value must leave host_ as the connection target. Without
  3591. // that guard the empty value would become the host argument, getaddrinfo
  3592. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3593. // loopback - silently connecting somewhere the caller never asked for.
  3594. // The server listens on loopback, so such a fallback would succeed and is
  3595. // therefore observable as a failure of this test.
  3596. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3597. Server svr;
  3598. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3599. res.set_content("Hello World!", "text/plain");
  3600. });
  3601. auto port = svr.bind_to_any_port(HOST);
  3602. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3603. auto se = detail::scope_exit([&] {
  3604. svr.stop();
  3605. thread.join();
  3606. ASSERT_FALSE(svr.is_running());
  3607. });
  3608. svr.wait_until_ready();
  3609. Client cli(blackhole, port);
  3610. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3611. cli.set_connection_timeout(1);
  3612. auto res = cli.Get("/hi");
  3613. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3614. }
  3615. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3616. auto host = "target.invalid";
  3617. Server svr;
  3618. std::string received_host;
  3619. svr.Get("/hi", [&](const Request &req, Response &res) {
  3620. received_host = req.get_header_value("Host");
  3621. res.set_content("Hello World!", "text/plain");
  3622. });
  3623. auto port = svr.bind_to_any_port("127.0.0.1");
  3624. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3625. auto se = detail::scope_exit([&] {
  3626. svr.stop();
  3627. thread.join();
  3628. ASSERT_FALSE(svr.is_running());
  3629. });
  3630. svr.wait_until_ready();
  3631. Client cli(host, port);
  3632. #pragma GCC diagnostic push
  3633. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3634. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3635. #pragma GCC diagnostic pop
  3636. auto res = cli.Get("/hi");
  3637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3638. EXPECT_EQ(StatusCode::OK_200, res->status);
  3639. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3640. }
  3641. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3642. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3643. Server svr;
  3644. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3645. res.set_content("Hello World!", "text/plain");
  3646. });
  3647. auto port = svr.bind_to_any_port("127.0.0.1");
  3648. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3649. auto se = detail::scope_exit([&] {
  3650. svr.stop();
  3651. thread.join();
  3652. ASSERT_FALSE(svr.is_running());
  3653. });
  3654. svr.wait_until_ready();
  3655. Client cli("127.0.0.1", port);
  3656. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3657. cli.set_connection_timeout(1);
  3658. auto res = cli.Get("/hi");
  3659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3660. EXPECT_EQ(StatusCode::OK_200, res->status);
  3661. }
  3662. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3663. auto host = "httpbingo.org";
  3664. auto path = std::string{"/absolute-redirect/3"};
  3665. #ifdef CPPHTTPLIB_SSL_ENABLED
  3666. SSLClient cli(host);
  3667. #else
  3668. Client cli(host);
  3669. #endif
  3670. cli.set_follow_location(true);
  3671. auto res = retry_service_failures([&] { return cli.Get(path); });
  3672. SKIP_ON_SERVICE_FAILURE(res);
  3673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3674. EXPECT_EQ(StatusCode::OK_200, res->status);
  3675. }
  3676. TEST(RedirectTest, Redirect_Online) {
  3677. auto host = "httpbingo.org";
  3678. auto path = std::string{"/redirect/3"};
  3679. #ifdef CPPHTTPLIB_SSL_ENABLED
  3680. SSLClient cli(host);
  3681. #else
  3682. Client cli(host);
  3683. #endif
  3684. cli.set_follow_location(true);
  3685. auto res = retry_service_failures([&] { return cli.Get(path); });
  3686. SKIP_ON_SERVICE_FAILURE(res);
  3687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3688. EXPECT_EQ(StatusCode::OK_200, res->status);
  3689. }
  3690. TEST(RelativeRedirectTest, Redirect_Online) {
  3691. auto host = "httpbingo.org";
  3692. auto path = std::string{"/relative-redirect/3"};
  3693. #ifdef CPPHTTPLIB_SSL_ENABLED
  3694. SSLClient cli(host);
  3695. #else
  3696. Client cli(host);
  3697. #endif
  3698. cli.set_follow_location(true);
  3699. auto res = retry_service_failures([&] { return cli.Get(path); });
  3700. SKIP_ON_SERVICE_FAILURE(res);
  3701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3702. EXPECT_EQ(StatusCode::OK_200, res->status);
  3703. }
  3704. TEST(TooManyRedirectTest, Redirect_Online) {
  3705. auto host = "httpbingo.org";
  3706. auto path = std::string{"/redirect/21"};
  3707. #ifdef CPPHTTPLIB_SSL_ENABLED
  3708. SSLClient cli(host);
  3709. #else
  3710. Client cli(host);
  3711. #endif
  3712. cli.set_follow_location(true);
  3713. auto res = retry_service_failures([&] { return cli.Get(path); });
  3714. SKIP_ON_SERVICE_FAILURE(res);
  3715. ASSERT_TRUE(!res);
  3716. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3717. }
  3718. #ifdef CPPHTTPLIB_SSL_ENABLED
  3719. TEST(YahooRedirectTest, Redirect_Online) {
  3720. Client cli("yahoo.com");
  3721. auto res = cli.Get("/");
  3722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3723. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3724. cli.set_follow_location(true);
  3725. res = cli.Get("/");
  3726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3727. EXPECT_EQ(StatusCode::OK_200, res->status);
  3728. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3729. }
  3730. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3731. #define REDIR_HOST "httpbingo.org"
  3732. #define REDIR_PATH "/redirect-to"
  3733. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3734. SSLClient cli(REDIR_HOST);
  3735. cli.set_follow_location(true);
  3736. auto res = retry_service_failures([&] {
  3737. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3738. });
  3739. SKIP_ON_SERVICE_FAILURE(res);
  3740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3741. EXPECT_EQ(StatusCode::OK_200, res->status);
  3742. }
  3743. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3744. SSLClient cli(REDIR_HOST);
  3745. cli.set_follow_location(true);
  3746. Params params;
  3747. params.emplace("url", "http://example.com");
  3748. params.emplace("status_code", "302");
  3749. auto res = retry_service_failures(
  3750. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3751. SKIP_ON_SERVICE_FAILURE(res);
  3752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3753. EXPECT_EQ(StatusCode::OK_200, res->status);
  3754. }
  3755. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3756. SSLClient cli(REDIR_HOST);
  3757. cli.set_follow_location(true);
  3758. Params params;
  3759. params.emplace("url", "http://example.com");
  3760. auto res = retry_service_failures([&] {
  3761. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3762. });
  3763. SKIP_ON_SERVICE_FAILURE(res);
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ(StatusCode::OK_200, res->status);
  3766. }
  3767. TEST(UrlWithSpace, Redirect_Online) {
  3768. SSLClient cli("edge.forgecdn.net");
  3769. cli.set_follow_location(true);
  3770. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3772. EXPECT_EQ(StatusCode::OK_200, res->status);
  3773. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3774. }
  3775. #endif
  3776. #if !defined(_WIN32) && !defined(_WIN64)
  3777. TEST(ReceiveSignals, Signal) {
  3778. auto setupSignalHandlers = []() {
  3779. struct sigaction act;
  3780. sigemptyset(&act.sa_mask);
  3781. act.sa_flags = SA_SIGINFO;
  3782. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3783. switch (sig) {
  3784. case SIGINT:
  3785. default: break;
  3786. }
  3787. };
  3788. ::sigaction(SIGINT, &act, nullptr);
  3789. };
  3790. Server svr;
  3791. int port = 0;
  3792. auto thread = std::thread([&]() {
  3793. setupSignalHandlers();
  3794. port = svr.bind_to_any_port(HOST);
  3795. svr.listen_after_bind();
  3796. });
  3797. auto se = detail::scope_exit([&] {
  3798. svr.stop();
  3799. thread.join();
  3800. ASSERT_FALSE(svr.is_running());
  3801. });
  3802. svr.wait_until_ready();
  3803. ASSERT_TRUE(svr.is_running());
  3804. pthread_kill(thread.native_handle(), SIGINT);
  3805. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3806. ASSERT_TRUE(svr.is_running());
  3807. }
  3808. #endif
  3809. TEST(RedirectToDifferentPort, Redirect) {
  3810. Server svr1;
  3811. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3812. res.set_content("Hello World!", "text/plain");
  3813. });
  3814. int svr1_port = 0;
  3815. auto thread1 = std::thread([&]() {
  3816. svr1_port = svr1.bind_to_any_port(HOST);
  3817. svr1.listen_after_bind();
  3818. });
  3819. Server svr2;
  3820. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3821. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3822. });
  3823. int svr2_port = 0;
  3824. auto thread2 = std::thread([&]() {
  3825. svr2_port = svr2.bind_to_any_port(HOST);
  3826. svr2.listen_after_bind();
  3827. });
  3828. auto se = detail::scope_exit([&] {
  3829. svr2.stop();
  3830. thread2.join();
  3831. svr1.stop();
  3832. thread1.join();
  3833. ASSERT_FALSE(svr2.is_running());
  3834. ASSERT_FALSE(svr1.is_running());
  3835. });
  3836. svr1.wait_until_ready();
  3837. svr2.wait_until_ready();
  3838. Client cli("localhost", svr2_port);
  3839. cli.set_follow_location(true);
  3840. auto res = cli.Get("/2");
  3841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3842. EXPECT_EQ(StatusCode::OK_200, res->status);
  3843. EXPECT_EQ("Hello World!", res->body);
  3844. }
  3845. // GET /redir on one server redirects to /target on another port, so the
  3846. // client follows it with a new client.
  3847. static Result
  3848. GetThroughRedirectToDifferentPort(Server::Handler target,
  3849. const std::function<void(Client &)> &setup,
  3850. const Headers &headers = Headers()) {
  3851. Server target_svr;
  3852. target_svr.Get("/target", target);
  3853. int target_port = 0;
  3854. auto target_thread = std::thread([&]() {
  3855. target_port = target_svr.bind_to_any_port(HOST);
  3856. target_svr.listen_after_bind();
  3857. });
  3858. Server origin_svr;
  3859. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3860. res.set_redirect(
  3861. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3862. });
  3863. int origin_port = 0;
  3864. auto origin_thread = std::thread([&]() {
  3865. origin_port = origin_svr.bind_to_any_port(HOST);
  3866. origin_svr.listen_after_bind();
  3867. });
  3868. auto se = detail::scope_exit([&] {
  3869. origin_svr.stop();
  3870. origin_thread.join();
  3871. target_svr.stop();
  3872. target_thread.join();
  3873. });
  3874. target_svr.wait_until_ready();
  3875. origin_svr.wait_until_ready();
  3876. Client cli("localhost", origin_port);
  3877. cli.set_follow_location(true);
  3878. setup(cli);
  3879. return cli.Get("/redir", headers);
  3880. }
  3881. static void
  3882. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3883. std::string captured_authorization;
  3884. auto result = GetThroughRedirectToDifferentPort(
  3885. [&](const Request &req, Response &res) {
  3886. captured_authorization = req.get_header_value("Authorization");
  3887. res.set_content("OK", "text/plain");
  3888. },
  3889. set_auth);
  3890. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3891. EXPECT_EQ(StatusCode::OK_200, result->status);
  3892. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3893. EXPECT_TRUE(captured_authorization.empty());
  3894. }
  3895. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3896. TestDoNotForwardCredentialsOnRedirect(
  3897. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3898. }
  3899. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3900. TestDoNotForwardCredentialsOnRedirect(
  3901. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3902. }
  3903. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3904. std::string captured_cookie;
  3905. auto result = GetThroughRedirectToDifferentPort(
  3906. [&](const Request &req, Response &res) {
  3907. captured_cookie = req.get_header_value("Cookie");
  3908. res.set_content("OK", "text/plain");
  3909. },
  3910. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3911. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3912. EXPECT_EQ(StatusCode::OK_200, result->status);
  3913. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3914. EXPECT_TRUE(captured_cookie.empty());
  3915. }
  3916. TEST(RedirectToSamePort, ForwardCookie) {
  3917. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3918. // header so that ordinary session flows keep working.
  3919. Server svr;
  3920. std::string captured_cookie;
  3921. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3922. res.set_redirect("/target", 302);
  3923. });
  3924. svr.Get("/target", [&](const Request &req, Response &res) {
  3925. captured_cookie = req.get_header_value("Cookie");
  3926. res.set_content("OK", "text/plain");
  3927. });
  3928. auto port = svr.bind_to_any_port(HOST);
  3929. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3930. auto se = detail::scope_exit([&] {
  3931. svr.stop();
  3932. thread.join();
  3933. ASSERT_FALSE(svr.is_running());
  3934. });
  3935. svr.wait_until_ready();
  3936. Client cli(HOST, port);
  3937. cli.set_follow_location(true);
  3938. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3939. auto res = cli.Get("/redir", headers);
  3940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3941. EXPECT_EQ(StatusCode::OK_200, res->status);
  3942. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3943. }
  3944. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3945. // The Location alone names the next target, on any origin.
  3946. Server target_svr;
  3947. std::string cross_target;
  3948. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3949. cross_target = req.target;
  3950. res.set_content("OK", "text/plain");
  3951. });
  3952. auto target_port = target_svr.bind_to_any_port(HOST);
  3953. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3954. Server origin_svr;
  3955. std::string same_target;
  3956. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3957. res.set_redirect(
  3958. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3959. });
  3960. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3961. res.set_redirect("/landing", 302);
  3962. });
  3963. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3964. same_target = req.target;
  3965. res.set_content("OK", "text/plain");
  3966. });
  3967. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3968. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3969. auto se = detail::scope_exit([&] {
  3970. origin_svr.stop();
  3971. origin_thread.join();
  3972. target_svr.stop();
  3973. target_thread.join();
  3974. });
  3975. target_svr.wait_until_ready();
  3976. origin_svr.wait_until_ready();
  3977. Client cli("localhost", origin_port);
  3978. cli.set_follow_location(true);
  3979. Request req;
  3980. req.method = "GET";
  3981. req.params = {{"api_key", "SECRET"}};
  3982. req.path = "/cross";
  3983. auto res = cli.send(req);
  3984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3985. EXPECT_EQ("/landing", cross_target);
  3986. req.path = "/same";
  3987. res = cli.send(req);
  3988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3989. EXPECT_EQ("/landing", same_target);
  3990. }
  3991. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3992. std::string authorization;
  3993. std::string trace_id;
  3994. auto result = GetThroughRedirectToDifferentPort(
  3995. [&](const Request &req, Response &res) {
  3996. authorization = req.get_header_value("Authorization");
  3997. trace_id = req.get_header_value("X-Trace-Id");
  3998. res.set_content("OK", "text/plain");
  3999. },
  4000. [](Client &cli) {
  4001. cli.set_default_headers(
  4002. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  4003. });
  4004. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4005. EXPECT_EQ(StatusCode::OK_200, result->status);
  4006. // Like a header given with the request, a default one goes along unless it
  4007. // carries credentials (RFC 9110 15.4).
  4008. EXPECT_TRUE(authorization.empty());
  4009. EXPECT_EQ("42", trace_id);
  4010. }
  4011. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4012. auto result = GetThroughRedirectToDifferentPort(
  4013. [](const Request &, Response &res) {
  4014. res.set_content(std::string(2048, 'x'), "text/plain");
  4015. },
  4016. [](Client &cli) { cli.set_payload_max_length(1024); });
  4017. EXPECT_FALSE(result);
  4018. }
  4019. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4020. auto result = GetThroughRedirectToDifferentPort(
  4021. [](const Request &req, Response &res) {
  4022. // Answer after a second, or once the client gives up.
  4023. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4024. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4025. }
  4026. res.set_content("late", "text/plain");
  4027. },
  4028. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4029. ASSERT_FALSE(result);
  4030. EXPECT_EQ(Error::Read, result.error());
  4031. }
  4032. #ifdef CPPHTTPLIB_SSL_ENABLED
  4033. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4034. auto result = GetThroughRedirectToDifferentPort(
  4035. [](const Request &, Response &res) {
  4036. res.status = StatusCode::Unauthorized_401;
  4037. res.set_header("WWW-Authenticate",
  4038. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4039. },
  4040. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4041. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4042. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4043. }
  4044. #endif
  4045. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4046. Server svr;
  4047. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4048. // Port number that overflows int — should not crash
  4049. res.set_redirect("http://localhost:99999999999999999999/target");
  4050. });
  4051. auto port = svr.bind_to_any_port(HOST);
  4052. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4053. auto se = detail::scope_exit([&] {
  4054. svr.stop();
  4055. thread.join();
  4056. ASSERT_FALSE(svr.is_running());
  4057. });
  4058. svr.wait_until_ready();
  4059. Client cli(HOST, port);
  4060. cli.set_follow_location(true);
  4061. auto res = cli.Get("/redir");
  4062. // Should fail gracefully, not crash (no valid response due to bad port)
  4063. EXPECT_FALSE(res);
  4064. }
  4065. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4066. Server svr;
  4067. auto port = svr.bind_to_any_port(HOST);
  4068. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4069. // The server's own port followed by junk must not be followed
  4070. res.set_redirect("http://" + std::string(HOST) + ":" +
  4071. std::to_string(port) + "junk/target");
  4072. });
  4073. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4074. res.set_content("target", "text/plain");
  4075. });
  4076. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4077. auto se = detail::scope_exit([&] {
  4078. svr.stop();
  4079. thread.join();
  4080. ASSERT_FALSE(svr.is_running());
  4081. });
  4082. svr.wait_until_ready();
  4083. Client cli(HOST, port);
  4084. cli.set_follow_location(true);
  4085. auto res = cli.Get("/redir");
  4086. EXPECT_FALSE(res);
  4087. }
  4088. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4089. Server target_svr;
  4090. std::atomic<int> target_hits{0};
  4091. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4092. target_hits++;
  4093. res.set_content("target", "text/plain");
  4094. });
  4095. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4096. res.set_content("target", "text/plain");
  4097. });
  4098. int target_port = 0;
  4099. auto target_thread = std::thread([&]() {
  4100. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4101. target_svr.listen_after_bind();
  4102. });
  4103. Server origin_svr;
  4104. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4105. res.set_redirect(req.get_param_value("to"));
  4106. });
  4107. int origin_port = 0;
  4108. auto origin_thread = std::thread([&]() {
  4109. origin_port = origin_svr.bind_to_any_port(HOST);
  4110. origin_svr.listen_after_bind();
  4111. });
  4112. auto se = detail::scope_exit([&] {
  4113. origin_svr.stop();
  4114. origin_thread.join();
  4115. target_svr.stop();
  4116. target_thread.join();
  4117. ASSERT_FALSE(origin_svr.is_running());
  4118. ASSERT_FALSE(target_svr.is_running());
  4119. });
  4120. target_svr.wait_until_ready();
  4121. origin_svr.wait_until_ready();
  4122. auto port = std::to_string(target_port);
  4123. for (const auto &to :
  4124. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4125. Client cli(HOST, origin_port);
  4126. cli.set_follow_location(true);
  4127. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4128. EXPECT_FALSE(res) << to;
  4129. }
  4130. EXPECT_EQ(0, target_hits);
  4131. Client cli(HOST, origin_port);
  4132. cli.set_follow_location(true);
  4133. auto res = cli.Get("/redir?to=" +
  4134. encode_query_component("//127.0.0.1:" + port + "/target"));
  4135. ASSERT_TRUE(res) << to_string(res.error());
  4136. EXPECT_EQ(StatusCode::OK_200, res->status);
  4137. EXPECT_EQ("target", res->body);
  4138. }
  4139. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4140. Server svr;
  4141. std::atomic<bool> followed{false};
  4142. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4143. res.status = StatusCode::NotModified_304;
  4144. res.set_header("Location", "/target");
  4145. });
  4146. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4147. res.status = StatusCode::UseProxy_305;
  4148. res.set_header("Location", "/target");
  4149. });
  4150. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4151. followed = true;
  4152. res.set_content("target", "text/plain");
  4153. });
  4154. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4155. auto se = detail::scope_exit([&] {
  4156. svr.stop();
  4157. th.join();
  4158. ASSERT_FALSE(svr.is_running());
  4159. });
  4160. svr.wait_until_ready();
  4161. Client cli("localhost", PORT);
  4162. cli.set_follow_location(true);
  4163. auto res = cli.Get("/304");
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4166. res = cli.Get("/305");
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4169. EXPECT_FALSE(followed);
  4170. }
  4171. TEST(RedirectFromPageWithContent, Redirect) {
  4172. Server svr;
  4173. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4174. res.set_content("___", "text/plain");
  4175. res.set_redirect("/2");
  4176. });
  4177. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4178. res.set_content("Hello World!", "text/plain");
  4179. });
  4180. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4181. auto se = detail::scope_exit([&] {
  4182. svr.stop();
  4183. th.join();
  4184. ASSERT_FALSE(svr.is_running());
  4185. });
  4186. svr.wait_until_ready();
  4187. {
  4188. Client cli("localhost", PORT);
  4189. cli.set_follow_location(true);
  4190. std::string body;
  4191. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4192. body.append(data, data_length);
  4193. return true;
  4194. });
  4195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4196. EXPECT_EQ(StatusCode::OK_200, res->status);
  4197. EXPECT_EQ("Hello World!", body);
  4198. }
  4199. {
  4200. Client cli("localhost", PORT);
  4201. std::string body;
  4202. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4203. body.append(data, data_length);
  4204. return true;
  4205. });
  4206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4207. EXPECT_EQ(StatusCode::Found_302, res->status);
  4208. EXPECT_EQ("___", body);
  4209. }
  4210. }
  4211. // A server can close the connection after a request with "Connection: close"
  4212. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4213. // redirected request must go out on a new connection.
  4214. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4215. #ifndef _WIN32
  4216. signal(SIGPIPE, SIG_IGN);
  4217. #endif
  4218. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4219. default_socket_options(srv);
  4220. sockaddr_in addr{};
  4221. addr.sin_family = AF_INET;
  4222. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4223. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4224. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4225. ASSERT_EQ(0, ::listen(srv, 2));
  4226. auto send_text = [](socket_t sock, const std::string &text) {
  4227. ::send(sock,
  4228. #ifdef _WIN32
  4229. static_cast<const char *>(text.c_str()),
  4230. static_cast<int>(text.size()),
  4231. #else
  4232. text.c_str(), text.size(),
  4233. #endif
  4234. 0);
  4235. };
  4236. auto reused = false;
  4237. auto server_thread = std::thread([&] {
  4238. char buf[4096];
  4239. auto first = ::accept(srv, nullptr, nullptr);
  4240. if (first == INVALID_SOCKET) { return; }
  4241. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4242. ::recv(first, buf, sizeof(buf), 0);
  4243. send_text(
  4244. first,
  4245. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4246. auto next = first;
  4247. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4248. reused = true;
  4249. } else {
  4250. detail::close_socket(first);
  4251. next = ::accept(srv, nullptr, nullptr);
  4252. if (next == INVALID_SOCKET) { return; }
  4253. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4254. ::recv(next, buf, sizeof(buf), 0);
  4255. }
  4256. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4257. "Connection: close\r\n\r\nok");
  4258. detail::close_socket(next);
  4259. });
  4260. Client cli("127.0.0.1", PORT + 2);
  4261. cli.set_follow_location(true);
  4262. cli.set_read_timeout(5, 0);
  4263. auto res = cli.Get("/1");
  4264. server_thread.join();
  4265. detail::close_socket(srv);
  4266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4267. EXPECT_EQ(StatusCode::OK_200, res->status);
  4268. EXPECT_EQ("ok", res->body);
  4269. EXPECT_FALSE(reused);
  4270. }
  4271. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4272. Server svr;
  4273. auto port_str = std::to_string(PORT);
  4274. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4275. auto expected_host = "[::1]:" + port_str;
  4276. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4277. res.set_content("___", "text/plain");
  4278. // res.set_redirect("/2");
  4279. res.set_redirect(redirect_url);
  4280. });
  4281. svr.Get("/2", [&](const Request &req, Response &res) {
  4282. auto host_header = req.headers.find("Host");
  4283. ASSERT_TRUE(host_header != req.headers.end());
  4284. EXPECT_EQ(expected_host, host_header->second);
  4285. res.set_content("Hello World!", "text/plain");
  4286. });
  4287. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4288. auto se = detail::scope_exit([&] {
  4289. svr.stop();
  4290. th.join();
  4291. ASSERT_FALSE(svr.is_running());
  4292. });
  4293. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4294. // actually starts anything, so the condition !svr.is_running() will
  4295. // always remain true, and the loop never stops.
  4296. // This basically counts how many milliseconds have passed since the
  4297. // call to svr.listen(), and if after 5 seconds nothing started yet
  4298. // aborts the test.
  4299. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4300. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4301. ASSERT_LT(milliseconds, 5000U);
  4302. }
  4303. {
  4304. Client cli("::1", PORT);
  4305. cli.set_follow_location(true);
  4306. std::string body;
  4307. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4308. body.append(data, data_length);
  4309. return true;
  4310. });
  4311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4312. EXPECT_EQ(StatusCode::OK_200, res->status);
  4313. EXPECT_EQ("Hello World!", body);
  4314. }
  4315. {
  4316. Client cli("::1", PORT);
  4317. std::string body;
  4318. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4319. body.append(data, data_length);
  4320. return true;
  4321. });
  4322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4323. EXPECT_EQ(StatusCode::Found_302, res->status);
  4324. EXPECT_EQ("___", body);
  4325. }
  4326. }
  4327. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4328. Server svr;
  4329. svr.Get("/foo", [](const Request &req, Response &res) {
  4330. auto a = req.params.find("a");
  4331. if (a != req.params.end()) {
  4332. res.set_content((*a).second, "text/plain");
  4333. res.status = StatusCode::OK_200;
  4334. } else {
  4335. res.status = StatusCode::BadRequest_400;
  4336. }
  4337. });
  4338. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4339. auto se = detail::scope_exit([&] {
  4340. svr.stop();
  4341. thread.join();
  4342. ASSERT_FALSE(svr.is_running());
  4343. });
  4344. svr.wait_until_ready();
  4345. {
  4346. Client cli(HOST, PORT);
  4347. cli.set_path_encode(false);
  4348. auto res = cli.Get("/foo?a=explicitly+encoded");
  4349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4350. EXPECT_EQ(StatusCode::OK_200, res->status);
  4351. // This expects it back with a space, as the `+` won't have been
  4352. // url-encoded, and server-side the params get decoded turning `+`
  4353. // into spaces.
  4354. EXPECT_EQ("explicitly encoded", res->body);
  4355. }
  4356. }
  4357. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4358. // When path encoding is disabled the client must transmit the supplied
  4359. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4360. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4361. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4362. // than a space (0x20). Assert on the raw wire target to catch this.
  4363. Server svr;
  4364. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4365. svr.Get("/foo", [&](const Request &req, Response &res) {
  4366. EXPECT_EQ(expected_target, req.target);
  4367. res.status = StatusCode::OK_200;
  4368. });
  4369. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4370. auto se = detail::scope_exit([&] {
  4371. svr.stop();
  4372. thread.join();
  4373. ASSERT_FALSE(svr.is_running());
  4374. });
  4375. svr.wait_until_ready();
  4376. {
  4377. Client cli(HOST, PORT);
  4378. cli.set_path_encode(false);
  4379. auto res = cli.Get(expected_target.c_str());
  4380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4381. EXPECT_EQ(StatusCode::OK_200, res->status);
  4382. }
  4383. }
  4384. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4385. // `open_stream()` used to skip the path encoding that the buffered send
  4386. // path applies, so the same `path` produced different bytes in the request
  4387. // line depending on which API was used. Assert the two agree.
  4388. Server svr;
  4389. std::string target;
  4390. svr.Get(".*", [&](const Request &req, Response &res) {
  4391. target = req.target;
  4392. res.status = StatusCode::OK_200;
  4393. });
  4394. auto port = svr.bind_to_any_port(HOST);
  4395. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4396. auto se = detail::scope_exit([&] {
  4397. svr.stop();
  4398. thread.join();
  4399. ASSERT_FALSE(svr.is_running());
  4400. });
  4401. svr.wait_until_ready();
  4402. struct {
  4403. const char *path;
  4404. const char *expected;
  4405. } cases[] = {
  4406. {"/a b?x=1", "/a%20b?x=1"},
  4407. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4408. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4409. };
  4410. for (const auto &c : cases) {
  4411. Client cli(HOST, port);
  4412. target.clear();
  4413. auto res = cli.Get(c.path);
  4414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4415. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4416. auto buffered_target = target;
  4417. target.clear();
  4418. auto handle = cli.open_stream("GET", c.path);
  4419. EXPECT_TRUE(handle.is_valid())
  4420. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4421. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4422. }
  4423. }
  4424. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4425. // The `set_path_encode(false)` contract — transmit the supplied target
  4426. // verbatim — must hold for the streaming API too.
  4427. Server svr;
  4428. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4429. std::string target;
  4430. svr.Get("/foo", [&](const Request &req, Response &res) {
  4431. target = req.target;
  4432. res.status = StatusCode::OK_200;
  4433. });
  4434. auto port = svr.bind_to_any_port(HOST);
  4435. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4436. auto se = detail::scope_exit([&] {
  4437. svr.stop();
  4438. thread.join();
  4439. ASSERT_FALSE(svr.is_running());
  4440. });
  4441. svr.wait_until_ready();
  4442. {
  4443. Client cli(HOST, port);
  4444. cli.set_path_encode(false);
  4445. auto handle = cli.open_stream("GET", expected_target);
  4446. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4447. EXPECT_EQ(expected_target, target);
  4448. }
  4449. }
  4450. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4451. // With path encoding enabled a CR/LF in the target is percent-encoded
  4452. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4453. // write_request_line still backstops `set_path_encode(false)`, which is
  4454. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4455. Server svr;
  4456. // Captured before routing: the decoded path contains a newline, which a
  4457. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4458. std::string target;
  4459. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4460. target = req.target;
  4461. res.status = StatusCode::OK_200;
  4462. return Server::HandlerResponse::Handled;
  4463. });
  4464. auto port = svr.bind_to_any_port(HOST);
  4465. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4466. auto se = detail::scope_exit([&] {
  4467. svr.stop();
  4468. thread.join();
  4469. ASSERT_FALSE(svr.is_running());
  4470. });
  4471. svr.wait_until_ready();
  4472. {
  4473. Client cli(HOST, port);
  4474. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4475. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4476. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4477. }
  4478. }
  4479. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4480. // Every control character is percent-encoded, not just CR/LF, so the target
  4481. // passes the request-target check in write_request_line.
  4482. Server svr;
  4483. std::string target;
  4484. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4485. target = req.target;
  4486. res.status = StatusCode::OK_200;
  4487. return Server::HandlerResponse::Handled;
  4488. });
  4489. auto port = svr.bind_to_any_port(HOST);
  4490. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4491. auto se = detail::scope_exit([&] {
  4492. svr.stop();
  4493. thread.join();
  4494. ASSERT_FALSE(svr.is_running());
  4495. });
  4496. svr.wait_until_ready();
  4497. {
  4498. Client cli(HOST, port);
  4499. auto res = cli.Get("/a\tb\x1b\x7f");
  4500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4501. EXPECT_EQ("/a%09b%1B%7F", target);
  4502. }
  4503. }
  4504. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4505. // Nothing may reach the wire: a raw CR/LF target would split the request
  4506. // line and inject headers.
  4507. Server svr;
  4508. // Pre-routing so that "not called" means nothing reached the server at all,
  4509. // rather than merely failing to match a handler pattern.
  4510. auto handler_called = false;
  4511. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4512. handler_called = true;
  4513. res.status = StatusCode::OK_200;
  4514. return Server::HandlerResponse::Handled;
  4515. });
  4516. auto port = svr.bind_to_any_port(HOST);
  4517. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4518. auto se = detail::scope_exit([&] {
  4519. svr.stop();
  4520. thread.join();
  4521. ASSERT_FALSE(svr.is_running());
  4522. });
  4523. svr.wait_until_ready();
  4524. {
  4525. Client cli(HOST, port);
  4526. cli.set_path_encode(false);
  4527. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4528. EXPECT_FALSE(handle.is_valid());
  4529. EXPECT_EQ(Error::Write, handle.error);
  4530. EXPECT_FALSE(handler_called);
  4531. }
  4532. }
  4533. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4534. // Which of the two branches runs is decided by whether the query component
  4535. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4536. // an empty query and must still fall back to building one from
  4537. // `req.params`, while a non-empty query must win over `req.params`.
  4538. Server svr;
  4539. std::string target;
  4540. svr.Get("/foo", [&](const Request &req, Response &res) {
  4541. target = req.target;
  4542. res.status = StatusCode::OK_200;
  4543. });
  4544. auto port = svr.bind_to_any_port(HOST);
  4545. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4546. auto se = detail::scope_exit([&] {
  4547. svr.stop();
  4548. thread.join();
  4549. ASSERT_FALSE(svr.is_running());
  4550. });
  4551. svr.wait_until_ready();
  4552. {
  4553. // Trailing `?` -> empty query component -> `req.params` is used.
  4554. Client cli(HOST, port);
  4555. Request req;
  4556. req.method = "GET";
  4557. req.path = "/foo?";
  4558. req.params.emplace("a", "1");
  4559. target.clear();
  4560. auto res = cli.send(req);
  4561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4562. EXPECT_EQ("/foo?a=1", target);
  4563. }
  4564. {
  4565. // Non-empty query in `req.path` -> `req.params` is not appended.
  4566. Client cli(HOST, port);
  4567. Request req;
  4568. req.method = "GET";
  4569. req.path = "/foo?b=2";
  4570. req.params.emplace("a", "1");
  4571. target.clear();
  4572. auto res = cli.send(req);
  4573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4574. EXPECT_EQ("/foo?b=2", target);
  4575. }
  4576. }
  4577. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4578. Server svr;
  4579. svr.Get("/", [](const Request &req, Response &) {
  4580. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4581. });
  4582. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4583. auto se = detail::scope_exit([&] {
  4584. svr.stop();
  4585. thread.join();
  4586. ASSERT_FALSE(svr.is_running());
  4587. });
  4588. svr.wait_until_ready();
  4589. {
  4590. Client cli(HOST, PORT);
  4591. cli.set_path_encode(false);
  4592. auto res = cli.Get("/?something=%0A");
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. }
  4596. }
  4597. TEST(BindServerTest, BindDualStack) {
  4598. Server svr;
  4599. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4600. res.set_content("Hello World!", "text/plain");
  4601. });
  4602. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4603. auto se = detail::scope_exit([&] {
  4604. svr.stop();
  4605. thread.join();
  4606. ASSERT_FALSE(svr.is_running());
  4607. });
  4608. svr.wait_until_ready();
  4609. {
  4610. Client cli("127.0.0.1", PORT);
  4611. auto res = cli.Get("/1");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("Hello World!", res->body);
  4615. }
  4616. {
  4617. Client cli("::1", PORT);
  4618. auto res = cli.Get("/1");
  4619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4620. EXPECT_EQ(StatusCode::OK_200, res->status);
  4621. EXPECT_EQ("Hello World!", res->body);
  4622. }
  4623. }
  4624. TEST(BindServerTest, BindAndListenSeparately) {
  4625. Server svr;
  4626. int port = svr.bind_to_any_port("0.0.0.0");
  4627. ASSERT_TRUE(svr.is_valid());
  4628. ASSERT_TRUE(port > 0);
  4629. svr.stop();
  4630. }
  4631. // Reports whether anything is still listening on a loopback port. A plain
  4632. // connect() is used instead of a Client request because a socket left bound by
  4633. // mistake accepts the connection into its backlog and never answers, which
  4634. // would hang the test instead of failing it.
  4635. static bool is_loopback_port_accepting(int port) {
  4636. sockaddr_in addr{};
  4637. addr.sin_family = AF_INET;
  4638. addr.sin_port = htons(static_cast<uint16_t>(port));
  4639. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4640. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4641. EXPECT_NE(sock, INVALID_SOCKET);
  4642. if (sock == INVALID_SOCKET) { return false; }
  4643. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4644. static_cast<socklen_t>(sizeof(addr)));
  4645. detail::close_socket(sock);
  4646. return ret == 0;
  4647. }
  4648. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4649. Server svr;
  4650. auto port = svr.bind_to_any_port("127.0.0.1");
  4651. ASSERT_TRUE(port > 0);
  4652. svr.stop();
  4653. // bind_to_any_port() already called listen(2), so until stop() closed the
  4654. // descriptor the port kept accepting connections into the backlog. ASSERT
  4655. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4656. // below blocks forever in the accept loop.
  4657. ASSERT_FALSE(is_loopback_port_accepting(port));
  4658. // Nothing is left to accept on, so listen_after_bind() must report failure
  4659. // instead of returning success without ever serving.
  4660. EXPECT_FALSE(svr.listen_after_bind());
  4661. // The failed listen marks the server decommissioned, so a waiter returns
  4662. // instead of spinning forever.
  4663. svr.wait_until_ready();
  4664. }
  4665. #ifdef CPPHTTPLIB_SSL_ENABLED
  4666. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4667. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4668. CLIENT_CA_CERT_DIR);
  4669. int port = svr.bind_to_any_port("0.0.0.0");
  4670. ASSERT_TRUE(svr.is_valid());
  4671. ASSERT_TRUE(port > 0);
  4672. svr.stop();
  4673. }
  4674. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4675. // or a rejected CustomRoute() registration would not stop the server binding.
  4676. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4677. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4678. CLIENT_CA_CERT_DIR);
  4679. ASSERT_TRUE(svr.is_valid());
  4680. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4681. EXPECT_FALSE(svr.is_valid());
  4682. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4683. }
  4684. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4685. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4686. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4687. int port = svr.bind_to_any_port("0.0.0.0");
  4688. ASSERT_TRUE(svr.is_valid());
  4689. ASSERT_TRUE(port > 0);
  4690. svr.stop();
  4691. }
  4692. TEST(BindServerTest, UpdateCertsPem) {
  4693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4694. int port = svr.bind_to_any_port("0.0.0.0");
  4695. ASSERT_TRUE(svr.is_valid());
  4696. ASSERT_TRUE(port > 0);
  4697. // Read PEM files
  4698. std::string cert_pem, key_pem, ca_pem;
  4699. read_file(SERVER_CERT_FILE, cert_pem);
  4700. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4701. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4702. // Update server certificates using PEM API
  4703. ASSERT_TRUE(
  4704. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4705. ASSERT_TRUE(svr.is_valid());
  4706. svr.stop();
  4707. }
  4708. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4709. // Start server with client CA (enables client auth)
  4710. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4711. ASSERT_TRUE(svr.is_valid());
  4712. bool handler_called = false;
  4713. svr.Get("/test", [&](const Request &req, Response &res) {
  4714. handler_called = true;
  4715. // Verify client certificate is present
  4716. auto cert = req.peer_cert();
  4717. EXPECT_TRUE(static_cast<bool>(cert));
  4718. res.set_content("ok", "text/plain");
  4719. });
  4720. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4721. auto se = detail::scope_exit([&] {
  4722. svr.stop();
  4723. t.join();
  4724. ASSERT_FALSE(svr.is_running());
  4725. });
  4726. svr.wait_until_ready();
  4727. // Read PEM files
  4728. std::string cert_pem, key_pem, ca_pem;
  4729. read_file(SERVER_CERT_FILE, cert_pem);
  4730. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4731. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4732. // Update server certificates and client CA using PEM API while server running
  4733. ASSERT_TRUE(
  4734. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4735. // Connect with client certificate
  4736. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4737. cli.enable_server_certificate_verification(false);
  4738. cli.set_connection_timeout(30);
  4739. auto res = cli.Get("/test");
  4740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4741. ASSERT_EQ(StatusCode::OK_200, res->status);
  4742. ASSERT_TRUE(handler_called);
  4743. EXPECT_EQ("ok", res->body);
  4744. }
  4745. // Puts a CA that did not sign the client's certificate in the old one's place.
  4746. static bool replace_client_ca(SSLServer &svr) {
  4747. std::string cert_pem, key_pem, ca_pem;
  4748. read_file(SERVER_CERT_FILE, cert_pem);
  4749. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4750. read_file(SERVER_CERT2_FILE, ca_pem);
  4751. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4752. ca_pem.c_str());
  4753. }
  4754. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4756. ASSERT_TRUE(svr.is_valid());
  4757. svr.Get("/test", [](const Request &, Response &res) {
  4758. res.set_content("ok", "text/plain");
  4759. });
  4760. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4761. auto se = detail::scope_exit([&] {
  4762. svr.stop();
  4763. t.join();
  4764. ASSERT_FALSE(svr.is_running());
  4765. });
  4766. svr.wait_until_ready();
  4767. auto get = [] {
  4768. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4769. cli.enable_server_certificate_verification(false);
  4770. return cli.Get("/test");
  4771. };
  4772. ASSERT_TRUE(get());
  4773. ASSERT_TRUE(replace_client_ca(svr));
  4774. EXPECT_FALSE(get());
  4775. }
  4776. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4777. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4779. ASSERT_TRUE(svr.is_valid());
  4780. tls::set_verify_callback(svr.tls_context(),
  4781. [](const tls::VerifyContext &) -> bool {
  4782. throw std::runtime_error("verify");
  4783. });
  4784. svr.Get("/test", [](const Request &, Response &res) {
  4785. res.set_content("ok", "text/plain");
  4786. });
  4787. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4788. auto se = detail::scope_exit([&] {
  4789. svr.stop();
  4790. t.join();
  4791. ASSERT_FALSE(svr.is_running());
  4792. });
  4793. svr.wait_until_ready();
  4794. auto get = [] {
  4795. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4796. cli.enable_server_certificate_verification(false);
  4797. return cli.Get("/test");
  4798. };
  4799. EXPECT_FALSE(get());
  4800. // The handshake is over, so an update does not wait for it.
  4801. std::string cert_pem, key_pem;
  4802. read_file(SERVER_CERT_FILE, cert_pem);
  4803. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4804. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4805. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4806. return v.preverify_ok;
  4807. });
  4808. auto res = get();
  4809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4810. EXPECT_EQ("ok", res->body);
  4811. }
  4812. #endif
  4813. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4814. // Sends each request over a new connection with a client certificate,
  4815. // resuming the session of the one before when there is one.
  4816. class ResumingClient {
  4817. public:
  4818. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4819. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4820. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4821. SSL_FILETYPE_PEM);
  4822. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4823. // callback, not through SSL_get1_session().
  4824. SSL_CTX_set_app_data(ctx_, this);
  4825. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4826. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4827. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4828. auto self = static_cast<ResumingClient *>(
  4829. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4830. SSL_SESSION_free(self->session_);
  4831. self->session_ = session;
  4832. return 1; // Keeps the reference
  4833. });
  4834. }
  4835. ~ResumingClient() {
  4836. SSL_SESSION_free(session_);
  4837. SSL_CTX_free(ctx_);
  4838. }
  4839. // Tells whether the request was answered.
  4840. bool get() {
  4841. auto error = Error::Success;
  4842. auto sock = detail::create_client_socket(
  4843. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4844. /*connection_timeout_sec=*/5, 0,
  4845. /*read_timeout_sec=*/5, 0,
  4846. /*write_timeout_sec=*/5, 0, std::string(), error);
  4847. if (sock == INVALID_SOCKET) { return false; }
  4848. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4849. auto ssl = SSL_new(ctx_);
  4850. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4851. SSL_set_fd(ssl, static_cast<int>(sock));
  4852. if (session_) { SSL_set_session(ssl, session_); }
  4853. if (SSL_connect(ssl) != 1) { return false; }
  4854. reused_ = SSL_session_reused(ssl) == 1;
  4855. // Reading the response also takes in a TLS 1.3 session ticket.
  4856. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4857. "Connection: close\r\n\r\n";
  4858. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4859. std::string res;
  4860. char buf[256];
  4861. int n;
  4862. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4863. res.append(buf, static_cast<size_t>(n));
  4864. }
  4865. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4866. SSL_shutdown(ssl);
  4867. return res.find("200 OK") != std::string::npos;
  4868. }
  4869. // Whether the last connection resumed a session
  4870. bool reused() const { return reused_; }
  4871. private:
  4872. SSL_CTX *ctx_;
  4873. SSL_SESSION *session_ = nullptr;
  4874. bool reused_ = false;
  4875. };
  4876. // A client that resumes its session gets through, but not once the client CA
  4877. // has changed, as a resumed session does not show the certificate again.
  4878. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4879. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4880. ASSERT_TRUE(svr.is_valid());
  4881. svr.Get("/test", [](const Request &, Response &res) {
  4882. res.set_content("ok", "text/plain");
  4883. });
  4884. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4885. auto se = detail::scope_exit([&] {
  4886. svr.stop();
  4887. t.join();
  4888. ASSERT_FALSE(svr.is_running());
  4889. });
  4890. svr.wait_until_ready();
  4891. ResumingClient cli;
  4892. ASSERT_TRUE(cli.get());
  4893. ASSERT_TRUE(cli.get());
  4894. EXPECT_TRUE(cli.reused());
  4895. ASSERT_TRUE(replace_client_ca(svr));
  4896. EXPECT_FALSE(cli.get());
  4897. }
  4898. // A resumed session does not show the certificate again, so the server does
  4899. // not resume one with a verify callback to run on it.
  4900. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4902. ASSERT_TRUE(svr.is_valid());
  4903. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4904. return v.preverify_ok;
  4905. });
  4906. svr.Get("/test", [](const Request &, Response &res) {
  4907. res.set_content("ok", "text/plain");
  4908. });
  4909. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4910. auto se = detail::scope_exit([&] {
  4911. svr.stop();
  4912. t.join();
  4913. ASSERT_FALSE(svr.is_running());
  4914. });
  4915. svr.wait_until_ready();
  4916. ResumingClient cli;
  4917. ASSERT_TRUE(cli.get());
  4918. ASSERT_TRUE(cli.get());
  4919. EXPECT_FALSE(cli.reused());
  4920. }
  4921. #endif
  4922. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4923. // wolfSSL shares its session cache between contexts, so a resumed session
  4924. // could carry a client certificate checked against another server's CA, or
  4925. // against a client CA since replaced.
  4926. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4928. ASSERT_TRUE(svr.is_valid());
  4929. // Trusts a CA that did not sign the client's certificate.
  4930. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4931. ASSERT_TRUE(other.is_valid());
  4932. for (auto s : {&svr, &other}) {
  4933. s->Get("/test", [](const Request &, Response &res) {
  4934. res.set_content("ok", "text/plain");
  4935. });
  4936. }
  4937. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4938. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4939. auto se = detail::scope_exit([&] {
  4940. other.stop();
  4941. svr.stop();
  4942. t2.join();
  4943. t.join();
  4944. });
  4945. svr.wait_until_ready();
  4946. other.wait_until_ready();
  4947. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4948. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4949. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4950. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4951. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4952. ASSERT_EQ(WOLFSSL_SUCCESS,
  4953. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4954. WOLFSSL_FILETYPE_PEM));
  4955. WOLFSSL_SESSION *session = nullptr;
  4956. auto session_se = detail::scope_exit([&] {
  4957. if (session) { wolfSSL_SESSION_free(session); }
  4958. });
  4959. // A request over a new connection, resuming `session` when there is one and
  4960. // keeping the connection's own in its place. Tells whether it was answered.
  4961. auto get = [&](int port) {
  4962. auto error = Error::Success;
  4963. auto sock = detail::create_client_socket(
  4964. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4965. /*connection_timeout_sec=*/5, 0,
  4966. /*read_timeout_sec=*/5, 0,
  4967. /*write_timeout_sec=*/5, 0, std::string(), error);
  4968. if (sock == INVALID_SOCKET) { return false; }
  4969. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4970. auto ssl = wolfSSL_new(ctx);
  4971. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4972. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4973. if (session) { wolfSSL_set_session(ssl, session); }
  4974. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4975. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4976. "Connection: close\r\n\r\n";
  4977. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4978. std::string res;
  4979. char buf[256];
  4980. int n;
  4981. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4982. res.append(buf, static_cast<size_t>(n));
  4983. }
  4984. wolfSSL_shutdown(ssl);
  4985. if (session) { wolfSSL_SESSION_free(session); }
  4986. session = wolfSSL_get1_session(ssl);
  4987. return res.find("200 OK") != std::string::npos;
  4988. };
  4989. ASSERT_TRUE(get(PORT));
  4990. EXPECT_FALSE(get(PORT + 1));
  4991. ASSERT_TRUE(get(PORT));
  4992. ASSERT_TRUE(replace_client_ca(svr));
  4993. EXPECT_FALSE(get(PORT));
  4994. }
  4995. #endif
  4996. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4997. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4998. ASSERT_TRUE(svr.is_valid());
  4999. // Keep-alive parking would wait for the ClientHello without a handshake.
  5000. svr.set_keep_alive_parking(false);
  5001. svr.Get("/test", [](const Request &, Response &res) {
  5002. res.set_content("ok", "text/plain");
  5003. });
  5004. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5005. auto se = detail::scope_exit([&] {
  5006. svr.stop();
  5007. t.join();
  5008. ASSERT_FALSE(svr.is_running());
  5009. });
  5010. svr.wait_until_ready();
  5011. // A connection that sends no ClientHello keeps its handshake in progress,
  5012. // once the server has had a moment to start it.
  5013. auto error = Error::Success;
  5014. auto sock = detail::create_client_socket(
  5015. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5016. /*connection_timeout_sec=*/5, 0,
  5017. /*read_timeout_sec=*/5, 0,
  5018. /*write_timeout_sec=*/5, 0, std::string(), error);
  5019. ASSERT_NE(INVALID_SOCKET, sock);
  5020. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5021. std::string cert_pem, key_pem;
  5022. read_file(SERVER_CERT_FILE, cert_pem);
  5023. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5024. auto update = std::async(std::launch::async, [&]() {
  5025. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5026. });
  5027. EXPECT_EQ(std::future_status::timeout,
  5028. update.wait_for(std::chrono::milliseconds(200)));
  5029. detail::close_socket(sock);
  5030. EXPECT_TRUE(update.get());
  5031. SSLClient cli(HOST, PORT);
  5032. cli.enable_server_certificate_verification(false);
  5033. auto res = cli.Get("/test");
  5034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5035. EXPECT_EQ(StatusCode::OK_200, res->status);
  5036. }
  5037. TEST(SSLClientServerTest, StopDoesNotWaitForHandshakeInProgress) {
  5038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5039. ASSERT_TRUE(svr.is_valid());
  5040. // Keep-alive parking would wait for the ClientHello without a handshake.
  5041. svr.set_keep_alive_parking(false);
  5042. svr.set_read_timeout(10, 0);
  5043. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5044. auto se = detail::scope_exit([&] {
  5045. svr.stop();
  5046. if (t.joinable()) { t.join(); }
  5047. });
  5048. svr.wait_until_ready();
  5049. // A connection that sends no ClientHello keeps its handshake in progress,
  5050. // once the server has had a moment to start it.
  5051. auto error = Error::Success;
  5052. auto sock = detail::create_client_socket(
  5053. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5054. /*connection_timeout_sec=*/5, 0,
  5055. /*read_timeout_sec=*/5, 0,
  5056. /*write_timeout_sec=*/5, 0, std::string(), error);
  5057. ASSERT_NE(INVALID_SOCKET, sock);
  5058. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  5059. auto start = std::chrono::steady_clock::now();
  5060. svr.stop();
  5061. t.join();
  5062. auto elapsed = std::chrono::steady_clock::now() - start;
  5063. detail::close_socket(sock);
  5064. EXPECT_LT(elapsed, std::chrono::seconds(3));
  5065. }
  5066. #endif
  5067. TEST(ErrorHandlerTest, ContentLength) {
  5068. Server svr;
  5069. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5070. res.status = StatusCode::OK_200;
  5071. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5072. "text/html"); // <= Content-Length still 13
  5073. });
  5074. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5075. res.set_content("Hello World!\n", "text/plain");
  5076. res.status = 524;
  5077. });
  5078. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5079. auto se = detail::scope_exit([&] {
  5080. svr.stop();
  5081. thread.join();
  5082. ASSERT_FALSE(svr.is_running());
  5083. });
  5084. svr.wait_until_ready();
  5085. {
  5086. Client cli(HOST, PORT);
  5087. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5089. EXPECT_EQ(StatusCode::OK_200, res->status);
  5090. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5091. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5092. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5093. }
  5094. }
  5095. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5096. TEST(ExceptionTest, WithoutExceptionHandler) {
  5097. Server svr;
  5098. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5099. throw std::runtime_error("exception...");
  5100. });
  5101. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5102. throw std::runtime_error("exception\r\n...");
  5103. });
  5104. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5105. auto se = detail::scope_exit([&] {
  5106. svr.stop();
  5107. listen_thread.join();
  5108. ASSERT_FALSE(svr.is_running());
  5109. });
  5110. svr.wait_until_ready();
  5111. Client cli("localhost", PORT);
  5112. {
  5113. auto res = cli.Get("/exception");
  5114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5115. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5116. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5117. }
  5118. {
  5119. auto res = cli.Get("/unknown");
  5120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5121. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5122. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5123. }
  5124. }
  5125. TEST(ExceptionTest, WithExceptionHandler) {
  5126. Server svr;
  5127. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5128. std::exception_ptr ep) {
  5129. EXPECT_FALSE(ep == nullptr);
  5130. try {
  5131. std::rethrow_exception(ep);
  5132. } catch (std::exception &e) {
  5133. EXPECT_EQ("abc", std::string(e.what()));
  5134. } catch (...) {}
  5135. res.status = StatusCode::InternalServerError_500;
  5136. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5137. "text/html"); // <= Content-Length still 13 at this point
  5138. });
  5139. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5140. res.set_content("Hello World!\n", "text/plain");
  5141. throw std::runtime_error("abc");
  5142. });
  5143. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5144. auto se = detail::scope_exit([&] {
  5145. svr.stop();
  5146. thread.join();
  5147. ASSERT_FALSE(svr.is_running());
  5148. });
  5149. svr.wait_until_ready();
  5150. for (size_t i = 0; i < 10; i++) {
  5151. Client cli(HOST, PORT);
  5152. for (size_t j = 0; j < 100; j++) {
  5153. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5158. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5159. }
  5160. cli.set_keep_alive(true);
  5161. for (size_t j = 0; j < 100; j++) {
  5162. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5164. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5165. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5166. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5168. }
  5169. }
  5170. }
  5171. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5172. Server svr;
  5173. svr.set_exception_handler(
  5174. [](const Request &, Response &res, std::exception_ptr) {
  5175. res.set_content("oops", "text/plain");
  5176. });
  5177. svr.Get("/throw", [](const Request &, Response &) {
  5178. throw std::runtime_error("throw");
  5179. });
  5180. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5181. res.status = StatusCode::Created_201;
  5182. throw std::runtime_error("created-then-throw");
  5183. });
  5184. auto port = svr.bind_to_any_port(HOST);
  5185. ASSERT_GT(port, 0);
  5186. thread t = thread([&] { svr.listen_after_bind(); });
  5187. auto se = detail::scope_exit([&] {
  5188. svr.stop();
  5189. t.join();
  5190. ASSERT_FALSE(svr.is_running());
  5191. });
  5192. svr.wait_until_ready();
  5193. Client cli(HOST, port);
  5194. for (auto path : {"/throw", "/created-then-throw"}) {
  5195. auto res = cli.Get(path);
  5196. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5197. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5198. }
  5199. }
  5200. TEST(ExceptionTest, AndErrorHandler) {
  5201. Server svr;
  5202. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5203. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5204. });
  5205. svr.set_exception_handler(
  5206. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5207. EXPECT_FALSE(ep == nullptr);
  5208. try {
  5209. std::rethrow_exception(ep);
  5210. } catch (std::exception &e) {
  5211. res.set_content(e.what(), "text/html");
  5212. } catch (...) {}
  5213. res.status = StatusCode::InternalServerError_500;
  5214. });
  5215. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5216. throw std::runtime_error("EXCEPTION");
  5217. });
  5218. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5219. res.set_content("ERROR", "text/html");
  5220. res.status = StatusCode::InternalServerError_500;
  5221. });
  5222. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5223. auto se = detail::scope_exit([&] {
  5224. svr.stop();
  5225. thread.join();
  5226. ASSERT_FALSE(svr.is_running());
  5227. });
  5228. svr.wait_until_ready();
  5229. Client cli(HOST, PORT);
  5230. {
  5231. auto res = cli.Get("/exception");
  5232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5233. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5234. EXPECT_EQ("EXCEPTION", res->body);
  5235. }
  5236. {
  5237. auto res = cli.Get("/error");
  5238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5239. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5240. EXPECT_EQ("ERROR", res->body);
  5241. }
  5242. {
  5243. auto res = cli.Get("/invalid");
  5244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5245. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5246. EXPECT_EQ("NOT_FOUND", res->body);
  5247. }
  5248. }
  5249. #endif
  5250. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5251. // An exception from a user callback outside process_request()'s try/catch
  5252. // used to unwind into the task queue - which does not catch - and terminate
  5253. // the process. Each test below runs the server on a single worker thread: a
  5254. // guard that catches the exception but still loses the thread would otherwise
  5255. // be hidden by a spare worker serving the follow-up request. Note that a
  5256. // regression here aborts the whole test binary rather than failing one test.
  5257. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5258. Server svr;
  5259. svr.new_task_queue = [] { return new ThreadPool(1); };
  5260. std::atomic<int> reported{0};
  5261. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5262. if (err == Error::UserCallbackException) { reported++; }
  5263. });
  5264. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5265. res.set_content_provider(
  5266. 1024, "text/plain",
  5267. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5268. sink.write("hello", 5);
  5269. throw std::runtime_error("from the content provider");
  5270. });
  5271. });
  5272. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5273. res.set_content("ok", "text/plain");
  5274. });
  5275. auto port = svr.bind_to_any_port(HOST);
  5276. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5277. auto se = detail::scope_exit([&] {
  5278. svr.stop();
  5279. listen_thread.join();
  5280. ASSERT_FALSE(svr.is_running());
  5281. });
  5282. svr.wait_until_ready();
  5283. {
  5284. Client cli(HOST, port);
  5285. cli.set_read_timeout(5, 0);
  5286. EXPECT_FALSE(cli.Get("/throw"));
  5287. }
  5288. EXPECT_TRUE(svr.is_running());
  5289. EXPECT_EQ(1, reported.load());
  5290. // A request on a fresh connection is still served.
  5291. {
  5292. Client cli(HOST, port);
  5293. auto res = cli.Get("/ok");
  5294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5295. EXPECT_EQ(StatusCode::OK_200, res->status);
  5296. EXPECT_EQ("ok", res->body);
  5297. }
  5298. }
  5299. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5300. Server svr;
  5301. svr.new_task_queue = [] { return new ThreadPool(1); };
  5302. std::atomic<bool> should_throw{true};
  5303. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5304. res.set_content("hi", "text/plain");
  5305. });
  5306. svr.set_post_routing_handler(
  5307. [&](const Request & /*req*/, Response & /*res*/) {
  5308. if (should_throw) {
  5309. throw std::runtime_error("from the post-routing handler");
  5310. }
  5311. });
  5312. auto port = svr.bind_to_any_port(HOST);
  5313. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5314. auto se = detail::scope_exit([&] {
  5315. svr.stop();
  5316. listen_thread.join();
  5317. ASSERT_FALSE(svr.is_running());
  5318. });
  5319. svr.wait_until_ready();
  5320. {
  5321. Client cli(HOST, port);
  5322. cli.set_read_timeout(5, 0);
  5323. EXPECT_FALSE(cli.Get("/hi"));
  5324. }
  5325. EXPECT_TRUE(svr.is_running());
  5326. should_throw = false;
  5327. {
  5328. Client cli(HOST, port);
  5329. auto res = cli.Get("/hi");
  5330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5331. EXPECT_EQ(StatusCode::OK_200, res->status);
  5332. EXPECT_EQ("hi", res->body);
  5333. }
  5334. }
  5335. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5336. // The guard reports the caught exception through the error logger, which is
  5337. // a user callback too. A logger that throws has to be contained as well, or
  5338. // the process would terminate from inside the catch.
  5339. Server svr;
  5340. svr.new_task_queue = [] { return new ThreadPool(1); };
  5341. std::atomic<int> reported{0};
  5342. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5343. if (err == Error::UserCallbackException) {
  5344. reported++;
  5345. throw std::runtime_error("from the error logger");
  5346. }
  5347. });
  5348. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5349. res.set_content_provider(
  5350. 1024, "text/plain",
  5351. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5352. sink.write("hello", 5);
  5353. throw std::runtime_error("from the content provider");
  5354. });
  5355. });
  5356. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5357. res.set_content("ok", "text/plain");
  5358. });
  5359. auto port = svr.bind_to_any_port(HOST);
  5360. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5361. auto se = detail::scope_exit([&] {
  5362. svr.stop();
  5363. listen_thread.join();
  5364. ASSERT_FALSE(svr.is_running());
  5365. });
  5366. svr.wait_until_ready();
  5367. {
  5368. Client cli(HOST, port);
  5369. cli.set_read_timeout(5, 0);
  5370. EXPECT_FALSE(cli.Get("/throw"));
  5371. }
  5372. EXPECT_TRUE(svr.is_running());
  5373. EXPECT_EQ(1, reported.load());
  5374. {
  5375. Client cli(HOST, port);
  5376. auto res = cli.Get("/ok");
  5377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5378. EXPECT_EQ(StatusCode::OK_200, res->status);
  5379. EXPECT_EQ("ok", res->body);
  5380. }
  5381. }
  5382. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5383. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5384. // so the exception unwinds through the ws::WebSocket object on its way to
  5385. // the guard. None of the HTTP cases above cross that.
  5386. Server svr;
  5387. svr.new_task_queue = [] { return new ThreadPool(1); };
  5388. std::atomic<int> reported{0};
  5389. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5390. if (err == Error::UserCallbackException) { reported++; }
  5391. });
  5392. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5393. throw std::runtime_error("from the WebSocket handler");
  5394. });
  5395. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5396. res.set_content("ok", "text/plain");
  5397. });
  5398. auto port = svr.bind_to_any_port(HOST);
  5399. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5400. auto se = detail::scope_exit([&] {
  5401. svr.stop();
  5402. listen_thread.join();
  5403. ASSERT_FALSE(svr.is_running());
  5404. });
  5405. svr.wait_until_ready();
  5406. {
  5407. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5408. "/ws");
  5409. auto res = client.connect();
  5410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5411. // The server dropped the connection instead of dying.
  5412. std::string msg;
  5413. EXPECT_FALSE(client.read(msg));
  5414. client.close();
  5415. }
  5416. EXPECT_TRUE(svr.is_running());
  5417. EXPECT_EQ(1, reported.load());
  5418. {
  5419. Client cli(HOST, port);
  5420. auto res = cli.Get("/ok");
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. EXPECT_EQ(StatusCode::OK_200, res->status);
  5423. EXPECT_EQ("ok", res->body);
  5424. }
  5425. }
  5426. #ifdef CPPHTTPLIB_SSL_ENABLED
  5427. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5428. // SSLServer::process_and_close_socket() is a separate overload with its own
  5429. // guard, so it is exercised on its own.
  5430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5431. ASSERT_TRUE(svr.is_valid());
  5432. svr.new_task_queue = [] { return new ThreadPool(1); };
  5433. std::atomic<int> reported{0};
  5434. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5435. if (err == Error::UserCallbackException) { reported++; }
  5436. });
  5437. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5438. res.set_content_provider(
  5439. 1024, "text/plain",
  5440. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5441. sink.write("hello", 5);
  5442. throw std::runtime_error("from the content provider");
  5443. });
  5444. });
  5445. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5446. res.set_content("ok", "text/plain");
  5447. });
  5448. auto port = svr.bind_to_any_port(HOST);
  5449. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5450. auto se = detail::scope_exit([&] {
  5451. svr.stop();
  5452. listen_thread.join();
  5453. ASSERT_FALSE(svr.is_running());
  5454. });
  5455. svr.wait_until_ready();
  5456. {
  5457. SSLClient cli(HOST, port);
  5458. cli.enable_server_certificate_verification(false);
  5459. cli.set_read_timeout(5, 0);
  5460. EXPECT_FALSE(cli.Get("/throw"));
  5461. }
  5462. EXPECT_TRUE(svr.is_running());
  5463. EXPECT_EQ(1, reported.load());
  5464. {
  5465. SSLClient cli(HOST, port);
  5466. cli.enable_server_certificate_verification(false);
  5467. auto res = cli.Get("/ok");
  5468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5469. EXPECT_EQ(StatusCode::OK_200, res->status);
  5470. EXPECT_EQ("ok", res->body);
  5471. }
  5472. }
  5473. #endif
  5474. #endif
  5475. TEST(NoContentTest, ContentLength) {
  5476. Server svr;
  5477. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5478. res.status = StatusCode::NoContent_204;
  5479. });
  5480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5481. auto se = detail::scope_exit([&] {
  5482. svr.stop();
  5483. thread.join();
  5484. ASSERT_FALSE(svr.is_running());
  5485. });
  5486. svr.wait_until_ready();
  5487. {
  5488. Client cli(HOST, PORT);
  5489. auto res = cli.Get("/hi");
  5490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5491. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5492. // RFC 9110 8.6: none in a 204 response
  5493. EXPECT_FALSE(res->has_header("Content-Length"));
  5494. }
  5495. }
  5496. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5497. Server svr;
  5498. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5499. res.set_header("Content-Length", "5");
  5500. res.set_content("hello world", "text/plain");
  5501. });
  5502. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5503. // A body that reads as the last chunk, were it taken as chunked
  5504. res.set_header("Transfer-Encoding", "chunked");
  5505. res.set_content("0\r\n\r\n", "text/plain");
  5506. });
  5507. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5508. res.set_header("Content-Length", "2");
  5509. res.set_content_provider(5, "text/plain",
  5510. [](size_t offset, size_t length, DataSink &sink) {
  5511. sink.write(&"hello"[offset], length);
  5512. return true;
  5513. });
  5514. });
  5515. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5516. res.set_header("Content-Length", "1234");
  5517. });
  5518. thread t = thread([&] { svr.listen(HOST, PORT); });
  5519. auto se = detail::scope_exit([&] {
  5520. svr.stop();
  5521. t.join();
  5522. ASSERT_FALSE(svr.is_running());
  5523. });
  5524. svr.wait_until_ready();
  5525. Client cli(HOST, PORT);
  5526. cli.set_read_timeout(1, 0);
  5527. auto expect_body = [&](const Result &res, const std::string &body) {
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. EXPECT_EQ(body, res->body);
  5530. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5531. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5532. };
  5533. Headers identity{{"Accept-Encoding", ""}};
  5534. expect_body(cli.Get("/body", identity), "hello world");
  5535. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5536. expect_body(cli.Get("/body",
  5537. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5538. "he");
  5539. expect_body(cli.Get("/provider", identity), "hello");
  5540. expect_body(cli.Get("/empty", identity), "");
  5541. // A HEAD response may give the length of the body a GET would get.
  5542. auto res = cli.Head("/empty");
  5543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5544. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5545. }
  5546. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5547. Server svr;
  5548. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5549. res.set_content("short", "text/plain");
  5550. });
  5551. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5552. res.body += " with a footer";
  5553. res.set_header("Transfer-Encoding", "chunked");
  5554. });
  5555. thread t = thread([&] { svr.listen(HOST, PORT); });
  5556. auto se = detail::scope_exit([&] {
  5557. svr.stop();
  5558. t.join();
  5559. ASSERT_FALSE(svr.is_running());
  5560. });
  5561. svr.wait_until_ready();
  5562. Client cli(HOST, PORT);
  5563. cli.set_read_timeout(1, 0);
  5564. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5566. EXPECT_EQ("short with a footer", res->body);
  5567. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5568. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5569. }
  5570. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5571. Server svr;
  5572. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5573. res.set_header("Content-Length", "3");
  5574. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5575. sink.write("abc", 3);
  5576. sink.done();
  5577. return true;
  5578. });
  5579. });
  5580. thread t = thread([&] { svr.listen(HOST, PORT); });
  5581. auto se = detail::scope_exit([&] {
  5582. svr.stop();
  5583. t.join();
  5584. ASSERT_FALSE(svr.is_running());
  5585. });
  5586. svr.wait_until_ready();
  5587. Client cli(HOST, PORT);
  5588. cli.set_keep_alive(true);
  5589. auto res = cli.Get("/");
  5590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5591. EXPECT_EQ("abc", res->body);
  5592. EXPECT_FALSE(res->has_header("Content-Length"));
  5593. EXPECT_EQ("close", res->get_header_value("Connection"));
  5594. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5595. // No body to delimit
  5596. auto head = cli.Head("/");
  5597. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5598. EXPECT_FALSE(head->has_header("Connection"));
  5599. }
  5600. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5601. #ifdef CPPHTTPLIB_SSL_ENABLED
  5602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5603. ASSERT_TRUE(svr.is_valid());
  5604. #else
  5605. Server svr;
  5606. #endif
  5607. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5608. if (req.path == "/routing_handler") {
  5609. res.set_header("PRE_ROUTING", "on");
  5610. res.set_content("Routing Handler", "text/plain");
  5611. return httplib::Server::HandlerResponse::Handled;
  5612. }
  5613. return httplib::Server::HandlerResponse::Unhandled;
  5614. });
  5615. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5616. res.set_content("Error", "text/html");
  5617. });
  5618. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5619. if (req.path == "/routing_handler") {
  5620. res.set_header("POST_ROUTING", "on");
  5621. }
  5622. });
  5623. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5624. res.set_content("Hello World!\n", "text/plain");
  5625. });
  5626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5627. auto se = detail::scope_exit([&] {
  5628. svr.stop();
  5629. thread.join();
  5630. ASSERT_FALSE(svr.is_running());
  5631. });
  5632. svr.wait_until_ready();
  5633. {
  5634. #ifdef CPPHTTPLIB_SSL_ENABLED
  5635. SSLClient cli(HOST, PORT);
  5636. cli.enable_server_certificate_verification(false);
  5637. #else
  5638. Client cli(HOST, PORT);
  5639. #endif
  5640. auto res = cli.Get("/routing_handler");
  5641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5642. EXPECT_EQ(StatusCode::OK_200, res->status);
  5643. EXPECT_EQ("Routing Handler", res->body);
  5644. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5645. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5646. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5647. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5648. }
  5649. {
  5650. #ifdef CPPHTTPLIB_SSL_ENABLED
  5651. SSLClient cli(HOST, PORT);
  5652. cli.enable_server_certificate_verification(false);
  5653. #else
  5654. Client cli(HOST, PORT);
  5655. #endif
  5656. auto res = cli.Get("/hi");
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. EXPECT_EQ(StatusCode::OK_200, res->status);
  5659. EXPECT_EQ("Hello World!\n", res->body);
  5660. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5661. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5662. }
  5663. {
  5664. #ifdef CPPHTTPLIB_SSL_ENABLED
  5665. SSLClient cli(HOST, PORT);
  5666. cli.enable_server_certificate_verification(false);
  5667. #else
  5668. Client cli(HOST, PORT);
  5669. #endif
  5670. auto res = cli.Get("/aaa");
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5673. EXPECT_EQ("Error", res->body);
  5674. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5675. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5676. }
  5677. }
  5678. TEST(RequestHandlerTest, PreRequestHandler) {
  5679. auto route_path = "/user/:user";
  5680. Server svr;
  5681. svr.Get("/hi", [](const Request &, Response &res) {
  5682. res.set_content("hi", "text/plain");
  5683. });
  5684. svr.Get(route_path, [](const Request &req, Response &res) {
  5685. res.set_content(req.path_params.at("user"), "text/plain");
  5686. });
  5687. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5688. if (req.matched_route == route_path) {
  5689. auto user = req.path_params.at("user");
  5690. if (user != "john") {
  5691. res.status = StatusCode::Forbidden_403;
  5692. res.set_content("error", "text/html");
  5693. return Server::HandlerResponse::Handled;
  5694. }
  5695. }
  5696. return Server::HandlerResponse::Unhandled;
  5697. });
  5698. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5699. auto se = detail::scope_exit([&] {
  5700. svr.stop();
  5701. thread.join();
  5702. ASSERT_FALSE(svr.is_running());
  5703. });
  5704. svr.wait_until_ready();
  5705. Client cli(HOST, PORT);
  5706. {
  5707. auto res = cli.Get("/hi");
  5708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5709. EXPECT_EQ(StatusCode::OK_200, res->status);
  5710. EXPECT_EQ("hi", res->body);
  5711. }
  5712. {
  5713. auto res = cli.Get("/user/john");
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. EXPECT_EQ(StatusCode::OK_200, res->status);
  5716. EXPECT_EQ("john", res->body);
  5717. }
  5718. {
  5719. auto res = cli.Get("/user/invalid-user");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5722. EXPECT_EQ("error", res->body);
  5723. }
  5724. }
  5725. // The pre-request handler must run before the request body is read, so a
  5726. // rejected request never forces the server to buffer a (potentially large)
  5727. // body. Here the posted body is larger than the payload limit: if the body
  5728. // were read first the server would answer 413, but because the pre-request
  5729. // handler runs first it answers 403 and the body is never read.
  5730. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5731. Server svr;
  5732. svr.set_payload_max_length(8);
  5733. auto handler_ran = false;
  5734. svr.Post("/reject", [&](const Request &req, Response &res) {
  5735. handler_ran = true;
  5736. res.set_content(req.body, "text/plain");
  5737. });
  5738. svr.Post("/accept", [](const Request &req, Response &res) {
  5739. res.set_content(req.body, "text/plain");
  5740. });
  5741. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5742. if (req.matched_route == "/reject") {
  5743. res.status = StatusCode::Forbidden_403;
  5744. res.set_content("denied", "text/plain");
  5745. return Server::HandlerResponse::Handled;
  5746. }
  5747. return Server::HandlerResponse::Unhandled;
  5748. });
  5749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5750. auto se = detail::scope_exit([&] {
  5751. svr.stop();
  5752. thread.join();
  5753. ASSERT_FALSE(svr.is_running());
  5754. });
  5755. svr.wait_until_ready();
  5756. Client cli(HOST, PORT);
  5757. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5758. // rejects with 403 before the body is read, so 413 is never reached.
  5759. {
  5760. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5762. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5763. EXPECT_EQ("denied", res->body);
  5764. EXPECT_FALSE(handler_ran);
  5765. }
  5766. // An approved route still reads the body and enforces the payload limit.
  5767. {
  5768. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5770. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5771. }
  5772. }
  5773. TEST(UserDataTest, BasicOperations) {
  5774. httplib::UserData ud;
  5775. // Initially empty
  5776. EXPECT_FALSE(ud.has("key"));
  5777. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5778. // set and get
  5779. ud.set("key", 42);
  5780. EXPECT_TRUE(ud.has("key"));
  5781. auto *p = ud.get<int>("key");
  5782. ASSERT_NE(nullptr, p);
  5783. EXPECT_EQ(42, *p);
  5784. // Type mismatch → nullptr
  5785. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5786. // Overwrite with different type
  5787. ud.set("key", std::string("hello"));
  5788. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5789. auto *s = ud.get<std::string>("key");
  5790. ASSERT_NE(nullptr, s);
  5791. EXPECT_EQ("hello", *s);
  5792. // erase
  5793. ud.erase("key");
  5794. EXPECT_FALSE(ud.has("key"));
  5795. // clear
  5796. ud.set("a", 1);
  5797. ud.set("b", 2);
  5798. ud.clear();
  5799. EXPECT_FALSE(ud.has("a"));
  5800. EXPECT_FALSE(ud.has("b"));
  5801. }
  5802. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5803. struct AuthCtx {
  5804. std::string user_id;
  5805. };
  5806. Server svr;
  5807. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5808. res.user_data.set("auth", AuthCtx{"alice"});
  5809. return Server::HandlerResponse::Unhandled;
  5810. });
  5811. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5812. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5813. ASSERT_NE(nullptr, ctx);
  5814. res.set_content("Hello " + ctx->user_id, "text/plain");
  5815. });
  5816. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5817. auto se = detail::scope_exit([&] {
  5818. svr.stop();
  5819. thread.join();
  5820. ASSERT_FALSE(svr.is_running());
  5821. });
  5822. svr.wait_until_ready();
  5823. Client cli(HOST, PORT);
  5824. auto res = cli.Get("/me");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::OK_200, res->status);
  5827. EXPECT_EQ("Hello alice", res->body);
  5828. }
  5829. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5830. struct RoleCtx {
  5831. std::string role;
  5832. };
  5833. Server svr;
  5834. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5835. res.user_data.set("role", RoleCtx{"admin"});
  5836. return Server::HandlerResponse::Unhandled;
  5837. });
  5838. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5839. auto *ctx = res.user_data.get<RoleCtx>("role");
  5840. ASSERT_NE(nullptr, ctx);
  5841. res.set_content(ctx->role, "text/plain");
  5842. });
  5843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5844. auto se = detail::scope_exit([&] {
  5845. svr.stop();
  5846. thread.join();
  5847. ASSERT_FALSE(svr.is_running());
  5848. });
  5849. svr.wait_until_ready();
  5850. Client cli(HOST, PORT);
  5851. auto res = cli.Get("/role");
  5852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5853. EXPECT_EQ(StatusCode::OK_200, res->status);
  5854. EXPECT_EQ("admin", res->body);
  5855. }
  5856. TEST(InvalidFormatTest, StatusCode) {
  5857. Server svr;
  5858. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5859. res.set_content("Hello World!\n", "text/plain");
  5860. res.status = 9999; // Status should be a three-digit code...
  5861. });
  5862. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5863. auto se = detail::scope_exit([&] {
  5864. svr.stop();
  5865. thread.join();
  5866. ASSERT_FALSE(svr.is_running());
  5867. });
  5868. svr.wait_until_ready();
  5869. {
  5870. Client cli(HOST, PORT);
  5871. auto res = cli.Get("/hi");
  5872. ASSERT_FALSE(res);
  5873. }
  5874. }
  5875. TEST(URLFragmentTest, WithFragment) {
  5876. Server svr;
  5877. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5878. EXPECT_TRUE(req.target == "/hi");
  5879. });
  5880. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5881. auto se = detail::scope_exit([&] {
  5882. svr.stop();
  5883. thread.join();
  5884. ASSERT_FALSE(svr.is_running());
  5885. });
  5886. svr.wait_until_ready();
  5887. {
  5888. Client cli(HOST, PORT);
  5889. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5890. EXPECT_TRUE(res);
  5891. EXPECT_EQ(StatusCode::OK_200, res->status);
  5892. res = cli.Get("/hi%23key1=val1=key2=val2");
  5893. EXPECT_TRUE(res);
  5894. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5895. }
  5896. }
  5897. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5898. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5899. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5900. Server svr;
  5901. std::vector<std::string> targets;
  5902. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5903. targets.push_back(req.target);
  5904. });
  5905. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5906. auto se = detail::scope_exit([&] {
  5907. svr.stop();
  5908. thread.join();
  5909. ASSERT_FALSE(svr.is_running());
  5910. });
  5911. svr.wait_until_ready();
  5912. Client cli(HOST, PORT);
  5913. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5914. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5915. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5916. // A '?' after the '#' belongs to the fragment, not to the query.
  5917. Request req;
  5918. req.method = "GET";
  5919. req.path = "/hi#f?x=1";
  5920. req.params.emplace("a", "1");
  5921. Response res;
  5922. auto error = Error::Success;
  5923. EXPECT_TRUE(cli.send(req, res, error));
  5924. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5925. "/hi?a=1"}),
  5926. targets);
  5927. }
  5928. TEST(HeaderWriter, SetHeaderWriter) {
  5929. Server svr;
  5930. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5931. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5932. return detail::write_headers(strm, hdrs);
  5933. });
  5934. svr.Get("/hi", [](const Request &req, Response &res) {
  5935. auto it = req.headers.find("CustomClientHeader");
  5936. EXPECT_TRUE(it != req.headers.end());
  5937. EXPECT_EQ(it->second, "CustomClientValue");
  5938. res.set_content("Hello World!\n", "text/plain");
  5939. });
  5940. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5941. auto se = detail::scope_exit([&] {
  5942. svr.stop();
  5943. thread.join();
  5944. ASSERT_FALSE(svr.is_running());
  5945. });
  5946. svr.wait_until_ready();
  5947. {
  5948. Client cli(HOST, PORT);
  5949. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5950. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5951. return detail::write_headers(strm, hdrs);
  5952. });
  5953. auto res = cli.Get("/hi");
  5954. EXPECT_TRUE(res);
  5955. EXPECT_EQ(StatusCode::OK_200, res->status);
  5956. auto it = res->headers.find("CustomServerHeader");
  5957. EXPECT_TRUE(it != res->headers.end());
  5958. EXPECT_EQ(it->second, "CustomServerValue");
  5959. }
  5960. }
  5961. class ServerTest : public ::testing::Test {
  5962. protected:
  5963. ServerTest()
  5964. : cli_(HOST, PORT)
  5965. #ifdef CPPHTTPLIB_SSL_ENABLED
  5966. ,
  5967. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5968. #endif
  5969. {
  5970. #ifdef CPPHTTPLIB_SSL_ENABLED
  5971. cli_.enable_server_certificate_verification(false);
  5972. #endif
  5973. // Allow LARGE_DATA (100MB) responses
  5974. cli_.set_payload_max_length(200 * 1024 * 1024);
  5975. }
  5976. virtual void SetUp() {
  5977. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5978. svr_.set_payload_max_length(200 * 1024 * 1024);
  5979. svr_.set_mount_point("/", "./www");
  5980. svr_.set_mount_point("/mount", "./www2");
  5981. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5982. svr_.Get("/hi",
  5983. [&](const Request & /*req*/, Response &res) {
  5984. res.set_content("Hello World!", "text/plain");
  5985. })
  5986. .Get("/file_content",
  5987. [&](const Request & /*req*/, Response &res) {
  5988. res.set_file_content("./www/dir/test.html");
  5989. })
  5990. .Get("/file_content_with_content_type",
  5991. [&](const Request & /*req*/, Response &res) {
  5992. res.set_file_content("./www/file", "text/plain");
  5993. })
  5994. .Get("/invalid_file_content",
  5995. [&](const Request & /*req*/, Response &res) {
  5996. res.set_file_content("./www/dir/invalid_file_path");
  5997. })
  5998. .Get("/http_response_splitting",
  5999. [&](const Request & /*req*/, Response &res) {
  6000. res.set_header("a", "1\r\nSet-Cookie: a=1");
  6001. EXPECT_EQ(0U, res.headers.size());
  6002. EXPECT_FALSE(res.has_header("a"));
  6003. res.set_header("a", "1\nSet-Cookie: a=1");
  6004. EXPECT_EQ(0U, res.headers.size());
  6005. EXPECT_FALSE(res.has_header("a"));
  6006. res.set_header("a", "1\rSet-Cookie: a=1");
  6007. EXPECT_EQ(0U, res.headers.size());
  6008. EXPECT_FALSE(res.has_header("a"));
  6009. res.set_header("a\r\nb", "0");
  6010. EXPECT_EQ(0U, res.headers.size());
  6011. EXPECT_FALSE(res.has_header("a"));
  6012. res.set_header("a\rb", "0");
  6013. EXPECT_EQ(0U, res.headers.size());
  6014. EXPECT_FALSE(res.has_header("a"));
  6015. res.set_header("a\nb", "0");
  6016. EXPECT_EQ(0U, res.headers.size());
  6017. EXPECT_FALSE(res.has_header("a"));
  6018. res.set_redirect("1\r\nSet-Cookie: a=1");
  6019. EXPECT_EQ(0U, res.headers.size());
  6020. EXPECT_FALSE(res.has_header("Location"));
  6021. })
  6022. .Get("/slow",
  6023. [&](const Request & /*req*/, Response &res) {
  6024. std::this_thread::sleep_for(std::chrono::seconds(4));
  6025. res.set_content("slow", "text/plain");
  6026. })
  6027. #if 0
  6028. .Post("/slowpost",
  6029. [&](const Request & /*req*/, Response &res) {
  6030. std::this_thread::sleep_for(std::chrono::seconds(2));
  6031. res.set_content("slow", "text/plain");
  6032. })
  6033. #endif
  6034. .Get("/remote_addr",
  6035. [&](const Request &req, Response &res) {
  6036. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  6037. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  6038. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6039. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6040. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6041. #endif
  6042. res.set_content(req.remote_addr, "text/plain");
  6043. })
  6044. .Get("/local_addr",
  6045. [&](const Request &req, Response &res) {
  6046. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6047. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6048. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6049. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6050. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6051. #endif
  6052. auto local_addr = req.local_addr;
  6053. auto local_port = std::to_string(req.local_port);
  6054. res.set_content(local_addr.append(":").append(local_port),
  6055. "text/plain");
  6056. })
  6057. .Get("/endwith%",
  6058. [&](const Request & /*req*/, Response &res) {
  6059. res.set_content("Hello World!", "text/plain");
  6060. })
  6061. .Get("/a\\+\\+b",
  6062. [&](const Request &req, Response &res) {
  6063. ASSERT_TRUE(req.has_param("a +b"));
  6064. auto val = req.get_param_value("a +b");
  6065. res.set_content(val, "text/plain");
  6066. })
  6067. .Get("/", [&](const Request & /*req*/,
  6068. Response &res) { res.set_redirect("/hi"); })
  6069. .Post("/1",
  6070. [](const Request & /*req*/, Response &res) {
  6071. res.set_redirect("/2", StatusCode::SeeOther_303);
  6072. })
  6073. .Get("/2",
  6074. [](const Request & /*req*/, Response &res) {
  6075. res.set_content("redirected.", "text/plain");
  6076. res.status = StatusCode::OK_200;
  6077. })
  6078. .Post("/person",
  6079. [&](const Request &req, Response &res) {
  6080. if (req.has_param("name") && req.has_param("note")) {
  6081. persons_[req.get_param_value("name")] =
  6082. req.get_param_value("note");
  6083. } else {
  6084. res.status = StatusCode::BadRequest_400;
  6085. }
  6086. })
  6087. .Put("/person",
  6088. [&](const Request &req, Response &res) {
  6089. if (req.has_param("name") && req.has_param("note")) {
  6090. persons_[req.get_param_value("name")] =
  6091. req.get_param_value("note");
  6092. } else {
  6093. res.status = StatusCode::BadRequest_400;
  6094. }
  6095. })
  6096. .Get("/person/(.*)",
  6097. [&](const Request &req, Response &res) {
  6098. string name = req.matches[1];
  6099. if (persons_.find(name) != persons_.end()) {
  6100. auto note = persons_[name];
  6101. res.set_content(note, "text/plain");
  6102. } else {
  6103. res.status = StatusCode::NotFound_404;
  6104. }
  6105. })
  6106. .Delete("/person",
  6107. [&](const Request &req, Response &res) {
  6108. if (req.has_param("name")) {
  6109. string name = req.get_param_value("name");
  6110. if (persons_.find(name) != persons_.end()) {
  6111. persons_.erase(name);
  6112. res.set_content("DELETED", "text/plain");
  6113. } else {
  6114. res.status = StatusCode::NotFound_404;
  6115. }
  6116. } else {
  6117. res.status = StatusCode::BadRequest_400;
  6118. }
  6119. })
  6120. .Post("/x-www-form-urlencoded-json",
  6121. [&](const Request &req, Response &res) {
  6122. auto json = req.get_param_value("json");
  6123. ASSERT_EQ(JSON_DATA, json);
  6124. res.set_content(json, "appliation/json");
  6125. res.status = StatusCode::OK_200;
  6126. })
  6127. .Get("/streamed-chunked",
  6128. [&](const Request & /*req*/, Response &res) {
  6129. res.set_chunked_content_provider(
  6130. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6131. sink.os << "123";
  6132. sink.os << "456";
  6133. sink.os << "789";
  6134. sink.done();
  6135. return true;
  6136. });
  6137. })
  6138. .Get("/streamed-chunked-with-prohibited-trailer",
  6139. [&](const Request & /*req*/, Response &res) {
  6140. auto i = new int(0);
  6141. // Declare both a prohibited trailer (Content-Length) and an
  6142. // allowed one
  6143. res.set_header("Trailer", "Content-Length, X-Allowed");
  6144. res.set_chunked_content_provider(
  6145. "text/plain",
  6146. [i](size_t /*offset*/, DataSink &sink) {
  6147. switch (*i) {
  6148. case 0: sink.os << "123"; break;
  6149. case 1: sink.os << "456"; break;
  6150. case 2: sink.os << "789"; break;
  6151. case 3: {
  6152. sink.done_with_trailer(
  6153. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6154. } break;
  6155. }
  6156. (*i)++;
  6157. return true;
  6158. },
  6159. [i](bool success) {
  6160. EXPECT_TRUE(success);
  6161. delete i;
  6162. });
  6163. })
  6164. .Get("/streamed-chunked2",
  6165. [&](const Request & /*req*/, Response &res) {
  6166. auto i = new int(0);
  6167. res.set_chunked_content_provider(
  6168. "text/plain",
  6169. [i](size_t /*offset*/, DataSink &sink) {
  6170. switch (*i) {
  6171. case 0: sink.os << "123"; break;
  6172. case 1: sink.os << "456"; break;
  6173. case 2: sink.os << "789"; break;
  6174. case 3: sink.done(); break;
  6175. }
  6176. (*i)++;
  6177. return true;
  6178. },
  6179. [i](bool success) {
  6180. EXPECT_TRUE(success);
  6181. delete i;
  6182. });
  6183. })
  6184. .Get("/streamed-chunked-with-trailer",
  6185. [&](const Request & /*req*/, Response &res) {
  6186. auto i = new int(0);
  6187. res.set_header("Trailer", "Dummy1, Dummy2");
  6188. res.set_chunked_content_provider(
  6189. "text/plain",
  6190. [i](size_t /*offset*/, DataSink &sink) {
  6191. switch (*i) {
  6192. case 0: sink.os << "123"; break;
  6193. case 1: sink.os << "456"; break;
  6194. case 2: sink.os << "789"; break;
  6195. case 3: {
  6196. sink.done_with_trailer(
  6197. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6198. } break;
  6199. }
  6200. (*i)++;
  6201. return true;
  6202. },
  6203. [i](bool success) {
  6204. EXPECT_TRUE(success);
  6205. delete i;
  6206. });
  6207. })
  6208. .Get("/streamed",
  6209. [&](const Request & /*req*/, Response &res) {
  6210. res.set_content_provider(
  6211. 6, "text/plain",
  6212. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6213. sink.os << (offset < 3 ? "a" : "b");
  6214. return true;
  6215. });
  6216. })
  6217. .Get("/streamed-without-length",
  6218. [&](const Request & /*req*/, Response &res) {
  6219. auto data = new std::string("abcdefg");
  6220. res.set_content_provider(
  6221. "text/plain",
  6222. [data](size_t offset, DataSink &sink) {
  6223. if (offset < data->size()) {
  6224. sink.os << data->substr(offset);
  6225. }
  6226. sink.done();
  6227. return true;
  6228. },
  6229. [data](bool success) {
  6230. EXPECT_TRUE(success);
  6231. delete data;
  6232. });
  6233. })
  6234. .Get("/streamed-with-range",
  6235. [&](const Request &req, Response &res) {
  6236. auto data = new std::string("abcdefg");
  6237. // An explicit status keeps the server from picking the 206 it
  6238. // would otherwise choose for a ranged request, so the response
  6239. // is not a partial representation.
  6240. auto status = req.get_param_value("status");
  6241. if (status == "200") {
  6242. res.status = StatusCode::OK_200;
  6243. } else if (status == "403") {
  6244. res.status = StatusCode::Forbidden_403;
  6245. }
  6246. res.set_content_provider(
  6247. data->size(), "text/plain",
  6248. [data](size_t offset, size_t length, DataSink &sink) {
  6249. size_t DATA_CHUNK_SIZE = 4;
  6250. const auto &d = *data;
  6251. auto out_len =
  6252. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6253. auto ret =
  6254. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6255. EXPECT_TRUE(ret);
  6256. return true;
  6257. },
  6258. [data, &req](bool success) {
  6259. EXPECT_EQ(success, !req.has_param("error"));
  6260. delete data;
  6261. });
  6262. })
  6263. .Get("/streamed-cancel",
  6264. [&](const Request & /*req*/, Response &res) {
  6265. res.set_content_provider(
  6266. size_t(-1), "text/plain",
  6267. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6268. sink.os << "data_chunk";
  6269. return true;
  6270. });
  6271. })
  6272. .Get("/regex-with-delimiter",
  6273. [&](const Request &req, Response & /*res*/) {
  6274. ASSERT_TRUE(req.has_param("key"));
  6275. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6276. })
  6277. .Get("/with-range",
  6278. [&](const Request & /*req*/, Response &res) {
  6279. res.set_content("abcdefg", "text/plain");
  6280. })
  6281. .Get("/test-start-time",
  6282. [&](const Request &req, Response & /*res*/) {
  6283. EXPECT_NE(req.start_time_,
  6284. std::chrono::steady_clock::time_point::min());
  6285. })
  6286. .Get("/with-range-customized-response",
  6287. [&](const Request & /*req*/, Response &res) {
  6288. res.status = StatusCode::BadRequest_400;
  6289. res.set_content(JSON_DATA, "application/json");
  6290. })
  6291. .Post("/chunked",
  6292. [&](const Request &req, Response & /*res*/) {
  6293. EXPECT_EQ(req.body, "dechunked post body");
  6294. })
  6295. .Post("/large-chunked",
  6296. [&](const Request &req, Response & /*res*/) {
  6297. std::string expected(6 * 30 * 1024u, 'a');
  6298. EXPECT_EQ(req.body, expected);
  6299. })
  6300. .Post("/multipart",
  6301. [&](const Request &req, Response & /*res*/) {
  6302. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6303. req.form.get_field_count("text2") +
  6304. req.form.get_field_count("file3") +
  6305. req.form.get_field_count("file4"));
  6306. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6307. req.form.get_file_count("file2"));
  6308. ASSERT_TRUE(!req.form.has_file("???"));
  6309. ASSERT_TRUE(!req.form.has_field("???"));
  6310. ASSERT_TRUE(req.body.empty());
  6311. {
  6312. const auto &text = req.form.get_field("text1");
  6313. EXPECT_EQ("text default", text);
  6314. }
  6315. {
  6316. const auto &text = req.form.get_field("text2");
  6317. EXPECT_EQ("aωb", text);
  6318. }
  6319. {
  6320. const auto &file = req.form.get_file("file1");
  6321. EXPECT_EQ("hello.txt", file.filename);
  6322. EXPECT_EQ("text/plain", file.content_type);
  6323. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6324. }
  6325. {
  6326. const auto &file = req.form.get_file("file2");
  6327. EXPECT_EQ("world.json", file.filename);
  6328. EXPECT_EQ("application/json", file.content_type);
  6329. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6330. }
  6331. {
  6332. const auto &text = req.form.get_field("file3");
  6333. EXPECT_EQ(0u, text.size());
  6334. }
  6335. {
  6336. const auto &text = req.form.get_field("file4");
  6337. EXPECT_EQ(0u, text.size());
  6338. }
  6339. })
  6340. .Post("/multipart/multi_file_values",
  6341. [&](const Request &req, Response & /*res*/) {
  6342. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6343. req.form.get_field_count("multi_text1"));
  6344. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6345. ASSERT_TRUE(!req.form.has_file("???"));
  6346. ASSERT_TRUE(!req.form.has_field("???"));
  6347. ASSERT_TRUE(req.body.empty());
  6348. {
  6349. const auto &text = req.form.get_field("text");
  6350. EXPECT_EQ("default text", text);
  6351. }
  6352. {
  6353. const auto &text1_values = req.form.get_fields("multi_text1");
  6354. EXPECT_EQ(2u, text1_values.size());
  6355. EXPECT_EQ("aaaaa", text1_values[0]);
  6356. EXPECT_EQ("bbbbb", text1_values[1]);
  6357. }
  6358. {
  6359. const auto &file1_values = req.form.get_files("multi_file1");
  6360. EXPECT_EQ(2u, file1_values.size());
  6361. auto file1 = file1_values[0];
  6362. EXPECT_EQ(file1.filename, "hello.txt");
  6363. EXPECT_EQ(file1.content_type, "text/plain");
  6364. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6365. auto file2 = file1_values[1];
  6366. EXPECT_EQ(file2.filename, "world.json");
  6367. EXPECT_EQ(file2.content_type, "application/json");
  6368. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6369. }
  6370. })
  6371. .Post("/empty",
  6372. [&](const Request &req, Response &res) {
  6373. EXPECT_EQ(req.body, "");
  6374. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6375. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6376. res.set_content("empty", "text/plain");
  6377. })
  6378. .Post("/empty-no-content-type",
  6379. [&](const Request &req, Response &res) {
  6380. EXPECT_EQ(req.body, "");
  6381. EXPECT_FALSE(req.has_header("Content-Type"));
  6382. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6383. res.set_content("empty-no-content-type", "text/plain");
  6384. })
  6385. .Post("/path-only",
  6386. [&](const Request &req, Response &res) {
  6387. EXPECT_EQ(req.body, "");
  6388. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6389. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6390. res.set_content("path-only", "text/plain");
  6391. })
  6392. .Post("/path-headers-only",
  6393. [&](const Request &req, Response &res) {
  6394. EXPECT_EQ(req.body, "");
  6395. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6396. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6397. EXPECT_EQ("world", req.get_header_value("hello"));
  6398. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6399. res.set_content("path-headers-only", "text/plain");
  6400. })
  6401. .Post("/post-large",
  6402. [&](const Request &req, Response &res) {
  6403. EXPECT_EQ(req.body, LARGE_DATA);
  6404. res.set_content(req.body, "text/plain");
  6405. })
  6406. .Post("/post-loopback",
  6407. [&](const Request &, Response &res,
  6408. ContentReader const &content_reader) {
  6409. std::string body;
  6410. content_reader([&](const char *data, size_t data_length) {
  6411. body.append(data, data_length);
  6412. return true;
  6413. });
  6414. res.set_content(body, "text/plain");
  6415. })
  6416. .Put("/put-loopback",
  6417. [&](const Request &, Response &res,
  6418. ContentReader const &content_reader) {
  6419. std::string body;
  6420. content_reader([&](const char *data, size_t data_length) {
  6421. body.append(data, data_length);
  6422. return true;
  6423. });
  6424. res.set_content(body, "text/plain");
  6425. })
  6426. .Patch("/patch-loopback",
  6427. [&](const Request &, Response &res,
  6428. ContentReader const &content_reader) {
  6429. std::string body;
  6430. content_reader([&](const char *data, size_t data_length) {
  6431. body.append(data, data_length);
  6432. return true;
  6433. });
  6434. res.set_content(body, "text/plain");
  6435. })
  6436. .Put("/empty-no-content-type",
  6437. [&](const Request &req, Response &res) {
  6438. EXPECT_EQ(req.body, "");
  6439. EXPECT_FALSE(req.has_header("Content-Type"));
  6440. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6441. res.set_content("empty-no-content-type", "text/plain");
  6442. })
  6443. .Put("/put",
  6444. [&](const Request &req, Response &res) {
  6445. EXPECT_EQ(req.body, "PUT");
  6446. res.set_content(req.body, "text/plain");
  6447. })
  6448. .Put("/put-large",
  6449. [&](const Request &req, Response &res) {
  6450. EXPECT_EQ(req.body, LARGE_DATA);
  6451. res.set_content(req.body, "text/plain");
  6452. })
  6453. .Patch("/patch",
  6454. [&](const Request &req, Response &res) {
  6455. EXPECT_EQ(req.body, "PATCH");
  6456. res.set_content(req.body, "text/plain");
  6457. })
  6458. .Delete("/delete",
  6459. [&](const Request & /*req*/, Response &res) {
  6460. res.set_content("DELETE", "text/plain");
  6461. })
  6462. .Delete("/delete-body",
  6463. [&](const Request &req, Response &res) {
  6464. EXPECT_EQ(req.body, "content");
  6465. res.set_content(req.body, "text/plain");
  6466. })
  6467. .Options(R"(\*)",
  6468. [&](const Request & /*req*/, Response &res) {
  6469. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6470. })
  6471. .CustomRoute("PROPFIND", "/dav/:id",
  6472. [&](const Request &req, Response &res) {
  6473. res.set_header("x-body-size",
  6474. std::to_string(req.body.size()));
  6475. res.set_header("x-matched-route", req.matched_route);
  6476. res.set_header("x-dav-id", req.path_params.at("id"));
  6477. res.status = StatusCode::MultiStatus_207;
  6478. res.set_content(req.body, "application/xml");
  6479. })
  6480. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6481. [&](const Request &req, Response &res) {
  6482. res.set_header("x-dav-match", req.matches[1]);
  6483. res.status = StatusCode::MultiStatus_207;
  6484. })
  6485. .CustomRoute("MKCOL", "/dav-mkcol",
  6486. [&](const Request &req, Response &res) {
  6487. EXPECT_TRUE(req.body.empty());
  6488. res.status = StatusCode::Created_201;
  6489. })
  6490. .CustomRoute(
  6491. "REPORT", "/dav-report",
  6492. [&](const Request & /*req*/, Response &res,
  6493. const ContentReader &content_reader) {
  6494. std::string body;
  6495. content_reader([&](const char *data, size_t data_length) {
  6496. body.append(data, data_length);
  6497. return true;
  6498. });
  6499. res.set_header("x-body-size", std::to_string(body.size()));
  6500. res.status = StatusCode::MultiStatus_207;
  6501. res.set_content(body, "application/xml");
  6502. })
  6503. .Get("/request-target",
  6504. [&](const Request &req, Response & /*res*/) {
  6505. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6506. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6507. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6508. })
  6509. .Get("/long-query-value",
  6510. [&](const Request &req, Response & /*res*/) {
  6511. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6512. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6513. })
  6514. .Get("/too-long-query-value",
  6515. [&](const Request &req, Response & /*res*/) {
  6516. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6517. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6518. })
  6519. .Get("/array-param",
  6520. [&](const Request &req, Response & /*res*/) {
  6521. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6522. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6523. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6524. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6525. })
  6526. .Get("/array-param-values",
  6527. [&](const Request &req, Response & /*res*/) {
  6528. auto values = req.get_param_values("array");
  6529. EXPECT_EQ(3u, values.size());
  6530. EXPECT_EQ("value1", values[0]);
  6531. EXPECT_EQ("value2", values[1]);
  6532. EXPECT_EQ("value3", values[2]);
  6533. auto empty = req.get_param_values("nonexistent");
  6534. EXPECT_TRUE(empty.empty());
  6535. })
  6536. .Post("/validate-no-multiple-headers",
  6537. [&](const Request &req, Response & /*res*/) {
  6538. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6539. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6540. })
  6541. .Post("/content_receiver",
  6542. [&](const Request &req, Response &res,
  6543. const ContentReader &content_reader) {
  6544. if (req.is_multipart_form_data()) {
  6545. std::vector<FormData> items;
  6546. content_reader(
  6547. [&](const FormData &file) {
  6548. items.push_back(file);
  6549. return true;
  6550. },
  6551. [&](const char *data, size_t data_length) {
  6552. items.back().content.append(data, data_length);
  6553. return true;
  6554. });
  6555. EXPECT_EQ(5u, items.size());
  6556. {
  6557. const auto &file = get_file_value(items, "text1");
  6558. EXPECT_TRUE(file.filename.empty());
  6559. EXPECT_EQ("text default", file.content);
  6560. }
  6561. {
  6562. const auto &file = get_file_value(items, "text2");
  6563. EXPECT_TRUE(file.filename.empty());
  6564. EXPECT_EQ("aωb", file.content);
  6565. }
  6566. {
  6567. const auto &file = get_file_value(items, "file1");
  6568. EXPECT_EQ("hello.txt", file.filename);
  6569. EXPECT_EQ("text/plain", file.content_type);
  6570. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6571. }
  6572. {
  6573. const auto &file = get_file_value(items, "file2");
  6574. EXPECT_EQ("world.json", file.filename);
  6575. EXPECT_EQ("application/json", file.content_type);
  6576. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6577. }
  6578. {
  6579. const auto &file = get_file_value(items, "file3");
  6580. EXPECT_TRUE(file.filename.empty());
  6581. EXPECT_EQ("application/octet-stream", file.content_type);
  6582. EXPECT_EQ(0u, file.content.size());
  6583. }
  6584. } else {
  6585. std::string body;
  6586. content_reader([&](const char *data, size_t data_length) {
  6587. EXPECT_EQ(7U, data_length);
  6588. body.append(data, data_length);
  6589. return true;
  6590. });
  6591. EXPECT_EQ(body, "content");
  6592. res.set_content(body, "text/plain");
  6593. }
  6594. })
  6595. .Put("/content_receiver",
  6596. [&](const Request & /*req*/, Response &res,
  6597. const ContentReader &content_reader) {
  6598. std::string body;
  6599. content_reader([&](const char *data, size_t data_length) {
  6600. body.append(data, data_length);
  6601. return true;
  6602. });
  6603. EXPECT_EQ(body, "content");
  6604. res.set_content(body, "text/plain");
  6605. })
  6606. .Patch("/content_receiver",
  6607. [&](const Request & /*req*/, Response &res,
  6608. const ContentReader &content_reader) {
  6609. std::string body;
  6610. content_reader([&](const char *data, size_t data_length) {
  6611. body.append(data, data_length);
  6612. return true;
  6613. });
  6614. EXPECT_EQ(body, "content");
  6615. res.set_content(body, "text/plain");
  6616. })
  6617. .Post("/query-string-and-body",
  6618. [&](const Request &req, Response & /*res*/) {
  6619. ASSERT_TRUE(req.has_param("key"));
  6620. EXPECT_EQ(req.get_param_value("key"), "value");
  6621. EXPECT_EQ(req.body, "content");
  6622. })
  6623. .Get("/last-request",
  6624. [&](const Request &req, Response & /*res*/) {
  6625. EXPECT_EQ("close", req.get_header_value("Connection"));
  6626. })
  6627. .Get(R"(/redirect/(\d+))",
  6628. [&](const Request &req, Response &res) {
  6629. auto num = std::stoi(req.matches[1]) + 1;
  6630. std::string url = "/redirect/" + std::to_string(num);
  6631. res.set_redirect(url);
  6632. })
  6633. .Post("/binary",
  6634. [&](const Request &req, Response &res) {
  6635. EXPECT_EQ(4U, req.body.size());
  6636. EXPECT_EQ("application/octet-stream",
  6637. req.get_header_value("Content-Type"));
  6638. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6639. res.set_content(req.body, "application/octet-stream");
  6640. })
  6641. .Put("/binary",
  6642. [&](const Request &req, Response &res) {
  6643. EXPECT_EQ(4U, req.body.size());
  6644. EXPECT_EQ("application/octet-stream",
  6645. req.get_header_value("Content-Type"));
  6646. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6647. res.set_content(req.body, "application/octet-stream");
  6648. })
  6649. .Patch("/binary",
  6650. [&](const Request &req, Response &res) {
  6651. EXPECT_EQ(4U, req.body.size());
  6652. EXPECT_EQ("application/octet-stream",
  6653. req.get_header_value("Content-Type"));
  6654. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6655. res.set_content(req.body, "application/octet-stream");
  6656. })
  6657. .Delete("/binary",
  6658. [&](const Request &req, Response &res) {
  6659. EXPECT_EQ(4U, req.body.size());
  6660. EXPECT_EQ("application/octet-stream",
  6661. req.get_header_value("Content-Type"));
  6662. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6663. res.set_content(req.body, "application/octet-stream");
  6664. })
  6665. .Get("/issue1772",
  6666. [&](const Request & /*req*/, Response &res) {
  6667. res.status = 401;
  6668. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6669. })
  6670. .Delete("/issue609",
  6671. [](const httplib::Request &, httplib::Response &res,
  6672. const httplib::ContentReader &) {
  6673. res.set_content("ok", "text/plain");
  6674. })
  6675. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6676. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6677. .Get("/compress",
  6678. [&](const Request & /*req*/, Response &res) {
  6679. res.set_content(
  6680. "12345678901234567890123456789012345678901234567890123456789"
  6681. "01234567890123456789012345678901234567890",
  6682. "text/plain");
  6683. })
  6684. .Get("/compress-with-charset",
  6685. [&](const Request & /*req*/, Response &res) {
  6686. res.set_content(
  6687. "12345678901234567890123456789012345678901234567890123456789"
  6688. "01234567890123456789012345678901234567890",
  6689. "application/json; charset=utf-8");
  6690. })
  6691. .Get("/nocompress",
  6692. [&](const Request & /*req*/, Response &res) {
  6693. res.set_content(
  6694. "12345678901234567890123456789012345678901234567890123456789"
  6695. "01234567890123456789012345678901234567890",
  6696. "application/octet-stream");
  6697. })
  6698. .Post("/compress-multipart",
  6699. [&](const Request &req, Response & /*res*/) {
  6700. EXPECT_EQ(2u, req.form.fields.size());
  6701. ASSERT_TRUE(!req.form.has_field("???"));
  6702. {
  6703. const auto &text = req.form.get_field("key1");
  6704. EXPECT_EQ("test", text);
  6705. }
  6706. {
  6707. const auto &text = req.form.get_field("key2");
  6708. EXPECT_EQ("--abcdefg123", text);
  6709. }
  6710. })
  6711. #endif
  6712. ;
  6713. persons_["john"] = "programmer";
  6714. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6715. svr_.wait_until_ready();
  6716. }
  6717. virtual void TearDown() {
  6718. svr_.stop();
  6719. if (!request_threads_.empty()) {
  6720. std::this_thread::sleep_for(std::chrono::seconds(1));
  6721. for (auto &t : request_threads_) {
  6722. t.join();
  6723. }
  6724. }
  6725. t_.join();
  6726. }
  6727. map<string, string> persons_;
  6728. #ifdef CPPHTTPLIB_SSL_ENABLED
  6729. SSLClient cli_;
  6730. SSLServer svr_;
  6731. #else
  6732. Client cli_;
  6733. Server svr_;
  6734. #endif
  6735. thread t_;
  6736. std::vector<thread> request_threads_;
  6737. };
  6738. TEST_F(ServerTest, GetMethod200) {
  6739. auto res = cli_.Get("/hi");
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. EXPECT_EQ("HTTP/1.1", res->version);
  6742. EXPECT_EQ(StatusCode::OK_200, res->status);
  6743. EXPECT_EQ("OK", res->reason);
  6744. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6745. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6746. EXPECT_EQ("Hello World!", res->body);
  6747. }
  6748. TEST_F(ServerTest, GetEmptyFile) {
  6749. auto res = cli_.Get("/empty_file");
  6750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6751. EXPECT_EQ(StatusCode::OK_200, res->status);
  6752. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6753. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6754. EXPECT_EQ("", res->body);
  6755. }
  6756. TEST_F(ServerTest, GetFileContent) {
  6757. auto res = cli_.Get("/file_content");
  6758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6759. EXPECT_EQ(StatusCode::OK_200, res->status);
  6760. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6761. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6762. EXPECT_EQ("test.html", res->body);
  6763. }
  6764. TEST_F(ServerTest, GetFileContentWithRange) {
  6765. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6767. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6768. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6769. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6770. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6771. EXPECT_EQ("est", res->body);
  6772. }
  6773. TEST_F(ServerTest, GetFileContentWithContentType) {
  6774. auto res = cli_.Get("/file_content_with_content_type");
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_EQ(StatusCode::OK_200, res->status);
  6777. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6778. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6779. EXPECT_EQ("file\n", res->body);
  6780. }
  6781. TEST_F(ServerTest, GetInvalidFileContent) {
  6782. auto res = cli_.Get("/invalid_file_content");
  6783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6784. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6785. }
  6786. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6787. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6789. EXPECT_EQ("HTTP/1.1", res->version);
  6790. EXPECT_EQ(StatusCode::OK_200, res->status);
  6791. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6792. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6793. EXPECT_EQ("Hello World!", res->body);
  6794. }
  6795. TEST_F(ServerTest, GetMethod302) {
  6796. auto res = cli_.Get("/");
  6797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6798. EXPECT_EQ(StatusCode::Found_302, res->status);
  6799. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6800. }
  6801. TEST_F(ServerTest, GetMethod302Redirect) {
  6802. cli_.set_follow_location(true);
  6803. auto res = cli_.Get("/");
  6804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6805. EXPECT_EQ(StatusCode::OK_200, res->status);
  6806. EXPECT_EQ("Hello World!", res->body);
  6807. EXPECT_EQ("/hi", res->location);
  6808. }
  6809. TEST_F(ServerTest, GetMethod404) {
  6810. auto res = cli_.Get("/invalid");
  6811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6812. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6813. }
  6814. TEST_F(ServerTest, HeadMethod200) {
  6815. auto res = cli_.Head("/hi");
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. EXPECT_EQ(StatusCode::OK_200, res->status);
  6818. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6819. EXPECT_TRUE(res->body.empty());
  6820. }
  6821. TEST_F(ServerTest, HeadMethod200Static) {
  6822. auto res = cli_.Head("/mount/dir/index.html");
  6823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6824. EXPECT_EQ(StatusCode::OK_200, res->status);
  6825. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6826. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6827. EXPECT_TRUE(res->body.empty());
  6828. }
  6829. TEST_F(ServerTest, HeadMethod404) {
  6830. auto res = cli_.Head("/invalid");
  6831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6832. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6833. EXPECT_TRUE(res->body.empty());
  6834. }
  6835. TEST_F(ServerTest, GetMethodPersonJohn) {
  6836. auto res = cli_.Get("/person/john");
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. EXPECT_EQ(StatusCode::OK_200, res->status);
  6839. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6840. EXPECT_EQ("programmer", res->body);
  6841. }
  6842. TEST_F(ServerTest, PostMethod1) {
  6843. auto res = cli_.Get("/person/john1");
  6844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6845. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6846. res = cli_.Post("/person", "name=john1&note=coder",
  6847. "application/x-www-form-urlencoded");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. ASSERT_EQ(StatusCode::OK_200, res->status);
  6850. res = cli_.Get("/person/john1");
  6851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6852. ASSERT_EQ(StatusCode::OK_200, res->status);
  6853. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6854. ASSERT_EQ("coder", res->body);
  6855. }
  6856. TEST_F(ServerTest, PostMethod2) {
  6857. auto res = cli_.Get("/person/john2");
  6858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6859. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6860. Params params;
  6861. params.emplace("name", "john2");
  6862. params.emplace("note", "coder");
  6863. res = cli_.Post("/person", params);
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. ASSERT_EQ(StatusCode::OK_200, res->status);
  6866. res = cli_.Get("/person/john2");
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. ASSERT_EQ(StatusCode::OK_200, res->status);
  6869. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6870. ASSERT_EQ("coder", res->body);
  6871. }
  6872. TEST_F(ServerTest, PutMethod3) {
  6873. auto res = cli_.Get("/person/john3");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6876. Params params;
  6877. params.emplace("name", "john3");
  6878. params.emplace("note", "coder");
  6879. res = cli_.Put("/person", params);
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. ASSERT_EQ(StatusCode::OK_200, res->status);
  6882. res = cli_.Get("/person/john3");
  6883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6884. ASSERT_EQ(StatusCode::OK_200, res->status);
  6885. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6886. ASSERT_EQ("coder", res->body);
  6887. }
  6888. TEST_F(ServerTest, DeleteMethod1) {
  6889. auto res = cli_.Get("/person/john4");
  6890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6891. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6892. Params params;
  6893. params.emplace("name", "john4");
  6894. params.emplace("note", "coder");
  6895. res = cli_.Post("/person", params);
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. ASSERT_EQ(StatusCode::OK_200, res->status);
  6898. res = cli_.Get("/person/john4");
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. ASSERT_EQ(StatusCode::OK_200, res->status);
  6901. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6902. ASSERT_EQ("coder", res->body);
  6903. Params delete_params;
  6904. delete_params.emplace("name", "john4");
  6905. res = cli_.Delete("/person", delete_params);
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. ASSERT_EQ(StatusCode::OK_200, res->status);
  6908. ASSERT_EQ("DELETED", res->body);
  6909. res = cli_.Get("/person/john4");
  6910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6911. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6912. }
  6913. TEST_F(ServerTest, DeleteMethod2) {
  6914. auto res = cli_.Get("/person/john5");
  6915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6916. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6917. Params params;
  6918. params.emplace("name", "john5");
  6919. params.emplace("note", "developer");
  6920. res = cli_.Post("/person", params);
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. ASSERT_EQ(StatusCode::OK_200, res->status);
  6923. res = cli_.Get("/person/john5");
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. ASSERT_EQ(StatusCode::OK_200, res->status);
  6926. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6927. ASSERT_EQ("developer", res->body);
  6928. Params delete_params;
  6929. delete_params.emplace("name", "john5");
  6930. Headers headers;
  6931. headers.emplace("Custom-Header", "test-value");
  6932. res = cli_.Delete("/person", headers, delete_params);
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. ASSERT_EQ(StatusCode::OK_200, res->status);
  6935. ASSERT_EQ("DELETED", res->body);
  6936. res = cli_.Get("/person/john5");
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6939. }
  6940. TEST_F(ServerTest, DeleteMethod3) {
  6941. auto res = cli_.Get("/person/john6");
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6944. Params params;
  6945. params.emplace("name", "john6");
  6946. params.emplace("note", "tester");
  6947. res = cli_.Post("/person", params);
  6948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6949. ASSERT_EQ(StatusCode::OK_200, res->status);
  6950. res = cli_.Get("/person/john6");
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. ASSERT_EQ(StatusCode::OK_200, res->status);
  6953. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6954. ASSERT_EQ("tester", res->body);
  6955. Params delete_params;
  6956. delete_params.emplace("name", "john6");
  6957. Headers headers;
  6958. headers.emplace("Custom-Header", "test-value");
  6959. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6961. ASSERT_EQ(StatusCode::OK_200, res->status);
  6962. ASSERT_EQ("DELETED", res->body);
  6963. res = cli_.Get("/person/john6");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6966. }
  6967. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6968. Params params;
  6969. params.emplace("json", JSON_DATA);
  6970. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6972. ASSERT_EQ(StatusCode::OK_200, res->status);
  6973. ASSERT_EQ(JSON_DATA, res->body);
  6974. }
  6975. TEST_F(ServerTest, PostEmptyContent) {
  6976. auto res = cli_.Post("/empty", "", "text/plain");
  6977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6978. ASSERT_EQ(StatusCode::OK_200, res->status);
  6979. ASSERT_EQ("empty", res->body);
  6980. }
  6981. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6982. auto res = cli_.Post("/empty-no-content-type");
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. ASSERT_EQ(StatusCode::OK_200, res->status);
  6985. ASSERT_EQ("empty-no-content-type", res->body);
  6986. }
  6987. TEST_F(ServerTest, PostPathOnly) {
  6988. auto res = cli_.Post("/path-only");
  6989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6990. ASSERT_EQ(StatusCode::OK_200, res->status);
  6991. ASSERT_EQ("path-only", res->body);
  6992. }
  6993. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6994. auto res = cli_.Post("/path-headers-only",
  6995. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. ASSERT_EQ(StatusCode::OK_200, res->status);
  6998. ASSERT_EQ("path-headers-only", res->body);
  6999. }
  7000. TEST_F(ServerTest, PostLarge) {
  7001. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. ASSERT_EQ(StatusCode::OK_200, res->status);
  7004. EXPECT_EQ(LARGE_DATA, res->body);
  7005. }
  7006. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  7007. auto res = cli_.Put("/empty-no-content-type");
  7008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7009. ASSERT_EQ(StatusCode::OK_200, res->status);
  7010. ASSERT_EQ("empty-no-content-type", res->body);
  7011. }
  7012. TEST_F(ServerTest, GetMethodDir) {
  7013. auto res = cli_.Get("/dir/");
  7014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7015. EXPECT_EQ(StatusCode::OK_200, res->status);
  7016. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7017. auto body = R"(<html>
  7018. <head>
  7019. </head>
  7020. <body>
  7021. <a href="/dir/test.html">Test</a>
  7022. <a href="/hi">hi</a>
  7023. </body>
  7024. </html>
  7025. )";
  7026. EXPECT_EQ(body, res->body);
  7027. }
  7028. TEST_F(ServerTest, GetMethodDirTest) {
  7029. auto res = cli_.Get("/dir/test.html");
  7030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7031. EXPECT_EQ(StatusCode::OK_200, res->status);
  7032. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7033. EXPECT_EQ("test.html", res->body);
  7034. }
  7035. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  7036. auto res = cli_.Get("/dir/../dir/test.html");
  7037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7038. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7039. }
  7040. TEST_F(ServerTest, GetMethodInvalidPath) {
  7041. auto res = cli_.Get("/dir/../test.html");
  7042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7043. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7044. }
  7045. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7046. auto res = cli_.Get("/../www/dir/test.html");
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7049. }
  7050. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7051. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7054. }
  7055. TEST_F(ServerTest, GetMethodDirMountTest) {
  7056. auto res = cli_.Get("/mount/dir/test.html");
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::OK_200, res->status);
  7059. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7060. EXPECT_EQ("test.html", res->body);
  7061. }
  7062. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7063. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7065. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7066. }
  7067. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7068. auto res = cli_.Get("/mount/dir/../test.html");
  7069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7070. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7071. }
  7072. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7073. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7076. }
  7077. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7078. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7081. }
  7082. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7083. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7086. }
  7087. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7088. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7090. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7091. }
  7092. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7093. auto res = cli_.Get("/mount/dir");
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7096. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7097. }
  7098. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7099. auto res = cli_.Get("//dir");
  7100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7101. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7102. EXPECT_FALSE(res->has_header("Location"));
  7103. }
  7104. TEST_F(ServerTest, PostMethod303) {
  7105. auto res = cli_.Post("/1", "body", "text/plain");
  7106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7107. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7108. EXPECT_EQ("/2", res->get_header_value("Location"));
  7109. }
  7110. TEST_F(ServerTest, PostMethod303Redirect) {
  7111. cli_.set_follow_location(true);
  7112. auto res = cli_.Post("/1", "body", "text/plain");
  7113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7114. EXPECT_EQ(StatusCode::OK_200, res->status);
  7115. EXPECT_EQ("redirected.", res->body);
  7116. EXPECT_EQ("/2", res->location);
  7117. }
  7118. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7119. auto res = cli_.Get("/dir/test.abcde");
  7120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7121. EXPECT_EQ(StatusCode::OK_200, res->status);
  7122. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7123. EXPECT_EQ("abcde", res->body);
  7124. }
  7125. TEST_F(ServerTest, StaticFileRange) {
  7126. auto res =
  7127. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7129. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7130. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7131. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7132. EXPECT_EQ(true, res->has_header("Content-Range"));
  7133. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7134. EXPECT_EQ(std::string("cd"), res->body);
  7135. }
  7136. TEST_F(ServerTest, StaticFileRanges) {
  7137. auto res = cli_.Get("/dir/test.abcde",
  7138. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7141. EXPECT_TRUE(
  7142. res->get_header_value("Content-Type")
  7143. .find(
  7144. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7145. 0);
  7146. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7147. }
  7148. TEST_F(ServerTest, StaticFileRangeHead) {
  7149. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7151. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7152. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7153. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7154. EXPECT_EQ(true, res->has_header("Content-Range"));
  7155. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7156. }
  7157. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7158. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7162. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7163. EXPECT_EQ(true, res->has_header("Content-Range"));
  7164. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7165. res->get_header_value("Content-Range"));
  7166. EXPECT_EQ("LAST\n", res->body);
  7167. }
  7168. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7169. auto res =
  7170. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7173. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7174. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7175. EXPECT_EQ(true, res->has_header("Content-Range"));
  7176. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7177. }
  7178. TEST_F(ServerTest, StaticFileBigFile) {
  7179. auto res = cli_.Get("/dir/1MB.txt");
  7180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7181. EXPECT_EQ(StatusCode::OK_200, res->status);
  7182. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7183. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7184. }
  7185. TEST_F(ServerTest, InvalidBaseDirMount) {
  7186. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7187. }
  7188. TEST_F(ServerTest, Binary) {
  7189. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7190. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7191. "application/octet-stream");
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. ASSERT_EQ(StatusCode::OK_200, res->status);
  7194. ASSERT_EQ(4U, res->body.size());
  7195. res = cli_.Put("/binary", binary.data(), binary.size(),
  7196. "application/octet-stream");
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. ASSERT_EQ(StatusCode::OK_200, res->status);
  7199. ASSERT_EQ(4U, res->body.size());
  7200. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7201. "application/octet-stream");
  7202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7203. ASSERT_EQ(StatusCode::OK_200, res->status);
  7204. ASSERT_EQ(4U, res->body.size());
  7205. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7206. "application/octet-stream");
  7207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7208. ASSERT_EQ(StatusCode::OK_200, res->status);
  7209. ASSERT_EQ(4U, res->body.size());
  7210. }
  7211. TEST_F(ServerTest, BinaryString) {
  7212. auto binary = std::string("\x00\x01\x02\x03", 4);
  7213. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7215. ASSERT_EQ(StatusCode::OK_200, res->status);
  7216. ASSERT_EQ(4U, res->body.size());
  7217. res = cli_.Put("/binary", binary, "application/octet-stream");
  7218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7219. ASSERT_EQ(StatusCode::OK_200, res->status);
  7220. ASSERT_EQ(4U, res->body.size());
  7221. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. ASSERT_EQ(StatusCode::OK_200, res->status);
  7224. ASSERT_EQ(4U, res->body.size());
  7225. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7227. ASSERT_EQ(StatusCode::OK_200, res->status);
  7228. ASSERT_EQ(4U, res->body.size());
  7229. }
  7230. TEST_F(ServerTest, EmptyRequest) {
  7231. auto res = cli_.Get("");
  7232. ASSERT_TRUE(!res);
  7233. EXPECT_EQ(Error::Connection, res.error());
  7234. }
  7235. TEST_F(ServerTest, LongRequest) {
  7236. std::string request;
  7237. for (size_t i = 0; i < 545; i++) {
  7238. request += "/TooLongRequest";
  7239. }
  7240. request += "OK";
  7241. auto res = cli_.Get(request.c_str());
  7242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7243. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7244. }
  7245. TEST_F(ServerTest, TooLongRequest) {
  7246. std::string request;
  7247. for (size_t i = 0; i < 546; i++) {
  7248. request += "/TooLongRequest";
  7249. }
  7250. request += "_NG";
  7251. auto start = std::chrono::high_resolution_clock::now();
  7252. cli_.set_keep_alive(true);
  7253. auto res = cli_.Get(request.c_str());
  7254. auto end = std::chrono::high_resolution_clock::now();
  7255. auto elapsed =
  7256. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7257. .count();
  7258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7259. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7260. EXPECT_LE(elapsed, 1000);
  7261. EXPECT_EQ("close", res->get_header_value("Connection"));
  7262. EXPECT_FALSE(cli_.is_socket_open());
  7263. }
  7264. TEST_F(ServerTest, AlmostTooLongRequest) {
  7265. // test for #2046 - URI length check shouldn't include other content on req
  7266. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7267. // leading /, space, HTTP/1.1)
  7268. std::string request =
  7269. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7270. auto res = cli_.Get(request.c_str());
  7271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7272. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7273. }
  7274. TEST_F(ServerTest, LongHeader) {
  7275. Request req;
  7276. req.method = "GET";
  7277. req.path = "/hi";
  7278. std::string host_and_port;
  7279. host_and_port += HOST;
  7280. host_and_port += ":";
  7281. host_and_port += std::to_string(PORT);
  7282. req.headers.emplace("Host", host_and_port.c_str());
  7283. req.headers.emplace("Accept", "*/*");
  7284. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7285. req.headers.emplace(
  7286. "Header-Name",
  7287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7305. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7306. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7307. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7308. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7309. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7313. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7315. "@@@@@@@@@@@@@@@@");
  7316. auto res = std::make_shared<Response>();
  7317. auto error = Error::Success;
  7318. auto ret = cli_.send(req, *res, error);
  7319. ASSERT_TRUE(ret);
  7320. EXPECT_EQ(StatusCode::OK_200, res->status);
  7321. }
  7322. TEST_F(ServerTest, LongQueryValue) {
  7323. auto start = std::chrono::high_resolution_clock::now();
  7324. cli_.set_keep_alive(true);
  7325. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7326. auto end = std::chrono::high_resolution_clock::now();
  7327. auto elapsed =
  7328. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7329. .count();
  7330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7331. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7332. EXPECT_LE(elapsed, 1000);
  7333. EXPECT_EQ("close", res->get_header_value("Connection"));
  7334. EXPECT_FALSE(cli_.is_socket_open());
  7335. }
  7336. TEST_F(ServerTest, TooLongQueryValue) {
  7337. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7338. ASSERT_FALSE(res);
  7339. EXPECT_EQ(Error::Read, res.error());
  7340. }
  7341. TEST_F(ServerTest, TooLongHeader) {
  7342. Request req;
  7343. req.method = "GET";
  7344. req.path = "/hi";
  7345. std::string host_and_port;
  7346. host_and_port += HOST;
  7347. host_and_port += ":";
  7348. host_and_port += std::to_string(PORT);
  7349. req.headers.emplace("Host", host_and_port.c_str());
  7350. req.headers.emplace("Accept", "*/*");
  7351. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7352. req.headers.emplace(
  7353. "Header-Name",
  7354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7373. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7374. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7375. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7376. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7378. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7379. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7380. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7381. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7382. "@@@@@@@@@@@@@@@@@");
  7383. auto res = std::make_shared<Response>();
  7384. auto error = Error::Success;
  7385. auto ret = cli_.send(req, *res, error);
  7386. ASSERT_TRUE(ret);
  7387. EXPECT_EQ(StatusCode::OK_200, res->status);
  7388. }
  7389. TEST_F(ServerTest, HeaderCountAtLimit) {
  7390. // Test with headers just under the 100 limit
  7391. httplib::Headers headers;
  7392. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7393. // This should keep us just under the 100 header limit
  7394. for (int i = 0; i < 95; i++) {
  7395. std::string name = "X-Test-Header-" + std::to_string(i);
  7396. std::string value = "value" + std::to_string(i);
  7397. headers.emplace(name, value);
  7398. }
  7399. // This should work fine as we're under the limit
  7400. auto res = cli_.Get("/hi", headers);
  7401. EXPECT_TRUE(res);
  7402. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7403. }
  7404. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7405. // Test with many headers to exceed the 100 limit
  7406. httplib::Headers headers;
  7407. // Add 150 headers to definitely exceed the 100 limit
  7408. for (int i = 0; i < 150; i++) {
  7409. std::string name = "X-Test-Header-" + std::to_string(i);
  7410. std::string value = "value" + std::to_string(i);
  7411. headers.emplace(name, value);
  7412. }
  7413. // This should fail due to exceeding header count limit
  7414. cli_.set_keep_alive(true);
  7415. auto res = cli_.Get("/hi", headers);
  7416. // The server should respond with 400 Bad Request
  7417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7418. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7419. EXPECT_EQ("close", res->get_header_value("Connection"));
  7420. EXPECT_FALSE(cli_.is_socket_open());
  7421. }
  7422. TEST_F(ServerTest, PercentEncoding) {
  7423. auto res = cli_.Get("/e%6edwith%");
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. }
  7427. TEST_F(ServerTest, PercentEncodingUnicode) {
  7428. auto res = cli_.Get("/e%u006edwith%");
  7429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7430. EXPECT_EQ(StatusCode::OK_200, res->status);
  7431. }
  7432. TEST_F(ServerTest, InvalidPercentEncoding) {
  7433. auto res = cli_.Get("/%endwith%");
  7434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7435. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7436. }
  7437. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7438. auto res = cli_.Get("/%uendwith%");
  7439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7440. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7441. }
  7442. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7443. auto res = cli_.Get("/hello?aaa=bbb%");
  7444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7446. }
  7447. TEST_F(ServerTest, PlusSignEncoding) {
  7448. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7450. EXPECT_EQ(StatusCode::OK_200, res->status);
  7451. EXPECT_EQ("a +b", res->body);
  7452. }
  7453. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7454. // This test simulates a potential DoS attack using many headers
  7455. // to verify our security fix prevents memory exhaustion
  7456. httplib::Headers attack_headers;
  7457. // Attempt to add many headers like an attacker would (200 headers to far
  7458. // exceed limit)
  7459. for (int i = 0; i < 200; i++) {
  7460. std::string name = "X-Attack-Header-" + std::to_string(i);
  7461. std::string value = "attack_payload_" + std::to_string(i);
  7462. attack_headers.emplace(name, value);
  7463. }
  7464. // Try to POST with excessive headers
  7465. cli_.set_keep_alive(true);
  7466. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7467. // Should either fail or return 400 Bad Request due to security limit
  7468. if (res) {
  7469. // If we get a response, it should be 400 Bad Request
  7470. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7471. EXPECT_EQ("close", res->get_header_value("Connection"));
  7472. }
  7473. EXPECT_FALSE(cli_.is_socket_open());
  7474. }
  7475. TEST_F(ServerTest, MultipartFormData) {
  7476. UploadFormDataItems items = {
  7477. {"text1", "text default", "", ""},
  7478. {"text2", "aωb", "", ""},
  7479. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7480. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7481. {"file3", "", "", "application/octet-stream"},
  7482. {"file4", "", "", " application/json tmp-string "}};
  7483. auto res = cli_.Post("/multipart", items);
  7484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7485. EXPECT_EQ(StatusCode::OK_200, res->status);
  7486. }
  7487. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7488. UploadFormDataItems items = {
  7489. {"text", "default text", "", ""},
  7490. {"multi_text1", "aaaaa", "", ""},
  7491. {"multi_text1", "bbbbb", "", ""},
  7492. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7493. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7494. "application/json"},
  7495. };
  7496. auto res = cli_.Post("/multipart/multi_file_values", items);
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::OK_200, res->status);
  7499. }
  7500. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7501. auto res = cli_.Get("/hi");
  7502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7503. EXPECT_EQ(StatusCode::OK_200, res->status);
  7504. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7505. EXPECT_EQ("Hello World!", res->body);
  7506. }
  7507. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7508. Request req;
  7509. req.method = "POST";
  7510. req.path = "/chunked";
  7511. std::string host_and_port;
  7512. host_and_port += HOST;
  7513. host_and_port += ":";
  7514. host_and_port += std::to_string(PORT);
  7515. req.headers.emplace("Host", host_and_port.c_str());
  7516. req.headers.emplace("Accept", "*/*");
  7517. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7518. req.headers.emplace("Content-Type", "text/plain");
  7519. req.headers.emplace("Content-Length", "0");
  7520. req.headers.emplace(
  7521. "Transfer-Encoding",
  7522. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7523. // Client does not chunk, so make a chunked body manually.
  7524. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7525. auto res = std::make_shared<Response>();
  7526. auto error = Error::Success;
  7527. auto ret = cli_.send(req, *res, error);
  7528. ASSERT_TRUE(ret);
  7529. EXPECT_EQ(StatusCode::OK_200, res->status);
  7530. }
  7531. template <typename ClientT>
  7532. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7533. int expected_status) {
  7534. Request req;
  7535. req.method = "POST";
  7536. req.path = "/chunked";
  7537. std::string host_and_port;
  7538. host_and_port += HOST;
  7539. host_and_port += ":";
  7540. host_and_port += std::to_string(PORT);
  7541. req.headers.emplace("Host", host_and_port.c_str());
  7542. req.headers.emplace("Content-Length", "0");
  7543. req.headers.emplace("Transfer-Encoding", "chunked");
  7544. req.body = body;
  7545. auto res = std::make_shared<Response>();
  7546. auto error = Error::Success;
  7547. ASSERT_TRUE(cli.send(req, *res, error));
  7548. EXPECT_EQ(expected_status, res->status);
  7549. }
  7550. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7551. // rather than treat them as valid lengths.
  7552. template <typename ClientT>
  7553. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7554. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7555. }
  7556. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7557. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7558. }
  7559. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7560. expect_chunked_body_rejected(
  7561. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7562. }
  7563. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7564. // chunk-size line carries no CR, LF or other control character ahead of its
  7565. // terminator. Such a line must be refused rather than read as extension text.
  7566. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7567. expect_chunked_body_rejected(
  7568. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7569. }
  7570. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7571. expect_chunked_body_rejected(
  7572. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7573. }
  7574. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7575. expect_chunked_body_rejected(
  7576. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7577. }
  7578. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7579. // The literal stays split: a hex escape consumes every hex digit that
  7580. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7581. expect_chunked_body_rejected(
  7582. cli_, "4;a\x01"
  7583. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7584. }
  7585. // The bytes around chunk data are no payload, so they cannot ride on the
  7586. // payload limit
  7587. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7588. // Small enough that the whole request is sent before the server turns it
  7589. // down, yet past the limit by the last chunks
  7590. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7591. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7592. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7593. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7594. SCOPED_TRACE(size_line.substr(0, 2));
  7595. std::string body;
  7596. for (auto c : std::string("dechunked post body")) {
  7597. body += size_line + "\r\n" + c + "\r\n";
  7598. }
  7599. body += "0\r\n\r\n";
  7600. expect_chunked_body_rejected(cli_, body.c_str());
  7601. }
  7602. }
  7603. TEST_F(ServerTest, AcceptsChunkExtension) {
  7604. expect_chunked_body_status(cli_,
  7605. "4;name=value\r\ndech\r\n"
  7606. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7607. "0;last\r\n\r\n",
  7608. StatusCode::OK_200);
  7609. }
  7610. TEST_F(ServerTest, GetStreamed2) {
  7611. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7614. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7615. EXPECT_EQ(true, res->has_header("Content-Range"));
  7616. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7617. EXPECT_EQ(std::string("ab"), res->body);
  7618. }
  7619. TEST_F(ServerTest, GetStreamed) {
  7620. auto res = cli_.Get("/streamed");
  7621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7622. EXPECT_EQ(StatusCode::OK_200, res->status);
  7623. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7624. EXPECT_EQ(std::string("aaabbb"), res->body);
  7625. }
  7626. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7627. auto res = cli_.Get("/streamed-without-length",
  7628. Headers{make_range_header({{0, -1}})});
  7629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7630. EXPECT_EQ(StatusCode::OK_200, res->status);
  7631. EXPECT_EQ(false, res->has_header("Content-Length"));
  7632. EXPECT_EQ(false, res->has_header("Content-Range"));
  7633. EXPECT_EQ(std::string("abcdefg"), res->body);
  7634. }
  7635. TEST_F(ServerTest, GetStreamedWithRange1) {
  7636. auto res =
  7637. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7640. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7641. EXPECT_EQ(true, res->has_header("Content-Range"));
  7642. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7643. EXPECT_EQ(std::string("def"), res->body);
  7644. }
  7645. TEST_F(ServerTest, GetStreamedWithRange2) {
  7646. auto res =
  7647. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7650. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7651. EXPECT_EQ(true, res->has_header("Content-Range"));
  7652. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7653. EXPECT_EQ(std::string("bcdefg"), res->body);
  7654. }
  7655. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7656. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7658. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7659. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7660. EXPECT_EQ(true, res->has_header("Content-Range"));
  7661. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7662. EXPECT_EQ(std::string("efg"), res->body);
  7663. }
  7664. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7665. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7666. // the entire representation.
  7667. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7668. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7670. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7671. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7672. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7673. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7674. }
  7675. }
  7676. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7677. auto res =
  7678. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7681. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7682. EXPECT_EQ(false, res->has_header("Content-Range"));
  7683. EXPECT_EQ(0U, res->body.size());
  7684. }
  7685. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7686. // Only a 206 is served as a partial representation. Under any other status
  7687. // `apply_ranges()` reported the full content length, so the body must match
  7688. // that header, and the content provider must never be asked for an offset
  7689. // outside the representation.
  7690. auto check = [&](int status, const char *range) {
  7691. auto path =
  7692. std::string("/streamed-with-range?status=") + std::to_string(status);
  7693. auto ctx = path + " Range: " + range;
  7694. auto res = cli_.Get(path, Headers{{"Range", range}});
  7695. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7696. EXPECT_EQ(status, res->status) << ctx;
  7697. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7699. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7700. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7701. };
  7702. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7703. check(403, "bytes=3-5");
  7704. // The offset is far past the representation.
  7705. check(403, "bytes=100000-100200");
  7706. // `first_pos` is still -1 here, and the bounds asserts in
  7707. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7708. check(403, "bytes=-3");
  7709. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7710. // multipart branch would have written one that is empty.
  7711. check(403, "bytes=1-2, 4-5");
  7712. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7713. // covers the whole representation.
  7714. check(200, "bytes=3-5");
  7715. check(200, "bytes=1-2, 4-5");
  7716. }
  7717. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7718. auto res =
  7719. cli_.Get("/streamed-with-range",
  7720. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7721. "92233720368547758079223372036854775807"}});
  7722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7723. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7724. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7725. EXPECT_EQ(false, res->has_header("Content-Range"));
  7726. EXPECT_EQ(0U, res->body.size());
  7727. }
  7728. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7729. auto res = cli_.Get(
  7730. "/with-range",
  7731. Headers{{"Range",
  7732. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7733. {"Accept-Encoding", ""}});
  7734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7735. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7736. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7737. EXPECT_EQ(true, res->has_header("Content-Range"));
  7738. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7739. EXPECT_EQ(std::string("abcdefg"), res->body);
  7740. }
  7741. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7742. auto res = cli_.Get("/with-range", Headers{
  7743. {"Range", "bytes=0-"},
  7744. {"Accept-Encoding", ""},
  7745. });
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7748. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7749. EXPECT_EQ(true, res->has_header("Content-Range"));
  7750. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7751. EXPECT_EQ(std::string("abcdefg"), res->body);
  7752. }
  7753. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7754. auto res = cli_.Get("/streamed-with-range",
  7755. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7758. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7759. EXPECT_EQ(false, res->has_header("Content-Range"));
  7760. EXPECT_EQ(267U, res->body.size());
  7761. // Check that both range contents are present
  7762. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7763. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7764. // Check that Content-Range headers are present for both ranges
  7765. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7766. std::string::npos);
  7767. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7768. std::string::npos);
  7769. }
  7770. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7771. Ranges ranges;
  7772. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7773. ranges.emplace_back(0, -1);
  7774. }
  7775. auto res = cli_.Get("/streamed-with-range?error",
  7776. Headers{{make_range_header(ranges)}});
  7777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7778. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7779. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7780. EXPECT_EQ(false, res->has_header("Content-Range"));
  7781. EXPECT_EQ(0U, res->body.size());
  7782. }
  7783. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7784. auto res = cli_.Get("/streamed-with-range",
  7785. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7787. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7788. EXPECT_EQ(5U, res->body.size());
  7789. // Check that overlapping ranges are coalesced into a single range
  7790. EXPECT_EQ("bcdef", res->body);
  7791. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7792. // Should be single range, not multipart
  7793. EXPECT_TRUE(res->has_header("Content-Range"));
  7794. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7795. }
  7796. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7797. auto res = cli_.Get("/streamed-with-range",
  7798. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7800. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7801. EXPECT_EQ(268U, res->body.size());
  7802. // Check that both range contents are present
  7803. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7804. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7805. // Check that Content-Range headers are present for both ranges
  7806. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7807. std::string::npos);
  7808. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7809. std::string::npos);
  7810. }
  7811. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7812. auto res = cli_.Get("/streamed-with-range",
  7813. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7816. EXPECT_EQ(269U, res->body.size());
  7817. // Check that both duplicate range contents are present
  7818. size_t first_abc = res->body.find("abc\r\n");
  7819. EXPECT_TRUE(first_abc != std::string::npos);
  7820. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7821. EXPECT_TRUE(second_abc != std::string::npos);
  7822. // Check that Content-Range headers are present for both ranges
  7823. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7824. EXPECT_TRUE(first_range != std::string::npos);
  7825. size_t second_range =
  7826. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7827. EXPECT_TRUE(second_range != std::string::npos);
  7828. }
  7829. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7830. auto res =
  7831. cli_.Get("/streamed-with-range?error",
  7832. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7834. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7835. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7836. EXPECT_EQ(false, res->has_header("Content-Range"));
  7837. EXPECT_EQ(0U, res->body.size());
  7838. }
  7839. TEST_F(ServerTest, GetStreamedEndless) {
  7840. uint64_t offset = 0;
  7841. auto res = cli_.Get("/streamed-cancel",
  7842. [&](const char * /*data*/, uint64_t data_length) {
  7843. if (offset < 100) {
  7844. offset += data_length;
  7845. return true;
  7846. }
  7847. return false;
  7848. });
  7849. ASSERT_TRUE(!res);
  7850. EXPECT_EQ(Error::Canceled, res.error());
  7851. }
  7852. TEST_F(ServerTest, ClientStop) {
  7853. std::atomic_size_t count{4};
  7854. std::vector<std::thread> threads;
  7855. for (auto i = count.load(); i != 0; --i) {
  7856. threads.emplace_back([&]() {
  7857. auto res = cli_.Get("/streamed-cancel",
  7858. [&](const char *, uint64_t) { return true; });
  7859. --count;
  7860. ASSERT_TRUE(!res);
  7861. EXPECT_TRUE(res.error() == Error::Canceled ||
  7862. res.error() == Error::Read || res.error() == Error::Write);
  7863. });
  7864. }
  7865. std::this_thread::sleep_for(std::chrono::seconds(2));
  7866. while (count != 0) {
  7867. cli_.stop();
  7868. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7869. }
  7870. for (auto &t : threads) {
  7871. t.join();
  7872. }
  7873. }
  7874. TEST_F(ServerTest, GetWithRange1) {
  7875. auto res = cli_.Get("/with-range", Headers{
  7876. make_range_header({{3, 5}}),
  7877. {"Accept-Encoding", ""},
  7878. });
  7879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7880. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7881. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7882. EXPECT_EQ(true, res->has_header("Content-Range"));
  7883. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7884. EXPECT_EQ(std::string("def"), res->body);
  7885. }
  7886. TEST_F(ServerTest, GetWithRange2) {
  7887. auto res = cli_.Get("/with-range", Headers{
  7888. make_range_header({{1, -1}}),
  7889. {"Accept-Encoding", ""},
  7890. });
  7891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7892. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7893. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7894. EXPECT_EQ(true, res->has_header("Content-Range"));
  7895. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7896. EXPECT_EQ(std::string("bcdefg"), res->body);
  7897. }
  7898. TEST_F(ServerTest, GetWithRange3) {
  7899. auto res = cli_.Get("/with-range", Headers{
  7900. make_range_header({{0, 0}}),
  7901. {"Accept-Encoding", ""},
  7902. });
  7903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7904. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7905. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7906. EXPECT_EQ(true, res->has_header("Content-Range"));
  7907. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7908. EXPECT_EQ(std::string("a"), res->body);
  7909. }
  7910. TEST_F(ServerTest, GetWithRange4) {
  7911. auto res = cli_.Get("/with-range", Headers{
  7912. make_range_header({{-1, 2}}),
  7913. {"Accept-Encoding", ""},
  7914. });
  7915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7917. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7918. EXPECT_EQ(true, res->has_header("Content-Range"));
  7919. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7920. EXPECT_EQ(std::string("fg"), res->body);
  7921. }
  7922. TEST_F(ServerTest, GetWithRange5) {
  7923. auto res = cli_.Get("/with-range", Headers{
  7924. make_range_header({{0, 5}}),
  7925. {"Accept-Encoding", ""},
  7926. });
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7929. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7930. EXPECT_EQ(true, res->has_header("Content-Range"));
  7931. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7932. EXPECT_EQ(std::string("abcdef"), res->body);
  7933. }
  7934. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7935. auto res =
  7936. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7938. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7939. }
  7940. TEST_F(ServerTest, GetWithRangeMultipart) {
  7941. auto res =
  7942. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7945. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7946. EXPECT_EQ(false, res->has_header("Content-Range"));
  7947. EXPECT_EQ(267U, res->body.size());
  7948. }
  7949. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7950. auto res = cli_.Get("/with-range",
  7951. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7953. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7954. }
  7955. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7956. auto res = cli_.Get("/with-range-customized-response",
  7957. Headers{{make_range_header({{1, 2}})}});
  7958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7959. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7960. EXPECT_EQ(true, res->has_header("Content-Length"));
  7961. EXPECT_EQ(false, res->has_header("Content-Range"));
  7962. EXPECT_EQ(JSON_DATA, res->body);
  7963. }
  7964. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7965. auto res = cli_.Get("/with-range-customized-response",
  7966. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7968. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7969. EXPECT_EQ(true, res->has_header("Content-Length"));
  7970. EXPECT_EQ(false, res->has_header("Content-Range"));
  7971. EXPECT_EQ(JSON_DATA, res->body);
  7972. }
  7973. TEST_F(ServerTest, Issue1772) {
  7974. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7977. }
  7978. TEST_F(ServerTest, Issue609) {
  7979. auto res = cli_.Delete("/issue609");
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::OK_200, res->status);
  7982. EXPECT_EQ(std::string("ok"), res->body);
  7983. }
  7984. TEST_F(ServerTest, GetStreamedChunked) {
  7985. auto res = cli_.Get("/streamed-chunked");
  7986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7987. EXPECT_EQ(StatusCode::OK_200, res->status);
  7988. EXPECT_EQ(std::string("123456789"), res->body);
  7989. }
  7990. TEST_F(ServerTest, GetStreamedChunked2) {
  7991. auto res = cli_.Get("/streamed-chunked2");
  7992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7993. EXPECT_EQ(StatusCode::OK_200, res->status);
  7994. EXPECT_EQ(std::string("123456789"), res->body);
  7995. }
  7996. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7997. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7999. EXPECT_EQ(StatusCode::OK_200, res->status);
  8000. EXPECT_EQ(std::string("123456789"), res->body);
  8001. EXPECT_TRUE(res->has_header("Trailer"));
  8002. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  8003. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  8004. // Trailers are now stored separately from headers (security fix)
  8005. EXPECT_EQ(2U, res->trailers.size());
  8006. EXPECT_TRUE(res->has_trailer("Dummy1"));
  8007. EXPECT_TRUE(res->has_trailer("Dummy2"));
  8008. EXPECT_FALSE(res->has_trailer("Dummy3"));
  8009. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  8010. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  8011. // Verify trailers are NOT in headers (security verification)
  8012. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  8013. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  8014. }
  8015. TEST_F(ServerTest, LargeChunkedPost) {
  8016. Request req;
  8017. req.method = "POST";
  8018. req.path = "/large-chunked";
  8019. std::string host_and_port;
  8020. host_and_port += HOST;
  8021. host_and_port += ":";
  8022. host_and_port += std::to_string(PORT);
  8023. req.headers.emplace("Host", host_and_port.c_str());
  8024. req.headers.emplace("Accept", "*/*");
  8025. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  8026. req.headers.emplace("Content-Type", "text/plain");
  8027. req.headers.emplace("Content-Length", "0");
  8028. req.headers.emplace("Transfer-Encoding", "chunked");
  8029. std::string long_string(30 * 1024u, 'a');
  8030. std::string chunk = "7800\r\n" + long_string + "\r\n";
  8031. // Attempt to make a large enough post to exceed OS buffers, to test that
  8032. // the server handles short reads if the full chunk data isn't available.
  8033. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  8034. auto res = std::make_shared<Response>();
  8035. auto error = Error::Success;
  8036. auto ret = cli_.send(req, *res, error);
  8037. ASSERT_TRUE(ret);
  8038. EXPECT_EQ(StatusCode::OK_200, res->status);
  8039. }
  8040. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8041. auto res = cli_.Get("/remote_addr");
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(StatusCode::OK_200, res->status);
  8044. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8045. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8046. }
  8047. TEST_F(ServerTest, GetMethodLocalAddr) {
  8048. auto res = cli_.Get("/local_addr");
  8049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8050. EXPECT_EQ(StatusCode::OK_200, res->status);
  8051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8052. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8053. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8054. }
  8055. TEST_F(ServerTest, HTTPResponseSplitting) {
  8056. auto res = cli_.Get("/http_response_splitting");
  8057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8058. EXPECT_EQ(StatusCode::OK_200, res->status);
  8059. }
  8060. TEST_F(ServerTest, SlowRequest) {
  8061. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8062. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8063. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8064. }
  8065. #if 0
  8066. TEST_F(ServerTest, SlowPost) {
  8067. char buffer[64 * 1024];
  8068. memset(buffer, 0x42, sizeof(buffer));
  8069. auto res = cli_.Post(
  8070. "/slowpost", 64 * 1024 * 1024,
  8071. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8072. auto ret = sink.write(buffer, sizeof(buffer));
  8073. EXPECT_TRUE(ret);
  8074. return true;
  8075. },
  8076. "text/plain");
  8077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8078. EXPECT_EQ(StatusCode::OK_200, res->status);
  8079. }
  8080. TEST_F(ServerTest, SlowPostFail) {
  8081. char buffer[64 * 1024];
  8082. memset(buffer, 0x42, sizeof(buffer));
  8083. cli_.set_write_timeout(std::chrono::seconds(0));
  8084. auto res = cli_.Post(
  8085. "/slowpost", 64 * 1024 * 1024,
  8086. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8087. sink.write(buffer, sizeof(buffer));
  8088. return true;
  8089. },
  8090. "text/plain");
  8091. ASSERT_TRUE(!res);
  8092. EXPECT_EQ(Error::Write, res.error());
  8093. }
  8094. #endif
  8095. TEST_F(ServerTest, Put) {
  8096. auto res = cli_.Put("/put", "PUT", "text/plain");
  8097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8098. EXPECT_EQ(StatusCode::OK_200, res->status);
  8099. EXPECT_EQ("PUT", res->body);
  8100. }
  8101. TEST_F(ServerTest, PutWithContentProvider) {
  8102. auto res = cli_.Put(
  8103. "/put", 3,
  8104. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8105. sink.os << "PUT";
  8106. return true;
  8107. },
  8108. "text/plain");
  8109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8110. EXPECT_EQ(StatusCode::OK_200, res->status);
  8111. EXPECT_EQ("PUT", res->body);
  8112. }
  8113. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8114. auto res = cli_.Post(
  8115. "/post", 42,
  8116. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8117. return false;
  8118. },
  8119. "text/plain");
  8120. ASSERT_TRUE(!res);
  8121. EXPECT_EQ(Error::Canceled, res.error());
  8122. }
  8123. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8124. auto res = cli_.Put(
  8125. "/put",
  8126. [](size_t /*offset*/, DataSink &sink) {
  8127. sink.os << "PUT";
  8128. sink.done();
  8129. return true;
  8130. },
  8131. "text/plain");
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. EXPECT_EQ("PUT", res->body);
  8135. }
  8136. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8137. auto res = cli_.Post(
  8138. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8139. "text/plain");
  8140. ASSERT_TRUE(!res);
  8141. EXPECT_EQ(Error::Canceled, res.error());
  8142. }
  8143. TEST_F(ServerTest, PostLoopBack) {
  8144. std::string body;
  8145. auto res = cli_.Post(
  8146. "/post-loopback", 9,
  8147. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8148. EXPECT_EQ(9u, length);
  8149. sink.write("123", 3);
  8150. sink.write("456", 3);
  8151. sink.write("789", 3);
  8152. return true;
  8153. },
  8154. "text/plain",
  8155. [&body](const char *data, size_t data_length) {
  8156. body.append(data, data_length);
  8157. return true;
  8158. });
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_EQ(StatusCode::OK_200, res->status);
  8161. EXPECT_EQ("123456789", body);
  8162. }
  8163. TEST_F(ServerTest, PutLoopBack) {
  8164. std::string body;
  8165. auto res = cli_.Put(
  8166. "/put-loopback", 9,
  8167. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8168. EXPECT_EQ(9u, length);
  8169. sink.write("123", 3);
  8170. sink.write("456", 3);
  8171. sink.write("789", 3);
  8172. return true;
  8173. },
  8174. "text/plain",
  8175. [&body](const char *data, size_t data_length) {
  8176. body.append(data, data_length);
  8177. return true;
  8178. });
  8179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8180. EXPECT_EQ(StatusCode::OK_200, res->status);
  8181. EXPECT_EQ("123456789", body);
  8182. }
  8183. TEST_F(ServerTest, PatchLoopBack) {
  8184. std::string body;
  8185. auto res = cli_.Patch(
  8186. "/patch-loopback", 9,
  8187. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8188. EXPECT_EQ(9u, length);
  8189. sink.write("123", 3);
  8190. sink.write("456", 3);
  8191. sink.write("789", 3);
  8192. return true;
  8193. },
  8194. "text/plain",
  8195. [&body](const char *data, size_t data_length) {
  8196. body.append(data, data_length);
  8197. return true;
  8198. });
  8199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8200. EXPECT_EQ(StatusCode::OK_200, res->status);
  8201. EXPECT_EQ("123456789", body);
  8202. }
  8203. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8204. std::string body;
  8205. auto res = cli_.Post(
  8206. "/post-loopback",
  8207. [](size_t /*offset*/, DataSink &sink) {
  8208. sink.write("123", 3);
  8209. sink.write("456", 3);
  8210. sink.write("789", 3);
  8211. sink.done();
  8212. return true;
  8213. },
  8214. "text/plain",
  8215. [&body](const char *data, size_t data_length) {
  8216. body.append(data, data_length);
  8217. return true;
  8218. });
  8219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8220. EXPECT_EQ(StatusCode::OK_200, res->status);
  8221. EXPECT_EQ("123456789", body);
  8222. }
  8223. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8224. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8225. cli_.set_compress(true);
  8226. auto res = cli_.Put(
  8227. "/put", 3,
  8228. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8229. sink.os << "PUT";
  8230. return true;
  8231. },
  8232. "text/plain");
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::OK_200, res->status);
  8235. EXPECT_EQ("PUT", res->body);
  8236. }
  8237. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8238. cli_.set_compress(true);
  8239. auto res = cli_.Post(
  8240. "/post", 42,
  8241. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8242. return false;
  8243. },
  8244. "text/plain");
  8245. ASSERT_TRUE(!res);
  8246. EXPECT_EQ(Error::Canceled, res.error());
  8247. }
  8248. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8249. cli_.set_compress(true);
  8250. auto res = cli_.Put(
  8251. "/put",
  8252. [](size_t /*offset*/, DataSink &sink) {
  8253. sink.os << "PUT";
  8254. sink.done();
  8255. return true;
  8256. },
  8257. "text/plain");
  8258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8259. EXPECT_EQ(StatusCode::OK_200, res->status);
  8260. EXPECT_EQ("PUT", res->body);
  8261. }
  8262. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8263. cli_.set_compress(true);
  8264. auto res = cli_.Post(
  8265. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8266. "text/plain");
  8267. ASSERT_TRUE(!res);
  8268. EXPECT_EQ(Error::Canceled, res.error());
  8269. }
  8270. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8271. cli_.set_compress(true);
  8272. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8274. EXPECT_EQ(StatusCode::OK_200, res->status);
  8275. EXPECT_EQ(LARGE_DATA, res->body);
  8276. }
  8277. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8278. #ifdef CPPHTTPLIB_SSL_ENABLED
  8279. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8280. Client cli(s.c_str());
  8281. cli.enable_server_certificate_verification(false);
  8282. #else
  8283. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8284. Client cli(s.c_str());
  8285. #endif
  8286. cli.set_compress(true);
  8287. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8289. EXPECT_EQ(StatusCode::OK_200, res->status);
  8290. EXPECT_EQ(LARGE_DATA, res->body);
  8291. // The compressed size should be less than a 10th of the original. May vary
  8292. // depending on the zlib library.
  8293. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8294. static_cast<uint64_t>(10 * 1024 * 1024));
  8295. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8296. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8297. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8298. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8299. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8300. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8301. #endif
  8302. }
  8303. TEST_F(ServerTest, PutContentWithDeflate) {
  8304. cli_.set_compress(false);
  8305. Headers headers;
  8306. headers.emplace("Content-Encoding", "deflate");
  8307. // PUT in deflate format:
  8308. auto res = cli_.Put("/put", headers,
  8309. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8311. EXPECT_EQ(StatusCode::OK_200, res->status);
  8312. EXPECT_EQ("PUT", res->body);
  8313. }
  8314. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8315. Headers headers;
  8316. headers.emplace("Accept-Encoding", "gzip, deflate");
  8317. auto res = cli_.Get("/streamed-chunked", headers);
  8318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8319. EXPECT_EQ(StatusCode::OK_200, res->status);
  8320. EXPECT_EQ(std::string("123456789"), res->body);
  8321. }
  8322. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8323. Headers headers;
  8324. headers.emplace("Accept-Encoding", "gzip, deflate");
  8325. auto res = cli_.Get("/streamed-chunked2", headers);
  8326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8327. EXPECT_EQ(StatusCode::OK_200, res->status);
  8328. EXPECT_EQ(std::string("123456789"), res->body);
  8329. }
  8330. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8331. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. }
  8335. TEST(GzipDecompressor, ChunkedDecompression) {
  8336. std::string data;
  8337. for (size_t i = 0; i < 32 * 1024; ++i) {
  8338. data.push_back(static_cast<char>('a' + i % 26));
  8339. }
  8340. std::string compressed_data;
  8341. {
  8342. httplib::detail::gzip_compressor compressor;
  8343. bool result = compressor.compress(
  8344. data.data(), data.size(),
  8345. /*last=*/true,
  8346. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8347. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8348. compressed_data_size);
  8349. return true;
  8350. });
  8351. ASSERT_TRUE(result);
  8352. }
  8353. std::string decompressed_data;
  8354. {
  8355. httplib::detail::gzip_decompressor decompressor;
  8356. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8357. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8358. size_t chunk_size = 130;
  8359. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8360. chunk_begin += chunk_size) {
  8361. size_t current_chunk_size =
  8362. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8363. bool result = decompressor.decompress(
  8364. compressed_data.data() + chunk_begin, current_chunk_size,
  8365. [&](const char *decompressed_data_chunk,
  8366. size_t decompressed_data_chunk_size) {
  8367. decompressed_data.insert(decompressed_data.size(),
  8368. decompressed_data_chunk,
  8369. decompressed_data_chunk_size);
  8370. return true;
  8371. });
  8372. ASSERT_TRUE(result);
  8373. }
  8374. }
  8375. ASSERT_EQ(data, decompressed_data);
  8376. }
  8377. TEST(GzipDecompressor, DeflateDecompression) {
  8378. std::string original_text = "Raw deflate without gzip";
  8379. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8380. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8381. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8382. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8383. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8384. std::string decompressed_data;
  8385. {
  8386. httplib::detail::gzip_decompressor decompressor;
  8387. bool result = decompressor.decompress(
  8388. compressed_data.data(), compressed_data.size(),
  8389. [&](const char *decompressed_data_chunk,
  8390. size_t decompressed_data_chunk_size) {
  8391. decompressed_data.insert(decompressed_data.size(),
  8392. decompressed_data_chunk,
  8393. decompressed_data_chunk_size);
  8394. return true;
  8395. });
  8396. ASSERT_TRUE(result);
  8397. }
  8398. ASSERT_EQ(original_text, decompressed_data);
  8399. }
  8400. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8401. std::string original_text = "Raw deflate without gzip";
  8402. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8403. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8404. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8405. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8406. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8407. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8408. std::string decompressed_data;
  8409. {
  8410. httplib::detail::gzip_decompressor decompressor;
  8411. bool result = decompressor.decompress(
  8412. compressed_data.data(), compressed_data.size(),
  8413. [&](const char *decompressed_data_chunk,
  8414. size_t decompressed_data_chunk_size) {
  8415. decompressed_data.insert(decompressed_data.size(),
  8416. decompressed_data_chunk,
  8417. decompressed_data_chunk_size);
  8418. return true;
  8419. });
  8420. ASSERT_TRUE(result);
  8421. }
  8422. ASSERT_EQ(original_text, decompressed_data);
  8423. }
  8424. #endif
  8425. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8426. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8427. Headers headers;
  8428. headers.emplace("Accept-Encoding", "br");
  8429. auto res = cli_.Get("/streamed-chunked", headers);
  8430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8431. EXPECT_EQ(StatusCode::OK_200, res->status);
  8432. EXPECT_EQ(std::string("123456789"), res->body);
  8433. }
  8434. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8435. Headers headers;
  8436. headers.emplace("Accept-Encoding", "br");
  8437. auto res = cli_.Get("/streamed-chunked2", headers);
  8438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8439. EXPECT_EQ(StatusCode::OK_200, res->status);
  8440. EXPECT_EQ(std::string("123456789"), res->body);
  8441. }
  8442. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8443. cli_.set_compress(true);
  8444. auto res = cli_.Put(
  8445. "/put", 3,
  8446. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8447. sink.os << "PUT";
  8448. return true;
  8449. },
  8450. "text/plain");
  8451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8452. EXPECT_EQ(StatusCode::OK_200, res->status);
  8453. EXPECT_EQ("PUT", res->body);
  8454. }
  8455. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8456. cli_.set_compress(true);
  8457. auto res = cli_.Put(
  8458. "/put",
  8459. [](size_t /*offset*/, DataSink &sink) {
  8460. sink.os << "PUT";
  8461. sink.done();
  8462. return true;
  8463. },
  8464. "text/plain");
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(StatusCode::OK_200, res->status);
  8467. EXPECT_EQ("PUT", res->body);
  8468. }
  8469. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8470. cli_.set_compress(true);
  8471. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. EXPECT_EQ(LARGE_DATA, res->body);
  8475. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8476. }
  8477. #endif
  8478. TEST_F(ServerTest, Patch) {
  8479. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8481. EXPECT_EQ(StatusCode::OK_200, res->status);
  8482. EXPECT_EQ("PATCH", res->body);
  8483. }
  8484. TEST_F(ServerTest, Delete) {
  8485. auto res = cli_.Delete("/delete");
  8486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8487. EXPECT_EQ(StatusCode::OK_200, res->status);
  8488. EXPECT_EQ("DELETE", res->body);
  8489. }
  8490. TEST_F(ServerTest, DeleteContentReceiver) {
  8491. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8493. EXPECT_EQ(StatusCode::OK_200, res->status);
  8494. EXPECT_EQ("content", res->body);
  8495. }
  8496. TEST_F(ServerTest, Options) {
  8497. auto res = cli_.Options("*");
  8498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8499. EXPECT_EQ(StatusCode::OK_200, res->status);
  8500. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8501. EXPECT_TRUE(res->body.empty());
  8502. }
  8503. TEST_F(ServerTest, URL) {
  8504. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8506. EXPECT_EQ(StatusCode::OK_200, res->status);
  8507. }
  8508. TEST_F(ServerTest, ArrayParam) {
  8509. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8511. EXPECT_EQ(StatusCode::OK_200, res->status);
  8512. }
  8513. TEST_F(ServerTest, ArrayParamValues) {
  8514. auto res =
  8515. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8517. EXPECT_EQ(StatusCode::OK_200, res->status);
  8518. }
  8519. TEST_F(ServerTest, NoMultipleHeaders) {
  8520. Headers headers = {{"Content-Length", "5"}};
  8521. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8522. "text/plain");
  8523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8524. EXPECT_EQ(StatusCode::OK_200, res->status);
  8525. }
  8526. TEST_F(ServerTest, PostContentReceiver) {
  8527. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8529. ASSERT_EQ(StatusCode::OK_200, res->status);
  8530. ASSERT_EQ("content", res->body);
  8531. }
  8532. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8533. UploadFormDataItems items = {
  8534. {"text1", "text default", "", ""},
  8535. {"text2", "aωb", "", ""},
  8536. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8537. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8538. {"file3", "", "", "application/octet-stream"},
  8539. };
  8540. auto res = cli_.Post("/content_receiver", items);
  8541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8542. EXPECT_EQ(StatusCode::OK_200, res->status);
  8543. }
  8544. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8545. UploadFormDataItems items = {
  8546. {"text1", "text default", "", ""},
  8547. {"text2", "aωb", "", ""},
  8548. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8549. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8550. {"file3", "", "", "application/octet-stream"},
  8551. };
  8552. auto boundary = std::string("+++++");
  8553. std::string body;
  8554. for (const auto &item : items) {
  8555. body += "--" + boundary + "\r\n";
  8556. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8557. if (!item.filename.empty()) {
  8558. body += "; filename=\"" + item.filename + "\"";
  8559. }
  8560. body += "\r\n";
  8561. if (!item.content_type.empty()) {
  8562. body += "Content-Type: " + item.content_type + "\r\n";
  8563. }
  8564. body += "\r\n";
  8565. body += item.content + "\r\n";
  8566. }
  8567. body += "--" + boundary + "--\r\n";
  8568. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8569. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8571. EXPECT_EQ(StatusCode::OK_200, res->status);
  8572. }
  8573. TEST(MultipartFormDataTest, FieldEscaping) {
  8574. Server svr;
  8575. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8576. const ContentReader &content_reader) {
  8577. ASSERT_TRUE(req.is_multipart_form_data());
  8578. std::vector<FormData> received;
  8579. content_reader(
  8580. [&](const FormData &file) {
  8581. received.push_back(file);
  8582. return true;
  8583. },
  8584. [&](const char *data, size_t data_length) {
  8585. received.back().content.append(data, data_length);
  8586. return true;
  8587. });
  8588. // '"', CR and LF in names and filenames are escaped following the
  8589. // WHATWG HTML standard, so each part still parses as a single part
  8590. // with no injected headers. Content types get CR/LF escaped too,
  8591. // while '"' (legal there, e.g. quoted charset) is preserved.
  8592. ASSERT_EQ(4U, received.size());
  8593. EXPECT_EQ("na%22me", received[0].name);
  8594. EXPECT_EQ("quoted name", received[0].content);
  8595. EXPECT_EQ("file", received[1].name);
  8596. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8597. received[1].filename);
  8598. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8599. EXPECT_EQ("injected", received[1].content);
  8600. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8601. EXPECT_EQ("my%22file.txt", received[2].filename);
  8602. EXPECT_EQ("cr lf name", received[2].content);
  8603. EXPECT_EQ("typed", received[3].name);
  8604. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8605. received[3].content_type);
  8606. EXPECT_EQ("typed content", received[3].content);
  8607. });
  8608. auto port = svr.bind_to_any_port("localhost");
  8609. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8610. auto se = detail::scope_exit([&] {
  8611. svr.stop();
  8612. t.join();
  8613. ASSERT_FALSE(svr.is_running());
  8614. });
  8615. svr.wait_until_ready();
  8616. Client cli("localhost", port);
  8617. UploadFormDataItems items = {
  8618. {"na\"me", "quoted name", "", ""},
  8619. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8620. "application/octet-stream"},
  8621. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8622. {"typed", "typed content", "",
  8623. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8624. };
  8625. auto res = cli.Post("/post", items);
  8626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8627. EXPECT_EQ(StatusCode::OK_200, res->status);
  8628. }
  8629. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8630. const UploadFormDataItems items = {
  8631. {"name1", "Content 1", "", ""},
  8632. {"name2", "Content 2", "file2.txt", "text/plain"},
  8633. };
  8634. Server svr;
  8635. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8636. const ContentReader &content_reader) {
  8637. ASSERT_TRUE(req.is_multipart_form_data());
  8638. std::vector<FormData> received;
  8639. content_reader(
  8640. [&](const FormData &file) {
  8641. received.push_back(file);
  8642. return true;
  8643. },
  8644. [&](const char *data, size_t data_length) {
  8645. received.back().content.append(data, data_length);
  8646. return true;
  8647. });
  8648. ASSERT_EQ(2U, received.size());
  8649. EXPECT_EQ("name1", received[0].name);
  8650. EXPECT_EQ("Content 1", received[0].content);
  8651. EXPECT_EQ("name2", received[1].name);
  8652. EXPECT_EQ("Content 2", received[1].content);
  8653. EXPECT_EQ("file2.txt", received[1].filename);
  8654. EXPECT_EQ("text/plain", received[1].content_type);
  8655. });
  8656. auto port = svr.bind_to_any_port("localhost");
  8657. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8658. auto se = detail::scope_exit([&] {
  8659. svr.stop();
  8660. t.join();
  8661. ASSERT_FALSE(svr.is_running());
  8662. });
  8663. svr.wait_until_ready();
  8664. Client cli("localhost", port);
  8665. // Whole-body serialization with a generated boundary
  8666. {
  8667. MultipartFormDataWriter writer;
  8668. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8669. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8670. writer.content_type());
  8671. auto body = writer.serialize(items);
  8672. EXPECT_EQ(body.size(), writer.content_length(items));
  8673. auto res = cli.Post("/post", body, writer.content_type());
  8674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8675. EXPECT_EQ(StatusCode::OK_200, res->status);
  8676. }
  8677. // Per-part framing with a custom boundary via a content provider
  8678. {
  8679. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8680. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8681. MultipartFormDataWriter writer("custom-boundary_123");
  8682. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8683. std::string body;
  8684. for (const auto &item : items) {
  8685. body += writer.item_begin(item);
  8686. body += item.content;
  8687. body += MultipartFormDataWriter::item_end();
  8688. }
  8689. body += writer.finish();
  8690. EXPECT_EQ(body.size(), writer.content_length(items));
  8691. auto res = cli.Post(
  8692. "/post", body.size(),
  8693. [&](size_t offset, size_t length, DataSink &sink) {
  8694. sink.write(body.data() + offset, length);
  8695. return true;
  8696. },
  8697. writer.content_type());
  8698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8699. EXPECT_EQ(StatusCode::OK_200, res->status);
  8700. }
  8701. }
  8702. TEST_F(ServerTest, PostContentReceiverGzip) {
  8703. cli_.set_compress(true);
  8704. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8706. ASSERT_EQ(StatusCode::OK_200, res->status);
  8707. ASSERT_EQ("content", res->body);
  8708. }
  8709. TEST_F(ServerTest, PutContentReceiver) {
  8710. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8712. ASSERT_EQ(StatusCode::OK_200, res->status);
  8713. ASSERT_EQ("content", res->body);
  8714. }
  8715. TEST_F(ServerTest, PatchContentReceiver) {
  8716. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8718. ASSERT_EQ(StatusCode::OK_200, res->status);
  8719. ASSERT_EQ("content", res->body);
  8720. }
  8721. template <typename ClientType>
  8722. void TestWithHeadersAndContentReceiver(
  8723. ClientType &cli,
  8724. std::function<Result(ClientType &, const std::string &, const Headers &,
  8725. const std::string &, const std::string &,
  8726. ContentReceiver, DownloadProgress)>
  8727. request_func) {
  8728. Headers headers;
  8729. headers.emplace("X-Custom-Header", "test-value");
  8730. std::string received_body;
  8731. auto res = request_func(
  8732. cli, "/content_receiver", headers, "content", "application/json",
  8733. [&](const char *data, size_t data_length) {
  8734. received_body.append(data, data_length);
  8735. return true;
  8736. },
  8737. nullptr);
  8738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8739. EXPECT_EQ(StatusCode::OK_200, res->status);
  8740. EXPECT_EQ("content", received_body);
  8741. }
  8742. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8743. #ifdef CPPHTTPLIB_SSL_ENABLED
  8744. using ClientT = SSLClient;
  8745. #else
  8746. using ClientT = Client;
  8747. #endif
  8748. TestWithHeadersAndContentReceiver<ClientT>(
  8749. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8750. const std::string &body, const std::string &content_type,
  8751. ContentReceiver receiver, DownloadProgress progress) {
  8752. return cli.Post(path, headers, body, content_type, receiver, progress);
  8753. });
  8754. }
  8755. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8756. #ifdef CPPHTTPLIB_SSL_ENABLED
  8757. using ClientT = SSLClient;
  8758. #else
  8759. using ClientT = Client;
  8760. #endif
  8761. TestWithHeadersAndContentReceiver<ClientT>(
  8762. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8763. const std::string &body, const std::string &content_type,
  8764. ContentReceiver receiver, DownloadProgress progress) {
  8765. return cli.Put(path, headers, body, content_type, receiver, progress);
  8766. });
  8767. }
  8768. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8769. #ifdef CPPHTTPLIB_SSL_ENABLED
  8770. using ClientT = SSLClient;
  8771. #else
  8772. using ClientT = Client;
  8773. #endif
  8774. TestWithHeadersAndContentReceiver<ClientT>(
  8775. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8776. const std::string &body, const std::string &content_type,
  8777. ContentReceiver receiver, DownloadProgress progress) {
  8778. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8779. });
  8780. }
  8781. template <typename ClientType>
  8782. void TestWithHeadersAndContentReceiverWithProgress(
  8783. ClientType &cli,
  8784. std::function<Result(ClientType &, const std::string &, const Headers &,
  8785. const std::string &, const std::string &,
  8786. ContentReceiver, DownloadProgress)>
  8787. request_func) {
  8788. Headers headers;
  8789. headers.emplace("X-Test-Header", "progress-test");
  8790. std::string received_body;
  8791. auto progress_called = false;
  8792. auto res = request_func(
  8793. cli, "/content_receiver", headers, "content", "text/plain",
  8794. [&](const char *data, size_t data_length) {
  8795. received_body.append(data, data_length);
  8796. return true;
  8797. },
  8798. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8799. progress_called = true;
  8800. return true;
  8801. });
  8802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8803. EXPECT_EQ(StatusCode::OK_200, res->status);
  8804. EXPECT_EQ("content", received_body);
  8805. EXPECT_TRUE(progress_called);
  8806. }
  8807. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8808. #ifdef CPPHTTPLIB_SSL_ENABLED
  8809. using ClientT = SSLClient;
  8810. #else
  8811. using ClientT = Client;
  8812. #endif
  8813. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8814. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8815. const std::string &body, const std::string &content_type,
  8816. ContentReceiver receiver, DownloadProgress progress) {
  8817. return cli.Post(path, headers, body, content_type, receiver, progress);
  8818. });
  8819. }
  8820. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8821. #ifdef CPPHTTPLIB_SSL_ENABLED
  8822. using ClientT = SSLClient;
  8823. #else
  8824. using ClientT = Client;
  8825. #endif
  8826. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8827. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8828. const std::string &body, const std::string &content_type,
  8829. ContentReceiver receiver, DownloadProgress progress) {
  8830. return cli.Put(path, headers, body, content_type, receiver, progress);
  8831. });
  8832. }
  8833. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8834. #ifdef CPPHTTPLIB_SSL_ENABLED
  8835. using ClientT = SSLClient;
  8836. #else
  8837. using ClientT = Client;
  8838. #endif
  8839. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8840. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8841. const std::string &body, const std::string &content_type,
  8842. ContentReceiver receiver, DownloadProgress progress) {
  8843. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8844. });
  8845. }
  8846. template <typename ClientType>
  8847. void TestWithHeadersAndContentReceiverError(
  8848. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8849. const Headers &, const std::string &,
  8850. const std::string &, ContentReceiver)>
  8851. request_func) {
  8852. Headers headers;
  8853. headers.emplace("X-Error-Test", "true");
  8854. std::string received_body;
  8855. auto receiver_failed = false;
  8856. auto res =
  8857. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8858. [&](const char *data, size_t data_length) {
  8859. received_body.append(data, data_length);
  8860. receiver_failed = true;
  8861. return false;
  8862. });
  8863. ASSERT_FALSE(res);
  8864. EXPECT_TRUE(receiver_failed);
  8865. }
  8866. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8867. #ifdef CPPHTTPLIB_SSL_ENABLED
  8868. using ClientT = SSLClient;
  8869. #else
  8870. using ClientT = Client;
  8871. #endif
  8872. TestWithHeadersAndContentReceiverError<ClientT>(
  8873. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8874. const std::string &body, const std::string &content_type,
  8875. ContentReceiver receiver) {
  8876. return cli.Post(path, headers, body, content_type, receiver);
  8877. });
  8878. }
  8879. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8880. #ifdef CPPHTTPLIB_SSL_ENABLED
  8881. using ClientT = SSLClient;
  8882. #else
  8883. using ClientT = Client;
  8884. #endif
  8885. TestWithHeadersAndContentReceiverError<ClientT>(
  8886. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8887. const std::string &body, const std::string &content_type,
  8888. ContentReceiver receiver) {
  8889. return cli.Put(path, headers, body, content_type, receiver);
  8890. });
  8891. }
  8892. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8893. #ifdef CPPHTTPLIB_SSL_ENABLED
  8894. using ClientT = SSLClient;
  8895. #else
  8896. using ClientT = Client;
  8897. #endif
  8898. TestWithHeadersAndContentReceiverError<ClientT>(
  8899. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8900. const std::string &body, const std::string &content_type,
  8901. ContentReceiver receiver) {
  8902. return cli.Patch(path, headers, body, content_type, receiver);
  8903. });
  8904. }
  8905. TEST_F(ServerTest, PostQueryStringAndBody) {
  8906. auto res =
  8907. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8909. ASSERT_EQ(StatusCode::OK_200, res->status);
  8910. }
  8911. TEST_F(ServerTest, HTTP2Magic) {
  8912. Request req;
  8913. req.method = "PRI";
  8914. req.path = "*";
  8915. req.body = "SM";
  8916. auto res = std::make_shared<Response>();
  8917. auto error = Error::Success;
  8918. auto ret = cli_.send(req, *res, error);
  8919. ASSERT_TRUE(ret);
  8920. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8921. }
  8922. TEST_F(ServerTest, KeepAlive) {
  8923. auto res = cli_.Get("/hi");
  8924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8925. EXPECT_EQ(StatusCode::OK_200, res->status);
  8926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8927. EXPECT_EQ("Hello World!", res->body);
  8928. res = cli_.Get("/hi");
  8929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8930. EXPECT_EQ(StatusCode::OK_200, res->status);
  8931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8932. EXPECT_EQ("Hello World!", res->body);
  8933. res = cli_.Get("/hi");
  8934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8935. EXPECT_EQ(StatusCode::OK_200, res->status);
  8936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8937. EXPECT_EQ("Hello World!", res->body);
  8938. res = cli_.Get("/not-exist");
  8939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8940. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8941. res = cli_.Post("/empty", "", "text/plain");
  8942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8943. EXPECT_EQ(StatusCode::OK_200, res->status);
  8944. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8945. EXPECT_EQ("empty", res->body);
  8946. EXPECT_EQ("close", res->get_header_value("Connection"));
  8947. res = cli_.Post(
  8948. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8949. "text/plain");
  8950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8951. EXPECT_EQ(StatusCode::OK_200, res->status);
  8952. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8953. EXPECT_EQ("empty", res->body);
  8954. cli_.set_keep_alive(false);
  8955. res = cli_.Get("/last-request");
  8956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8957. EXPECT_EQ(StatusCode::OK_200, res->status);
  8958. EXPECT_EQ("close", res->get_header_value("Connection"));
  8959. }
  8960. TEST_F(ServerTest, TooManyRedirect) {
  8961. cli_.set_follow_location(true);
  8962. auto res = cli_.Get("/redirect/0");
  8963. ASSERT_TRUE(!res);
  8964. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8965. }
  8966. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8967. Request req;
  8968. req.method = "FOOBAR";
  8969. req.path = "/hi";
  8970. cli_.set_keep_alive(true);
  8971. auto res = cli_.send(req);
  8972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8973. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8974. EXPECT_EQ("close", res->get_header_value("Connection"));
  8975. EXPECT_FALSE(cli_.is_socket_open());
  8976. }
  8977. TEST_F(ServerTest, CustomRouteReadsBody) {
  8978. const std::string xml =
  8979. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8980. Request req;
  8981. req.method = "PROPFIND";
  8982. req.path = "/dav/dir";
  8983. req.set_header("Depth", "1");
  8984. req.body = xml;
  8985. auto res = cli_.send(req);
  8986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8987. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8988. EXPECT_EQ(xml, res->body);
  8989. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8990. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8991. }
  8992. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8993. Request req;
  8994. req.method = "PROPFIND";
  8995. req.path = "/dav/42";
  8996. auto res = cli_.send(req);
  8997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8998. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8999. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  9000. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  9001. }
  9002. TEST_F(ServerTest, CustomRouteRegexPattern) {
  9003. Request req;
  9004. req.method = "PROPFIND";
  9005. req.path = "/dav-re/123";
  9006. auto res = cli_.send(req);
  9007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9008. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9009. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  9010. }
  9011. TEST_F(ServerTest, CustomRouteWithoutBody) {
  9012. Request req;
  9013. req.method = "MKCOL";
  9014. req.path = "/dav-mkcol";
  9015. auto res = cli_.send(req);
  9016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9017. EXPECT_EQ(StatusCode::Created_201, res->status);
  9018. }
  9019. TEST_F(ServerTest, CustomRouteWithContentReader) {
  9020. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  9021. Request req;
  9022. req.method = "REPORT";
  9023. req.path = "/dav-report";
  9024. req.body = xml;
  9025. auto res = cli_.send(req);
  9026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9027. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9028. EXPECT_EQ(xml, res->body);
  9029. }
  9030. // A content reader route must fire even when the request carries no body,
  9031. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  9032. // Without that, a body-less PROPFIND-style request would fall through to 404.
  9033. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  9034. Request req;
  9035. req.method = "REPORT";
  9036. req.path = "/dav-report";
  9037. auto res = cli_.send(req);
  9038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9039. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9040. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9041. }
  9042. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9043. Request req;
  9044. req.method = "PROPFIND";
  9045. req.path = "/not-dav";
  9046. auto res = cli_.send(req);
  9047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9048. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9049. }
  9050. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9051. Request req;
  9052. req.method = "UNLOCK";
  9053. req.path = "/dav/dir";
  9054. cli_.set_keep_alive(true);
  9055. auto res = cli_.send(req);
  9056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9057. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9058. EXPECT_EQ("close", res->get_header_value("Connection"));
  9059. EXPECT_FALSE(cli_.is_socket_open());
  9060. }
  9061. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9062. // The mount point serves this path, but only for GET and HEAD.
  9063. auto get_res = cli_.Get("/dir/index.html");
  9064. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9065. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9066. Request req;
  9067. req.method = "PROPFIND";
  9068. req.path = "/dir/index.html";
  9069. auto res = cli_.send(req);
  9070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9072. }
  9073. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9074. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9075. cli_.set_keep_alive(true);
  9076. for (auto i = 0; i < 2; i++) {
  9077. Request req;
  9078. req.method = "PROPFIND";
  9079. req.path = "/dav/dir";
  9080. req.body = xml;
  9081. auto res = cli_.send(req);
  9082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9083. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9084. EXPECT_EQ(xml, res->body);
  9085. EXPECT_TRUE(cli_.is_socket_open());
  9086. }
  9087. // A built-in method must still be served on the same connection.
  9088. cli_.set_keep_alive(false);
  9089. auto res = cli_.Get("/hi");
  9090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9091. EXPECT_EQ(StatusCode::OK_200, res->status);
  9092. EXPECT_EQ("close", res->get_header_value("Connection"));
  9093. }
  9094. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9095. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9096. Request req;
  9097. req.method = "PROPFIND";
  9098. req.path = "/dav/dir";
  9099. req.set_header("Expect", "100-continue");
  9100. req.body = xml;
  9101. auto res = cli_.send(req);
  9102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9103. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9104. EXPECT_EQ(xml, res->body);
  9105. }
  9106. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9107. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9108. TEST_F(ServerTest, Gzip) {
  9109. Headers headers;
  9110. headers.emplace("Accept-Encoding", "gzip, deflate");
  9111. auto res = cli_.Get("/compress", headers);
  9112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9113. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9114. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9115. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9116. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9117. "7890123456789012345678901234567890",
  9118. res->body);
  9119. EXPECT_EQ(StatusCode::OK_200, res->status);
  9120. }
  9121. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9122. Headers headers;
  9123. headers.emplace("Accept-Encoding", "gzip, deflate");
  9124. auto res = cli_.Get("/compress-with-charset", headers);
  9125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9126. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9127. EXPECT_EQ("application/json; charset=utf-8",
  9128. res->get_header_value("Content-Type"));
  9129. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9130. "7890123456789012345678901234567890",
  9131. res->body);
  9132. EXPECT_EQ(StatusCode::OK_200, res->status);
  9133. }
  9134. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9135. Headers headers;
  9136. headers.emplace("Accept-Encoding", "");
  9137. auto res = cli_.Get("/compress", headers);
  9138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9139. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9140. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9141. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9142. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9143. "7890123456789012345678901234567890",
  9144. res->body);
  9145. EXPECT_EQ(StatusCode::OK_200, res->status);
  9146. }
  9147. TEST_F(ServerTest, GzipWithContentReceiver) {
  9148. Headers headers;
  9149. headers.emplace("Accept-Encoding", "gzip, deflate");
  9150. std::string body;
  9151. auto res =
  9152. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9153. EXPECT_EQ(100U, data_length);
  9154. body.append(data, data_length);
  9155. return true;
  9156. });
  9157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9158. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9160. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9161. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9162. "7890123456789012345678901234567890",
  9163. body);
  9164. EXPECT_EQ(StatusCode::OK_200, res->status);
  9165. }
  9166. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9167. Headers headers;
  9168. headers.emplace("Accept-Encoding", "gzip, deflate");
  9169. cli_.set_decompress(false);
  9170. auto res = cli_.Get("/compress", headers);
  9171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9172. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9173. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9174. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9175. EXPECT_EQ(33U, res->body.size());
  9176. EXPECT_EQ(StatusCode::OK_200, res->status);
  9177. }
  9178. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9179. Headers headers;
  9180. headers.emplace("Accept-Encoding", "");
  9181. std::string body;
  9182. auto res =
  9183. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9184. EXPECT_EQ(100U, data_length);
  9185. body.append(data, data_length);
  9186. return true;
  9187. });
  9188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9189. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9190. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9191. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9192. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9193. "7890123456789012345678901234567890",
  9194. body);
  9195. EXPECT_EQ(StatusCode::OK_200, res->status);
  9196. }
  9197. TEST_F(ServerTest, NoGzip) {
  9198. Headers headers;
  9199. headers.emplace("Accept-Encoding", "gzip, deflate");
  9200. auto res = cli_.Get("/nocompress", headers);
  9201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9202. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9203. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9204. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9205. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9206. "7890123456789012345678901234567890",
  9207. res->body);
  9208. EXPECT_EQ(StatusCode::OK_200, res->status);
  9209. }
  9210. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9211. Headers headers;
  9212. headers.emplace("Accept-Encoding", "gzip, deflate");
  9213. std::string body;
  9214. auto res = cli_.Get("/nocompress", headers,
  9215. [&](const char *data, size_t data_length) {
  9216. EXPECT_EQ(100U, data_length);
  9217. body.append(data, data_length);
  9218. return true;
  9219. });
  9220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9221. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9222. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9223. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9224. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9225. "7890123456789012345678901234567890",
  9226. body);
  9227. EXPECT_EQ(StatusCode::OK_200, res->status);
  9228. }
  9229. TEST_F(ServerTest, MultipartFormDataGzip) {
  9230. UploadFormDataItems items = {
  9231. {"key1", "test", "", ""},
  9232. {"key2", "--abcdefg123", "", ""},
  9233. };
  9234. cli_.set_compress(true);
  9235. auto res = cli_.Post("/compress-multipart", items);
  9236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9237. EXPECT_EQ(StatusCode::OK_200, res->status);
  9238. }
  9239. #endif
  9240. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9241. // Static file compression is opt-in, so these run their own server rather than
  9242. // flipping it on for the shared ServerTest fixture, which would silently
  9243. // rewrite what every other static file test is asserting.
  9244. class StaticFileCompressionTest : public ::testing::Test {
  9245. protected:
  9246. void TearDown() override {
  9247. if (t_.joinable()) {
  9248. svr_.stop();
  9249. t_.join();
  9250. }
  9251. }
  9252. int start(const std::function<void(Server &)> &configure = nullptr) {
  9253. // Serves the same tree as a directory of build-time compressed assets
  9254. // would be served: the mount point names the coding the files are already
  9255. // stored in. Registered before "/" so it is the one that matches.
  9256. svr_.set_mount_point("/pre-encoded", "./www",
  9257. {{"Content-Encoding", "gzip"}});
  9258. svr_.set_mount_point("/", "./www");
  9259. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9260. res.set_file_content("./www/dir/index.html", "text/html");
  9261. });
  9262. svr_.Get("/pre-encoded-file-content",
  9263. [](const Request & /*req*/, Response &res) {
  9264. res.set_header("Content-Encoding", "gzip");
  9265. res.set_file_content("./www/dir/index.html", "text/html");
  9266. });
  9267. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9268. res.set_content_provider(
  9269. 6, "text/plain",
  9270. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9271. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9272. return true;
  9273. });
  9274. });
  9275. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9276. res.set_content_provider(
  9277. 1000, "text/plain",
  9278. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9279. if (offset < 100) {
  9280. std::string data(100, 'A');
  9281. sink.write(data.data(), data.size());
  9282. return true;
  9283. }
  9284. std::this_thread::sleep_for(std::chrono::seconds(2));
  9285. std::string data(900, 'B');
  9286. sink.write(data.data(), data.size());
  9287. return true;
  9288. });
  9289. });
  9290. if (configure) { configure(svr_); }
  9291. auto port = svr_.bind_to_any_port(HOST);
  9292. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9293. svr_.wait_until_ready();
  9294. return port;
  9295. }
  9296. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9297. // Every file under ./www except 1MB.txt is smaller than the default
  9298. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9299. // it out of the way.
  9300. static void enable_without_floor(Server &svr) {
  9301. svr.set_static_file_compression(true);
  9302. svr.set_static_file_compression_min_length(0);
  9303. }
  9304. Server svr_;
  9305. std::thread t_;
  9306. };
  9307. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9308. auto port = start();
  9309. Client cli(HOST, port);
  9310. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9312. EXPECT_EQ(StatusCode::OK_200, res->status);
  9313. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9314. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9315. EXPECT_EQ(1048576U, res->body.size());
  9316. }
  9317. TEST_F(StaticFileCompressionTest, MountPoint) {
  9318. auto port = start(enable);
  9319. Client cli(HOST, port);
  9320. cli.set_decompress(false);
  9321. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9323. EXPECT_EQ(StatusCode::OK_200, res->status);
  9324. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9325. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9326. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9327. // The response stays self-delimiting: a length, not a chunked body.
  9328. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9329. EXPECT_EQ(std::to_string(res->body.size()),
  9330. res->get_header_value("Content-Length"));
  9331. EXPECT_LT(res->body.size(), 1048576U);
  9332. EXPECT_FALSE(res->body.empty());
  9333. }
  9334. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9335. auto port = start(enable);
  9336. Client cli(HOST, port);
  9337. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9339. EXPECT_EQ(StatusCode::OK_200, res->status);
  9340. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9341. EXPECT_EQ(1048576U, res->body.size());
  9342. }
  9343. TEST_F(StaticFileCompressionTest, FileContent) {
  9344. auto port = start(enable_without_floor);
  9345. Client cli(HOST, port);
  9346. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9348. EXPECT_EQ(StatusCode::OK_200, res->status);
  9349. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9350. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9351. EXPECT_EQ(104U, res->body.size());
  9352. }
  9353. // A handler that serves an already-encoded file names the coding itself. The
  9354. // file-backed path decided its coding from Accept-Encoding and the content
  9355. // type alone, so it compressed the stored bytes a second time and appended a
  9356. // second Content-Encoding field line.
  9357. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9358. auto port = start(enable_without_floor);
  9359. Client cli(HOST, port);
  9360. cli.set_decompress(false);
  9361. auto res = cli.Get("/pre-encoded-file-content",
  9362. Headers{{"Accept-Encoding", "gzip"}});
  9363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9364. EXPECT_EQ(StatusCode::OK_200, res->status);
  9365. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9366. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9367. // Vary belongs to a coding the server chose, and it chose none here.
  9368. EXPECT_FALSE(res->has_header("Vary"));
  9369. // The file travels exactly as it is stored on disk.
  9370. EXPECT_EQ(104U, res->body.size());
  9371. }
  9372. // The 1MB file clears the default floor, so this one runs the configuration a
  9373. // deployment would actually have.
  9374. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9375. auto port = start(enable);
  9376. Client cli(HOST, port);
  9377. cli.set_decompress(false);
  9378. auto res =
  9379. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9381. EXPECT_EQ(StatusCode::OK_200, res->status);
  9382. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9383. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9384. EXPECT_FALSE(res->has_header("Vary"));
  9385. EXPECT_EQ(1048576U, res->body.size());
  9386. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9387. }
  9388. TEST_F(StaticFileCompressionTest, Head) {
  9389. auto port = start(enable);
  9390. Client cli(HOST, port);
  9391. cli.set_decompress(false);
  9392. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9393. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9394. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9396. EXPECT_EQ(StatusCode::OK_200, res->status);
  9397. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9398. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9399. // HEAD still reports the size a GET would return.
  9400. EXPECT_EQ(get->get_header_value("Content-Length"),
  9401. res->get_header_value("Content-Length"));
  9402. EXPECT_TRUE(res->body.empty());
  9403. }
  9404. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9405. auto port = start(enable);
  9406. Client cli(HOST, port);
  9407. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9408. {"Accept-Encoding", "gzip"}});
  9409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9410. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9411. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9412. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9413. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9414. EXPECT_EQ("cd", res->body);
  9415. }
  9416. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9417. auto port = start(enable);
  9418. Client cli(HOST, port);
  9419. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9421. EXPECT_EQ(StatusCode::OK_200, res->status);
  9422. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9423. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9424. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9425. }
  9426. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9427. auto port = start(enable);
  9428. Client cli(HOST, port);
  9429. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9431. EXPECT_EQ(StatusCode::OK_200, res->status);
  9432. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9433. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9434. EXPECT_TRUE(res->body.empty());
  9435. }
  9436. TEST_F(StaticFileCompressionTest, MinLength) {
  9437. auto port = start(enable);
  9438. Client cli(HOST, port);
  9439. // 104 bytes, well under the default floor. Compressing it would add the
  9440. // gzip header and trailer to a body that already fits in one packet.
  9441. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9443. EXPECT_EQ(StatusCode::OK_200, res->status);
  9444. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9445. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9446. }
  9447. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9448. auto port = start([](Server &svr) {
  9449. svr.set_static_file_compression(true);
  9450. svr.set_static_file_compression_min_length(1);
  9451. });
  9452. Client cli(HOST, port);
  9453. cli.set_decompress(false);
  9454. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9456. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9457. // A 9-byte file comes back larger than it went in, because gzip's header and
  9458. // trailer outweigh anything deflate can save. That is the end of the range
  9459. // the floor exists to keep out.
  9460. EXPECT_GT(res->body.size(), 9U);
  9461. }
  9462. TEST_F(StaticFileCompressionTest, MaxLength) {
  9463. auto port = start([](Server &svr) {
  9464. svr.set_static_file_compression(true);
  9465. svr.set_static_file_compression_min_length(0);
  9466. svr.set_static_file_compression_max_length(1024);
  9467. });
  9468. Client cli(HOST, port);
  9469. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9470. // defines `small` as a macro on Windows.
  9471. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9472. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9473. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9474. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9475. // Under it: compressed.
  9476. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9477. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9478. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9479. }
  9480. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9481. auto port = start(enable_without_floor);
  9482. Client cli(HOST, port);
  9483. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9484. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9485. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9486. auto identity_etag = identity->get_header_value("ETag");
  9487. ASSERT_FALSE(identity_etag.empty());
  9488. auto gzipped =
  9489. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9490. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9491. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9492. auto gzip_etag = gzipped->get_header_value("ETag");
  9493. ASSERT_FALSE(gzip_etag.empty());
  9494. // Two representations, two validators.
  9495. EXPECT_NE(identity_etag, gzip_etag);
  9496. // Each one revalidates against the request that would produce it...
  9497. auto fresh =
  9498. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9499. {"If-None-Match", gzip_etag}});
  9500. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9501. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9502. auto fresh_identity =
  9503. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9504. {"If-None-Match", identity_etag}});
  9505. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9506. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9507. // ...and not against the other representation.
  9508. auto crossed =
  9509. cli.Get("/dir/index.html",
  9510. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9511. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9512. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9513. }
  9514. // The opt-in covers responses the server reads off disk itself. A caller's own
  9515. // known-length provider keeps its Content-Length and, more importantly, keeps
  9516. // delivering incrementally: routing it through a compressor would hold every
  9517. // write back until zlib's window filled.
  9518. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9519. auto port = start(enable);
  9520. Client cli(HOST, port);
  9521. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9523. EXPECT_EQ(StatusCode::OK_200, res->status);
  9524. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9525. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9526. EXPECT_EQ("aaabbb", res->body);
  9527. }
  9528. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9529. auto port = start(enable);
  9530. Client cli(HOST, port);
  9531. cli.set_read_timeout(1, 0);
  9532. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9533. Headers{{"Accept-Encoding", "gzip"}});
  9534. ASSERT_TRUE(handle.is_valid());
  9535. // The provider writes 100 bytes and then stalls for longer than the read
  9536. // timeout. Those first bytes have to arrive anyway: run the response through
  9537. // a compressor and zlib holds them until its window fills, so the read would
  9538. // come back empty instead.
  9539. char buf[256];
  9540. auto n = handle.read(buf, sizeof(buf));
  9541. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9542. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9543. }
  9544. #endif
  9545. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9546. TEST_F(ServerTest, Brotli) {
  9547. Headers headers;
  9548. headers.emplace("Accept-Encoding", "br");
  9549. auto res = cli_.Get("/compress", headers);
  9550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9551. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9552. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9553. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9554. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9555. "7890123456789012345678901234567890",
  9556. res->body);
  9557. EXPECT_EQ(StatusCode::OK_200, res->status);
  9558. }
  9559. #endif
  9560. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9561. TEST_F(ServerTest, Zstd) {
  9562. Headers headers;
  9563. headers.emplace("Accept-Encoding", "zstd");
  9564. auto res = cli_.Get("/compress", headers);
  9565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9566. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9567. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9568. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9569. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9570. "7890123456789012345678901234567890",
  9571. res->body);
  9572. EXPECT_EQ(StatusCode::OK_200, res->status);
  9573. }
  9574. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9575. Headers headers;
  9576. headers.emplace("Accept-Encoding", "");
  9577. auto res = cli_.Get("/compress", headers);
  9578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9579. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9580. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9581. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9582. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9583. "7890123456789012345678901234567890",
  9584. res->body);
  9585. EXPECT_EQ(StatusCode::OK_200, res->status);
  9586. }
  9587. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9588. Headers headers;
  9589. headers.emplace("Accept-Encoding", "zstd");
  9590. std::string body;
  9591. auto res =
  9592. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9593. EXPECT_EQ(100U, data_length);
  9594. body.append(data, data_length);
  9595. return true;
  9596. });
  9597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9598. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9599. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9600. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9601. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9602. "7890123456789012345678901234567890",
  9603. body);
  9604. EXPECT_EQ(StatusCode::OK_200, res->status);
  9605. }
  9606. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9607. Headers headers;
  9608. headers.emplace("Accept-Encoding", "zstd");
  9609. cli_.set_decompress(false);
  9610. auto res = cli_.Get("/compress", headers);
  9611. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9612. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9613. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9614. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9616. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9618. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9619. EXPECT_EQ(StatusCode::OK_200, res->status);
  9620. ASSERT_EQ(26U, res->body.size());
  9621. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9622. 0);
  9623. }
  9624. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9625. Headers headers;
  9626. headers.emplace("Accept-Encoding", "");
  9627. std::string body;
  9628. auto res =
  9629. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9630. EXPECT_EQ(100U, data_length);
  9631. body.append(data, data_length);
  9632. return true;
  9633. });
  9634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9635. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9636. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9637. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9638. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9639. "7890123456789012345678901234567890",
  9640. body);
  9641. EXPECT_EQ(StatusCode::OK_200, res->status);
  9642. }
  9643. TEST_F(ServerTest, NoZstd) {
  9644. Headers headers;
  9645. headers.emplace("Accept-Encoding", "zstd");
  9646. auto res = cli_.Get("/nocompress", headers);
  9647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9648. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9649. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9650. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9651. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9652. "7890123456789012345678901234567890",
  9653. res->body);
  9654. EXPECT_EQ(StatusCode::OK_200, res->status);
  9655. }
  9656. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9657. Headers headers;
  9658. headers.emplace("Accept-Encoding", "zstd");
  9659. std::string body;
  9660. auto res = cli_.Get("/nocompress", headers,
  9661. [&](const char *data, size_t data_length) {
  9662. EXPECT_EQ(100U, data_length);
  9663. body.append(data, data_length);
  9664. return true;
  9665. });
  9666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9667. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9668. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9669. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9670. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9671. "7890123456789012345678901234567890",
  9672. body);
  9673. EXPECT_EQ(StatusCode::OK_200, res->status);
  9674. }
  9675. // TODO: How to enable zstd ??
  9676. TEST_F(ServerTest, MultipartFormDataZstd) {
  9677. UploadFormDataItems items = {
  9678. {"key1", "test", "", ""},
  9679. {"key2", "--abcdefg123", "", ""},
  9680. };
  9681. Headers headers;
  9682. headers.emplace("Accept-Encoding", "zstd");
  9683. cli_.set_compress(true);
  9684. auto res = cli_.Post("/compress-multipart", headers, items);
  9685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9686. EXPECT_EQ(StatusCode::OK_200, res->status);
  9687. }
  9688. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9689. Headers headers;
  9690. headers.emplace("Accept-Encoding", "zstd");
  9691. cli_.set_compress(true);
  9692. auto res = cli_.Put(
  9693. "/put", headers, 3,
  9694. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9695. sink.os << "PUT";
  9696. return true;
  9697. },
  9698. "text/plain");
  9699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9700. EXPECT_EQ(StatusCode::OK_200, res->status);
  9701. EXPECT_EQ("PUT", res->body);
  9702. }
  9703. // Pre-compression logging tests
  9704. TEST_F(ServerTest, PreCompressionLogging) {
  9705. // Test data for compression (matches the actual /compress endpoint content)
  9706. const std::string test_content =
  9707. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9708. "3456789012345678901234567890";
  9709. // Variables to capture logging data
  9710. std::string pre_compression_body;
  9711. std::string pre_compression_content_type;
  9712. std::string pre_compression_content_encoding;
  9713. std::string post_compression_body;
  9714. std::string post_compression_content_type;
  9715. std::string post_compression_content_encoding;
  9716. // Set up pre-compression logger
  9717. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9718. const Response &res) {
  9719. pre_compression_body = res.body;
  9720. pre_compression_content_type = res.get_header_value("Content-Type");
  9721. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9722. });
  9723. // Set up post-compression logger
  9724. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9725. post_compression_body = res.body;
  9726. post_compression_content_type = res.get_header_value("Content-Type");
  9727. post_compression_content_encoding =
  9728. res.get_header_value("Content-Encoding");
  9729. });
  9730. // Test with gzip compression
  9731. Headers headers;
  9732. headers.emplace("Accept-Encoding", "gzip");
  9733. auto res = cli_.Get("/compress", headers);
  9734. // Verify response was compressed
  9735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9736. EXPECT_EQ(StatusCode::OK_200, res->status);
  9737. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9738. // Verify pre-compression logger captured uncompressed content
  9739. EXPECT_EQ(test_content, pre_compression_body);
  9740. EXPECT_EQ("text/plain", pre_compression_content_type);
  9741. EXPECT_TRUE(pre_compression_content_encoding
  9742. .empty()); // No encoding header before compression
  9743. // Verify post-compression logger captured compressed content
  9744. EXPECT_NE(test_content,
  9745. post_compression_body); // Should be different after compression
  9746. EXPECT_EQ("text/plain", post_compression_content_type);
  9747. EXPECT_EQ("gzip", post_compression_content_encoding);
  9748. // Verify compressed content is smaller
  9749. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9750. }
  9751. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9752. const std::string test_content =
  9753. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9754. "3456789012345678901234567890";
  9755. std::string pre_compression_body;
  9756. std::string post_compression_body;
  9757. svr_.set_pre_compression_logger(
  9758. [&](const Request & /*req*/, const Response &res) {
  9759. pre_compression_body = res.body;
  9760. });
  9761. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9762. post_compression_body = res.body;
  9763. });
  9764. Headers headers;
  9765. headers.emplace("Accept-Encoding", "br");
  9766. auto res = cli_.Get("/compress", headers);
  9767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9768. EXPECT_EQ(StatusCode::OK_200, res->status);
  9769. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9770. // Verify pre-compression content is uncompressed
  9771. EXPECT_EQ(test_content, pre_compression_body);
  9772. // Verify post-compression content is compressed
  9773. EXPECT_NE(test_content, post_compression_body);
  9774. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9775. }
  9776. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9777. const std::string test_content =
  9778. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9779. "3456789012345678901234567890";
  9780. std::string pre_compression_body;
  9781. std::string post_compression_body;
  9782. svr_.set_pre_compression_logger(
  9783. [&](const Request & /*req*/, const Response &res) {
  9784. pre_compression_body = res.body;
  9785. });
  9786. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9787. post_compression_body = res.body;
  9788. });
  9789. // Request without compression (use /nocompress endpoint)
  9790. Headers headers;
  9791. auto res = cli_.Get("/nocompress", headers);
  9792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9793. EXPECT_EQ(StatusCode::OK_200, res->status);
  9794. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9795. // Pre-compression logger should not be called when no compression is applied
  9796. EXPECT_TRUE(
  9797. pre_compression_body.empty()); // Pre-compression logger not called
  9798. EXPECT_EQ(
  9799. test_content,
  9800. post_compression_body); // Post-compression logger captures final content
  9801. }
  9802. TEST_F(ServerTest, LoggerSeesContentLength) {
  9803. size_t logged_content_length = 0;
  9804. std::string logged_content_length_header;
  9805. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9806. logged_content_length = res.content_length_;
  9807. logged_content_length_header = res.get_header_value("Content-Length");
  9808. });
  9809. auto res = cli_.Get("/nocompress");
  9810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9811. EXPECT_EQ(StatusCode::OK_200, res->status);
  9812. EXPECT_EQ(res->body.size(), logged_content_length);
  9813. EXPECT_EQ(std::to_string(logged_content_length),
  9814. logged_content_length_header);
  9815. }
  9816. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9817. const std::string test_content =
  9818. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9819. "3456789012345678901234567890";
  9820. std::string pre_compression_body;
  9821. bool pre_logger_called = false;
  9822. // Set only pre-compression logger
  9823. svr_.set_pre_compression_logger(
  9824. [&](const Request & /*req*/, const Response &res) {
  9825. pre_compression_body = res.body;
  9826. pre_logger_called = true;
  9827. });
  9828. Headers headers;
  9829. headers.emplace("Accept-Encoding", "gzip");
  9830. auto res = cli_.Get("/compress", headers);
  9831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9832. EXPECT_EQ(StatusCode::OK_200, res->status);
  9833. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9834. // Verify pre-compression logger was called
  9835. EXPECT_TRUE(pre_logger_called);
  9836. EXPECT_EQ(test_content, pre_compression_body);
  9837. }
  9838. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9839. {
  9840. // Test with Expect: 100-continue header - success case
  9841. // Server returns 100 Continue, client sends body, server returns 200 OK
  9842. Request req;
  9843. req.method = "POST";
  9844. req.path = "/post-large";
  9845. req.set_header("Expect", "100-continue");
  9846. req.body = LARGE_DATA;
  9847. Response res;
  9848. auto error = Error::Success;
  9849. cli_.set_keep_alive(true);
  9850. auto ret = cli_.send(req, res, error);
  9851. EXPECT_TRUE(ret);
  9852. EXPECT_EQ(StatusCode::OK_200, res.status);
  9853. EXPECT_EQ(LARGE_DATA, res.body);
  9854. }
  9855. {
  9856. // Test with Expect: 100-continue header - error case
  9857. // Client should not send the body when server returns an error
  9858. Request req;
  9859. req.method = "POST";
  9860. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9861. req.set_header("Expect", "100-continue");
  9862. req.body = LARGE_DATA;
  9863. Response res;
  9864. auto error = Error::Success;
  9865. auto start = std::chrono::high_resolution_clock::now();
  9866. cli_.set_keep_alive(true);
  9867. auto ret = cli_.send(req, res, error);
  9868. auto end = std::chrono::high_resolution_clock::now();
  9869. auto elapsed =
  9870. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9871. .count();
  9872. // With Expect: 100-continue, request completes successfully but with error
  9873. EXPECT_TRUE(ret);
  9874. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9875. EXPECT_EQ("close", res.get_header_value("Connection"));
  9876. EXPECT_FALSE(cli_.is_socket_open());
  9877. EXPECT_LE(elapsed, 2000);
  9878. }
  9879. {
  9880. // Send an extra GET request to ensure error recovery without hanging
  9881. Request req;
  9882. req.method = "GET";
  9883. req.path = "/hi";
  9884. auto start = std::chrono::high_resolution_clock::now();
  9885. auto res = cli_.send(req);
  9886. auto end = std::chrono::high_resolution_clock::now();
  9887. auto elapsed =
  9888. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9889. .count();
  9890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9891. EXPECT_EQ(StatusCode::OK_200, res->status);
  9892. EXPECT_EQ("Hello World!", res->body);
  9893. EXPECT_LE(elapsed, 500);
  9894. }
  9895. }
  9896. TEST(ZstdDecompressor, ChunkedDecompression) {
  9897. std::string data;
  9898. for (size_t i = 0; i < 32 * 1024; ++i) {
  9899. data.push_back(static_cast<char>('a' + i % 26));
  9900. }
  9901. std::string compressed_data;
  9902. {
  9903. httplib::detail::zstd_compressor compressor;
  9904. bool result = compressor.compress(
  9905. data.data(), data.size(),
  9906. /*last=*/true,
  9907. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9908. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9909. compressed_data_size);
  9910. return true;
  9911. });
  9912. ASSERT_TRUE(result);
  9913. }
  9914. std::string decompressed_data;
  9915. {
  9916. httplib::detail::zstd_decompressor decompressor;
  9917. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9918. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9919. size_t chunk_size = 130;
  9920. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9921. chunk_begin += chunk_size) {
  9922. size_t current_chunk_size =
  9923. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9924. bool result = decompressor.decompress(
  9925. compressed_data.data() + chunk_begin, current_chunk_size,
  9926. [&](const char *decompressed_data_chunk,
  9927. size_t decompressed_data_chunk_size) {
  9928. decompressed_data.insert(decompressed_data.size(),
  9929. decompressed_data_chunk,
  9930. decompressed_data_chunk_size);
  9931. return true;
  9932. });
  9933. ASSERT_TRUE(result);
  9934. }
  9935. }
  9936. ASSERT_EQ(data, decompressed_data);
  9937. }
  9938. TEST(ZstdDecompressor, Decompress) {
  9939. std::string original_text = "Compressed with ZSTD";
  9940. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9941. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9942. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9943. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9944. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9945. std::string decompressed_data;
  9946. {
  9947. httplib::detail::zstd_decompressor decompressor;
  9948. bool result = decompressor.decompress(
  9949. compressed_data.data(), compressed_data.size(),
  9950. [&](const char *decompressed_data_chunk,
  9951. size_t decompressed_data_chunk_size) {
  9952. decompressed_data.insert(decompressed_data.size(),
  9953. decompressed_data_chunk,
  9954. decompressed_data_chunk_size);
  9955. return true;
  9956. });
  9957. ASSERT_TRUE(result);
  9958. }
  9959. ASSERT_EQ(original_text, decompressed_data);
  9960. }
  9961. #endif
  9962. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9963. // separate chunks so that the server sees each part in its own read(). Used to
  9964. // place a read boundary at a specific offset of a request body.
  9965. static bool send_request_in_parts(time_t read_timeout_sec,
  9966. const std::vector<std::string> &parts,
  9967. std::string *resp = nullptr,
  9968. int port = PORT) {
  9969. auto error = Error::Success;
  9970. auto client_sock = detail::create_client_socket(
  9971. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9972. /*connection_timeout_sec=*/5, 0,
  9973. /*read_timeout_sec=*/5, 0,
  9974. /*write_timeout_sec=*/5, 0, std::string(), error);
  9975. if (client_sock == INVALID_SOCKET) { return false; }
  9976. auto ret = detail::process_client_socket(
  9977. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9978. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9979. for (size_t i = 0; i < parts.size(); i++) {
  9980. const auto &part = parts[i];
  9981. if (part.size() !=
  9982. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9983. return false;
  9984. }
  9985. if (i + 1 < parts.size()) {
  9986. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9987. }
  9988. }
  9989. char buf[512];
  9990. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9991. while (line_reader.getline()) {
  9992. if (resp) { *resp += line_reader.ptr(); }
  9993. }
  9994. return true;
  9995. });
  9996. detail::close_socket(client_sock);
  9997. return ret;
  9998. }
  9999. // Sends a raw request to a server listening at HOST:PORT.
  10000. static bool send_request(time_t read_timeout_sec, const std::string &req,
  10001. std::string *resp = nullptr, int port = PORT) {
  10002. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  10003. }
  10004. #ifdef CPPHTTPLIB_SSL_ENABLED
  10005. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  10006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10007. ASSERT_TRUE(svr.is_valid());
  10008. svr.set_read_timeout(1, 0);
  10009. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10010. auto se = detail::scope_exit([&] {
  10011. svr.stop();
  10012. t.join();
  10013. ASSERT_FALSE(svr.is_running());
  10014. });
  10015. svr.wait_until_ready();
  10016. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  10017. // keeps each wait well within the read timeout. The server gives up a
  10018. // second in, so the bytes sent after that fail.
  10019. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  10020. parts.resize(26, std::string(1, '\0'));
  10021. EXPECT_FALSE(send_request_in_parts(5, parts));
  10022. }
  10023. #endif
  10024. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10025. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  10026. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  10027. const std::vector<std::string> &parts,
  10028. std::string *resp = nullptr,
  10029. int port = PORT) {
  10030. auto error = Error::Success;
  10031. auto sock = detail::create_client_socket(
  10032. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10033. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  10034. /*write_timeout_sec=*/5, 0, std::string(), error);
  10035. if (sock == INVALID_SOCKET) { return false; }
  10036. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10037. auto ctx = SSL_CTX_new(TLS_client_method());
  10038. auto ssl = SSL_new(ctx);
  10039. auto ssl_se = detail::scope_exit([&] {
  10040. SSL_free(ssl);
  10041. SSL_CTX_free(ctx);
  10042. });
  10043. SSL_set_fd(ssl, static_cast<int>(sock));
  10044. if (SSL_connect(ssl) != 1) { return false; }
  10045. for (size_t i = 0; i < parts.size(); i++) {
  10046. const auto &part = parts[i];
  10047. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10048. static_cast<int>(part.size())) {
  10049. return false;
  10050. }
  10051. if (i + 1 < parts.size()) {
  10052. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10053. }
  10054. }
  10055. char buf[512];
  10056. int n;
  10057. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10058. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10059. }
  10060. return true;
  10061. }
  10062. #endif
  10063. // The request line, then a header value a byte at a time.
  10064. static std::vector<std::string> slow_request_head_parts() {
  10065. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10066. parts.resize(26, "a");
  10067. parts.emplace_back("\r\n\r\n");
  10068. return parts;
  10069. }
  10070. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10071. // within the one-second read timeout. The server gives up a second in, before
  10072. // the head is complete.
  10073. static void
  10074. expect_slow_request_head_dropped(Server &svr,
  10075. const std::function<std::string()> &send) {
  10076. std::atomic<bool> handled(false);
  10077. svr.Get("/", [&](const Request &, Response &res) {
  10078. handled = true;
  10079. res.set_content("ok", "text/plain");
  10080. });
  10081. svr.set_read_timeout(1, 0);
  10082. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10083. auto se = detail::scope_exit([&] {
  10084. svr.stop();
  10085. t.join();
  10086. ASSERT_FALSE(svr.is_running());
  10087. });
  10088. svr.wait_until_ready();
  10089. auto resp = send();
  10090. EXPECT_FALSE(handled);
  10091. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10092. }
  10093. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10094. Server svr;
  10095. expect_slow_request_head_dropped(svr, [] {
  10096. std::string resp;
  10097. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10098. return resp;
  10099. });
  10100. }
  10101. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10102. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10103. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10104. ASSERT_TRUE(svr.is_valid());
  10105. expect_slow_request_head_dropped(svr, [] {
  10106. std::string resp;
  10107. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10108. return resp;
  10109. });
  10110. }
  10111. #endif
  10112. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10113. Server svr;
  10114. std::string header_value;
  10115. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10116. header_value = req.get_header_value("foo");
  10117. res.set_content("ok", "text/plain");
  10118. });
  10119. thread t = thread([&] { svr.listen(HOST, PORT); });
  10120. auto se = detail::scope_exit([&] {
  10121. svr.stop();
  10122. t.join();
  10123. ASSERT_FALSE(svr.is_running());
  10124. });
  10125. svr.wait_until_ready();
  10126. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10127. // like characters are not treated the same - use vertical tab and escape.
  10128. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10129. "foo: \t \v bar \x1B\t \r\n"
  10130. "Connection: close\r\n"
  10131. "\r\n";
  10132. std::string res;
  10133. ASSERT_TRUE(send_request(5, req, &res));
  10134. EXPECT_EQ(header_value, "");
  10135. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10136. }
  10137. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10138. Server svr;
  10139. std::string received;
  10140. svr.Get("/order", [&](const Request &req, Response &res) {
  10141. received = entries_to_string(req.headers);
  10142. res.set_content("ok", "text/plain");
  10143. });
  10144. auto port = svr.bind_to_any_port(HOST);
  10145. thread t = thread([&] { svr.listen_after_bind(); });
  10146. auto se = detail::scope_exit([&] {
  10147. svr.stop();
  10148. t.join();
  10149. ASSERT_FALSE(svr.is_running());
  10150. });
  10151. svr.wait_until_ready();
  10152. const std::string req = "GET /order HTTP/1.1\r\n"
  10153. "Host: localhost\r\n"
  10154. "X-First: 1\r\n"
  10155. "X-Dup: a\r\n"
  10156. "X-Second: 2\r\n"
  10157. "X-Dup: b\r\n"
  10158. "Connection: close\r\n"
  10159. "\r\n";
  10160. std::string res;
  10161. ASSERT_TRUE(send_request(5, req, &res, port));
  10162. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10163. EXPECT_EQ(
  10164. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10165. received);
  10166. }
  10167. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10168. Server svr;
  10169. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10170. res.set_header("Set-Cookie", "first=1");
  10171. res.set_header("X-Between", "y");
  10172. res.set_header("Set-Cookie", "second=2");
  10173. res.set_content("ok", "text/plain");
  10174. });
  10175. auto port = svr.bind_to_any_port(HOST);
  10176. thread t = thread([&] { svr.listen_after_bind(); });
  10177. auto se = detail::scope_exit([&] {
  10178. svr.stop();
  10179. t.join();
  10180. ASSERT_FALSE(svr.is_running());
  10181. });
  10182. svr.wait_until_ready();
  10183. Client cli(HOST, port);
  10184. auto res = cli.Get("/cookies");
  10185. ASSERT_TRUE(res);
  10186. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10187. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10188. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10189. }
  10190. // A stream may send a byte at a time with a small extension on each chunk,
  10191. // however long it runs
  10192. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10193. Server svr;
  10194. svr.Post("/count", [](const Request &req, Response &res) {
  10195. res.set_content(std::to_string(req.body.size()), "text/plain");
  10196. });
  10197. auto port = svr.bind_to_any_port(HOST);
  10198. ASSERT_LT(0, port);
  10199. thread t = thread([&] { svr.listen_after_bind(); });
  10200. auto se = detail::scope_exit([&] {
  10201. svr.stop();
  10202. t.join();
  10203. ASSERT_FALSE(svr.is_running());
  10204. });
  10205. svr.wait_until_ready();
  10206. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10207. "\r\nTransfer-Encoding: chunked\r\n"
  10208. "Connection: close\r\n\r\n";
  10209. for (auto i = 0; i < 4096; i++) {
  10210. req += "1;a=b\r\nx\r\n";
  10211. }
  10212. req += "0\r\n\r\n";
  10213. std::string res;
  10214. ASSERT_TRUE(send_request(5, req, &res, port));
  10215. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10216. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10217. }
  10218. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10219. Server svr;
  10220. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10221. auto i = new int(0);
  10222. res.set_header("Trailer", "X-Safe, X-Reflected");
  10223. res.set_chunked_content_provider(
  10224. "text/plain",
  10225. [i](size_t /*offset*/, DataSink &sink) {
  10226. if (*i == 0) {
  10227. sink.os << "body";
  10228. } else {
  10229. Headers trailer;
  10230. // A valid trailer that must survive.
  10231. trailer.emplace("X-Safe", "safe");
  10232. // Attacker-controlled value carrying CR/LF (response splitting).
  10233. trailer.emplace("X-Reflected",
  10234. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10235. // Attacker-controlled name carrying CR/LF.
  10236. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10237. sink.done_with_trailer(trailer);
  10238. }
  10239. (*i)++;
  10240. return true;
  10241. },
  10242. [i](bool /*success*/) { delete i; });
  10243. });
  10244. thread t = thread([&] { svr.listen(HOST, PORT); });
  10245. auto se = detail::scope_exit([&] {
  10246. svr.stop();
  10247. t.join();
  10248. ASSERT_FALSE(svr.is_running());
  10249. });
  10250. svr.wait_until_ready();
  10251. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10252. "Host: " + HOST +
  10253. "\r\n"
  10254. "Connection: close\r\n"
  10255. "\r\n";
  10256. std::string res;
  10257. ASSERT_TRUE(send_request(5, req, &res));
  10258. // The injected fields must not appear anywhere in the raw response.
  10259. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10260. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10261. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10262. // Invalid trailers are dropped entirely, matching set_header().
  10263. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10264. // The valid trailer still passes through.
  10265. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10266. }
  10267. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10268. // A custom header writer gets only the fields the default one writes
  10269. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10270. std::string s;
  10271. for (const auto &h : hdrs) {
  10272. s += h.first + ": " + h.second + "\r\n";
  10273. }
  10274. s += "\r\n";
  10275. return strm.write(s.data(), s.size());
  10276. };
  10277. for (auto custom_writer : {false, true}) {
  10278. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10279. Server svr;
  10280. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10281. svr.set_post_routing_handler([](const Request &, Response &res) {
  10282. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10283. });
  10284. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10285. // res.headers is a public field an application can populate directly,
  10286. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10287. // A valid header that must survive.
  10288. res.headers.emplace("X-Safe", "safe");
  10289. // Attacker-controlled value carrying CR/LF (response splitting).
  10290. res.headers.emplace("X-Reflected",
  10291. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10292. // Attacker-controlled name carrying CR/LF.
  10293. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10294. res.set_content("body", "text/plain");
  10295. });
  10296. thread t = thread([&] { svr.listen(HOST, PORT); });
  10297. auto se = detail::scope_exit([&] {
  10298. svr.stop();
  10299. t.join();
  10300. ASSERT_FALSE(svr.is_running());
  10301. });
  10302. svr.wait_until_ready();
  10303. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10304. "Host: " + HOST +
  10305. "\r\n"
  10306. "Connection: close\r\n"
  10307. "\r\n";
  10308. std::string res;
  10309. ASSERT_TRUE(send_request(5, req, &res));
  10310. // The injected fields must not appear anywhere in the raw response.
  10311. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10312. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10313. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10314. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10315. // Invalid headers are dropped entirely, matching set_header().
  10316. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10317. // The valid header still passes through.
  10318. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10319. }
  10320. }
  10321. // Forward declaration: in split builds split.py strips `inline` and moves the
  10322. // definition into httplib.cc, so detail::write_request_line is not visible from
  10323. // the public httplib.h. Re-declaring it here lets the tests link against the
  10324. // symbol in both header-only and split builds.
  10325. namespace httplib {
  10326. namespace detail {
  10327. ssize_t write_request_line(Stream &strm, const std::string &method,
  10328. const std::string &path);
  10329. } // namespace detail
  10330. } // namespace httplib
  10331. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10332. // A well-formed target is written verbatim.
  10333. {
  10334. detail::BufferStream strm;
  10335. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10336. EXPECT_GT(n, 0);
  10337. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10338. }
  10339. // A target carrying CR/LF, SP or other control octets must be rejected
  10340. // before anything reaches the wire, otherwise it splits the request line and
  10341. // injects a header or a whole request.
  10342. const std::string evil_targets[] = {
  10343. "/a\r\nInjected: pwned",
  10344. "/a\rInjected",
  10345. "/a\nInjected",
  10346. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10347. "/a b",
  10348. "/a\tb",
  10349. "/a\x7f",
  10350. };
  10351. for (const auto &evil : evil_targets) {
  10352. detail::BufferStream strm;
  10353. auto n = detail::write_request_line(strm, "GET", evil);
  10354. EXPECT_LT(n, 0);
  10355. EXPECT_TRUE(strm.get_buffer().empty());
  10356. }
  10357. }
  10358. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10359. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10360. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10361. // target reaches write_request. The client must fail cleanly with
  10362. // Error::Write instead of putting a request-line-less, header-injecting
  10363. // request on the wire.
  10364. Server svr;
  10365. svr.Get("/a", [](const Request &, Response &res) {
  10366. res.set_content("ok", "text/plain");
  10367. });
  10368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10369. auto se = detail::scope_exit([&] {
  10370. svr.stop();
  10371. thread.join();
  10372. ASSERT_FALSE(svr.is_running());
  10373. });
  10374. svr.wait_until_ready();
  10375. {
  10376. Client cli(HOST, PORT);
  10377. cli.set_path_encode(false);
  10378. // The request is rejected before anything is written, so the connection
  10379. // stays silent and the subsequent response read would otherwise block for
  10380. // the full default read timeout. Shorten it -- the assertion is on the
  10381. // error, not the timeout.
  10382. cli.set_read_timeout(1, 0);
  10383. auto res = cli.Get("/a\r\nInjected: pwned");
  10384. EXPECT_FALSE(res);
  10385. EXPECT_EQ(Error::Write, res.error());
  10386. }
  10387. }
  10388. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10389. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10390. // including extension methods.
  10391. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10392. for (const auto &method : good_methods) {
  10393. detail::BufferStream strm;
  10394. auto n = detail::write_request_line(strm, method, "/");
  10395. EXPECT_GT(n, 0);
  10396. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10397. }
  10398. // A method carrying CR/LF would split the request line and smuggle a whole
  10399. // request ahead of the real one. A space or an empty method corrupts the
  10400. // request line. All must be rejected before anything reaches the wire.
  10401. const std::string evil_methods[] = {
  10402. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10403. "GET\r\nInjected: pwned",
  10404. "GET\r",
  10405. "GET\n",
  10406. "GE T",
  10407. "",
  10408. };
  10409. for (const auto &evil : evil_methods) {
  10410. detail::BufferStream strm;
  10411. auto n = detail::write_request_line(strm, evil, "/");
  10412. EXPECT_LT(n, 0);
  10413. EXPECT_TRUE(strm.get_buffer().empty());
  10414. }
  10415. }
  10416. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10417. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10418. // through Client::send must fail with Error::Write and no request, neither
  10419. // the smuggled one nor the real one, may reach the server.
  10420. Server svr;
  10421. std::atomic<int> request_count(0);
  10422. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10423. request_count++;
  10424. res.status = StatusCode::OK_200;
  10425. return Server::HandlerResponse::Handled;
  10426. });
  10427. auto port = svr.bind_to_any_port(HOST);
  10428. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10429. auto se = detail::scope_exit([&] {
  10430. svr.stop();
  10431. thread.join();
  10432. ASSERT_FALSE(svr.is_running());
  10433. });
  10434. svr.wait_until_ready();
  10435. {
  10436. Client cli(HOST, port);
  10437. const std::string evil_methods[] = {
  10438. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10439. "GE T",
  10440. "",
  10441. };
  10442. for (const auto &evil : evil_methods) {
  10443. Request req;
  10444. req.method = evil;
  10445. req.path = "/";
  10446. auto res = cli.send(req);
  10447. EXPECT_FALSE(res);
  10448. EXPECT_EQ(Error::Write, res.error());
  10449. }
  10450. auto handle =
  10451. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10452. EXPECT_FALSE(handle.is_valid());
  10453. EXPECT_EQ(Error::Write, handle.error);
  10454. // A valid request on the same client still goes through.
  10455. auto res = cli.Get("/");
  10456. ASSERT_TRUE(res);
  10457. EXPECT_EQ(StatusCode::OK_200, res->status);
  10458. }
  10459. EXPECT_EQ(1, request_count.load());
  10460. }
  10461. // Sends a raw request and verifies that there isn't a crash or exception.
  10462. static void test_raw_request(const std::string &req,
  10463. std::string *out = nullptr) {
  10464. Server svr;
  10465. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10466. res.set_content("ok", "text/plain");
  10467. });
  10468. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10469. res.set_content("ok", "text/plain");
  10470. });
  10471. svr.Get("/header_field_value_check",
  10472. [&](const Request & /*req*/, Response &res) {
  10473. res.set_content("ok", "text/plain");
  10474. });
  10475. svr.CustomRoute("PROPFIND", "/dav",
  10476. [&](const Request & /*req*/, Response &res) {
  10477. res.status = StatusCode::MultiStatus_207;
  10478. });
  10479. // Server read timeout must be longer than the client read timeout for the
  10480. // bug to reproduce, probably to force the server to process a request
  10481. // without a trailing blank line.
  10482. const time_t client_read_timeout_sec = 1;
  10483. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10484. bool listen_thread_ok = false;
  10485. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10486. auto se = detail::scope_exit([&] {
  10487. svr.stop();
  10488. t.join();
  10489. ASSERT_FALSE(svr.is_running());
  10490. EXPECT_TRUE(listen_thread_ok);
  10491. });
  10492. svr.wait_until_ready();
  10493. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10494. }
  10495. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10496. // A certain header line causes an exception if the header property is parsed
  10497. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10498. test_raw_request(
  10499. "GET /hi HTTP/1.1\r\n"
  10500. " : "
  10501. " "
  10502. " ");
  10503. }
  10504. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10505. // A certain header line causes an exception if the header property *name* is
  10506. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10507. // greedy matcher and requires backtracking when there are a lot of ":"
  10508. // characters.
  10509. // This occurs with libc++ but not libstdc++.
  10510. test_raw_request(
  10511. "GET /hi HTTP/1.1\r\n"
  10512. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10513. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10514. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10515. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10516. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10517. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10518. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10519. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10520. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10521. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10522. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10523. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10524. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10525. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10526. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10527. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10528. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10529. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10530. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10531. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10532. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10533. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10534. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10535. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10536. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10537. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10538. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10539. "&&&%%%");
  10540. }
  10541. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10542. // Make sure this doesn't crash the server.
  10543. // In a previous version of the header line regex, the "\r" rendered the line
  10544. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10545. // a new position where the leading white space ended and the field value
  10546. // began.
  10547. // The crash occurs with libc++ but not libstdc++.
  10548. test_raw_request("GET /hi HTTP/1.1\r\n"
  10549. "a:" +
  10550. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10551. "\r\n"
  10552. "\r\n");
  10553. }
  10554. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10555. const char *rejected[] = {
  10556. // RFC 9112 §3: one SP between the parts, and nothing else
  10557. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10558. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10559. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10560. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10561. // A request-target has no fragment
  10562. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10563. // An HTTP/1.1 request needs a Host
  10564. "GET /hi HTTP/1.1\r\n\r\n",
  10565. };
  10566. for (auto request : rejected) {
  10567. std::string out;
  10568. test_raw_request(request, &out);
  10569. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10570. }
  10571. std::string out;
  10572. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10573. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10574. }
  10575. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10576. // RFC 9112 §6.1
  10577. const char *requests[] = {
  10578. "PUT /put_hi HTTP/1.1\r\n"
  10579. "Host: localhost\r\n"
  10580. "Content-Length: 0\r\n"
  10581. "Transfer-Encoding: chunked\r\n"
  10582. "\r\n"
  10583. "0\r\n\r\n",
  10584. "PUT /put_hi HTTP/1.0\r\n"
  10585. "Connection: keep-alive\r\n"
  10586. "Transfer-Encoding: chunked\r\n"
  10587. "\r\n"
  10588. "0\r\n\r\n",
  10589. };
  10590. for (auto request : requests) {
  10591. std::string out;
  10592. test_raw_request(request, &out);
  10593. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10594. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10595. }
  10596. }
  10597. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10598. std::string out;
  10599. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10600. "Content-Type: text/plain\r\n"
  10601. "Transfer-Encoding: chunked\r\n"
  10602. "\r\n"
  10603. "nothex\r\n",
  10604. &out);
  10605. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10606. }
  10607. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10608. std::string out;
  10609. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10610. "Content-Type: text/plain\r\n"
  10611. "Transfer-Encoding: chunked\r\n"
  10612. "\r\n"
  10613. "3\r\n"
  10614. "xyz\r\n"
  10615. "NaN\r\n",
  10616. &out);
  10617. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10618. }
  10619. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10620. std::string out;
  10621. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10622. "Content-Type: text/plain\r\n"
  10623. "Transfer-Encoding: chunked\r\n"
  10624. "\r\n"
  10625. // Length is too large for 64 bits.
  10626. "1ffffffffffffffff\r\n"
  10627. "xyz\r\n",
  10628. &out);
  10629. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10630. }
  10631. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10632. test_raw_request("GET /hi HTTP/1.1\r\n"
  10633. "Content-Type: text/plain\r\n\r");
  10634. }
  10635. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10636. std::string out;
  10637. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10638. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10639. }
  10640. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10641. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10642. std::string out;
  10643. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10644. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10645. }
  10646. }
  10647. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10648. std::string out;
  10649. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10650. "Host: localhost\r\n"
  10651. "Connection: close\r\n\r\n",
  10652. &out);
  10653. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10654. }
  10655. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10656. Server svr;
  10657. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10658. EXPECT_TRUE(!req.remote_addr.empty());
  10659. });
  10660. thread t = thread([&] { svr.listen(HOST, PORT); });
  10661. auto se = detail::scope_exit([&] {
  10662. svr.stop();
  10663. t.join();
  10664. ASSERT_FALSE(svr.is_running());
  10665. });
  10666. svr.wait_until_ready();
  10667. // Send an invalid request line to trigger Bad Request
  10668. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10669. std::string out;
  10670. ASSERT_TRUE(send_request(5, bad_req, &out));
  10671. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10672. }
  10673. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10674. // answered right away rather than blocking on a read that waits for EOF.
  10675. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10676. std::string out;
  10677. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10678. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10679. }
  10680. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10681. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10682. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10683. for (const auto *method : methods) {
  10684. Server svr;
  10685. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10686. EXPECT_FALSE(svr.is_valid()) << method;
  10687. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10688. }
  10689. }
  10690. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10691. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10692. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10693. for (const auto *method : methods) {
  10694. Server svr;
  10695. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10696. EXPECT_FALSE(svr.is_valid()) << method;
  10697. }
  10698. }
  10699. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10700. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10701. "COPY", "MOVE", "LOCK",
  10702. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10703. Server svr;
  10704. for (const auto *method : methods) {
  10705. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10706. }
  10707. EXPECT_TRUE(svr.is_valid());
  10708. }
  10709. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10710. Server svr;
  10711. svr.CustomRoute("POST", "/x",
  10712. [](const Request &, Response &, const ContentReader &) {});
  10713. EXPECT_FALSE(svr.is_valid());
  10714. }
  10715. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10716. Server svr;
  10717. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10718. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10719. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10720. EXPECT_FALSE(svr.is_valid());
  10721. }
  10722. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10723. Server svr;
  10724. auto captured = Error::Success;
  10725. svr.set_error_logger(
  10726. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10727. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10728. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10729. }
  10730. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10731. std::string out;
  10732. std::string request(
  10733. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10734. test_raw_request(request, &out);
  10735. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10736. }
  10737. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10738. std::string out;
  10739. std::string request(
  10740. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10741. test_raw_request(request, &out);
  10742. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10743. }
  10744. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10745. std::string out;
  10746. std::string request(
  10747. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10748. test_raw_request(request, &out);
  10749. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10750. }
  10751. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10752. std::string out;
  10753. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10754. "Host: localhost\r\n"
  10755. "Test: \r\n\r\n",
  10756. &out);
  10757. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10758. }
  10759. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10760. Server svr;
  10761. std::string x_custom;
  10762. std::string cookie;
  10763. std::string xff;
  10764. std::string x_unicode;
  10765. std::string x_iis;
  10766. svr.Get("/check", [&](const Request &req, Response &res) {
  10767. x_custom = req.get_header_value("X-Custom");
  10768. cookie = req.get_header_value("Cookie");
  10769. xff = req.get_header_value("X-Forwarded-For");
  10770. x_unicode = req.get_header_value("X-Unicode");
  10771. x_iis = req.get_header_value("X-IIS");
  10772. res.set_content("ok", "text/plain");
  10773. });
  10774. thread t = thread([&] { svr.listen(HOST, PORT); });
  10775. auto se = detail::scope_exit([&] {
  10776. svr.stop();
  10777. t.join();
  10778. ASSERT_FALSE(svr.is_running());
  10779. });
  10780. svr.wait_until_ready();
  10781. const std::string req = "GET /check HTTP/1.1\r\n"
  10782. "Host: localhost\r\n"
  10783. "X-Custom: a%0D%0AInjected: b\r\n"
  10784. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10785. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10786. "X-Unicode: %E3%81%82\r\n"
  10787. "X-IIS: %u00E9\r\n"
  10788. "Connection: close\r\n"
  10789. "\r\n";
  10790. std::string res;
  10791. ASSERT_TRUE(send_request(5, req, &res));
  10792. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10793. // Every value must be returned verbatim (wire form), with no decoding.
  10794. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10795. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10796. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10797. EXPECT_EQ("%E3%81%82", x_unicode);
  10798. EXPECT_EQ("%u00E9", x_iis);
  10799. }
  10800. // Applications that previously relied on automatic percent-decoding can
  10801. // reproduce the old behavior by explicitly calling decode_path_component()
  10802. // or, for RFC 3986 conformance, decode_uri_component().
  10803. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10804. Server svr;
  10805. std::string decoded;
  10806. svr.Get("/check", [&](const Request &req, Response &res) {
  10807. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10808. res.set_content("ok", "text/plain");
  10809. });
  10810. thread t = thread([&] { svr.listen(HOST, PORT); });
  10811. auto se = detail::scope_exit([&] {
  10812. svr.stop();
  10813. t.join();
  10814. ASSERT_FALSE(svr.is_running());
  10815. });
  10816. svr.wait_until_ready();
  10817. const std::string req = "GET /check HTTP/1.1\r\n"
  10818. "Host: localhost\r\n"
  10819. "X-Custom: hello%20world\r\n"
  10820. "Connection: close\r\n"
  10821. "\r\n";
  10822. std::string res;
  10823. ASSERT_TRUE(send_request(5, req, &res));
  10824. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10825. EXPECT_EQ("hello world", decoded);
  10826. }
  10827. // Regression test for #2033. Browsers send Referer values that include
  10828. // percent-encoded characters such as %0A inside the URL. Decoding the
  10829. // header value would either trip the post-decode CR/LF/NUL guard (the
  10830. // original bug, returning 400) or, after that guard was relaxed, silently
  10831. // store a literal LF — both unacceptable. The wire form must round-trip.
  10832. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10833. Server svr;
  10834. std::string referer;
  10835. svr.Get("/check", [&](const Request &req, Response &res) {
  10836. referer = req.get_header_value("Referer");
  10837. res.set_content("ok", "text/plain");
  10838. });
  10839. thread t = thread([&] { svr.listen(HOST, PORT); });
  10840. auto se = detail::scope_exit([&] {
  10841. svr.stop();
  10842. t.join();
  10843. ASSERT_FALSE(svr.is_running());
  10844. });
  10845. svr.wait_until_ready();
  10846. const std::string req = "GET /check HTTP/1.1\r\n"
  10847. "Host: localhost\r\n"
  10848. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10849. "Connection: close\r\n"
  10850. "\r\n";
  10851. std::string res;
  10852. ASSERT_TRUE(send_request(5, req, &res));
  10853. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10854. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10855. }
  10856. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10857. Server svr;
  10858. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10859. res.set_header("Cache-Control", "no-cache");
  10860. res.set_chunked_content_provider(
  10861. "text/event-stream", [](size_t offset, DataSink &sink) {
  10862. std::string s = "data:";
  10863. s += std::to_string(offset);
  10864. s += "\n\n";
  10865. auto ret = sink.write(s.data(), s.size());
  10866. EXPECT_TRUE(ret);
  10867. std::this_thread::sleep_for(std::chrono::seconds(1));
  10868. return true;
  10869. });
  10870. });
  10871. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10872. svr.wait_until_ready();
  10873. Client client(HOST, PORT);
  10874. const Headers headers = {{"Accept", "text/event-stream"}};
  10875. auto get_thread = std::thread([&client, &headers]() {
  10876. auto res = client.Get(
  10877. "/events", headers,
  10878. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10879. });
  10880. auto se = detail::scope_exit([&] {
  10881. svr.stop();
  10882. get_thread.join();
  10883. listen_thread.join();
  10884. ASSERT_FALSE(svr.is_running());
  10885. });
  10886. // Give GET time to get a few messages.
  10887. std::this_thread::sleep_for(std::chrono::seconds(2));
  10888. }
  10889. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10890. httplib::Server svr;
  10891. svr.Post("/hi",
  10892. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10893. res.status = StatusCode::OK_200;
  10894. });
  10895. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10896. svr.wait_until_ready();
  10897. Client cli(HOST, PORT);
  10898. auto res = cli.Post("/hi", "data", "text/plain");
  10899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10900. EXPECT_EQ(StatusCode::OK_200, res->status);
  10901. svr.stop();
  10902. thread.join();
  10903. ASSERT_FALSE(svr.is_running());
  10904. res = cli.Post("/hi", "data", "text/plain");
  10905. ASSERT_FALSE(res);
  10906. }
  10907. TEST(ServerStopTest, ListenFailure) {
  10908. Server svr;
  10909. auto t = thread([&]() {
  10910. auto ret = svr.listen("????", PORT);
  10911. EXPECT_FALSE(ret);
  10912. });
  10913. svr.wait_until_ready();
  10914. svr.stop();
  10915. t.join();
  10916. }
  10917. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10918. TEST(ServerStopTest, Decommision) {
  10919. Server svr;
  10920. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10921. for (int i = 0; i < 4; i++) {
  10922. auto is_even = !(i % 2);
  10923. std::thread t{[&] {
  10924. try {
  10925. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10926. if (is_even) {
  10927. throw std::runtime_error("Some thing that happens to go wrong.");
  10928. }
  10929. svr.listen(HOST, PORT);
  10930. } catch (...) { svr.decommission(); }
  10931. }};
  10932. svr.wait_until_ready();
  10933. // Server is up
  10934. {
  10935. Client cli(HOST, PORT);
  10936. auto res = cli.Get("/hi");
  10937. if (is_even) {
  10938. EXPECT_FALSE(res);
  10939. } else {
  10940. EXPECT_TRUE(res);
  10941. EXPECT_EQ("hi...", res->body);
  10942. }
  10943. }
  10944. svr.stop();
  10945. t.join();
  10946. // Server is down...
  10947. {
  10948. Client cli(HOST, PORT);
  10949. auto res = cli.Get("/hi");
  10950. EXPECT_FALSE(res);
  10951. }
  10952. }
  10953. }
  10954. #endif
  10955. // Helper function for string body upload progress tests
  10956. template <typename SetupHandler, typename ClientCall>
  10957. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10958. ClientCall &&client_call,
  10959. const string &body) {
  10960. Server svr;
  10961. setup_handler(svr);
  10962. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10963. auto se = detail::scope_exit([&] {
  10964. svr.stop();
  10965. t.join();
  10966. });
  10967. svr.wait_until_ready();
  10968. Client cli(HOST, PORT);
  10969. vector<uint64_t> progress_values;
  10970. bool progress_called = false;
  10971. auto res =
  10972. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10973. progress_values.push_back(current);
  10974. progress_called = true;
  10975. return true;
  10976. });
  10977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10978. EXPECT_EQ(200, res->status);
  10979. EXPECT_TRUE(progress_called);
  10980. }
  10981. TEST(UploadProgressTest, PostStringBodyBasic) {
  10982. TestStringBodyUploadProgress(
  10983. [](Server &svr) {
  10984. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10985. res.set_content("received", "text/plain");
  10986. });
  10987. },
  10988. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10989. return cli.Post("/test", body, "text/plain", progress_callback);
  10990. },
  10991. "test data for upload progress");
  10992. }
  10993. TEST(UploadProgressTest, PutStringBodyBasic) {
  10994. TestStringBodyUploadProgress(
  10995. [](Server &svr) {
  10996. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10997. res.set_content("put received", "text/plain");
  10998. });
  10999. },
  11000. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11001. return cli.Put("/test", body, "text/plain", progress_callback);
  11002. },
  11003. "put test data for upload progress");
  11004. }
  11005. TEST(UploadProgressTest, PatchStringBodyBasic) {
  11006. TestStringBodyUploadProgress(
  11007. [](Server &svr) {
  11008. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  11009. res.set_content("patch received", "text/plain");
  11010. });
  11011. },
  11012. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11013. return cli.Patch("/test", body, "text/plain", progress_callback);
  11014. },
  11015. "patch test data for upload progress");
  11016. }
  11017. // Helper function for content provider upload progress tests
  11018. template <typename SetupHandler, typename ClientCall>
  11019. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  11020. ClientCall &&client_call) {
  11021. Server svr;
  11022. setup_handler(svr);
  11023. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11024. auto se = detail::scope_exit([&] {
  11025. svr.stop();
  11026. t.join();
  11027. });
  11028. svr.wait_until_ready();
  11029. Client cli(HOST, PORT);
  11030. vector<uint64_t> progress_values;
  11031. auto res =
  11032. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11033. progress_values.push_back(current);
  11034. return true;
  11035. });
  11036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11037. EXPECT_EQ(200, res->status);
  11038. EXPECT_FALSE(progress_values.empty());
  11039. }
  11040. TEST(UploadProgressTest, PostContentProviderProgress) {
  11041. TestContentProviderUploadProgress(
  11042. [](Server &svr) {
  11043. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11044. res.set_content("provider received", "text/plain");
  11045. });
  11046. },
  11047. [](Client &cli, UploadProgress progress_callback) {
  11048. return cli.Post(
  11049. "/test", 9,
  11050. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11051. sink.os << "test data";
  11052. return true;
  11053. },
  11054. "text/plain", progress_callback);
  11055. });
  11056. }
  11057. // Helper function for multipart upload progress tests
  11058. template <typename SetupHandler, typename ClientCall>
  11059. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11060. ClientCall &&client_call,
  11061. const string &endpoint) {
  11062. Server svr;
  11063. setup_handler(svr);
  11064. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11065. auto se = detail::scope_exit([&] {
  11066. svr.stop();
  11067. t.join();
  11068. });
  11069. svr.wait_until_ready();
  11070. Client cli(HOST, PORT);
  11071. vector<uint64_t> progress_values;
  11072. UploadFormDataItems items = {
  11073. {"field1", "value1", "", ""},
  11074. {"field2", "longer value for progress tracking test", "", ""},
  11075. {"file1", "file content data for upload progress", "test.txt",
  11076. "text/plain"}};
  11077. auto res = client_call(cli, endpoint, items,
  11078. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11079. progress_values.push_back(current);
  11080. return true;
  11081. });
  11082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11083. EXPECT_EQ(200, res->status);
  11084. EXPECT_FALSE(progress_values.empty());
  11085. }
  11086. TEST(UploadProgressTest, PostMultipartProgress) {
  11087. TestMultipartUploadProgress(
  11088. [](Server &svr) {
  11089. svr.Post("/multipart", [](const Request &req, Response &res) {
  11090. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11091. res.set_content("multipart received", "text/plain");
  11092. });
  11093. },
  11094. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11095. UploadProgress progress_callback) {
  11096. return cli.Post(endpoint, items, progress_callback);
  11097. },
  11098. "/multipart");
  11099. }
  11100. // Helper function for basic download progress tests
  11101. template <typename SetupHandler, typename ClientCall>
  11102. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11103. ClientCall &&client_call, const string &endpoint,
  11104. size_t expected_content_size) {
  11105. Server svr;
  11106. setup_handler(svr);
  11107. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11108. auto se = detail::scope_exit([&] {
  11109. svr.stop();
  11110. t.join();
  11111. });
  11112. svr.wait_until_ready();
  11113. Client cli(HOST, PORT);
  11114. vector<uint64_t> progress_values;
  11115. auto res = client_call(cli, endpoint,
  11116. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11117. progress_values.push_back(current);
  11118. return true;
  11119. });
  11120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11121. EXPECT_EQ(200, res->status);
  11122. EXPECT_FALSE(progress_values.empty());
  11123. EXPECT_EQ(expected_content_size, res->body.size());
  11124. }
  11125. TEST(DownloadProgressTest, GetBasic) {
  11126. TestBasicDownloadProgress(
  11127. [](Server &svr) {
  11128. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11129. string content(1000, 'D');
  11130. res.set_content(content, "text/plain");
  11131. });
  11132. },
  11133. [](Client &cli, const string &endpoint,
  11134. DownloadProgress progress_callback) {
  11135. return cli.Get(endpoint, progress_callback);
  11136. },
  11137. "/download", 1000u);
  11138. }
  11139. // Helper function for content receiver download progress tests
  11140. template <typename SetupHandler, typename ClientCall>
  11141. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11142. ClientCall &&client_call,
  11143. const string &endpoint,
  11144. size_t expected_content_size) {
  11145. Server svr;
  11146. setup_handler(svr);
  11147. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11148. auto se = detail::scope_exit([&] {
  11149. svr.stop();
  11150. t.join();
  11151. });
  11152. svr.wait_until_ready();
  11153. Client cli(HOST, PORT);
  11154. vector<uint64_t> progress_values;
  11155. string received_body;
  11156. auto res = client_call(
  11157. cli, endpoint,
  11158. [&](const char *data, size_t data_length) -> bool {
  11159. received_body.append(data, data_length);
  11160. return true;
  11161. },
  11162. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11163. progress_values.push_back(current);
  11164. return true;
  11165. });
  11166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11167. EXPECT_EQ(200, res->status);
  11168. EXPECT_FALSE(progress_values.empty());
  11169. EXPECT_EQ(expected_content_size, received_body.size());
  11170. EXPECT_TRUE(res->body.empty());
  11171. }
  11172. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11173. TestContentReceiverDownloadProgress(
  11174. [](Server &svr) {
  11175. svr.Get("/download-receiver",
  11176. [](const Request & /*req*/, Response &res) {
  11177. string content(2000, 'R');
  11178. res.set_content(content, "text/plain");
  11179. });
  11180. },
  11181. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11182. DownloadProgress progress_callback) {
  11183. return cli.Get(endpoint, content_receiver, progress_callback);
  11184. },
  11185. "/download-receiver", 2000u);
  11186. }
  11187. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11188. // A provider reaching a pass with nothing to hand over - an empty buffer
  11189. // popped off a queue, say - must not be taken to mean the body is finished.
  11190. // It used to end the loop with the terminating chunk unwritten while the
  11191. // server still considered the response complete, so the peer waited for an
  11192. // end that never arrived.
  11193. Server svr;
  11194. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11195. auto step = std::make_shared<int>(0);
  11196. res.set_chunked_content_provider("text/plain",
  11197. [step](size_t /*offset*/, DataSink &sink) {
  11198. switch ((*step)++) {
  11199. case 0: sink.write("", 0); break;
  11200. case 1: sink.write("hello", 5); break;
  11201. default: sink.done(); break;
  11202. }
  11203. return true;
  11204. });
  11205. });
  11206. auto port = svr.bind_to_any_port(HOST);
  11207. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11208. auto listen_se = detail::scope_exit([&] {
  11209. svr.stop();
  11210. listen_thread.join();
  11211. ASSERT_FALSE(svr.is_running());
  11212. });
  11213. svr.wait_until_ready();
  11214. Client cli(HOST, port);
  11215. // Without the fix the body is never terminated, so bound the wait rather
  11216. // than letting the test hang on the default read timeout.
  11217. cli.set_read_timeout(5, 0);
  11218. auto res = cli.Get("/stream");
  11219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11220. EXPECT_EQ(StatusCode::OK_200, res->status);
  11221. EXPECT_EQ("hello", res->body);
  11222. }
  11223. TEST(StreamingTest, NoContentLengthStreaming) {
  11224. Server svr;
  11225. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11226. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11227. if (offset < 6) {
  11228. sink.os << (offset < 3 ? "a" : "b");
  11229. } else {
  11230. sink.done();
  11231. }
  11232. return true;
  11233. });
  11234. });
  11235. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11236. auto listen_se = detail::scope_exit([&] {
  11237. svr.stop();
  11238. listen_thread.join();
  11239. ASSERT_FALSE(svr.is_running());
  11240. });
  11241. svr.wait_until_ready();
  11242. Client client(HOST, PORT);
  11243. auto get_thread = std::thread([&client]() {
  11244. std::string s;
  11245. auto res =
  11246. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11247. s += std::string(data, len);
  11248. return true;
  11249. });
  11250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11251. EXPECT_EQ(StatusCode::OK_200, res->status);
  11252. EXPECT_EQ("aaabbb", s);
  11253. });
  11254. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11255. // Give GET time to get a few messages.
  11256. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11257. }
  11258. TEST(MountTest, Unmount) {
  11259. Server svr;
  11260. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11261. auto se = detail::scope_exit([&] {
  11262. svr.stop();
  11263. listen_thread.join();
  11264. ASSERT_FALSE(svr.is_running());
  11265. });
  11266. svr.wait_until_ready();
  11267. Client cli("localhost", PORT);
  11268. svr.set_mount_point("/mount2", "./www2");
  11269. auto res = cli.Get("/");
  11270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11271. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11272. res = cli.Get("/mount2/dir/test.html");
  11273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11274. EXPECT_EQ(StatusCode::OK_200, res->status);
  11275. svr.set_mount_point("/", "./www");
  11276. res = cli.Get("/dir/");
  11277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11278. EXPECT_EQ(StatusCode::OK_200, res->status);
  11279. svr.remove_mount_point("/");
  11280. res = cli.Get("/dir/");
  11281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11282. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11283. svr.remove_mount_point("/mount2");
  11284. res = cli.Get("/mount2/dir/test.html");
  11285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11287. }
  11288. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11289. Server svr;
  11290. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11291. svr.Get("/api/hello", [](const Request &, Response &res) {
  11292. res.set_content("api", "text/plain");
  11293. });
  11294. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11295. auto se = detail::scope_exit([&] {
  11296. svr.stop();
  11297. listen_thread.join();
  11298. ASSERT_FALSE(svr.is_running());
  11299. });
  11300. svr.wait_until_ready();
  11301. Client cli(HOST, PORT);
  11302. auto res = cli.Get("/dir/test.html");
  11303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11304. EXPECT_EQ(StatusCode::OK_200, res->status);
  11305. res = cli.Get("/api/hello");
  11306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11307. EXPECT_EQ(StatusCode::OK_200, res->status);
  11308. EXPECT_EQ("api", res->body);
  11309. }
  11310. TEST(MountTest, PathSegmentBoundary) {
  11311. Server svr;
  11312. svr.set_mount_point("/mount2", "./www2");
  11313. svr.set_mount_point("/", "./www");
  11314. auto port = svr.bind_to_any_port(HOST);
  11315. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11316. auto se = detail::scope_exit([&] {
  11317. svr.stop();
  11318. listen_thread.join();
  11319. ASSERT_FALSE(svr.is_running());
  11320. });
  11321. svr.wait_until_ready();
  11322. Client cli(HOST, port);
  11323. auto res = cli.Get("/mount2/dir/test.html");
  11324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11325. EXPECT_EQ(StatusCode::OK_200, res->status);
  11326. // "/mount2" must not match part-way through a path segment.
  11327. res = cli.Get("/mount2dir/test.html");
  11328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11329. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11330. // A mount point ending in '/' keeps matching every path below it.
  11331. res = cli.Get("/dir/test.html");
  11332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11333. EXPECT_EQ(StatusCode::OK_200, res->status);
  11334. }
  11335. TEST(MountTest, Redicect) {
  11336. Server svr;
  11337. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11338. auto se = detail::scope_exit([&] {
  11339. svr.stop();
  11340. listen_thread.join();
  11341. ASSERT_FALSE(svr.is_running());
  11342. });
  11343. svr.set_mount_point("/", "./www");
  11344. svr.wait_until_ready();
  11345. Client cli("localhost", PORT);
  11346. auto res = cli.Get("/dir/");
  11347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11348. EXPECT_EQ(StatusCode::OK_200, res->status);
  11349. res = cli.Get("/dir");
  11350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11351. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11352. res = cli.Get("/file");
  11353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11354. EXPECT_EQ(StatusCode::OK_200, res->status);
  11355. res = cli.Get("/file/");
  11356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11357. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11358. cli.set_follow_location(true);
  11359. res = cli.Get("/dir");
  11360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11361. EXPECT_EQ(StatusCode::OK_200, res->status);
  11362. }
  11363. TEST(MountTest, MultibytesPathName) {
  11364. Server svr;
  11365. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11366. auto se = detail::scope_exit([&] {
  11367. svr.stop();
  11368. listen_thread.join();
  11369. ASSERT_FALSE(svr.is_running());
  11370. });
  11371. svr.set_mount_point("/", "./www");
  11372. svr.wait_until_ready();
  11373. Client cli("localhost", PORT);
  11374. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11376. EXPECT_EQ(StatusCode::OK_200, res->status);
  11377. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11378. }
  11379. // A mount point serves no path with an empty segment or one ending in '.' or
  11380. // a space, so a guard in the pre-routing handler sees the path of every file
  11381. // that is served
  11382. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11383. Server svr;
  11384. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11385. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11386. if (req.path == "/dir/test.html") {
  11387. res.status = StatusCode::Unauthorized_401;
  11388. return Server::HandlerResponse::Handled;
  11389. }
  11390. return Server::HandlerResponse::Unhandled;
  11391. });
  11392. auto port = svr.bind_to_any_port(HOST);
  11393. ASSERT_LT(0, port);
  11394. thread t = thread([&] { svr.listen_after_bind(); });
  11395. auto se = detail::scope_exit([&] {
  11396. svr.stop();
  11397. t.join();
  11398. ASSERT_FALSE(svr.is_running());
  11399. });
  11400. svr.wait_until_ready();
  11401. Client cli(HOST, port);
  11402. for (auto path :
  11403. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11404. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11405. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11406. "/dir/test.html%3A%3A$DATA"}) {
  11407. SCOPED_TRACE(path);
  11408. auto res = cli.Get(path);
  11409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11411. }
  11412. }
  11413. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11414. Server svr;
  11415. svr.set_mount_point("/", "./www");
  11416. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11417. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11418. auto port = svr.bind_to_any_port(HOST);
  11419. ASSERT_GT(port, 0);
  11420. thread t = thread([&] { svr.listen_after_bind(); });
  11421. auto se = detail::scope_exit([&] {
  11422. svr.stop();
  11423. t.join();
  11424. ASSERT_FALSE(svr.is_running());
  11425. });
  11426. svr.wait_until_ready();
  11427. Client cli(HOST, port);
  11428. auto res = cli.Get("/dir/test.abcde");
  11429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11430. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11431. res = cli.Get("/dir/test.html");
  11432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11433. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11434. }
  11435. #ifdef _WIN32
  11436. // Issue #2435: mmap::open() must succeed even when another handle holds
  11437. // the file open for writing (e.g. an active log file).
  11438. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11439. const char *path = "mmap_concurrent_writer_test.txt";
  11440. const char *content = "hello";
  11441. {
  11442. std::ofstream f(path, std::ios::binary);
  11443. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11444. }
  11445. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11446. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11447. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11448. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11449. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11450. detail::mmap m(path);
  11451. ASSERT_TRUE(m.is_open());
  11452. EXPECT_EQ(strlen(content), m.size());
  11453. char buf[8];
  11454. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11455. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11456. }
  11457. #endif
  11458. #ifndef _WIN32
  11459. // A directory or a device has no size to serve.
  11460. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11461. const char *path = "./mmap_not_regular_test_dir";
  11462. ASSERT_EQ(0, ::mkdir(path, 0755));
  11463. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11464. for (auto p : {path, "/dev/null"}) {
  11465. detail::mmap m(p);
  11466. EXPECT_FALSE(m.is_open()) << p;
  11467. EXPECT_EQ(0U, m.size()) << p;
  11468. }
  11469. Server svr;
  11470. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11471. res.set_file_content("/dev/null");
  11472. });
  11473. auto port = svr.bind_to_any_port(HOST);
  11474. thread t = thread([&] { svr.listen_after_bind(); });
  11475. auto se = detail::scope_exit([&] {
  11476. svr.stop();
  11477. t.join();
  11478. });
  11479. svr.wait_until_ready();
  11480. auto res = Client(HOST, port).Get("/null");
  11481. ASSERT_TRUE(res);
  11482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11483. }
  11484. #endif
  11485. #ifdef __linux__
  11486. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11487. TEST(MmapTest, FileIsNotMapped) {
  11488. const char *path = "mmap_not_mapped_test.txt";
  11489. {
  11490. std::ofstream f(path, std::ios::binary);
  11491. f << "hello";
  11492. }
  11493. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11494. detail::mmap m(path);
  11495. ASSERT_TRUE(m.is_open());
  11496. std::ifstream maps("/proc/self/maps");
  11497. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11498. std::istreambuf_iterator<char>());
  11499. EXPECT_EQ(std::string::npos, mappings.find(path));
  11500. }
  11501. #endif
  11502. TEST(KeepAliveTest, ReadTimeout) {
  11503. Server svr;
  11504. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11505. std::this_thread::sleep_for(std::chrono::seconds(2));
  11506. res.set_content("a", "text/plain");
  11507. });
  11508. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11509. res.set_content("b", "text/plain");
  11510. });
  11511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11512. auto se = detail::scope_exit([&] {
  11513. svr.stop();
  11514. listen_thread.join();
  11515. ASSERT_FALSE(svr.is_running());
  11516. });
  11517. svr.wait_until_ready();
  11518. Client cli("localhost", PORT);
  11519. cli.set_keep_alive(true);
  11520. cli.set_read_timeout(std::chrono::seconds(1));
  11521. auto resa = cli.Get("/a");
  11522. ASSERT_FALSE(resa);
  11523. EXPECT_EQ(Error::Read, resa.error());
  11524. auto resb = cli.Get("/b");
  11525. ASSERT_TRUE(resb);
  11526. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11527. EXPECT_EQ("b", resb->body);
  11528. }
  11529. TEST(KeepAliveTest, MaxCount) {
  11530. size_t keep_alive_max_count = 3;
  11531. Server svr;
  11532. svr.set_keep_alive_max_count(keep_alive_max_count);
  11533. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11534. res.set_content("Hello World!", "text/plain");
  11535. });
  11536. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11537. auto se = detail::scope_exit([&] {
  11538. svr.stop();
  11539. listen_thread.join();
  11540. ASSERT_FALSE(svr.is_running());
  11541. });
  11542. svr.wait_until_ready();
  11543. Client cli(HOST, PORT);
  11544. cli.set_keep_alive(true);
  11545. for (size_t i = 0; i < 5; i++) {
  11546. auto result = cli.Get("/hi");
  11547. ASSERT_TRUE(result);
  11548. EXPECT_EQ(StatusCode::OK_200, result->status);
  11549. if (i == keep_alive_max_count - 1) {
  11550. EXPECT_EQ("close", result->get_header_value("Connection"));
  11551. } else {
  11552. EXPECT_FALSE(result->has_header("Connection"));
  11553. }
  11554. }
  11555. }
  11556. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11557. // can pull the next one into the server's buffer. The server must serve it
  11558. // without waiting for the socket to become readable again. The keep-alive
  11559. // timeout outlasts the client's read timeout, so a request left waiting for it
  11560. // shows up as a missing response.
  11561. static void serve_pipelining_routes(Server &svr,
  11562. const std::function<void(int)> &client) {
  11563. svr.set_keep_alive_timeout(5);
  11564. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11565. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11566. });
  11567. svr.Post("/echo", [](const Request &req, Response &res) {
  11568. res.set_content("echo " + req.body, "text/plain");
  11569. });
  11570. auto port = svr.bind_to_any_port(HOST);
  11571. thread t = thread([&] { svr.listen_after_bind(); });
  11572. auto se = detail::scope_exit([&] {
  11573. svr.stop();
  11574. t.join();
  11575. });
  11576. svr.wait_until_ready();
  11577. client(port);
  11578. }
  11579. static std::string
  11580. send_pipelined_requests(const std::vector<std::string> &parts) {
  11581. Server svr;
  11582. std::string res;
  11583. serve_pipelining_routes(svr, [&](int port) {
  11584. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11585. });
  11586. return res;
  11587. }
  11588. static void expect_in_order(const std::string &res,
  11589. const std::vector<std::string> &bodies) {
  11590. size_t pos = 0;
  11591. for (const auto &body : bodies) {
  11592. pos = res.find(body, pos);
  11593. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11594. pos += body.size();
  11595. }
  11596. }
  11597. TEST(KeepAliveTest, PipelinedRequests) {
  11598. auto res = send_pipelined_requests(
  11599. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11600. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11601. "Content-Length: 4\r\n\r\nbody"
  11602. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11603. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11604. }
  11605. // The second request starts in the server's buffer and ends on the socket.
  11606. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11607. auto res =
  11608. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11609. "GET /hi/2 HTTP/1.1\r\nHo",
  11610. "st: localhost\r\nConnection: close\r\n\r\n"});
  11611. expect_in_order(res, {"hi 1", "hi 2"});
  11612. }
  11613. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11614. // CRLF after a body does not turn into a 400 for the next request.
  11615. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11616. auto res = send_pipelined_requests(
  11617. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11618. "Content-Length: 4\r\n\r\nbody\r\n"
  11619. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11620. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11621. expect_in_order(res, {"echo body", "hi 2"});
  11622. }
  11623. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11624. // must not be served as the next request.
  11625. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11626. auto res = send_pipelined_requests(
  11627. {"INVALID REQUEST LINE\r\n\r\n"
  11628. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11629. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11630. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11631. }
  11632. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11633. // Over TLS, the next request is held by the TLS library as already decrypted
  11634. // data rather than on the socket.
  11635. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11637. std::string res;
  11638. serve_pipelining_routes(svr, [&](int port) {
  11639. // One part, so all three requests arrive in one TLS record
  11640. EXPECT_TRUE(send_ssl_request_in_parts(
  11641. 2,
  11642. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11643. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11644. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11645. &res, port));
  11646. });
  11647. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11648. }
  11649. #endif
  11650. TEST(KeepAliveTest, Issue1041) {
  11651. Server svr;
  11652. svr.set_keep_alive_timeout(3);
  11653. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11654. res.set_content("Hello World!", "text/plain");
  11655. });
  11656. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11657. auto se = detail::scope_exit([&] {
  11658. svr.stop();
  11659. listen_thread.join();
  11660. ASSERT_FALSE(svr.is_running());
  11661. });
  11662. svr.wait_until_ready();
  11663. Client cli(HOST, PORT);
  11664. cli.set_keep_alive(true);
  11665. auto result = cli.Get("/hi");
  11666. ASSERT_TRUE(result);
  11667. EXPECT_EQ(StatusCode::OK_200, result->status);
  11668. std::this_thread::sleep_for(std::chrono::seconds(5));
  11669. result = cli.Get("/hi");
  11670. ASSERT_TRUE(result);
  11671. EXPECT_EQ(StatusCode::OK_200, result->status);
  11672. }
  11673. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11674. Server svr;
  11675. svr.set_keep_alive_max_count(0);
  11676. std::set<int> remote_ports;
  11677. svr.Get("/hi", [&](const Request &req, Response &res) {
  11678. remote_ports.insert(req.remote_port);
  11679. res.set_content("hi", "text/plain");
  11680. });
  11681. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11682. auto se = detail::scope_exit([&] {
  11683. svr.stop();
  11684. listen_thread.join();
  11685. ASSERT_FALSE(svr.is_running());
  11686. });
  11687. svr.wait_until_ready();
  11688. Client cli(HOST, PORT);
  11689. cli.set_keep_alive(true);
  11690. for (int i = 0; i < 3; i++) {
  11691. auto res = cli.Get("/hi");
  11692. ASSERT_TRUE(res);
  11693. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11694. }
  11695. // All three over one connection
  11696. EXPECT_EQ(1u, remote_ports.size());
  11697. }
  11698. // Forward declaration (see the base64_encode note).
  11699. namespace httplib {
  11700. namespace detail {
  11701. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11702. } // namespace detail
  11703. } // namespace httplib
  11704. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11705. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11706. #ifndef _WIN32
  11707. signal(SIGPIPE, SIG_IGN);
  11708. #endif
  11709. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11710. ASSERT_NE(INVALID_SOCKET, srv);
  11711. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11712. default_socket_options(srv);
  11713. sockaddr_in addr{};
  11714. addr.sin_family = AF_INET;
  11715. addr.sin_port = 0;
  11716. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11717. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11718. ASSERT_EQ(0, ::listen(srv, 2));
  11719. socklen_t addr_len = sizeof(addr);
  11720. ASSERT_EQ(0,
  11721. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11722. auto port = ntohs(addr.sin_port);
  11723. struct Peer {
  11724. socket_t sock = INVALID_SOCKET;
  11725. #ifdef CPPHTTPLIB_SSL_ENABLED
  11726. tls::session_t session = nullptr;
  11727. #endif
  11728. };
  11729. #ifdef CPPHTTPLIB_SSL_ENABLED
  11730. tls::ctx_t ctx = nullptr;
  11731. if (use_tls) {
  11732. ctx = tls::create_server_context();
  11733. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11734. nullptr);
  11735. }
  11736. auto ctx_se = detail::scope_exit([&] {
  11737. if (ctx) { tls::free_context(ctx); }
  11738. });
  11739. #endif
  11740. auto close_peer = [](Peer &peer) {
  11741. #ifdef CPPHTTPLIB_SSL_ENABLED
  11742. if (peer.session) { tls::free_session(peer.session); }
  11743. #endif
  11744. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11745. };
  11746. auto accept_peer = [&]() {
  11747. Peer peer;
  11748. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11749. peer.sock = ::accept(srv, nullptr, nullptr);
  11750. if (peer.sock == INVALID_SOCKET) { return peer; }
  11751. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11752. #ifdef CPPHTTPLIB_SSL_ENABLED
  11753. if (use_tls) {
  11754. peer.session = tls::create_session(ctx, peer.sock);
  11755. tls::TlsError err;
  11756. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err,
  11757. nullptr)) {
  11758. close_peer(peer);
  11759. return Peer();
  11760. }
  11761. }
  11762. #endif
  11763. return peer;
  11764. };
  11765. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11766. #ifdef CPPHTTPLIB_SSL_ENABLED
  11767. tls::TlsError err;
  11768. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11769. #endif
  11770. return detail::read_socket(peer.sock, buf, len, 0);
  11771. };
  11772. auto read_head = [&](const Peer &peer) {
  11773. std::string head;
  11774. char buf[1024];
  11775. while (head.find("\r\n\r\n") == std::string::npos) {
  11776. auto n = read_some(peer, buf, sizeof(buf));
  11777. if (n <= 0) { break; }
  11778. head.append(buf, static_cast<size_t>(n));
  11779. }
  11780. };
  11781. auto send_text = [](const Peer &peer, const std::string &text) {
  11782. #ifdef CPPHTTPLIB_SSL_ENABLED
  11783. tls::TlsError err;
  11784. if (peer.session) {
  11785. tls::write(peer.session, text.data(), text.size(), err);
  11786. return;
  11787. }
  11788. #endif
  11789. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11790. };
  11791. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11792. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11793. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11794. // Sent once the first response is read, so that it lands on an idle socket
  11795. std::promise<void> first_response_read;
  11796. auto first_response_read_future = first_response_read.get_future();
  11797. auto server_thread = std::thread([&] {
  11798. auto peer1 = accept_peer();
  11799. if (peer1.sock == INVALID_SOCKET) { return; }
  11800. read_head(peer1);
  11801. if (same_write) {
  11802. send_text(peer1, first + stray);
  11803. } else {
  11804. send_text(peer1, first);
  11805. first_response_read_future.wait_for(std::chrono::seconds(5));
  11806. send_text(peer1, stray);
  11807. }
  11808. // peer1 stays open, so only the unread data can tell the client
  11809. auto peer2 = accept_peer();
  11810. if (peer2.sock != INVALID_SOCKET) {
  11811. read_head(peer2);
  11812. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11813. "Connection: close\r\n\r\nsecond");
  11814. close_peer(peer2);
  11815. }
  11816. close_peer(peer1);
  11817. });
  11818. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11819. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11820. std::to_string(port));
  11821. #ifdef CPPHTTPLIB_SSL_ENABLED
  11822. cli.enable_server_certificate_verification(false);
  11823. #endif
  11824. cli.set_keep_alive(true);
  11825. cli.set_read_timeout(5, 0);
  11826. auto res = cli.Get("/1");
  11827. first_response_read.set_value();
  11828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11829. EXPECT_EQ("first", res->body);
  11830. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11831. res = cli.Get("/2");
  11832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11833. EXPECT_EQ(StatusCode::OK_200, res->status);
  11834. EXPECT_EQ("second", res->body);
  11835. }
  11836. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11837. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11838. }
  11839. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11840. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11841. }
  11842. #ifdef CPPHTTPLIB_SSL_ENABLED
  11843. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11844. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11845. }
  11846. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11847. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11848. }
  11849. #endif
  11850. TEST(KeepAliveTest, Issue1959) {
  11851. Server svr;
  11852. svr.set_keep_alive_timeout(5);
  11853. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11854. res.set_content("a", "text/plain");
  11855. });
  11856. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11857. auto se = detail::scope_exit([&] {
  11858. if (!svr.is_running()) return;
  11859. svr.stop();
  11860. listen_thread.join();
  11861. ASSERT_FALSE(svr.is_running());
  11862. });
  11863. svr.wait_until_ready();
  11864. Client cli("localhost", PORT);
  11865. cli.set_keep_alive(true);
  11866. using namespace std::chrono;
  11867. auto start = steady_clock::now();
  11868. cli.Get("/a");
  11869. svr.stop();
  11870. listen_thread.join();
  11871. auto end = steady_clock::now();
  11872. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11873. EXPECT_LT(elapsed, 5000);
  11874. }
  11875. #ifdef CPPHTTPLIB_SSL_ENABLED
  11876. TEST(KeepAliveTest, SSLClientReconnection) {
  11877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11878. ASSERT_TRUE(svr.is_valid());
  11879. svr.set_keep_alive_timeout(1);
  11880. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11881. res.set_content("Hello World!", "text/plain");
  11882. });
  11883. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11884. auto se = detail::scope_exit([&] {
  11885. svr.stop();
  11886. listen_thread.join();
  11887. ASSERT_FALSE(svr.is_running());
  11888. });
  11889. svr.wait_until_ready();
  11890. SSLClient cli(HOST, PORT);
  11891. cli.enable_server_certificate_verification(false);
  11892. cli.set_keep_alive(true);
  11893. auto result = cli.Get("/hi");
  11894. ASSERT_TRUE(result);
  11895. EXPECT_EQ(StatusCode::OK_200, result->status);
  11896. result = cli.Get("/hi");
  11897. ASSERT_TRUE(result);
  11898. EXPECT_EQ(StatusCode::OK_200, result->status);
  11899. std::this_thread::sleep_for(std::chrono::seconds(2));
  11900. // Recoonect
  11901. result = cli.Get("/hi");
  11902. ASSERT_TRUE(result);
  11903. EXPECT_EQ(StatusCode::OK_200, result->status);
  11904. result = cli.Get("/hi");
  11905. ASSERT_TRUE(result);
  11906. EXPECT_EQ(StatusCode::OK_200, result->status);
  11907. }
  11908. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11909. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11910. ASSERT_TRUE(svr.is_valid());
  11911. svr.set_keep_alive_timeout(1);
  11912. std::string content = "reconnect";
  11913. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11914. res.set_content("Hello World!", "text/plain");
  11915. });
  11916. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11917. auto se = detail::scope_exit([&] {
  11918. svr.stop();
  11919. listen_thread.join();
  11920. ASSERT_FALSE(svr.is_running());
  11921. });
  11922. svr.wait_until_ready();
  11923. SSLClient cli(HOST, PORT);
  11924. cli.enable_server_certificate_verification(false);
  11925. cli.set_keep_alive(true);
  11926. auto result = cli.Post(
  11927. "/hi", content.size(),
  11928. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11929. sink.write(content.c_str(), content.size());
  11930. return true;
  11931. },
  11932. "text/plain");
  11933. ASSERT_TRUE(result);
  11934. EXPECT_EQ(200, result->status);
  11935. std::this_thread::sleep_for(std::chrono::seconds(2));
  11936. // Recoonect
  11937. result = cli.Post(
  11938. "/hi", content.size(),
  11939. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11940. sink.write(content.c_str(), content.size());
  11941. return true;
  11942. },
  11943. "text/plain");
  11944. ASSERT_TRUE(result);
  11945. EXPECT_EQ(200, result->status);
  11946. result = cli.Post(
  11947. "/hi", content.size(),
  11948. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11949. sink.write(content.c_str(), content.size());
  11950. return true;
  11951. },
  11952. "text/plain");
  11953. ASSERT_TRUE(result);
  11954. EXPECT_EQ(200, result->status);
  11955. }
  11956. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11957. using namespace httplib::tls;
  11958. {
  11959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11960. ASSERT_TRUE(svr.is_valid());
  11961. svr.Get("/sni", [&](const Request &req, Response &res) {
  11962. std::string expected = req.sni();
  11963. EXPECT_EQ(expected, req.get_param_value("expected"));
  11964. res.set_content("ok", "text/plain");
  11965. });
  11966. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11967. auto se = detail::scope_exit([&] {
  11968. svr.stop();
  11969. listen_thread.join();
  11970. ASSERT_FALSE(svr.is_running());
  11971. });
  11972. svr.wait_until_ready();
  11973. {
  11974. SSLClient cli("localhost", PORT);
  11975. cli.enable_server_certificate_verification(false);
  11976. auto res = cli.Get("/sni?expected=localhost");
  11977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11978. }
  11979. {
  11980. SSLClient cli("::1", PORT);
  11981. cli.enable_server_certificate_verification(false);
  11982. auto res = cli.Get("/sni?expected=");
  11983. // NOTE: This may fail if the server is listening on IPv4 only
  11984. // (e.g., when localhost resolves to 127.0.0.1 only)
  11985. if (res) {
  11986. EXPECT_EQ(StatusCode::OK_200, res->status);
  11987. } else {
  11988. EXPECT_EQ(Error::Connection, res.error());
  11989. }
  11990. }
  11991. }
  11992. }
  11993. // The SNI of a failed handshake does not reach the next connection that the
  11994. // same worker thread serves
  11995. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11997. ASSERT_TRUE(svr.is_valid());
  11998. svr.new_task_queue = [] { return new ThreadPool(1); };
  11999. svr.Get("/sni", [](const Request &req, Response &res) {
  12000. res.set_content(req.sni(), "text/plain");
  12001. });
  12002. auto port = svr.bind_to_any_port("127.0.0.1");
  12003. ASSERT_LT(0, port);
  12004. thread t = thread([&] { svr.listen_after_bind(); });
  12005. auto se = detail::scope_exit([&] {
  12006. svr.stop();
  12007. t.join();
  12008. ASSERT_FALSE(svr.is_running());
  12009. });
  12010. svr.wait_until_ready();
  12011. {
  12012. // Sends SNI, then rejects the server certificate, which the CA did not sign
  12013. SSLClient cli("localhost", port);
  12014. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  12015. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  12016. auto res = cli.Get("/sni");
  12017. ASSERT_FALSE(res);
  12018. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12019. }
  12020. // An IP host sends no SNI (RFC 6066)
  12021. SSLClient cli("127.0.0.1", port);
  12022. cli.enable_server_certificate_verification(false);
  12023. auto res = cli.Get("/sni");
  12024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12025. EXPECT_EQ("", res->body);
  12026. }
  12027. #endif
  12028. TEST(ClientProblemDetectionTest, ContentProvider) {
  12029. Server svr;
  12030. size_t content_length = 1024 * 1024;
  12031. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12032. res.set_content_provider(
  12033. content_length, "text/plain",
  12034. [&](size_t offset, size_t length, DataSink &sink) {
  12035. auto out_len = std::min(length, static_cast<size_t>(1024));
  12036. std::string out(out_len, '@');
  12037. sink.write(out.data(), out_len);
  12038. return offset < 4096;
  12039. },
  12040. [](bool success) { ASSERT_FALSE(success); });
  12041. });
  12042. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12043. res.set_content_provider(
  12044. 0, "text/plain",
  12045. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12046. EXPECT_TRUE(false);
  12047. return true;
  12048. },
  12049. [](bool success) { ASSERT_FALSE(success); });
  12050. });
  12051. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12052. auto se = detail::scope_exit([&] {
  12053. svr.stop();
  12054. listen_thread.join();
  12055. ASSERT_FALSE(svr.is_running());
  12056. });
  12057. svr.wait_until_ready();
  12058. Client cli("localhost", PORT);
  12059. {
  12060. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12061. size_t /*data_length*/) { return false; });
  12062. ASSERT_FALSE(res);
  12063. }
  12064. {
  12065. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12066. size_t /*data_length*/) { return false; });
  12067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12068. }
  12069. }
  12070. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12071. // A provider that reports success without writing anything and without
  12072. // calling done() used to be handed the same offset and length again on every
  12073. // pass, so it spun for as long as the peer stayed connected.
  12074. Server svr;
  12075. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12076. res.set_content("ok", "text/plain");
  12077. });
  12078. auto port = svr.bind_to_any_port(HOST);
  12079. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12080. auto se = detail::scope_exit([&] {
  12081. svr.stop();
  12082. listen_thread.join();
  12083. ASSERT_FALSE(svr.is_running());
  12084. });
  12085. svr.wait_until_ready();
  12086. std::atomic<int> call_count{0};
  12087. Client cli(HOST, port);
  12088. auto res = cli.Post(
  12089. "/", 1024,
  12090. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12091. // Give up after enough passes to show the spin, so that losing the
  12092. // check below fails this test instead of hanging it.
  12093. return ++call_count < 100;
  12094. },
  12095. "text/plain");
  12096. ASSERT_FALSE(res);
  12097. EXPECT_EQ(Error::Write, res.error());
  12098. EXPECT_EQ(1, call_count.load());
  12099. }
  12100. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12101. // A writer only has to assign `write`. The other three used to be left as
  12102. // empty std::functions, so a provider calling one threw
  12103. // std::bad_function_call out of the thread running it and took the whole
  12104. // process down.
  12105. DataSink sink;
  12106. std::string written;
  12107. sink.write = [&](const char *data, size_t data_len) {
  12108. written.append(data, data_len);
  12109. return true;
  12110. };
  12111. EXPECT_TRUE(sink.is_writable());
  12112. sink.done();
  12113. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12114. EXPECT_TRUE(written.empty());
  12115. }
  12116. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12117. // A sink that cannot carry trailers still has to finish.
  12118. DataSink sink;
  12119. auto done_count = 0;
  12120. sink.done = [&]() { done_count++; };
  12121. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12122. EXPECT_EQ(1, done_count);
  12123. }
  12124. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12125. Server svr;
  12126. const std::string body(4096, 'x');
  12127. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12128. res.set_content_provider(body.size(), "text/plain",
  12129. [&](size_t offset, size_t length, DataSink &sink) {
  12130. sink.write(body.data() + offset, length);
  12131. sink.done();
  12132. return true;
  12133. });
  12134. });
  12135. auto port = svr.bind_to_any_port(HOST);
  12136. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12137. auto se = detail::scope_exit([&] {
  12138. svr.stop();
  12139. listen_thread.join();
  12140. ASSERT_FALSE(svr.is_running());
  12141. });
  12142. svr.wait_until_ready();
  12143. Client cli(HOST, port);
  12144. auto res = cli.Get("/");
  12145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12146. EXPECT_EQ(StatusCode::OK_200, res->status);
  12147. EXPECT_EQ(body, res->body);
  12148. }
  12149. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12150. Server svr;
  12151. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12152. res.set_content_provider(
  12153. 1024, "text/plain",
  12154. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12155. sink.write("hello", 5);
  12156. sink.done(); // short of the 1024 bytes the response promised
  12157. return true;
  12158. });
  12159. });
  12160. auto port = svr.bind_to_any_port(HOST);
  12161. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12162. auto se = detail::scope_exit([&] {
  12163. svr.stop();
  12164. listen_thread.join();
  12165. ASSERT_FALSE(svr.is_running());
  12166. });
  12167. svr.wait_until_ready();
  12168. Client cli(HOST, port);
  12169. cli.set_read_timeout(5, 0);
  12170. // The response is short of its Content-Length, so the client cannot read a
  12171. // complete body. What matters is that this returns at all: a no-op done()
  12172. // would leave the writer looping over a provider that never makes progress.
  12173. auto res = cli.Get("/");
  12174. EXPECT_FALSE(res);
  12175. }
  12176. // Read as the next response by a peer that sees it after a framed body.
  12177. static const std::string smuggled_response =
  12178. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12179. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12180. Server svr;
  12181. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12182. res.set_content_provider(
  12183. 5, "text/plain",
  12184. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12185. auto data = "AAAAA" + smuggled_response;
  12186. sink.write(data.data(), data.size());
  12187. return true;
  12188. });
  12189. });
  12190. thread t = thread([&] { svr.listen(HOST, PORT); });
  12191. auto se = detail::scope_exit([&] {
  12192. svr.stop();
  12193. t.join();
  12194. ASSERT_FALSE(svr.is_running());
  12195. });
  12196. svr.wait_until_ready();
  12197. std::string resp;
  12198. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12199. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12200. resp.clear();
  12201. ASSERT_TRUE(send_request(
  12202. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12203. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12204. }
  12205. TEST(NoContentTest, BodyIsNotSent) {
  12206. Server svr;
  12207. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12208. res.status = StatusCode::NoContent_204;
  12209. res.set_content(smuggled_response, "text/plain");
  12210. });
  12211. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12212. res.status = StatusCode::NotModified_304;
  12213. res.set_chunked_content_provider(
  12214. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12215. sink.write(smuggled_response.data(), smuggled_response.size());
  12216. sink.done();
  12217. return true;
  12218. });
  12219. });
  12220. thread t = thread([&] { svr.listen(HOST, PORT); });
  12221. auto se = detail::scope_exit([&] {
  12222. svr.stop();
  12223. t.join();
  12224. ASSERT_FALSE(svr.is_running());
  12225. });
  12226. svr.wait_until_ready();
  12227. for (auto path : {"/204", "/304"}) {
  12228. std::string resp;
  12229. ASSERT_TRUE(send_request(
  12230. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12231. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12232. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12233. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12234. }
  12235. }
  12236. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12237. Server svr;
  12238. std::atomic<bool> smuggled(false);
  12239. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12240. res.set_content("ok", "text/plain");
  12241. });
  12242. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12243. smuggled = true;
  12244. });
  12245. auto port = svr.bind_to_any_port(HOST);
  12246. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12247. auto se = detail::scope_exit([&] {
  12248. svr.stop();
  12249. listen_thread.join();
  12250. ASSERT_FALSE(svr.is_running());
  12251. });
  12252. svr.wait_until_ready();
  12253. // What follows the body would be read as the next request.
  12254. Client cli(HOST, port);
  12255. auto res = cli.Post(
  12256. "/", 5,
  12257. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12258. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12259. sink.write(data.data(), data.size());
  12260. return true;
  12261. },
  12262. "text/plain");
  12263. ASSERT_FALSE(res);
  12264. EXPECT_EQ(Error::Write, res.error());
  12265. EXPECT_FALSE(smuggled);
  12266. }
  12267. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12268. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12269. // The compressed path builds the whole body before connecting, so this
  12270. // fails client-side and never reaches a server.
  12271. Client cli(HOST, PORT);
  12272. cli.set_compress(true);
  12273. auto res = cli.Post(
  12274. "/", 1024,
  12275. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12276. sink.write("hello", 5);
  12277. sink.done(); // short of the 1024 bytes the request announced
  12278. return true;
  12279. },
  12280. "text/plain");
  12281. ASSERT_FALSE(res);
  12282. EXPECT_EQ(Error::Write, res.error());
  12283. }
  12284. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12285. Server svr;
  12286. std::string received;
  12287. size_t content_length_count = 0;
  12288. bool has_transfer_encoding = true;
  12289. svr.Post("/echo", [&](const Request &req, Response &res) {
  12290. received = req.body;
  12291. content_length_count = req.get_header_value_count("Content-Length");
  12292. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12293. res.set_content("ok", "text/plain");
  12294. });
  12295. svr.Get("/next", [](const Request &, Response &res) {
  12296. res.set_content("next", "text/plain");
  12297. });
  12298. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12299. auto se = detail::scope_exit([&] {
  12300. svr.stop();
  12301. listen_thread.join();
  12302. ASSERT_FALSE(svr.is_running());
  12303. });
  12304. svr.wait_until_ready();
  12305. Client cli(HOST, PORT);
  12306. cli.set_keep_alive(true);
  12307. cli.set_compress(true);
  12308. const std::string body = "hello world";
  12309. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12310. auto res = cli.Post("/echo", headers, body, "text/plain");
  12311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12312. EXPECT_EQ(StatusCode::OK_200, res->status);
  12313. EXPECT_EQ(body, received);
  12314. EXPECT_EQ(1u, content_length_count);
  12315. EXPECT_FALSE(has_transfer_encoding);
  12316. // The rest of a truncated body would be read as this request
  12317. auto res2 = cli.Get("/next");
  12318. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12319. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12320. EXPECT_EQ("next", res2->body);
  12321. }
  12322. #endif
  12323. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12324. Server svr;
  12325. std::string received;
  12326. size_t content_length_count = 1;
  12327. bool has_transfer_encoding = false;
  12328. svr.Post("/echo", [&](const Request &req, Response &res) {
  12329. received = req.body;
  12330. content_length_count = req.get_header_value_count("Content-Length");
  12331. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12332. res.set_content("ok", "text/plain");
  12333. });
  12334. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12335. auto se = detail::scope_exit([&] {
  12336. svr.stop();
  12337. listen_thread.join();
  12338. ASSERT_FALSE(svr.is_running());
  12339. });
  12340. svr.wait_until_ready();
  12341. Client cli(HOST, PORT);
  12342. cli.set_keep_alive(true);
  12343. const std::string body = "hello world";
  12344. Headers headers = {{"Content-Length", "5"}};
  12345. auto res = cli.Post(
  12346. "/echo", headers,
  12347. [&](size_t /*offset*/, DataSink &sink) {
  12348. sink.write(body.data(), body.size());
  12349. sink.done();
  12350. return true;
  12351. },
  12352. "text/plain");
  12353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12354. EXPECT_EQ(StatusCode::OK_200, res->status);
  12355. EXPECT_EQ(body, received);
  12356. EXPECT_EQ(0u, content_length_count);
  12357. EXPECT_TRUE(has_transfer_encoding);
  12358. }
  12359. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12360. Server svr;
  12361. svr.set_error_handler([](Request const &, Response &res) -> void {
  12362. res.set_chunked_content_provider(
  12363. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12364. sink.os << "hello";
  12365. sink.os << "world";
  12366. sink.done();
  12367. return true;
  12368. });
  12369. });
  12370. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12371. auto se = detail::scope_exit([&] {
  12372. svr.stop();
  12373. listen_thread.join();
  12374. ASSERT_FALSE(svr.is_running());
  12375. });
  12376. svr.wait_until_ready();
  12377. Client cli("localhost", PORT);
  12378. auto res = cli.Get("/");
  12379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12380. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12381. EXPECT_EQ("helloworld", res->body);
  12382. }
  12383. // A body set after a content provider must replace it, not be sent through it.
  12384. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12385. Server svr;
  12386. svr.set_mount_point("/", "./www");
  12387. svr.set_file_request_handler([](const Request &req, Response &res) {
  12388. if (req.path == "/dir/test.html") {
  12389. res.status = StatusCode::Forbidden_403;
  12390. res.set_content(std::string(5000, 'D'), "text/plain");
  12391. } else if (req.path == "/file") {
  12392. res.status = StatusCode::Forbidden_403;
  12393. res.body = "Denied";
  12394. }
  12395. });
  12396. auto port = svr.bind_to_any_port(HOST);
  12397. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12398. auto se = detail::scope_exit([&] {
  12399. svr.stop();
  12400. t.join();
  12401. ASSERT_FALSE(svr.is_running());
  12402. });
  12403. svr.wait_until_ready();
  12404. Client cli(HOST, port);
  12405. {
  12406. auto res = cli.Get("/dir/test.html");
  12407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12408. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12409. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12410. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12411. }
  12412. {
  12413. auto res = cli.Get("/file");
  12414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12415. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12416. EXPECT_EQ("Denied", res->body);
  12417. }
  12418. {
  12419. auto res = cli.Get("/dir/index.html");
  12420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12421. EXPECT_EQ(StatusCode::OK_200, res->status);
  12422. EXPECT_EQ(0U, res->body.find("<html>"));
  12423. }
  12424. }
  12425. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12426. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12427. Server svr;
  12428. std::vector<bool> released;
  12429. std::mutex released_mutex;
  12430. auto releaser = [&](bool success) {
  12431. std::lock_guard<std::mutex> guard(released_mutex);
  12432. released.push_back(success);
  12433. };
  12434. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12435. return sink.write(&"hello"[offset], length);
  12436. };
  12437. svr.Get("/sized", [&](const Request &, Response &res) {
  12438. res.status = StatusCode::NotFound_404;
  12439. res.set_content_provider(5, "text/plain", provider, releaser);
  12440. });
  12441. svr.Get("/chunked", [&](const Request &, Response &res) {
  12442. res.status = StatusCode::ServiceUnavailable_503;
  12443. res.set_chunked_content_provider(
  12444. "text/plain",
  12445. [](size_t, DataSink &sink) {
  12446. sink.os << "chunk";
  12447. sink.done();
  12448. return true;
  12449. },
  12450. releaser);
  12451. });
  12452. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12453. res.set_content_provider(5, "text/plain", provider, releaser);
  12454. throw std::runtime_error("after the provider");
  12455. });
  12456. svr.set_error_handler([](const Request &req, Response &res) {
  12457. // Leave the exception handler's content to it.
  12458. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12459. res.set_content(std::string(1000, 'E'), "text/html");
  12460. return Server::HandlerResponse::Handled;
  12461. });
  12462. svr.set_exception_handler(
  12463. [](const Request &, Response &res, std::exception_ptr) {
  12464. res.status = StatusCode::InternalServerError_500;
  12465. res.set_content(std::string(1000, 'X'), "text/html");
  12466. });
  12467. auto port = svr.bind_to_any_port(HOST);
  12468. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12469. auto se = detail::scope_exit([&] {
  12470. svr.stop();
  12471. t.join();
  12472. ASSERT_FALSE(svr.is_running());
  12473. });
  12474. svr.wait_until_ready();
  12475. Client cli(HOST, port);
  12476. {
  12477. auto res = cli.Get("/sized");
  12478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12480. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12481. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12482. }
  12483. {
  12484. auto res = cli.Get("/chunked");
  12485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12486. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12487. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12488. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12489. }
  12490. {
  12491. auto res = cli.Get("/throw");
  12492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12493. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12494. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12495. }
  12496. std::lock_guard<std::mutex> guard(released_mutex);
  12497. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12498. }
  12499. #endif
  12500. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12501. Server svr;
  12502. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12503. return sink.write(&"abc"[offset], length);
  12504. };
  12505. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12506. res.set_file_content("./www/dir/test.html");
  12507. res.set_content("body", "text/plain");
  12508. });
  12509. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12510. res.set_content(std::string(100, 'B'), "text/plain");
  12511. res.set_file_content("./www/dir/test.html");
  12512. });
  12513. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12514. res.set_content(std::string(100, 'B'), "text/plain");
  12515. res.set_content_provider(3, "text/x-provider", abc);
  12516. });
  12517. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12518. res.set_content_provider(3, "text/x-provider", abc);
  12519. res.set_content(std::string(100, 'B'), "text/plain");
  12520. });
  12521. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12522. res.set_content_provider(3, "text/x-provider", abc);
  12523. res.set_file_content("./www/dir/test.html", "text/x-file");
  12524. });
  12525. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12526. res.set_file_content("./www/dir/test.html");
  12527. res.set_header("Content-Type", "text/x-handler");
  12528. });
  12529. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12530. res.set_content_provider(3, "text/plain", abc);
  12531. res.body = "direct";
  12532. });
  12533. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12534. res.set_file_content("./www/dir/test.html");
  12535. res.body = "direct";
  12536. });
  12537. auto port = svr.bind_to_any_port(HOST);
  12538. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12539. auto se = detail::scope_exit([&] {
  12540. svr.stop();
  12541. t.join();
  12542. ASSERT_FALSE(svr.is_running());
  12543. });
  12544. svr.wait_until_ready();
  12545. Client cli(HOST, port);
  12546. auto expect_body = [&](const char *path, const std::string &body,
  12547. const std::string &type) {
  12548. // Uncompressed, so Content-Length can be compared with the body.
  12549. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12550. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12551. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12552. EXPECT_EQ(body, res->body) << path;
  12553. EXPECT_EQ(std::to_string(body.size()),
  12554. res->get_header_value("Content-Length"))
  12555. << path;
  12556. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12557. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12558. };
  12559. expect_body("/file-then-body", "body", "text/plain");
  12560. expect_body("/body-then-file", "test.html", "text/html");
  12561. expect_body("/body-then-provider", "abc", "text/x-provider");
  12562. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12563. expect_body("/provider-then-file", "test.html", "text/x-file");
  12564. expect_body("/file-then-header", "test.html", "text/x-handler");
  12565. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12566. expect_body("/file-then-direct-body", "direct", "text/plain");
  12567. // Ranges are checked against the body, not the dropped provider.
  12568. {
  12569. auto res = cli.Get("/provider-then-direct-body",
  12570. Headers{{make_range_header({{1, 2}})}});
  12571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12572. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12573. EXPECT_EQ("ir", res->body);
  12574. }
  12575. {
  12576. auto res = cli.Get("/file-then-direct-body",
  12577. Headers{{make_range_header({{7, 8}})}});
  12578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12579. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12580. }
  12581. }
  12582. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12583. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12584. const char *path = "./truncated_while_served.txt";
  12585. const size_t size = 32 * 1024 * 1024;
  12586. {
  12587. std::ofstream f(path, std::ios::binary);
  12588. f << std::string(size, 'x');
  12589. }
  12590. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12591. // Over TLS, where the bytes are encrypted in this process rather than
  12592. // copied by send().
  12593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12594. svr.Get("/file", [&](const Request &, Response &res) {
  12595. res.set_file_content(path, "text/plain");
  12596. });
  12597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12598. auto se = detail::scope_exit([&] {
  12599. svr.stop();
  12600. thread.join();
  12601. ASSERT_FALSE(svr.is_running());
  12602. });
  12603. svr.wait_until_ready();
  12604. // The file shrinks once the first bytes are in, as a rewrite in place
  12605. // would, and reading the mapping past its new end used to raise SIGBUS.
  12606. SSLClient cli(HOST, PORT);
  12607. cli.enable_server_certificate_verification(false);
  12608. size_t received = 0;
  12609. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12610. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12611. received += len;
  12612. return true;
  12613. });
  12614. EXPECT_FALSE(res);
  12615. EXPECT_LT(received, size);
  12616. }
  12617. #endif
  12618. // Forward declaration (see the base64_encode note).
  12619. namespace httplib {
  12620. namespace detail {
  12621. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12622. const std::string &content_type,
  12623. EncodingType encoding);
  12624. } // namespace detail
  12625. } // namespace httplib
  12626. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12627. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12628. ASSERT_TRUE(mm->is_open());
  12629. Response res;
  12630. detail::set_file_content_provider(res, mm, "text/html",
  12631. detail::EncodingType::None);
  12632. std::string out;
  12633. DataSink sink;
  12634. sink.write = [&](const char *d, size_t l) {
  12635. out.append(d, l);
  12636. return true;
  12637. };
  12638. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12639. EXPECT_EQ("test.html", out);
  12640. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12641. EXPECT_EQ("test.html", out);
  12642. }
  12643. TEST(LongPollingTest, ClientCloseDetection) {
  12644. Server svr;
  12645. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12646. res.set_chunked_content_provider(
  12647. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12648. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12649. sink.os << "hello";
  12650. auto count = 10;
  12651. while (count > 0 && sink.is_writable()) {
  12652. this_thread::sleep_for(chrono::milliseconds(10));
  12653. count--;
  12654. }
  12655. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12656. return true;
  12657. });
  12658. });
  12659. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12660. auto se = detail::scope_exit([&] {
  12661. svr.stop();
  12662. listen_thread.join();
  12663. ASSERT_FALSE(svr.is_running());
  12664. });
  12665. svr.wait_until_ready();
  12666. Client cli("localhost", PORT);
  12667. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12668. EXPECT_EQ("hello", string(data, data_length));
  12669. return false; // close the socket immediately.
  12670. });
  12671. ASSERT_FALSE(res);
  12672. }
  12673. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12674. Server svr;
  12675. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12676. res.set_chunked_content_provider(
  12677. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12678. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12679. sink.os << "hello";
  12680. EXPECT_TRUE(sink.os.good());
  12681. // Wait for the client to close the connection
  12682. auto count = 10;
  12683. while (count > 0 && sink.is_writable()) {
  12684. this_thread::sleep_for(chrono::milliseconds(10));
  12685. count--;
  12686. }
  12687. // After client disconnect, write repeatedly until the socket
  12688. // write actually fails (small writes may be absorbed by the
  12689. // kernel buffer)
  12690. std::string chunk(1024, 'x');
  12691. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12692. sink.os << chunk;
  12693. }
  12694. EXPECT_TRUE(sink.os.fail());
  12695. return true;
  12696. });
  12697. });
  12698. auto port = svr.bind_to_any_port("localhost");
  12699. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12700. auto se = detail::scope_exit([&] {
  12701. svr.stop();
  12702. listen_thread.join();
  12703. ASSERT_FALSE(svr.is_running());
  12704. });
  12705. svr.wait_until_ready();
  12706. Client cli("localhost", port);
  12707. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12708. EXPECT_EQ("hello", string(data, data_length));
  12709. return false; // close the socket immediately.
  12710. });
  12711. ASSERT_FALSE(res);
  12712. }
  12713. TEST(GetWithParametersTest, GetWithParameters) {
  12714. Server svr;
  12715. svr.Get("/", [&](const Request &req, Response &) {
  12716. EXPECT_EQ("world", req.get_param_value("hello"));
  12717. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12718. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12719. });
  12720. svr.Get("/params", [&](const Request &req, Response &) {
  12721. EXPECT_EQ("world", req.get_param_value("hello"));
  12722. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12723. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12724. });
  12725. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12726. EXPECT_EQ("resource-id", req.matches[1]);
  12727. EXPECT_EQ("foo", req.get_param_value("param1"));
  12728. EXPECT_EQ("bar", req.get_param_value("param2"));
  12729. });
  12730. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12731. EXPECT_EQ("user-id", req.path_params.at("id"));
  12732. EXPECT_EQ("foo", req.get_param_value("param1"));
  12733. EXPECT_EQ("bar", req.get_param_value("param2"));
  12734. });
  12735. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12736. auto se = detail::scope_exit([&] {
  12737. svr.stop();
  12738. listen_thread.join();
  12739. ASSERT_FALSE(svr.is_running());
  12740. });
  12741. svr.wait_until_ready();
  12742. {
  12743. Client cli(HOST, PORT);
  12744. Params params;
  12745. params.emplace("hello", "world");
  12746. params.emplace("hello2", "world2");
  12747. params.emplace("hello3", "world3");
  12748. auto res = cli.Get("/", params, Headers{});
  12749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12750. EXPECT_EQ(StatusCode::OK_200, res->status);
  12751. }
  12752. {
  12753. Client cli(HOST, PORT);
  12754. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12756. EXPECT_EQ(StatusCode::OK_200, res->status);
  12757. }
  12758. {
  12759. Client cli(HOST, PORT);
  12760. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12762. EXPECT_EQ(StatusCode::OK_200, res->status);
  12763. }
  12764. {
  12765. Client cli(HOST, PORT);
  12766. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12768. EXPECT_EQ(StatusCode::OK_200, res->status);
  12769. }
  12770. }
  12771. TEST(GetWithParametersTest, GetWithParameters2) {
  12772. Server svr;
  12773. svr.Get("/", [&](const Request &req, Response &res) {
  12774. auto text = req.get_param_value("hello");
  12775. res.set_content(text, "text/plain");
  12776. });
  12777. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12778. auto se = detail::scope_exit([&] {
  12779. svr.stop();
  12780. listen_thread.join();
  12781. ASSERT_FALSE(svr.is_running());
  12782. });
  12783. svr.wait_until_ready();
  12784. Client cli("localhost", PORT);
  12785. Params params;
  12786. params.emplace("hello", "world");
  12787. std::string body;
  12788. auto res = cli.Get("/", params, Headers{},
  12789. [&](const char *data, size_t data_length) {
  12790. body.append(data, data_length);
  12791. return true;
  12792. });
  12793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12794. EXPECT_EQ(StatusCode::OK_200, res->status);
  12795. EXPECT_EQ("world", body);
  12796. }
  12797. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12798. Server svr;
  12799. svr.Get("/search", [&](const Request &req, Response &res) {
  12800. auto q = req.get_param_value("q");
  12801. res.set_content(q, "text/plain");
  12802. });
  12803. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12804. auto se = detail::scope_exit([&] {
  12805. svr.stop();
  12806. listen_thread.join();
  12807. ASSERT_FALSE(svr.is_running());
  12808. });
  12809. svr.wait_until_ready();
  12810. Client cli("localhost", PORT);
  12811. // Verify that Get(path, params) works without requiring Headers argument
  12812. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12814. EXPECT_EQ(StatusCode::OK_200, res->status);
  12815. EXPECT_EQ("cpp-httplib", res->body);
  12816. }
  12817. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12818. auto host = "httpbingo.org";
  12819. auto path = std::string{"/range/32"};
  12820. #ifdef CPPHTTPLIB_SSL_ENABLED
  12821. SSLClient cli(host);
  12822. #else
  12823. Client cli(host);
  12824. #endif
  12825. cli.set_default_headers({make_range_header({{1, 10}})});
  12826. cli.set_connection_timeout(5);
  12827. {
  12828. auto res = retry_service_failures([&] { return cli.Get(path); });
  12829. SKIP_ON_SERVICE_FAILURE(res);
  12830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12831. EXPECT_EQ("bcdefghijk", res->body);
  12832. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12833. }
  12834. {
  12835. auto res = retry_service_failures([&] { return cli.Get(path); });
  12836. SKIP_ON_SERVICE_FAILURE(res);
  12837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12838. EXPECT_EQ("bcdefghijk", res->body);
  12839. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12840. }
  12841. }
  12842. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12843. Server svr;
  12844. svr.set_default_headers({{"Hello", "World"}});
  12845. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12846. res.set_content("ok", "text/plain");
  12847. });
  12848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12849. auto se = detail::scope_exit([&] {
  12850. svr.stop();
  12851. listen_thread.join();
  12852. ASSERT_FALSE(svr.is_running());
  12853. });
  12854. svr.wait_until_ready();
  12855. Client cli("localhost", PORT);
  12856. auto res = cli.Get("/");
  12857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12858. EXPECT_EQ(StatusCode::OK_200, res->status);
  12859. EXPECT_EQ("ok", res->body);
  12860. EXPECT_EQ("World", res->get_header_value("Hello"));
  12861. }
  12862. #ifdef CPPHTTPLIB_SSL_ENABLED
  12863. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12865. ASSERT_TRUE(svr.is_valid());
  12866. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12867. std::this_thread::sleep_for(std::chrono::seconds(2));
  12868. res.set_content("a", "text/plain");
  12869. });
  12870. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12871. res.set_content("b", "text/plain");
  12872. });
  12873. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12874. auto se = detail::scope_exit([&] {
  12875. svr.stop();
  12876. listen_thread.join();
  12877. ASSERT_FALSE(svr.is_running());
  12878. });
  12879. svr.wait_until_ready();
  12880. SSLClient cli("localhost", PORT);
  12881. cli.enable_server_certificate_verification(false);
  12882. cli.set_keep_alive(true);
  12883. cli.set_read_timeout(std::chrono::seconds(1));
  12884. auto resa = cli.Get("/a");
  12885. ASSERT_TRUE(!resa);
  12886. EXPECT_EQ(Error::Read, resa.error());
  12887. auto resb = cli.Get("/b");
  12888. ASSERT_TRUE(resb);
  12889. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12890. EXPECT_EQ("b", resb->body);
  12891. }
  12892. // Closing an idle keep-alive connection sends close_notify and returns. The
  12893. // server must not wait for the client's close_notify: an idle client never
  12894. // sends one, so the worker would be held until the read timeout expires, and
  12895. // stop() would wait for it.
  12896. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12898. ASSERT_TRUE(svr.is_valid());
  12899. svr.set_keep_alive_timeout(1);
  12900. svr.set_read_timeout(10, 0);
  12901. svr.Get("/", [](const Request &, Response &res) {
  12902. res.set_content("ok", "text/plain");
  12903. });
  12904. auto port = svr.bind_to_any_port(HOST);
  12905. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12906. auto se = detail::scope_exit([&] {
  12907. if (listen_thread.joinable()) {
  12908. svr.stop();
  12909. listen_thread.join();
  12910. }
  12911. });
  12912. svr.wait_until_ready();
  12913. SSLClient cli(HOST, port);
  12914. cli.enable_server_certificate_verification(false);
  12915. cli.set_keep_alive(true);
  12916. auto res = cli.Get("/");
  12917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12918. EXPECT_EQ(StatusCode::OK_200, res->status);
  12919. // Stay idle past the keep-alive timeout so the server closes the connection.
  12920. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12921. auto start = std::chrono::steady_clock::now();
  12922. svr.stop();
  12923. listen_thread.join();
  12924. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12925. std::chrono::steady_clock::now() - start)
  12926. .count();
  12927. EXPECT_LT(elapsed, 3000);
  12928. }
  12929. #endif
  12930. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12931. protected:
  12932. ServerTestWithAI_PASSIVE()
  12933. : cli_(HOST, PORT)
  12934. #ifdef CPPHTTPLIB_SSL_ENABLED
  12935. ,
  12936. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12937. #endif
  12938. {
  12939. #ifdef CPPHTTPLIB_SSL_ENABLED
  12940. cli_.enable_server_certificate_verification(false);
  12941. #endif
  12942. }
  12943. virtual void SetUp() {
  12944. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12945. res.set_content("Hello World!", "text/plain");
  12946. });
  12947. t_ = thread(
  12948. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12949. svr_.wait_until_ready();
  12950. }
  12951. virtual void TearDown() {
  12952. svr_.stop();
  12953. t_.join();
  12954. }
  12955. #ifdef CPPHTTPLIB_SSL_ENABLED
  12956. SSLClient cli_;
  12957. SSLServer svr_;
  12958. #else
  12959. Client cli_;
  12960. Server svr_;
  12961. #endif
  12962. thread t_;
  12963. };
  12964. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12965. auto res = cli_.Get("/hi");
  12966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12967. EXPECT_EQ(StatusCode::OK_200, res->status);
  12968. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12969. EXPECT_EQ("Hello World!", res->body);
  12970. }
  12971. class ServerUpDownTest : public ::testing::Test {
  12972. protected:
  12973. ServerUpDownTest() : cli_(HOST, PORT) {}
  12974. virtual void SetUp() {
  12975. t_ = thread([&]() {
  12976. svr_.bind_to_any_port(HOST);
  12977. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12978. ASSERT_TRUE(svr_.listen_after_bind());
  12979. });
  12980. svr_.wait_until_ready();
  12981. }
  12982. virtual void TearDown() {
  12983. svr_.stop();
  12984. t_.join();
  12985. }
  12986. Client cli_;
  12987. Server svr_;
  12988. thread t_;
  12989. };
  12990. TEST_F(ServerUpDownTest, QuickStartStop) {
  12991. // Should not crash, especially when run with
  12992. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12993. }
  12994. class PayloadMaxLengthTest : public ::testing::Test {
  12995. protected:
  12996. PayloadMaxLengthTest()
  12997. : cli_(HOST, PORT)
  12998. #ifdef CPPHTTPLIB_SSL_ENABLED
  12999. ,
  13000. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13001. #endif
  13002. {
  13003. #ifdef CPPHTTPLIB_SSL_ENABLED
  13004. cli_.enable_server_certificate_verification(false);
  13005. #endif
  13006. }
  13007. virtual void SetUp() {
  13008. svr_.set_payload_max_length(8);
  13009. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13010. res.set_content("test", "text/plain");
  13011. });
  13012. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13013. svr_.wait_until_ready();
  13014. }
  13015. virtual void TearDown() {
  13016. svr_.stop();
  13017. t_.join();
  13018. }
  13019. #ifdef CPPHTTPLIB_SSL_ENABLED
  13020. SSLClient cli_;
  13021. SSLServer svr_;
  13022. #else
  13023. Client cli_;
  13024. Server svr_;
  13025. #endif
  13026. thread t_;
  13027. };
  13028. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  13029. auto res = cli_.Post("/test", "123456789", "text/plain");
  13030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13031. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13032. res = cli_.Post("/test", "12345678", "text/plain");
  13033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13034. EXPECT_EQ(StatusCode::OK_200, res->status);
  13035. }
  13036. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  13037. // Test chunked encoding with payload exceeding the 8-byte limit
  13038. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  13039. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  13040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13041. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13042. }
  13043. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13044. // Test chunked encoding with payload within the 8-byte limit
  13045. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13046. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13048. EXPECT_EQ(StatusCode::OK_200, res->status);
  13049. }
  13050. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13051. // Test using send_request to send chunked data exceeding payload limit
  13052. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13053. "Host: " +
  13054. std::string(HOST) + ":" + std::to_string(PORT) +
  13055. "\r\n"
  13056. "Transfer-Encoding: chunked\r\n"
  13057. "Connection: close\r\n"
  13058. "\r\n"
  13059. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13060. "0123456789\r\n"
  13061. "0\r\n" // End chunk
  13062. "\r\n";
  13063. std::string response;
  13064. bool result = send_request(1, chunked_request, &response);
  13065. if (!result) {
  13066. // If send_request fails, it might be because the server closed the
  13067. // connection due to payload limit enforcement, which is acceptable
  13068. SUCCEED()
  13069. << "Server rejected oversized chunked request (connection closed)";
  13070. } else {
  13071. // If we got a response, check if it's an error response or connection was
  13072. // closed early Short response length indicates connection was closed due to
  13073. // payload limit
  13074. if (response.length() <= 10) {
  13075. SUCCEED() << "Server closed connection for oversized chunked request";
  13076. } else {
  13077. // Check for error status codes
  13078. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13079. response.find("Payload Too Large") != std::string::npos ||
  13080. response.find("400") != std::string::npos);
  13081. }
  13082. }
  13083. }
  13084. class LargePayloadMaxLengthTest : public ::testing::Test {
  13085. protected:
  13086. LargePayloadMaxLengthTest()
  13087. : cli_(HOST, PORT)
  13088. #ifdef CPPHTTPLIB_SSL_ENABLED
  13089. ,
  13090. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13091. #endif
  13092. {
  13093. #ifdef CPPHTTPLIB_SSL_ENABLED
  13094. cli_.enable_server_certificate_verification(false);
  13095. #endif
  13096. }
  13097. virtual void SetUp() {
  13098. // Set 10MB payload limit
  13099. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13100. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13101. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13102. res.set_content("Large payload test", "text/plain");
  13103. });
  13104. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13105. svr_.wait_until_ready();
  13106. }
  13107. virtual void TearDown() {
  13108. svr_.stop();
  13109. t_.join();
  13110. }
  13111. #ifdef CPPHTTPLIB_SSL_ENABLED
  13112. SSLClient cli_;
  13113. SSLServer svr_;
  13114. #else
  13115. Client cli_;
  13116. Server svr_;
  13117. #endif
  13118. thread t_;
  13119. };
  13120. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13121. // Test chunked encoding with payload within 10MB limit
  13122. std::string medium_payload(5 * 1024 * 1024,
  13123. 'A'); // 5MB payload, within 10MB limit
  13124. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13126. EXPECT_EQ(StatusCode::OK_200, res->status);
  13127. }
  13128. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13129. // Test chunked encoding with payload exceeding 10MB limit
  13130. std::string large_payload(12 * 1024 * 1024,
  13131. 'B'); // 12MB payload, exceeds 10MB limit
  13132. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13133. // Server may either return 413 or close the connection
  13134. if (res) {
  13135. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13136. } else {
  13137. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13138. }
  13139. }
  13140. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13141. Server svr;
  13142. svr.Get("/", [](const Request &, Response &res) {
  13143. // Claims the most the client accepts, far more than it sends, then drops
  13144. // the connection.
  13145. res.set_content_provider(std::string().max_size(), "text/plain",
  13146. [](size_t, size_t, DataSink &sink) {
  13147. sink.write("abc", 3);
  13148. return false;
  13149. });
  13150. });
  13151. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13152. auto se = detail::scope_exit([&] {
  13153. svr.stop();
  13154. thread.join();
  13155. ASSERT_FALSE(svr.is_running());
  13156. });
  13157. svr.wait_until_ready();
  13158. Client cli(HOST, PORT);
  13159. cli.set_payload_max_length(0);
  13160. EXPECT_FALSE(cli.Get("/"));
  13161. }
  13162. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13163. // Stream API does, not as a plain read failure
  13164. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13165. Server svr;
  13166. svr.Get("/big", [](const Request &, Response &res) {
  13167. res.set_content(std::string(100000, 'b'), "text/plain");
  13168. });
  13169. auto port = svr.bind_to_any_port(HOST);
  13170. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13171. auto se = detail::scope_exit([&] {
  13172. svr.stop();
  13173. thread.join();
  13174. });
  13175. svr.wait_until_ready();
  13176. Client cli(HOST, port);
  13177. cli.set_payload_max_length(1000);
  13178. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13179. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13180. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13181. [](const char *, size_t) { return true; });
  13182. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13183. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13184. // Small on the wire, over the limit once decompressed
  13185. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13186. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13187. #endif
  13188. }
  13189. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13190. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13191. // path.
  13192. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13193. Server svr;
  13194. const size_t LIMIT = 64 * 1024; // 64KB
  13195. svr.set_payload_max_length(LIMIT);
  13196. size_t total = 0;
  13197. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13198. const ContentReader &content_reader) {
  13199. content_reader([&](const char * /*data*/, size_t len) {
  13200. total += len;
  13201. return true;
  13202. });
  13203. res.status = 200;
  13204. res.set_content("stream_ok", "text/plain");
  13205. });
  13206. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13207. auto se = detail::scope_exit([&] {
  13208. svr.stop();
  13209. thread.join();
  13210. ASSERT_FALSE(svr.is_running());
  13211. });
  13212. svr.wait_until_ready();
  13213. // Prepare 256KB raw data and gzip-compress it
  13214. std::string raw(256 * 1024, 'A');
  13215. std::string gz;
  13216. {
  13217. z_stream zs{};
  13218. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13219. Z_DEFAULT_STRATEGY);
  13220. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13221. zs.avail_in = static_cast<uInt>(raw.size());
  13222. char outbuf[4096];
  13223. int ret;
  13224. do {
  13225. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13226. zs.avail_out = sizeof(outbuf);
  13227. ret = deflate(&zs, Z_FINISH);
  13228. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13229. } while (ret != Z_STREAM_END);
  13230. deflateEnd(&zs);
  13231. }
  13232. Client cli(HOST, PORT);
  13233. cli.set_connection_timeout(std::chrono::seconds(5));
  13234. Headers headers = {{"Content-Encoding", "gzip"}};
  13235. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13236. "application/octet-stream");
  13237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13238. // Server must reject oversized decompressed payloads with 413.
  13239. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13240. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13241. EXPECT_LE(total, LIMIT);
  13242. }
  13243. #endif
  13244. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13245. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13246. // the payload must be passed through untouched instead of being rejected.
  13247. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13248. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13249. Server svr;
  13250. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13251. res.set_content(body, "image/jpeg");
  13252. res.set_header("Content-Encoding", "UTF-8");
  13253. });
  13254. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13255. res.set_content(body, "image/jpeg");
  13256. res.set_header("Content-Encoding", "identity");
  13257. });
  13258. svr.Post("/echo", [](const Request &req, Response &res) {
  13259. res.set_content(req.body, "image/jpeg");
  13260. });
  13261. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13262. auto se = detail::scope_exit([&] {
  13263. svr.stop();
  13264. t.join();
  13265. ASSERT_FALSE(svr.is_running());
  13266. });
  13267. svr.wait_until_ready();
  13268. Client cli(HOST, PORT);
  13269. {
  13270. auto res = cli.Get("/image");
  13271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13272. EXPECT_EQ(StatusCode::OK_200, res->status);
  13273. EXPECT_EQ(body, res->body);
  13274. }
  13275. {
  13276. auto res = cli.Get("/identity");
  13277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13278. EXPECT_EQ(StatusCode::OK_200, res->status);
  13279. EXPECT_EQ(body, res->body);
  13280. }
  13281. {
  13282. // The same applies to a request body reaching the server.
  13283. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13284. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13286. EXPECT_EQ(StatusCode::OK_200, res->status);
  13287. EXPECT_EQ(body, res->body);
  13288. }
  13289. }
  13290. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13291. // gzip-encoded response even when the build has no zlib support.
  13292. static const char GZIPPED_HELLO_WORLD[] = {
  13293. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13294. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13295. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13296. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13297. // A content coding is a whole token, not something the field value merely
  13298. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13299. // as "fibre" look like Brotli, and turned a multi-coding value like
  13300. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13301. // it was never meant to see.
  13302. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13303. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13304. Server svr;
  13305. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13306. res.set_content(body, "image/jpeg");
  13307. res.set_header("Content-Encoding", "fibre");
  13308. });
  13309. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13310. res.set_content(body, "image/jpeg");
  13311. res.set_header("Content-Encoding", "gzip, br");
  13312. });
  13313. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13314. res.set_content(body, "image/jpeg");
  13315. res.set_header("Content-Encoding", "x-zstd-ish");
  13316. });
  13317. auto port = svr.bind_to_any_port(HOST);
  13318. thread t = thread([&]() { svr.listen_after_bind(); });
  13319. auto se = detail::scope_exit([&] {
  13320. svr.stop();
  13321. t.join();
  13322. ASSERT_FALSE(svr.is_running());
  13323. });
  13324. svr.wait_until_ready();
  13325. Client cli(HOST, port);
  13326. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13327. auto res = cli.Get(path);
  13328. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13329. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13330. // Not a coding we recognize, so the payload comes back untouched
  13331. EXPECT_EQ(body, res->body) << path;
  13332. }
  13333. }
  13334. // A content coding cpp-httplib recognizes but was not built with must be
  13335. // reported as such. Handing the still-compressed payload back to the caller
  13336. // would silently corrupt it.
  13337. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13338. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13339. Server svr;
  13340. // "image/jpeg" keeps the server from applying a content coding of its own,
  13341. // so the hand-crafted Content-Encoding below survives.
  13342. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13343. res.set_content(gzipped, "image/jpeg");
  13344. res.set_header("Content-Encoding", "gzip");
  13345. });
  13346. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13347. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13348. res.set_content(gzipped, "image/jpeg");
  13349. res.set_header("Content-Encoding", "GZIP");
  13350. });
  13351. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13352. auto se = detail::scope_exit([&] {
  13353. svr.stop();
  13354. t.join();
  13355. ASSERT_FALSE(svr.is_running());
  13356. });
  13357. svr.wait_until_ready();
  13358. Client cli(HOST, PORT);
  13359. {
  13360. auto res = cli.Get("/gzipped");
  13361. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13363. EXPECT_EQ("Hello World!", res->body);
  13364. #else
  13365. ASSERT_FALSE(res);
  13366. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13367. #endif
  13368. }
  13369. {
  13370. // open_stream() must behave the same way.
  13371. auto handle = cli.open_stream("GET", "/gzipped");
  13372. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13373. ASSERT_TRUE(handle.is_valid());
  13374. std::string received;
  13375. char buf[256];
  13376. ssize_t n;
  13377. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13378. received.append(buf, static_cast<size_t>(n));
  13379. }
  13380. EXPECT_EQ("Hello World!", received);
  13381. #else
  13382. EXPECT_FALSE(handle.is_valid());
  13383. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13384. #endif
  13385. }
  13386. {
  13387. // A differently-cased coding must not be mistaken for an unknown one, or
  13388. // the body would be handed back still compressed.
  13389. auto res = cli.Get("/gzipped-uppercase");
  13390. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13392. EXPECT_EQ("Hello World!", res->body);
  13393. #else
  13394. ASSERT_FALSE(res);
  13395. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13396. #endif
  13397. }
  13398. }
  13399. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13400. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13401. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13402. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13403. // body a second time and appending a second Content-Encoding field line, so
  13404. // clients that decode one coding per listed value handed back raw gzip bytes.
  13405. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13406. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13407. Server svr;
  13408. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13409. // keeps the server from applying a coding of its own.
  13410. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13411. res.set_content(gzipped, "text/plain");
  13412. res.set_header("Content-Encoding", "gzip");
  13413. });
  13414. auto port = svr.bind_to_any_port(HOST);
  13415. thread t = thread([&]() { svr.listen_after_bind(); });
  13416. auto se = detail::scope_exit([&] {
  13417. svr.stop();
  13418. t.join();
  13419. ASSERT_FALSE(svr.is_running());
  13420. });
  13421. svr.wait_until_ready();
  13422. Client cli(HOST, port);
  13423. Headers headers = {{"Accept-Encoding", "gzip"}};
  13424. auto res = cli.Get("/pre-gzipped", headers);
  13425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13426. EXPECT_EQ(StatusCode::OK_200, res->status);
  13427. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13428. EXPECT_EQ("Hello World!", res->body);
  13429. }
  13430. // set_compress(false) sends every handler response as it is, buffered or
  13431. // streamed
  13432. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13433. const std::string text(1000, 'a');
  13434. Server svr;
  13435. svr.set_compress(false);
  13436. svr.Get("/buffered", [&](const Request &, Response &res) {
  13437. res.set_content(text, "text/plain");
  13438. });
  13439. svr.Get("/streamed", [&](const Request &, Response &res) {
  13440. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13441. sink.write(text.data(), text.size());
  13442. sink.done();
  13443. return true;
  13444. });
  13445. });
  13446. auto port = svr.bind_to_any_port(HOST);
  13447. ASSERT_LT(0, port);
  13448. thread t = thread([&] { svr.listen_after_bind(); });
  13449. auto se = detail::scope_exit([&] {
  13450. svr.stop();
  13451. t.join();
  13452. ASSERT_FALSE(svr.is_running());
  13453. });
  13454. svr.wait_until_ready();
  13455. Client cli(HOST, port);
  13456. cli.set_decompress(false);
  13457. for (auto path : {"/buffered", "/streamed"}) {
  13458. SCOPED_TRACE(path);
  13459. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13461. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13462. EXPECT_EQ(text, res->body);
  13463. }
  13464. }
  13465. // A chunked provider settles its coding where the headers are written and
  13466. // reuses it at write time. Both ends of that have to hold: a handler's own
  13467. // Content-Encoding suppresses the coding, and a response without one is still
  13468. // compressed as it always was.
  13469. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13470. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13471. const std::string plain = "Hello World! Hello World! Hello World!";
  13472. Server svr;
  13473. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13474. res.set_header("Content-Encoding", "gzip");
  13475. res.set_chunked_content_provider(
  13476. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13477. sink.write(gzipped.data(), gzipped.size());
  13478. sink.done();
  13479. return true;
  13480. });
  13481. });
  13482. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13483. res.set_chunked_content_provider(
  13484. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13485. sink.write(plain.data(), plain.size());
  13486. sink.done();
  13487. return true;
  13488. });
  13489. });
  13490. auto port = svr.bind_to_any_port(HOST);
  13491. thread t = thread([&]() { svr.listen_after_bind(); });
  13492. auto se = detail::scope_exit([&] {
  13493. svr.stop();
  13494. t.join();
  13495. ASSERT_FALSE(svr.is_running());
  13496. });
  13497. svr.wait_until_ready();
  13498. Client cli(HOST, port);
  13499. Headers headers = {{"Accept-Encoding", "gzip"}};
  13500. {
  13501. auto res = cli.Get("/pre-gzipped", headers);
  13502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13503. EXPECT_EQ(StatusCode::OK_200, res->status);
  13504. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13505. EXPECT_EQ("Hello World!", res->body);
  13506. }
  13507. {
  13508. auto res = cli.Get("/negotiated", headers);
  13509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13510. EXPECT_EQ(StatusCode::OK_200, res->status);
  13511. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13512. EXPECT_EQ(plain, res->body);
  13513. }
  13514. }
  13515. #endif
  13516. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13517. // the same message as the comma-joined one, so both have to be read the same
  13518. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13519. // single gzip coding, and a body the sender says was encoded twice was handed
  13520. // back after one pass, still compressed but presented as decoded.
  13521. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13522. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13523. Server svr;
  13524. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13525. res.set_content(body, "image/jpeg");
  13526. res.headers.emplace("Content-Encoding", "gzip");
  13527. res.headers.emplace("Content-Encoding", "gzip");
  13528. });
  13529. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13530. res.set_content(body, "image/jpeg");
  13531. res.set_header("Content-Encoding", "gzip, gzip");
  13532. });
  13533. auto port = svr.bind_to_any_port(HOST);
  13534. thread t = thread([&]() { svr.listen_after_bind(); });
  13535. auto se = detail::scope_exit([&] {
  13536. svr.stop();
  13537. t.join();
  13538. ASSERT_FALSE(svr.is_running());
  13539. });
  13540. svr.wait_until_ready();
  13541. Client cli(HOST, port);
  13542. // Two codings is not something cpp-httplib decodes, so both representations
  13543. // take the pass-through path rather than one of them being gunzipped once.
  13544. for (const char *path : {"/split", "/joined"}) {
  13545. auto res = cli.Get(path);
  13546. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13547. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13548. EXPECT_EQ(body, res->body) << path;
  13549. }
  13550. }
  13551. // Regression test for DoS vulnerability: a malicious server sending a response
  13552. // without Content-Length header must not cause unbounded memory consumption on
  13553. // the client side. The client should stop reading after a reasonable limit,
  13554. // similar to the server-side set_payload_max_length protection.
  13555. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13556. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13557. #ifndef _WIN32
  13558. signal(SIGPIPE, SIG_IGN);
  13559. #endif
  13560. auto server_thread = std::thread([] {
  13561. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13562. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13563. default_socket_options(srv);
  13564. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13565. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13566. sockaddr_in addr{};
  13567. addr.sin_family = AF_INET;
  13568. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13569. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13570. int opt = 1;
  13571. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13572. #ifdef _WIN32
  13573. reinterpret_cast<const char *>(&opt),
  13574. #else
  13575. &opt,
  13576. #endif
  13577. sizeof(opt));
  13578. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13579. ::listen(srv, 1);
  13580. sockaddr_in cli_addr{};
  13581. socklen_t cli_len = sizeof(cli_addr);
  13582. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13583. if (cli != INVALID_SOCKET) {
  13584. char buf[4096];
  13585. ::recv(cli, buf, sizeof(buf), 0);
  13586. // Malicious response: no Content-Length, no chunked encoding
  13587. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13588. "Connection: close\r\n"
  13589. "\r\n";
  13590. ::send(cli,
  13591. #ifdef _WIN32
  13592. static_cast<const char *>(response_header.c_str()),
  13593. static_cast<int>(response_header.size()),
  13594. #else
  13595. response_header.c_str(), response_header.size(),
  13596. #endif
  13597. 0);
  13598. // Send 10MB of data
  13599. std::string chunk(64 * 1024, 'A');
  13600. size_t total_sent = 0;
  13601. while (total_sent < MALICIOUS_DATA_SIZE) {
  13602. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13603. auto sent = ::send(cli,
  13604. #ifdef _WIN32
  13605. static_cast<const char *>(chunk.c_str()),
  13606. static_cast<int>(to_send),
  13607. #else
  13608. chunk.c_str(), to_send,
  13609. #endif
  13610. 0);
  13611. if (sent <= 0) break;
  13612. total_sent += static_cast<size_t>(sent);
  13613. }
  13614. detail::close_socket(cli);
  13615. }
  13616. detail::close_socket(srv);
  13617. });
  13618. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13619. size_t total_read = 0;
  13620. {
  13621. Client cli("127.0.0.1", PORT + 2);
  13622. cli.set_read_timeout(5, 0);
  13623. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13624. auto stream = cli.open_stream("GET", "/malicious");
  13625. ASSERT_TRUE(stream.is_valid());
  13626. char buffer[64 * 1024];
  13627. ssize_t n;
  13628. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13629. total_read += static_cast<size_t>(n);
  13630. }
  13631. } // StreamHandle and Client destroyed here, closing the socket
  13632. server_thread.join();
  13633. // With set_payload_max_length, the client must stop reading before consuming
  13634. // all 10MB. The read loop should be cut off at or near the configured limit.
  13635. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13636. << "Client read " << total_read << " bytes, exceeding the configured "
  13637. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13638. }
  13639. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13640. // the entire response body without truncation.
  13641. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13642. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13643. #ifndef _WIN32
  13644. signal(SIGPIPE, SIG_IGN);
  13645. #endif
  13646. auto server_thread = std::thread([] {
  13647. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13648. default_socket_options(srv);
  13649. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13650. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13651. sockaddr_in addr{};
  13652. addr.sin_family = AF_INET;
  13653. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13654. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13655. int opt = 1;
  13656. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13657. #ifdef _WIN32
  13658. reinterpret_cast<const char *>(&opt),
  13659. #else
  13660. &opt,
  13661. #endif
  13662. sizeof(opt));
  13663. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13664. ::listen(srv, 1);
  13665. sockaddr_in cli_addr{};
  13666. socklen_t cli_len = sizeof(cli_addr);
  13667. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13668. if (cli != INVALID_SOCKET) {
  13669. char buf[4096];
  13670. ::recv(cli, buf, sizeof(buf), 0);
  13671. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13672. "Connection: close\r\n"
  13673. "\r\n";
  13674. ::send(cli,
  13675. #ifdef _WIN32
  13676. static_cast<const char *>(response_header.c_str()),
  13677. static_cast<int>(response_header.size()),
  13678. #else
  13679. response_header.c_str(), response_header.size(),
  13680. #endif
  13681. 0);
  13682. std::string chunk(64 * 1024, 'A');
  13683. size_t total_sent = 0;
  13684. while (total_sent < DATA_SIZE) {
  13685. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13686. auto sent = ::send(cli,
  13687. #ifdef _WIN32
  13688. static_cast<const char *>(chunk.c_str()),
  13689. static_cast<int>(to_send),
  13690. #else
  13691. chunk.c_str(), to_send,
  13692. #endif
  13693. 0);
  13694. if (sent <= 0) break;
  13695. total_sent += static_cast<size_t>(sent);
  13696. }
  13697. #ifdef _WIN32
  13698. ::shutdown(cli, SD_SEND);
  13699. #else
  13700. ::shutdown(cli, SHUT_WR);
  13701. #endif
  13702. // Drain until the client closes its end, ensuring all data is delivered
  13703. char drain[1024];
  13704. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13705. detail::close_socket(cli);
  13706. }
  13707. detail::close_socket(srv);
  13708. });
  13709. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13710. size_t total_read = 0;
  13711. {
  13712. Client cli("127.0.0.1", PORT + 2);
  13713. cli.set_read_timeout(5, 0);
  13714. cli.set_payload_max_length(0); // 0 means no limit
  13715. auto stream = cli.open_stream("GET", "/data");
  13716. ASSERT_TRUE(stream.is_valid());
  13717. char buffer[64 * 1024];
  13718. ssize_t n;
  13719. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13720. total_read += static_cast<size_t>(n);
  13721. }
  13722. }
  13723. server_thread.join();
  13724. EXPECT_EQ(total_read, DATA_SIZE)
  13725. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13726. << " bytes without truncation, but only read " << total_read << " bytes.";
  13727. }
  13728. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13729. // enormous Content-Length must not cause the client to pre-allocate a huge
  13730. // response body buffer. The reservation is capped at payload_max_length_, and
  13731. // the read itself fails when the body exceeds the limit.
  13732. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13733. #ifndef _WIN32
  13734. signal(SIGPIPE, SIG_IGN);
  13735. #endif
  13736. auto server_thread = std::thread([] {
  13737. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13738. default_socket_options(srv);
  13739. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13740. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13741. sockaddr_in addr{};
  13742. addr.sin_family = AF_INET;
  13743. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13744. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13745. int opt = 1;
  13746. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13747. #ifdef _WIN32
  13748. reinterpret_cast<const char *>(&opt),
  13749. #else
  13750. &opt,
  13751. #endif
  13752. sizeof(opt));
  13753. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13754. ::listen(srv, 1);
  13755. sockaddr_in cli_addr{};
  13756. socklen_t cli_len = sizeof(cli_addr);
  13757. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13758. if (cli != INVALID_SOCKET) {
  13759. char buf[4096];
  13760. ::recv(cli, buf, sizeof(buf), 0);
  13761. // Malicious response: claim a 20GB body but send only a tiny payload.
  13762. std::string response = "HTTP/1.1 200 OK\r\n"
  13763. "Content-Length: 20000000000\r\n"
  13764. "\r\n"
  13765. "abc";
  13766. ::send(cli,
  13767. #ifdef _WIN32
  13768. static_cast<const char *>(response.c_str()),
  13769. static_cast<int>(response.size()),
  13770. #else
  13771. response.c_str(), response.size(),
  13772. #endif
  13773. 0);
  13774. detail::close_socket(cli);
  13775. }
  13776. detail::close_socket(srv);
  13777. });
  13778. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13779. {
  13780. Client cli("127.0.0.1", PORT + 2);
  13781. cli.set_read_timeout(5, 0);
  13782. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13783. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13784. // (server claims more bytes than payload_max_length permits), but it must
  13785. // not exhaust memory before getting there.
  13786. auto res = cli.Get("/malicious");
  13787. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13788. }
  13789. server_thread.join();
  13790. }
  13791. // Verify that content_receiver bypasses the default payload_max_length,
  13792. // allowing streaming downloads larger than 100MB without requiring an explicit
  13793. // set_payload_max_length call.
  13794. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13795. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13796. #ifndef _WIN32
  13797. signal(SIGPIPE, SIG_IGN);
  13798. #endif
  13799. auto server_thread = std::thread([] {
  13800. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13801. default_socket_options(srv);
  13802. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13803. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13804. sockaddr_in addr{};
  13805. addr.sin_family = AF_INET;
  13806. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13807. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13808. int opt = 1;
  13809. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13810. #ifdef _WIN32
  13811. reinterpret_cast<const char *>(&opt),
  13812. #else
  13813. &opt,
  13814. #endif
  13815. sizeof(opt));
  13816. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13817. ::listen(srv, 1);
  13818. sockaddr_in cli_addr{};
  13819. socklen_t cli_len = sizeof(cli_addr);
  13820. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13821. if (cli != INVALID_SOCKET) {
  13822. char buf[4096];
  13823. ::recv(cli, buf, sizeof(buf), 0);
  13824. // Response with Content-Length larger than default 100MB limit
  13825. auto content_length = std::to_string(DATA_SIZE);
  13826. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13827. "Content-Length: " +
  13828. content_length +
  13829. "\r\n"
  13830. "Connection: close\r\n"
  13831. "\r\n";
  13832. ::send(cli,
  13833. #ifdef _WIN32
  13834. static_cast<const char *>(response_header.c_str()),
  13835. static_cast<int>(response_header.size()),
  13836. #else
  13837. response_header.c_str(), response_header.size(),
  13838. #endif
  13839. 0);
  13840. std::string chunk(64 * 1024, 'A');
  13841. size_t total_sent = 0;
  13842. while (total_sent < DATA_SIZE) {
  13843. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13844. auto sent = ::send(cli,
  13845. #ifdef _WIN32
  13846. static_cast<const char *>(chunk.c_str()),
  13847. static_cast<int>(to_send),
  13848. #else
  13849. chunk.c_str(), to_send,
  13850. #endif
  13851. 0);
  13852. if (sent <= 0) break;
  13853. total_sent += static_cast<size_t>(sent);
  13854. }
  13855. detail::close_socket(cli);
  13856. }
  13857. detail::close_socket(srv);
  13858. });
  13859. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13860. size_t total_received = 0;
  13861. {
  13862. Client cli("127.0.0.1", PORT + 2);
  13863. cli.set_read_timeout(10, 0);
  13864. // Do NOT call set_payload_max_length — use the default 100MB limit
  13865. auto res =
  13866. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13867. total_received += data_length;
  13868. return true;
  13869. });
  13870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13871. EXPECT_EQ(StatusCode::OK_200, res->status);
  13872. }
  13873. server_thread.join();
  13874. EXPECT_EQ(total_received, DATA_SIZE)
  13875. << "With content_receiver, the client should read all " << DATA_SIZE
  13876. << " bytes despite the default 100MB payload_max_length, but only read "
  13877. << total_received << " bytes.";
  13878. }
  13879. // Verify that an explicit set_payload_max_length smaller than the response is
  13880. // enforced even when a content_receiver is used.
  13881. TEST(ClientVulnerabilityTest,
  13882. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13883. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13884. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13885. #ifndef _WIN32
  13886. signal(SIGPIPE, SIG_IGN);
  13887. #endif
  13888. auto server_thread = std::thread([] {
  13889. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13890. default_socket_options(srv);
  13891. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13892. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13893. sockaddr_in addr{};
  13894. addr.sin_family = AF_INET;
  13895. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13896. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13897. int opt = 1;
  13898. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13899. #ifdef _WIN32
  13900. reinterpret_cast<const char *>(&opt),
  13901. #else
  13902. &opt,
  13903. #endif
  13904. sizeof(opt));
  13905. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13906. ::listen(srv, 1);
  13907. sockaddr_in cli_addr{};
  13908. socklen_t cli_len = sizeof(cli_addr);
  13909. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13910. if (cli != INVALID_SOCKET) {
  13911. char buf[4096];
  13912. ::recv(cli, buf, sizeof(buf), 0);
  13913. auto content_length = std::to_string(DATA_SIZE);
  13914. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13915. "Content-Length: " +
  13916. content_length +
  13917. "\r\n"
  13918. "Connection: close\r\n"
  13919. "\r\n";
  13920. ::send(cli,
  13921. #ifdef _WIN32
  13922. static_cast<const char *>(response_header.c_str()),
  13923. static_cast<int>(response_header.size()),
  13924. #else
  13925. response_header.c_str(), response_header.size(),
  13926. #endif
  13927. 0);
  13928. std::string chunk(64 * 1024, 'A');
  13929. size_t total_sent = 0;
  13930. while (total_sent < DATA_SIZE) {
  13931. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13932. auto sent = ::send(cli,
  13933. #ifdef _WIN32
  13934. static_cast<const char *>(chunk.c_str()),
  13935. static_cast<int>(to_send),
  13936. #else
  13937. chunk.c_str(), to_send,
  13938. #endif
  13939. 0);
  13940. if (sent <= 0) break;
  13941. total_sent += static_cast<size_t>(sent);
  13942. }
  13943. detail::close_socket(cli);
  13944. }
  13945. detail::close_socket(srv);
  13946. });
  13947. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13948. size_t total_received = 0;
  13949. {
  13950. Client cli("127.0.0.1", PORT + 2);
  13951. cli.set_read_timeout(10, 0);
  13952. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13953. auto res =
  13954. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13955. total_received += data_length;
  13956. return true;
  13957. });
  13958. // Should fail because 200MB exceeds the explicit 150MB limit
  13959. EXPECT_FALSE(res);
  13960. }
  13961. server_thread.join();
  13962. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13963. << "Client with content_receiver should respect the explicit "
  13964. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13965. << total_received << " bytes.";
  13966. }
  13967. // Verify that an explicit set_payload_max_length larger than the response
  13968. // allows the content_receiver to read all data successfully.
  13969. TEST(ClientVulnerabilityTest,
  13970. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13971. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13972. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13973. #ifndef _WIN32
  13974. signal(SIGPIPE, SIG_IGN);
  13975. #endif
  13976. auto server_thread = std::thread([] {
  13977. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13978. default_socket_options(srv);
  13979. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13980. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13981. sockaddr_in addr{};
  13982. addr.sin_family = AF_INET;
  13983. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13984. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13985. int opt = 1;
  13986. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13987. #ifdef _WIN32
  13988. reinterpret_cast<const char *>(&opt),
  13989. #else
  13990. &opt,
  13991. #endif
  13992. sizeof(opt));
  13993. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13994. ::listen(srv, 1);
  13995. sockaddr_in cli_addr{};
  13996. socklen_t cli_len = sizeof(cli_addr);
  13997. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13998. if (cli != INVALID_SOCKET) {
  13999. char buf[4096];
  14000. ::recv(cli, buf, sizeof(buf), 0);
  14001. auto content_length = std::to_string(DATA_SIZE);
  14002. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14003. "Content-Length: " +
  14004. content_length +
  14005. "\r\n"
  14006. "Connection: close\r\n"
  14007. "\r\n";
  14008. ::send(cli,
  14009. #ifdef _WIN32
  14010. static_cast<const char *>(response_header.c_str()),
  14011. static_cast<int>(response_header.size()),
  14012. #else
  14013. response_header.c_str(), response_header.size(),
  14014. #endif
  14015. 0);
  14016. std::string chunk(64 * 1024, 'A');
  14017. size_t total_sent = 0;
  14018. while (total_sent < DATA_SIZE) {
  14019. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14020. auto sent = ::send(cli,
  14021. #ifdef _WIN32
  14022. static_cast<const char *>(chunk.c_str()),
  14023. static_cast<int>(to_send),
  14024. #else
  14025. chunk.c_str(), to_send,
  14026. #endif
  14027. 0);
  14028. if (sent <= 0) break;
  14029. total_sent += static_cast<size_t>(sent);
  14030. }
  14031. #ifdef _WIN32
  14032. ::shutdown(cli, SD_SEND);
  14033. #else
  14034. ::shutdown(cli, SHUT_WR);
  14035. #endif
  14036. char drain[1024];
  14037. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  14038. detail::close_socket(cli);
  14039. }
  14040. detail::close_socket(srv);
  14041. });
  14042. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14043. size_t total_received = 0;
  14044. {
  14045. Client cli("127.0.0.1", PORT + 2);
  14046. cli.set_read_timeout(10, 0);
  14047. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14048. auto res =
  14049. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14050. total_received += data_length;
  14051. return true;
  14052. });
  14053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14054. EXPECT_EQ(StatusCode::OK_200, res->status);
  14055. }
  14056. server_thread.join();
  14057. EXPECT_EQ(total_received, DATA_SIZE)
  14058. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14059. << " bytes (larger than " << DATA_SIZE
  14060. << " bytes response), content_receiver should read all data, but only "
  14061. "read "
  14062. << total_received << " bytes.";
  14063. }
  14064. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14065. // Regression test for "zip bomb" attack on the client side: a malicious server
  14066. // sends a small gzip-compressed response that decompresses to a huge payload.
  14067. // The client must enforce payload_max_length on the decompressed size.
  14068. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14069. constexpr size_t DECOMPRESSED_SIZE =
  14070. 10 * 1024 * 1024; // 10MB after decompression
  14071. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14072. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14073. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14074. std::string compressed;
  14075. {
  14076. httplib::detail::gzip_compressor compressor;
  14077. bool ok =
  14078. compressor.compress(uncompressed.data(), uncompressed.size(),
  14079. /*last=*/true, [&](const char *buf, size_t len) {
  14080. compressed.append(buf, len);
  14081. return true;
  14082. });
  14083. ASSERT_TRUE(ok);
  14084. }
  14085. // Sanity: compressed data should be much smaller than the decompressed size
  14086. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14087. #ifndef _WIN32
  14088. signal(SIGPIPE, SIG_IGN);
  14089. #endif
  14090. // Set up the listening socket in the main thread so the server is guaranteed
  14091. // to be ready before the client connects (eliminates race condition).
  14092. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14093. default_socket_options(srv);
  14094. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14095. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14096. sockaddr_in addr{};
  14097. addr.sin_family = AF_INET;
  14098. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14099. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14100. int opt = 1;
  14101. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14102. #ifdef _WIN32
  14103. reinterpret_cast<const char *>(&opt),
  14104. #else
  14105. &opt,
  14106. #endif
  14107. sizeof(opt));
  14108. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14109. ASSERT_EQ(0, ::listen(srv, 1));
  14110. auto server_thread = std::thread([&compressed, srv] {
  14111. sockaddr_in cli_addr{};
  14112. socklen_t cli_len = sizeof(cli_addr);
  14113. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14114. if (cli != INVALID_SOCKET) {
  14115. // Read the full HTTP request (until \r\n\r\n)
  14116. char buf[4096];
  14117. size_t total = 0;
  14118. while (total < sizeof(buf)) {
  14119. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14120. if (n <= 0) break;
  14121. total += static_cast<size_t>(n);
  14122. // Check for end of headers
  14123. if (total >= 4) {
  14124. std::string req(buf, total);
  14125. if (req.find("\r\n\r\n") != std::string::npos) break;
  14126. }
  14127. }
  14128. // Malicious response: gzip-compressed body, no Content-Length
  14129. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14130. "Content-Encoding: gzip\r\n"
  14131. "Connection: close\r\n"
  14132. "\r\n";
  14133. ::send(cli,
  14134. #ifdef _WIN32
  14135. static_cast<const char *>(response_header.c_str()),
  14136. static_cast<int>(response_header.size()),
  14137. #else
  14138. response_header.c_str(), response_header.size(),
  14139. #endif
  14140. 0);
  14141. // Send the compressed payload (small on the wire, huge when decompressed)
  14142. size_t total_sent = 0;
  14143. while (total_sent < compressed.size()) {
  14144. auto to_send = std::min(compressed.size() - total_sent,
  14145. static_cast<size_t>(64 * 1024));
  14146. auto sent =
  14147. ::send(cli,
  14148. #ifdef _WIN32
  14149. static_cast<const char *>(compressed.c_str() + total_sent),
  14150. static_cast<int>(to_send),
  14151. #else
  14152. compressed.c_str() + total_sent, to_send,
  14153. #endif
  14154. 0);
  14155. if (sent <= 0) break;
  14156. total_sent += static_cast<size_t>(sent);
  14157. }
  14158. detail::close_socket(cli);
  14159. }
  14160. });
  14161. auto se = detail::scope_exit([&] {
  14162. detail::close_socket(srv);
  14163. server_thread.join();
  14164. });
  14165. size_t total_decompressed = 0;
  14166. {
  14167. Client cli("127.0.0.1", PORT + 3);
  14168. cli.set_read_timeout(5, 0);
  14169. cli.set_decompress(true);
  14170. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14171. auto stream = cli.open_stream("GET", "/zipbomb");
  14172. ASSERT_TRUE(stream.is_valid());
  14173. char buffer[64 * 1024];
  14174. ssize_t n;
  14175. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14176. total_decompressed += static_cast<size_t>(n);
  14177. }
  14178. }
  14179. // The decompressed size must be capped by payload_max_length. Without
  14180. // protection, the client would decompress the full 10MB from a tiny
  14181. // compressed payload, enabling a zip bomb DoS attack.
  14182. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14183. << "Client decompressed " << total_decompressed
  14184. << " bytes from a gzip response. The decompressed size should be "
  14185. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14186. }
  14187. #endif
  14188. TEST(HostAndPortPropertiesTest, NoSSL) {
  14189. httplib::Client cli("www.google.com", 1234);
  14190. ASSERT_EQ("www.google.com", cli.host());
  14191. ASSERT_EQ(1234, cli.port());
  14192. }
  14193. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14194. httplib::Client cli("www.google.com:1234");
  14195. ASSERT_EQ("www.google.com", cli.host());
  14196. ASSERT_EQ(1234, cli.port());
  14197. }
  14198. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14199. // Port number that overflows int — should not crash, client becomes invalid
  14200. httplib::Client cli("http://www.google.com:99999999999999999999");
  14201. ASSERT_FALSE(cli.is_valid());
  14202. }
  14203. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14204. // Port 99999 exceeds valid range (1-65535) — should not crash
  14205. httplib::Client cli("http://www.google.com:99999");
  14206. ASSERT_FALSE(cli.is_valid());
  14207. auto res = cli.Get("/");
  14208. EXPECT_FALSE(res);
  14209. EXPECT_EQ(Error::Connection, res.error());
  14210. }
  14211. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14212. httplib::Client cli("http://user:pass@localhost:1234");
  14213. ASSERT_FALSE(cli.is_valid());
  14214. EXPECT_FALSE(cli.Get("/"));
  14215. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14216. }
  14217. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14218. httplib::Client cli("http://www.google.com:80abc");
  14219. ASSERT_FALSE(cli.is_valid());
  14220. }
  14221. #ifdef CPPHTTPLIB_SSL_ENABLED
  14222. TEST(HostAndPortPropertiesTest, SSL) {
  14223. httplib::SSLClient cli("www.google.com");
  14224. ASSERT_EQ("www.google.com", cli.host());
  14225. ASSERT_EQ(443, cli.port());
  14226. }
  14227. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14228. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14229. std::string cert;
  14230. read_file(CA_CERT_FILE, cert);
  14231. httplib::SSLClient httplib_client("www.google.com");
  14232. // Load CA store first time
  14233. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14234. // Load CA store second time (update)
  14235. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14236. // Verify client is still valid and can make connections
  14237. httplib_client.enable_server_certificate_verification(true);
  14238. auto res = httplib_client.Get("/");
  14239. // Any status: Google may redirect or rate-limit CI runners.
  14240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14241. }
  14242. TEST(SSLClientTest, ServerNameIndication_Online) {
  14243. auto host = "httpbingo.org";
  14244. auto path = std::string{"/get"};
  14245. SSLClient cli(host, 443);
  14246. auto res = retry_service_failures([&] { return cli.Get(path); });
  14247. SKIP_ON_SERVICE_FAILURE(res);
  14248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14249. ASSERT_EQ(StatusCode::OK_200, res->status);
  14250. }
  14251. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14252. // Use a site that will cause SSL verification failure due to self-signed cert
  14253. SSLClient cli("self-signed.badssl.com", 443);
  14254. cli.enable_server_certificate_verification(true);
  14255. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14256. SKIP_ON_SERVICE_FAILURE(res);
  14257. ASSERT_TRUE(!res);
  14258. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14259. // Verify backend error is captured for SSLServerVerification
  14260. // This occurs when certificate verification fails
  14261. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14262. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14263. EXPECT_NE(0UL, res.ssl_backend_error());
  14264. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14265. res.ssl_error());
  14266. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14267. #if !defined(_WIN32) || \
  14268. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14269. // On non-Windows or when Windows Schannel is disabled, the error comes
  14270. // from OpenSSL's verification
  14271. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14272. res.ssl_backend_error());
  14273. #endif
  14274. #endif
  14275. }
  14276. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14277. // Use a site where hostname doesn't match the certificate
  14278. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14279. SSLClient cli("wrong.host.badssl.com", 443);
  14280. cli.enable_server_certificate_verification(true);
  14281. cli.enable_server_hostname_verification(true);
  14282. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14283. SKIP_ON_SERVICE_FAILURE(res);
  14284. ASSERT_TRUE(!res);
  14285. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14286. // Verify backend error is captured for hostname verification failure
  14287. EXPECT_NE(0UL, res.ssl_backend_error());
  14288. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14289. res.ssl_error());
  14290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14291. #if !defined(_WIN32) || \
  14292. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14293. // On non-Windows or when Windows Schannel is disabled, the error comes
  14294. // from OpenSSL's hostname verification
  14295. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14296. res.ssl_backend_error());
  14297. #endif
  14298. #endif
  14299. }
  14300. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14301. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14302. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14303. SSLClient cli("www.google.com", 443);
  14304. cli.enable_server_certificate_verification(true);
  14305. auto res = cli.Get("/");
  14306. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14307. }
  14308. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14309. SSLClient cli("www.google.com", 443);
  14310. cli.enable_server_certificate_verification(true);
  14311. cli.enable_windows_certificate_verification(false);
  14312. auto res = cli.Get("/");
  14313. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14314. }
  14315. // The server sends an intermediate cross-signed by a root Windows trusts,
  14316. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14317. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14318. SSLClient cli("accounts.spotify.com", 443);
  14319. auto res = cli.Get("/");
  14320. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14321. << " ssl_backend_error=" << res.ssl_backend_error();
  14322. }
  14323. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14324. // policy status, which no backend reports for a self-signed certificate.
  14325. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14326. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14327. ASSERT_TRUE(svr.is_valid());
  14328. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14329. auto se = detail::scope_exit([&] {
  14330. svr.stop();
  14331. t.join();
  14332. ASSERT_FALSE(svr.is_running());
  14333. });
  14334. svr.wait_until_ready();
  14335. SSLClient cli("127.0.0.1", PORT);
  14336. cli.set_connection_timeout(30);
  14337. auto res = cli.Get("/");
  14338. ASSERT_FALSE(res);
  14339. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14340. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14341. }
  14342. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14343. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14344. ASSERT_TRUE(svr.is_valid());
  14345. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14346. auto se = detail::scope_exit([&] {
  14347. svr.stop();
  14348. t.join();
  14349. ASSERT_FALSE(svr.is_running());
  14350. });
  14351. svr.wait_until_ready();
  14352. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14353. {
  14354. ws::WebSocketClient client(url);
  14355. auto res = client.connect();
  14356. ASSERT_FALSE(res);
  14357. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14358. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14359. res.ssl_backend_error());
  14360. }
  14361. {
  14362. ws::WebSocketClient client(url);
  14363. client.enable_windows_certificate_verification(false);
  14364. auto res = client.connect();
  14365. ASSERT_FALSE(res);
  14366. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14367. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14368. res.ssl_backend_error());
  14369. }
  14370. }
  14371. #endif
  14372. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14373. Client cli("https://google.com");
  14374. auto res = cli.Get("/");
  14375. // Any status: Google may redirect or rate-limit CI runners.
  14376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14377. }
  14378. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14379. SSLClient cli("google.com");
  14380. cli.set_ca_cert_path(CA_CERT_FILE);
  14381. auto res = cli.Get("/");
  14382. // Any status: Google may redirect or rate-limit CI runners.
  14383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14384. }
  14385. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14386. SSLClient cli("google.com");
  14387. cli.enable_server_certificate_verification(true);
  14388. cli.set_ca_cert_path("hello");
  14389. auto res = cli.Get("/");
  14390. ASSERT_TRUE(!res);
  14391. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14392. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14393. // should be set
  14394. EXPECT_EQ(0, res.ssl_error());
  14395. // Verify backend error is captured for SSLLoadingCerts
  14396. // This error occurs when loading CA certificates fails
  14397. EXPECT_NE(0UL, res.ssl_backend_error());
  14398. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14399. // OpenSSL specific error codes:
  14400. // > openssl errstr 0x80000002
  14401. // error:80000002:system library::No such file or directory
  14402. // > openssl errstr 0xA000126
  14403. // error:0A000126:SSL routines::unexpected eof while reading
  14404. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14405. res.ssl_backend_error() == 0xA000126);
  14406. #endif
  14407. }
  14408. TEST(SSLClientTest, ServerCertificateVerification4) {
  14409. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14410. ASSERT_TRUE(svr.is_valid());
  14411. svr.Get("/test", [&](const Request &, Response &res) {
  14412. res.set_content("test", "text/plain");
  14413. svr.stop();
  14414. ASSERT_TRUE(true);
  14415. });
  14416. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14417. auto se = detail::scope_exit([&] {
  14418. t.join();
  14419. ASSERT_FALSE(svr.is_running());
  14420. });
  14421. svr.wait_until_ready();
  14422. SSLClient cli("127.0.0.1", PORT);
  14423. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14424. cli.enable_server_certificate_verification(true);
  14425. cli.set_connection_timeout(30);
  14426. auto res = cli.Get("/test");
  14427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14428. ASSERT_EQ(StatusCode::OK_200, res->status);
  14429. }
  14430. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14431. std::string cert;
  14432. read_file(CA_CERT_FILE, cert);
  14433. SSLClient cli("google.com");
  14434. cli.load_ca_cert_store(cert.data(), cert.size());
  14435. const auto res = cli.Get("/");
  14436. // Any status: Google may redirect or rate-limit CI runners.
  14437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14438. }
  14439. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14440. // clang-format off
  14441. static constexpr char cert[] =
  14442. "GlobalSign Root CA\n"
  14443. "==================\n"
  14444. "-----BEGIN CERTIFICATE-----\n"
  14445. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14446. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14447. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14448. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14449. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14450. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14451. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14452. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14453. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14454. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14455. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14456. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14457. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14458. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14459. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14460. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14461. "-----END CERTIFICATE-----\n";
  14462. // clang-format on
  14463. SSLClient cli("google.com");
  14464. cli.load_ca_cert_store(cert, sizeof(cert));
  14465. const auto res = cli.Get("/");
  14466. // Any status: Google may redirect or rate-limit CI runners.
  14467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14468. }
  14469. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14470. SSLClient cli("www.youtube.com");
  14471. cli.set_ca_cert_path(CA_CERT_FILE);
  14472. cli.enable_server_certificate_verification(true);
  14473. cli.set_follow_location(true);
  14474. auto res = cli.Get("/");
  14475. // Any status: Google may redirect or rate-limit CI runners.
  14476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14477. }
  14478. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14479. SSLClient cli("wWw.YouTube.Com");
  14480. cli.set_ca_cert_path(CA_CERT_FILE);
  14481. cli.enable_server_certificate_verification(true);
  14482. cli.enable_server_hostname_verification(true);
  14483. cli.set_follow_location(true);
  14484. auto res = cli.Get("/");
  14485. // Any status: Google may redirect or rate-limit CI runners.
  14486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14487. }
  14488. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14489. SSLClient cli("gOoGlE.COm");
  14490. cli.enable_server_certificate_verification(true);
  14491. cli.enable_server_hostname_verification(true);
  14492. cli.set_follow_location(true);
  14493. auto res = cli.Get("/");
  14494. // Any status: Google may redirect or rate-limit CI runners.
  14495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14496. }
  14497. TEST(SSLClientTest, Issue2004_Online) {
  14498. Client client("https://google.com");
  14499. client.set_follow_location(true);
  14500. auto res = client.Get("/");
  14501. // Any status: Google may redirect or rate-limit CI runners.
  14502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14503. }
  14504. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14505. // Create SSLClient with invalid cert/key to make is_valid() return false
  14506. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14507. "nonexistent_key.pem");
  14508. // is_valid() should be false due to cert loading failure
  14509. ASSERT_FALSE(cli.is_valid());
  14510. auto res = cli.Get("/");
  14511. ASSERT_FALSE(res);
  14512. EXPECT_EQ(Error::SSLConnection, res.error());
  14513. }
  14514. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14515. // Test for Issue #2251: SSL error not properly reported when client cert
  14516. // and key paths are swapped or mismatched
  14517. // This simulates the scenario where user accidentally swaps the cert and key
  14518. // files
  14519. // Using client cert file as private key and vice versa (completely wrong)
  14520. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14521. // Should fail validation due to cert/key mismatch
  14522. ASSERT_FALSE(cli.is_valid());
  14523. // Attempt to make a request should fail with proper error
  14524. auto res = cli.Get("/");
  14525. ASSERT_FALSE(res);
  14526. EXPECT_EQ(Error::SSLConnection, res.error());
  14527. // SSL error should be recorded in the Result object (this is the key fix for
  14528. // Issue #2251)
  14529. auto backend_error = res.ssl_backend_error();
  14530. EXPECT_NE(0u, backend_error);
  14531. }
  14532. // Tests cert/key mismatch detection at the TLS context level
  14533. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14534. // Test that using mismatched cert/key causes connection failure.
  14535. // We verify this at the SSLClient level rather than through internal
  14536. // TLS API functions.
  14537. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14538. cli.enable_server_certificate_verification(false);
  14539. cli.set_connection_timeout(2);
  14540. // The mismatch should cause a connection or handshake error
  14541. auto res = cli.Get("/test");
  14542. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14543. // Either way, the request should fail
  14544. EXPECT_FALSE(res);
  14545. }
  14546. #endif
  14547. #if 0
  14548. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14549. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14550. ASSERT_TRUE(cli != nullptr);
  14551. cli->set_address_family(AF_INET6);
  14552. cli->set_interface("en0");
  14553. auto res = cli->Get("/get");
  14554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14555. ASSERT_EQ(StatusCode::OK_200, res->status);
  14556. }
  14557. #endif
  14558. // Client certificate tests - work with all TLS backends
  14559. #ifdef CPPHTTPLIB_SSL_ENABLED
  14560. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14561. void ClientCertPresent(
  14562. const std::string &client_cert_file,
  14563. const std::string &client_private_key_file,
  14564. const std::string &client_encrypted_private_key_pass = std::string(),
  14565. const ClientCertServerSetup &setup = nullptr) {
  14566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14567. ASSERT_TRUE(svr.is_valid());
  14568. if (setup) { setup(svr); }
  14569. svr.Get("/test", [&](const Request &req, Response &res) {
  14570. res.set_content("test", "text/plain");
  14571. auto cert = req.peer_cert();
  14572. ASSERT_TRUE(static_cast<bool>(cert));
  14573. std::string common_name = cert.subject_cn();
  14574. EXPECT_EQ("Common Name", common_name);
  14575. });
  14576. auto port = svr.bind_to_any_port(HOST);
  14577. ASSERT_LT(0, port);
  14578. thread t = thread([&]() { svr.listen_after_bind(); });
  14579. auto se = detail::scope_exit([&] {
  14580. svr.stop();
  14581. t.join();
  14582. ASSERT_FALSE(svr.is_running());
  14583. });
  14584. svr.wait_until_ready();
  14585. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14586. client_encrypted_private_key_pass);
  14587. cli.enable_server_certificate_verification(false);
  14588. cli.set_connection_timeout(30);
  14589. auto res = cli.Get("/test");
  14590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14591. ASSERT_EQ(StatusCode::OK_200, res->status);
  14592. }
  14593. TEST(SSLClientServerTest, ClientCertPresent) {
  14594. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14595. }
  14596. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14597. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14598. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14599. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14600. }
  14601. // Expects svr, which must require client certificates, to reject a client
  14602. // that has none
  14603. void RejectsClientWithoutCert(SSLServer &svr) {
  14604. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14605. auto port = svr.bind_to_any_port(HOST);
  14606. ASSERT_LT(0, port);
  14607. thread t = thread([&]() { svr.listen_after_bind(); });
  14608. auto se = detail::scope_exit([&] {
  14609. svr.stop();
  14610. t.join();
  14611. ASSERT_FALSE(svr.is_running());
  14612. });
  14613. svr.wait_until_ready();
  14614. SSLClient cli(HOST, port);
  14615. cli.set_connection_timeout(30);
  14616. // Skip the server certificate check, so that the request fails because the
  14617. // client certificate is missing rather than because cert.pem is not trusted
  14618. cli.enable_server_certificate_verification(false);
  14619. auto res = cli.Get("/test");
  14620. ASSERT_FALSE(res);
  14621. // The server rejects the client during the handshake, or on TLS 1.3 right
  14622. // after it, which the client notices on its first write or read
  14623. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14624. res.error() == Error::Write || res.error() == Error::Read)
  14625. << to_string(res.error());
  14626. if (res.error() == Error::SSLConnection) {
  14627. EXPECT_NE(0UL, res.ssl_backend_error());
  14628. }
  14629. // A rejection noticed on the write keeps the TLS error the write hit
  14630. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14631. }
  14632. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14634. ASSERT_TRUE(svr.is_valid());
  14635. if (setup) { setup(svr); }
  14636. RejectsClientWithoutCert(svr);
  14637. }
  14638. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14639. // A server that requires client certificates must keep requiring them after
  14640. // setup changes it, and keep accepting a client that has one
  14641. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14642. ClientCertMissing(setup);
  14643. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14644. setup);
  14645. }
  14646. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14647. ClientCertStillRequired([](SSLServer &svr) {
  14648. ASSERT_TRUE(tls::set_verify_callback(
  14649. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14650. });
  14651. }
  14652. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14653. ClientCertStillRequired([](SSLServer &svr) {
  14654. ASSERT_TRUE(tls::set_verify_callback(
  14655. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14656. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14657. });
  14658. }
  14659. // The client verifies the server certificate during the handshake, so a
  14660. // server that fails the check never gets the client certificate, even when a
  14661. // verifier of the client's own accepts it
  14662. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14663. struct Case {
  14664. const char *trusted_ca;
  14665. const char *host;
  14666. Error error;
  14667. };
  14668. // cert2.pem names localhost: the first client does not trust it, and the
  14669. // second trusts it but asks for another name
  14670. for (const auto &c :
  14671. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14672. Case{SERVER_CERT2_FILE, "example.com",
  14673. Error::SSLServerHostnameVerification}}) {
  14674. for (auto with_verifier : {false, true}) {
  14675. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14676. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14677. CLIENT_CA_CERT_FILE);
  14678. ASSERT_TRUE(svr.is_valid());
  14679. std::atomic<bool> got_client_cert{false};
  14680. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14681. [&](const tls::VerifyContext &) {
  14682. got_client_cert = true;
  14683. return true;
  14684. }));
  14685. auto port = svr.bind_to_any_port("127.0.0.1");
  14686. ASSERT_LT(0, port);
  14687. thread t = thread([&] { svr.listen_after_bind(); });
  14688. svr.wait_until_ready();
  14689. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14690. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14691. cli.set_ca_cert_path(c.trusted_ca);
  14692. if (with_verifier) {
  14693. cli.set_server_certificate_verifier(
  14694. [](const tls::VerifyContext &) { return true; });
  14695. }
  14696. auto res = cli.Get("/");
  14697. EXPECT_FALSE(res);
  14698. EXPECT_EQ(c.error, res.error());
  14699. svr.stop();
  14700. t.join();
  14701. EXPECT_FALSE(got_client_cert);
  14702. }
  14703. }
  14704. }
  14705. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14706. std::string cert_pem, key_pem, ca_pem;
  14707. read_file(SERVER_CERT_FILE, cert_pem);
  14708. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14709. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14710. ASSERT_TRUE(
  14711. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14712. }
  14713. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14714. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14715. ASSERT_TRUE(svr.is_valid());
  14716. UpdateCertsPemWithClientCA(svr);
  14717. RejectsClientWithoutCert(svr);
  14718. }
  14719. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14720. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14721. }
  14722. // A TLS error from one request must not show up in a later request's Result
  14723. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14725. ASSERT_TRUE(svr.is_valid());
  14726. svr.Get("/test", [](const Request &, Response &res) {
  14727. res.set_content("test", "text/plain");
  14728. });
  14729. auto port = svr.bind_to_any_port(HOST);
  14730. ASSERT_LT(0, port);
  14731. thread t = thread([&]() { svr.listen_after_bind(); });
  14732. auto se = detail::scope_exit([&] {
  14733. svr.stop();
  14734. t.join();
  14735. ASSERT_FALSE(svr.is_running());
  14736. });
  14737. svr.wait_until_ready();
  14738. SSLClient cli(HOST, port);
  14739. cli.set_connection_timeout(30);
  14740. cli.enable_server_hostname_verification(false);
  14741. // cert.pem is not trusted, so the handshake fails
  14742. ASSERT_FALSE(cli.Get("/test"));
  14743. cli.enable_server_certificate_verification(false);
  14744. auto res = cli.Get("/test");
  14745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14746. EXPECT_EQ(0, res.ssl_error());
  14747. EXPECT_EQ(0UL, res.ssl_backend_error());
  14748. }
  14749. // PEM memory-based constructor tests (works with all TLS backends).
  14750. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14751. // terminator after it.
  14752. void PemMemoryClientCertPresent(
  14753. const std::string &client_cert_file,
  14754. const std::string &client_private_key_file,
  14755. const std::string &client_encrypted_private_key_pass = std::string(),
  14756. bool exact_size = false) {
  14757. // Read PEM files into memory
  14758. std::string server_cert_pem, server_key_pem;
  14759. std::string client_ca_pem;
  14760. std::string client_cert_pem, client_key_pem;
  14761. read_file(SERVER_CERT_FILE, server_cert_pem);
  14762. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14763. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14764. read_file(client_cert_file, client_cert_pem);
  14765. read_file(client_private_key_file, client_key_pem);
  14766. std::list<std::vector<char>> exact_copies;
  14767. auto data = [&](const std::string &pem) -> const char * {
  14768. if (!exact_size) { return pem.c_str(); }
  14769. exact_copies.emplace_back(pem.begin(), pem.end());
  14770. return exact_copies.back().data();
  14771. };
  14772. // Create server with PEM memory
  14773. SSLServer::PemMemory server_pem = {
  14774. data(server_cert_pem),
  14775. server_cert_pem.size(),
  14776. data(server_key_pem),
  14777. server_key_pem.size(),
  14778. data(client_ca_pem),
  14779. client_ca_pem.size(),
  14780. nullptr // no password for server key
  14781. };
  14782. SSLServer svr(server_pem);
  14783. ASSERT_TRUE(svr.is_valid());
  14784. svr.Get("/test", [&](const Request &req, Response &res) {
  14785. res.set_content("test", "text/plain");
  14786. auto cert = req.peer_cert();
  14787. ASSERT_TRUE(static_cast<bool>(cert));
  14788. EXPECT_EQ("Common Name", cert.subject_cn());
  14789. });
  14790. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14791. auto se = detail::scope_exit([&] {
  14792. svr.stop();
  14793. t.join();
  14794. ASSERT_FALSE(svr.is_running());
  14795. });
  14796. svr.wait_until_ready();
  14797. // Create client with PEM memory
  14798. const char *password = client_encrypted_private_key_pass.empty()
  14799. ? nullptr
  14800. : client_encrypted_private_key_pass.c_str();
  14801. SSLClient::PemMemory client_pem = {
  14802. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14803. client_key_pem.size(), password};
  14804. SSLClient cli(HOST, PORT, client_pem);
  14805. cli.enable_server_certificate_verification(false);
  14806. cli.set_connection_timeout(30);
  14807. auto res = cli.Get("/test");
  14808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14809. ASSERT_EQ(StatusCode::OK_200, res->status);
  14810. }
  14811. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14812. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14813. }
  14814. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14815. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14816. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14817. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14818. }
  14819. // A server built from PEM memory with a client CA requires client certificates,
  14820. // also when the CA is a NUL-terminated string passed with a length of 0
  14821. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14822. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14823. read_file(SERVER_CERT_FILE, server_cert_pem);
  14824. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14825. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14826. SSLServer::PemMemory server_pem = {
  14827. server_cert_pem.c_str(),
  14828. server_cert_pem.size(),
  14829. server_key_pem.c_str(),
  14830. server_key_pem.size(),
  14831. client_ca_pem.c_str(),
  14832. client_ca_pem.size(),
  14833. nullptr // no password for server key
  14834. };
  14835. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14836. SCOPED_TRACE(client_ca_pem_len);
  14837. server_pem.client_ca_pem_len = client_ca_pem_len;
  14838. SSLServer svr(server_pem);
  14839. ASSERT_TRUE(svr.is_valid());
  14840. RejectsClientWithoutCert(svr);
  14841. }
  14842. // An empty CA fails to load instead of turning the check off
  14843. server_pem.client_ca_pem = "";
  14844. server_pem.client_ca_pem_len = 0;
  14845. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14846. }
  14847. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14848. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14849. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14850. true);
  14851. }
  14852. // A length shorter than the PEM cuts it short, so it no longer loads
  14853. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14854. std::string cert, key;
  14855. read_file(SERVER_CERT_FILE, cert);
  14856. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14857. for (auto cut_cert : {true, false}) {
  14858. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14859. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14860. SSLServer::PemMemory server_pem = {
  14861. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14862. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14863. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14864. key_len, nullptr};
  14865. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14866. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14867. key.c_str(), key_len, nullptr};
  14868. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14869. }
  14870. }
  14871. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14872. class NoListenSSLServer : public SSLServer {
  14873. public:
  14874. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14875. const char *client_ca_cert_file_path,
  14876. const char *client_ca_cert_dir_path = nullptr)
  14877. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14878. client_ca_cert_dir_path),
  14879. stop_(false) {}
  14880. std::atomic_bool stop_;
  14881. private:
  14882. bool process_and_close_socket(socket_t /*sock*/) override {
  14883. // Don't create SSL context
  14884. while (!stop_.load()) {
  14885. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14886. }
  14887. return true;
  14888. }
  14889. };
  14890. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14891. CLIENT_CA_CERT_FILE);
  14892. ASSERT_TRUE(svr.is_valid());
  14893. // Keep-alive parking would bypass the override.
  14894. svr.set_keep_alive_parking(false);
  14895. svr.Get("/test", [&](const Request &, Response &res) {
  14896. res.set_content("test", "text/plain");
  14897. });
  14898. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14899. auto se = detail::scope_exit([&] {
  14900. svr.stop_ = true;
  14901. svr.stop();
  14902. t.join();
  14903. ASSERT_FALSE(svr.is_running());
  14904. });
  14905. svr.wait_until_ready();
  14906. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14907. cli.enable_server_certificate_verification(false);
  14908. cli.set_connection_timeout(1);
  14909. auto res = cli.Get("/test");
  14910. ASSERT_TRUE(!res);
  14911. EXPECT_EQ(Error::SSLConnection, res.error());
  14912. // Timeout results in WantRead error code (maps to backend-specific value)
  14913. EXPECT_NE(0, res.ssl_error());
  14914. }
  14915. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14916. // Test SSLServer with client certificate verification using the standard
  14917. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14919. CLIENT_CA_CERT_DIR);
  14920. ASSERT_TRUE(svr.is_valid());
  14921. svr.Get("/test", [&](const Request &req, Response &res) {
  14922. res.set_content("test", "text/plain");
  14923. auto cert = req.peer_cert();
  14924. ASSERT_TRUE(static_cast<bool>(cert));
  14925. auto common_name = cert.subject_cn();
  14926. EXPECT_EQ("Common Name", common_name);
  14927. });
  14928. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14929. auto se = detail::scope_exit([&] {
  14930. svr.stop();
  14931. t.join();
  14932. ASSERT_FALSE(svr.is_running());
  14933. });
  14934. svr.wait_until_ready();
  14935. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14936. cli.enable_server_certificate_verification(false);
  14937. cli.set_connection_timeout(30);
  14938. auto res = cli.Get("/test");
  14939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14940. ASSERT_EQ(StatusCode::OK_200, res->status);
  14941. }
  14942. // Test verify_hostname on every backend: a host is named by a SAN only
  14943. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14944. using namespace httplib::tls;
  14945. // We need a running server to test against
  14946. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14947. ASSERT_TRUE(svr.is_valid());
  14948. svr.Get("/test", [](const Request &, Response &res) {
  14949. res.set_content("ok", "text/plain");
  14950. });
  14951. thread t([&]() { svr.listen(HOST, PORT); });
  14952. auto se = detail::scope_exit([&] {
  14953. svr.stop();
  14954. t.join();
  14955. });
  14956. svr.wait_until_ready();
  14957. bool verify_callback_called = false;
  14958. bool verify_result_wrong = false;
  14959. SSLClient cli(HOST, PORT);
  14960. cli.enable_server_certificate_verification(true);
  14961. cli.set_ca_cert_path(CA_CERT_FILE);
  14962. cli.set_connection_timeout(5);
  14963. // Note: Test certificate has CN="Common Name", not "localhost"
  14964. bool verify_result_cn = false;
  14965. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14966. verify_callback_called = true;
  14967. if (!ctx.cert) return false;
  14968. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14969. verify_result_cn = ctx.check_hostname("Common Name");
  14970. // Test 2: wrong hostname should not match
  14971. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14972. return true; // Accept for the purpose of this test
  14973. });
  14974. auto res = cli.Get("/test");
  14975. // The request may succeed or fail depending on cert configuration
  14976. // but the callback should have been called
  14977. ASSERT_TRUE(verify_callback_called)
  14978. << "Verify callback should have been called";
  14979. EXPECT_FALSE(verify_result_cn)
  14980. << "verify_hostname must not match the certificate CN (no SAN)";
  14981. // Wrong hostname should not match
  14982. EXPECT_FALSE(verify_result_wrong)
  14983. << "verify_hostname should not match 'wronghost.example.com'";
  14984. }
  14985. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14986. // backend verifies it.
  14987. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14988. // Certificate CN is "localhost" and it carries no SAN.
  14989. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14990. ASSERT_TRUE(svr.is_valid());
  14991. svr.Get("/test", [](const Request &, Response &res) {
  14992. res.set_content("ok", "text/plain");
  14993. });
  14994. auto port = svr.bind_to_any_port(HOST);
  14995. thread t([&]() { svr.listen_after_bind(); });
  14996. auto se = detail::scope_exit([&] {
  14997. svr.stop();
  14998. t.join();
  14999. });
  15000. svr.wait_until_ready();
  15001. SSLClient cli("localhost", port);
  15002. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  15003. cli.enable_server_certificate_verification(true);
  15004. cli.set_connection_timeout(5);
  15005. auto res = cli.Get("/test");
  15006. ASSERT_FALSE(res);
  15007. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  15008. // The same certificate is accepted once host name verification is off, so the
  15009. // failure above is the host name and not the chain.
  15010. cli.enable_server_hostname_verification(false);
  15011. res = cli.Get("/test");
  15012. ASSERT_TRUE(res) << to_string(res.error());
  15013. EXPECT_EQ(StatusCode::OK_200, res->status);
  15014. }
  15015. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  15016. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  15017. // X509_check_ip behavior and must hold for every backend.
  15018. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  15019. using namespace httplib::tls;
  15020. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  15021. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15022. ASSERT_TRUE(svr.is_valid());
  15023. svr.Get("/test", [](const Request &, Response &res) {
  15024. res.set_content("ok", "text/plain");
  15025. });
  15026. thread t([&]() { svr.listen(HOST, PORT); });
  15027. auto se = detail::scope_exit([&] {
  15028. svr.stop();
  15029. t.join();
  15030. });
  15031. svr.wait_until_ready();
  15032. bool verify_callback_called = false;
  15033. bool ip_matched_via_cn = true;
  15034. SSLClient cli(HOST, PORT);
  15035. cli.enable_server_certificate_verification(true);
  15036. cli.set_ca_cert_path(CA_CERT_FILE);
  15037. cli.set_connection_timeout(5);
  15038. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15039. verify_callback_called = true;
  15040. if (!ctx.cert) return false;
  15041. // The IP appears only in the CN, so it must NOT be accepted.
  15042. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  15043. return true; // Accept for the purpose of this test
  15044. });
  15045. cli.Get("/test");
  15046. ASSERT_TRUE(verify_callback_called)
  15047. << "Verify callback should have been called";
  15048. EXPECT_FALSE(ip_matched_via_cn)
  15049. << "An IP host must not be authenticated via the certificate CN";
  15050. }
  15051. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15052. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15053. using namespace httplib::tls;
  15054. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15055. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15056. ASSERT_TRUE(svr.is_valid());
  15057. svr.Get("/test", [](const Request &, Response &res) {
  15058. res.set_content("ok", "text/plain");
  15059. });
  15060. thread t([&]() { svr.listen(HOST, PORT); });
  15061. auto se = detail::scope_exit([&] {
  15062. svr.stop();
  15063. t.join();
  15064. });
  15065. svr.wait_until_ready();
  15066. bool verify_callback_called = false;
  15067. bool san_matched = false;
  15068. bool wrong_ipv6_matched = true;
  15069. bool cn_ipv6_matched = true;
  15070. SSLClient cli(HOST, PORT);
  15071. cli.enable_server_certificate_verification(true);
  15072. cli.set_ca_cert_path(CA_CERT_FILE);
  15073. cli.set_connection_timeout(5);
  15074. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15075. verify_callback_called = true;
  15076. if (!ctx.cert) return false;
  15077. // Matches the IPv6 iPAddress SAN.
  15078. san_matched = ctx.check_hostname("2001:db8::1");
  15079. // A different IPv6 address must not match.
  15080. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15081. // "::1" lives only in the CN, so it must not be accepted.
  15082. cn_ipv6_matched = ctx.check_hostname("::1");
  15083. return true; // Accept for the purpose of this test
  15084. });
  15085. cli.Get("/test");
  15086. ASSERT_TRUE(verify_callback_called)
  15087. << "Verify callback should have been called";
  15088. EXPECT_TRUE(san_matched)
  15089. << "verify_hostname should match an IPv6 iPAddress SAN";
  15090. EXPECT_FALSE(wrong_ipv6_matched)
  15091. << "verify_hostname should not match a non-matching IPv6 address";
  15092. EXPECT_FALSE(cn_ipv6_matched)
  15093. << "An IPv6 host must not be authenticated via the certificate CN";
  15094. }
  15095. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15096. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15097. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15098. using namespace httplib::tls;
  15099. // SANs: DNS:a.zz, IP:42.46.122.122
  15100. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15101. ASSERT_TRUE(svr.is_valid());
  15102. svr.Get("/test", [](const Request &, Response &res) {
  15103. res.set_content("ok", "text/plain");
  15104. });
  15105. auto port = svr.bind_to_any_port(HOST);
  15106. thread t([&]() { svr.listen_after_bind(); });
  15107. auto se = detail::scope_exit([&] {
  15108. svr.stop();
  15109. t.join();
  15110. });
  15111. svr.wait_until_ready();
  15112. bool verify_callback_called = false;
  15113. bool dns_san_matched = false;
  15114. bool ip_san_matched = false;
  15115. bool ip_matched_via_dns_san = true;
  15116. bool dns_matched_via_ip_san = true;
  15117. bool cn_matched_next_to_dns_san = true;
  15118. SSLClient cli(HOST, port);
  15119. cli.enable_server_certificate_verification(true);
  15120. cli.set_ca_cert_path(CA_CERT_FILE);
  15121. cli.set_connection_timeout(5);
  15122. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15123. verify_callback_called = true;
  15124. if (!ctx.cert) return false;
  15125. dns_san_matched = ctx.check_hostname("a.zz");
  15126. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15127. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15128. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15129. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15130. return true; // Accept for the purpose of this test
  15131. });
  15132. cli.Get("/test");
  15133. ASSERT_TRUE(verify_callback_called)
  15134. << "Verify callback should have been called";
  15135. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15136. EXPECT_TRUE(ip_san_matched)
  15137. << "verify_hostname should match an iPAddress SAN";
  15138. EXPECT_FALSE(ip_matched_via_dns_san)
  15139. << "An IP host must not be authenticated via a dNSName SAN";
  15140. EXPECT_FALSE(dns_matched_via_ip_san)
  15141. << "A DNS host must not be authenticated via an iPAddress SAN";
  15142. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15143. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15144. }
  15145. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15146. // "www.*.example.test" names one host and not every host under example.test.
  15147. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15148. using namespace httplib::tls;
  15149. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15150. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15151. ASSERT_TRUE(svr.is_valid());
  15152. svr.Get("/test", [](const Request &, Response &res) {
  15153. res.set_content("ok", "text/plain");
  15154. });
  15155. auto port = svr.bind_to_any_port(HOST);
  15156. thread t([&]() { svr.listen_after_bind(); });
  15157. auto se = detail::scope_exit([&] {
  15158. svr.stop();
  15159. t.join();
  15160. });
  15161. svr.wait_until_ready();
  15162. bool verify_callback_called = false;
  15163. bool leftmost_wildcard_matched = false;
  15164. bool wildcard_spanned_labels = true;
  15165. bool inner_wildcard_matched = true;
  15166. SSLClient cli(HOST, port);
  15167. cli.enable_server_certificate_verification(true);
  15168. cli.set_ca_cert_path(CA_CERT_FILE);
  15169. cli.set_connection_timeout(5);
  15170. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15171. verify_callback_called = true;
  15172. if (!ctx.cert) return false;
  15173. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15174. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15175. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15176. return true; // Accept for the purpose of this test
  15177. });
  15178. cli.Get("/test");
  15179. ASSERT_TRUE(verify_callback_called)
  15180. << "Verify callback should have been called";
  15181. EXPECT_TRUE(leftmost_wildcard_matched)
  15182. << "A leftmost wildcard should match a single label";
  15183. EXPECT_FALSE(wildcard_spanned_labels)
  15184. << "A wildcard label must not match more than one label";
  15185. EXPECT_FALSE(inner_wildcard_matched)
  15186. << "A wildcard outside the leftmost label must not be honoured";
  15187. }
  15188. // sans() must report each SAN entry under its own type.
  15189. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15190. using namespace httplib::tls;
  15191. // SANs: DNS:a.zz, IP:42.46.122.122
  15192. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15193. ASSERT_TRUE(svr.is_valid());
  15194. svr.Get("/test", [](const Request &, Response &res) {
  15195. res.set_content("ok", "text/plain");
  15196. });
  15197. auto port = svr.bind_to_any_port(HOST);
  15198. thread t([&]() { svr.listen_after_bind(); });
  15199. auto se = detail::scope_exit([&] {
  15200. svr.stop();
  15201. t.join();
  15202. });
  15203. svr.wait_until_ready();
  15204. bool verify_callback_called = false;
  15205. std::vector<SanEntry> sans;
  15206. SSLClient cli(HOST, port);
  15207. cli.enable_server_certificate_verification(true);
  15208. cli.set_ca_cert_path(CA_CERT_FILE);
  15209. cli.set_connection_timeout(5);
  15210. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15211. verify_callback_called = true;
  15212. if (!ctx.cert) return false;
  15213. sans = ctx.sans();
  15214. return true; // Accept for the purpose of this test
  15215. });
  15216. cli.Get("/test");
  15217. ASSERT_TRUE(verify_callback_called)
  15218. << "Verify callback should have been called";
  15219. auto has_san = [&](SanType type, const std::string &value) {
  15220. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15221. return san.type == type && san.value == value;
  15222. });
  15223. };
  15224. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15225. << "sans() should report the dNSName SAN";
  15226. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15227. << "sans() should report the iPAddress SAN";
  15228. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15229. << "sans() must not report the dNSName SAN as an address";
  15230. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15231. << "sans() must not report the iPAddress SAN as a DNS name";
  15232. }
  15233. #endif
  15234. // mbedTLS-specific callback constructor test
  15235. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15236. #ifdef CPPHTTPLIB_SSL_ENABLED
  15237. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15238. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15239. ASSERT_TRUE(svr.is_valid());
  15240. // Set up a handler to verify client certificate is present
  15241. bool client_cert_verified = false;
  15242. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15243. // Verify that client certificate was provided
  15244. client_cert_verified = true;
  15245. res.set_content("success", "text/plain");
  15246. });
  15247. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15248. auto se = detail::scope_exit([&] {
  15249. svr.stop();
  15250. t.join();
  15251. ASSERT_FALSE(svr.is_running());
  15252. });
  15253. svr.wait_until_ready();
  15254. // Client with certificate
  15255. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15256. cli.enable_server_certificate_verification(false);
  15257. cli.set_connection_timeout(30);
  15258. auto res = cli.Get("/test");
  15259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15260. ASSERT_EQ(StatusCode::OK_200, res->status);
  15261. ASSERT_TRUE(client_cert_verified);
  15262. EXPECT_EQ("success", res->body);
  15263. }
  15264. #endif
  15265. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15266. // backends
  15267. #ifdef CPPHTTPLIB_SSL_ENABLED
  15268. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15269. using namespace httplib::tls;
  15270. // Test that when client CA cert file is provided,
  15271. // the server properly requests and validates client certificates
  15272. // Create a server with client authentication
  15273. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15274. ASSERT_TRUE(svr.is_valid());
  15275. bool handler_called = false;
  15276. svr.Get("/test", [&](const Request &req, Response &res) {
  15277. handler_called = true;
  15278. // Verify that a client certificate was provided
  15279. auto cert = req.peer_cert();
  15280. ASSERT_TRUE(static_cast<bool>(cert));
  15281. // Get the issuer name
  15282. std::string issuer_str = cert.issuer_name();
  15283. ASSERT_FALSE(issuer_str.empty());
  15284. // The client certificate should be issued by our test CA
  15285. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15286. res.set_content("authenticated", "text/plain");
  15287. });
  15288. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15289. auto se = detail::scope_exit([&] {
  15290. svr.stop();
  15291. t.join();
  15292. ASSERT_FALSE(svr.is_running());
  15293. });
  15294. svr.wait_until_ready();
  15295. // Connect with a client certificate issued by the CA
  15296. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15297. cli.enable_server_certificate_verification(false);
  15298. cli.set_connection_timeout(30);
  15299. auto res = cli.Get("/test");
  15300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15301. ASSERT_EQ(StatusCode::OK_200, res->status);
  15302. ASSERT_TRUE(handler_called);
  15303. EXPECT_EQ("authenticated", res->body);
  15304. }
  15305. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15306. using namespace httplib::tls;
  15307. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15308. ASSERT_TRUE(svr.is_valid());
  15309. svr.Get("/test", [](const Request &, Response &res) {
  15310. res.set_content("ok", "text/plain");
  15311. });
  15312. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15313. auto se = detail::scope_exit([&] {
  15314. svr.stop();
  15315. t.join();
  15316. });
  15317. svr.wait_until_ready();
  15318. SSLClient cli(HOST, PORT);
  15319. cli.enable_server_certificate_verification(false);
  15320. cli.set_connection_timeout(30);
  15321. bool cert_checked = false;
  15322. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15323. if (ctx.cert) {
  15324. auto sans = ctx.sans();
  15325. // Test certificate may or may not have SANs - just verify the API
  15326. // works If SANs exist, verify the types are valid
  15327. for (const auto &san : sans) {
  15328. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15329. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15330. san.type == SanType::OTHER);
  15331. EXPECT_FALSE(san.value.empty());
  15332. }
  15333. cert_checked = true;
  15334. }
  15335. return true;
  15336. });
  15337. auto res = cli.Get("/test");
  15338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15339. EXPECT_TRUE(cert_checked);
  15340. }
  15341. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15342. using namespace httplib::tls;
  15343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15344. ASSERT_TRUE(svr.is_valid());
  15345. svr.Get("/test", [](const Request &, Response &res) {
  15346. res.set_content("ok", "text/plain");
  15347. });
  15348. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15349. auto se = detail::scope_exit([&] {
  15350. svr.stop();
  15351. t.join();
  15352. });
  15353. svr.wait_until_ready();
  15354. SSLClient cli(HOST, PORT);
  15355. cli.enable_server_certificate_verification(false);
  15356. cli.set_connection_timeout(30);
  15357. bool validity_checked = false;
  15358. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15359. if (ctx.cert) {
  15360. time_t not_before = 0, not_after = 0;
  15361. bool result = ctx.validity(not_before, not_after);
  15362. EXPECT_TRUE(result);
  15363. // Verify that not_before < now < not_after for a valid cert
  15364. time_t now = time(nullptr);
  15365. EXPECT_LT(not_before, now);
  15366. EXPECT_GT(not_after, now);
  15367. validity_checked = true;
  15368. }
  15369. return true;
  15370. });
  15371. auto res = cli.Get("/test");
  15372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15373. EXPECT_TRUE(validity_checked);
  15374. }
  15375. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15376. using namespace httplib::tls;
  15377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15378. ASSERT_TRUE(svr.is_valid());
  15379. svr.Get("/test", [](const Request &, Response &res) {
  15380. res.set_content("ok", "text/plain");
  15381. });
  15382. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15383. auto se = detail::scope_exit([&] {
  15384. svr.stop();
  15385. t.join();
  15386. });
  15387. svr.wait_until_ready();
  15388. SSLClient cli(HOST, PORT);
  15389. cli.enable_server_certificate_verification(false);
  15390. cli.set_connection_timeout(30);
  15391. bool serial_checked = false;
  15392. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15393. if (ctx.cert) {
  15394. std::string serial = ctx.serial();
  15395. EXPECT_FALSE(serial.empty());
  15396. // Serial should be a hex string
  15397. for (char c : serial) {
  15398. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15399. (c >= 'a' && c <= 'f'));
  15400. }
  15401. serial_checked = true;
  15402. }
  15403. return true;
  15404. });
  15405. auto res = cli.Get("/test");
  15406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15407. EXPECT_TRUE(serial_checked);
  15408. }
  15409. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15410. // Test 1: Valid CA file - no error should be recorded
  15411. {
  15412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15413. CLIENT_CA_CERT_FILE);
  15414. ASSERT_TRUE(svr.is_valid());
  15415. // With valid setup, last_ssl_error should be 0
  15416. EXPECT_EQ(0, svr.ssl_last_error());
  15417. }
  15418. // Test 2: Invalid CA file content
  15419. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15420. {
  15421. // Create a temporary file with completely invalid content
  15422. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15423. {
  15424. std::ofstream ofs(temp_invalid_ca);
  15425. ofs << "This is not a certificate file at all\n";
  15426. ofs << "Just plain text content\n";
  15427. }
  15428. // Create server with invalid CA file
  15429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15430. // Clean up temporary file
  15431. std::remove(temp_invalid_ca);
  15432. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15433. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15434. // Note: SSL_CTX_load_verify_locations typically fails first,
  15435. // but our error handling code path is still exercised
  15436. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15437. }
  15438. }
  15439. TEST(VerifyCallbackTest, VerifyContextFields) {
  15440. using namespace httplib::tls;
  15441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15442. ASSERT_TRUE(svr.is_valid());
  15443. svr.Get("/test", [](const Request &, Response &res) {
  15444. res.set_content("ok", "text/plain");
  15445. });
  15446. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15447. auto se = detail::scope_exit([&] {
  15448. svr.stop();
  15449. t.join();
  15450. });
  15451. svr.wait_until_ready();
  15452. SSLClient cli(HOST, PORT);
  15453. cli.enable_server_certificate_verification(false);
  15454. cli.set_connection_timeout(30);
  15455. int callback_count = 0;
  15456. bool saw_leaf_cert = false;
  15457. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15458. if (ctx.cert) {
  15459. callback_count++;
  15460. // We should see at least one certificate (the leaf)
  15461. std::string cn = ctx.subject_cn();
  15462. if (!cn.empty()) { saw_leaf_cert = true; }
  15463. // Verify context fields are populated
  15464. EXPECT_NE(ctx.session, nullptr);
  15465. EXPECT_GE(ctx.depth, 0);
  15466. }
  15467. return true;
  15468. });
  15469. auto res = cli.Get("/test");
  15470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15471. EXPECT_GT(callback_count, 0);
  15472. EXPECT_TRUE(saw_leaf_cert);
  15473. }
  15474. // A verifier that accepts runs alongside the built-in verification, and is the
  15475. // only check once that is turned off.
  15476. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15477. using namespace httplib::tls;
  15478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15479. ASSERT_TRUE(svr.is_valid());
  15480. svr.Get("/test", [](const Request &, Response &res) {
  15481. res.set_content("ok", "text/plain");
  15482. });
  15483. auto port = svr.bind_to_any_port(HOST);
  15484. thread t([&]() { svr.listen_after_bind(); });
  15485. auto se = detail::scope_exit([&] {
  15486. svr.stop();
  15487. t.join();
  15488. });
  15489. svr.wait_until_ready();
  15490. SSLClient cli(HOST, port);
  15491. cli.enable_server_hostname_verification(false);
  15492. auto calls = 0;
  15493. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15494. calls++;
  15495. return true;
  15496. });
  15497. // cert.pem is not trusted
  15498. auto res = cli.Get("/test");
  15499. ASSERT_FALSE(res);
  15500. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15501. EXPECT_GT(calls, 0);
  15502. cli.enable_server_certificate_verification(false);
  15503. res = cli.Get("/test");
  15504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15505. EXPECT_EQ("ok", res->body);
  15506. }
  15507. // A verifier belongs to the client that set it, not to the thread that set it.
  15508. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15509. using namespace httplib::tls;
  15510. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15511. ASSERT_TRUE(svr.is_valid());
  15512. svr.Get("/test", [](const Request &, Response &res) {
  15513. res.set_content("ok", "text/plain");
  15514. });
  15515. auto port = svr.bind_to_any_port(HOST);
  15516. thread t([&]() { svr.listen_after_bind(); });
  15517. auto se = detail::scope_exit([&] {
  15518. svr.stop();
  15519. t.join();
  15520. });
  15521. svr.wait_until_ready();
  15522. auto rejecting_calls = 0;
  15523. SSLClient rejecting(HOST, port);
  15524. rejecting.enable_server_certificate_verification(false);
  15525. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15526. rejecting_calls++;
  15527. return false;
  15528. });
  15529. auto accepting_calls = 0;
  15530. SSLClient accepting(HOST, port);
  15531. accepting.enable_server_certificate_verification(false);
  15532. // Set on another thread than the requests below.
  15533. thread([&]() {
  15534. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15535. accepting_calls++;
  15536. return true;
  15537. });
  15538. }).join();
  15539. // Requested on another thread than the verifier was set on.
  15540. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15541. EXPECT_GT(rejecting_calls, 0);
  15542. auto res = accepting.Get("/test");
  15543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15544. EXPECT_GT(accepting_calls, 0);
  15545. }
  15546. // A verifier replaced while a handshake runs it lives until it returns.
  15547. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15548. using namespace httplib::tls;
  15549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15550. ASSERT_TRUE(svr.is_valid());
  15551. svr.Get("/test", [](const Request &, Response &res) {
  15552. res.set_content("ok", "text/plain");
  15553. });
  15554. auto port = svr.bind_to_any_port(HOST);
  15555. thread t([&]() { svr.listen_after_bind(); });
  15556. auto se = detail::scope_exit([&] {
  15557. svr.stop();
  15558. t.join();
  15559. });
  15560. svr.wait_until_ready();
  15561. SSLClient cli(HOST, port);
  15562. cli.enable_server_certificate_verification(false);
  15563. std::promise<void> entered;
  15564. std::promise<void> replaced;
  15565. auto replaced_future = replaced.get_future();
  15566. auto first_call = true;
  15567. // Long enough to live on the heap
  15568. std::string expected(64, 'v');
  15569. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15570. if (first_call) {
  15571. first_call = false;
  15572. entered.set_value();
  15573. replaced_future.wait();
  15574. }
  15575. return expected == std::string(64, 'v');
  15576. });
  15577. thread request([&]() {
  15578. auto res = cli.Get("/test");
  15579. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15580. });
  15581. entered.get_future().wait();
  15582. cli.set_server_certificate_verifier(
  15583. [](const VerifyContext &) { return true; });
  15584. replaced.set_value();
  15585. request.join();
  15586. }
  15587. // VerifyContext::session is the same handle the other tls:: functions take.
  15588. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15589. using namespace httplib::tls;
  15590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15591. ASSERT_TRUE(svr.is_valid());
  15592. svr.Get("/test", [](const Request &, Response &res) {
  15593. res.set_content("ok", "text/plain");
  15594. });
  15595. auto port = svr.bind_to_any_port(HOST);
  15596. thread t([&]() { svr.listen_after_bind(); });
  15597. auto se = detail::scope_exit([&] {
  15598. svr.stop();
  15599. t.join();
  15600. });
  15601. svr.wait_until_ready();
  15602. SSLClient cli(HOST, port);
  15603. cli.enable_server_certificate_verification(false);
  15604. session_t verifier_session = nullptr;
  15605. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15606. verifier_session = ctx.session;
  15607. return true;
  15608. });
  15609. session_t session_verifier_session = nullptr;
  15610. cli.set_session_verifier([&](session_t session) {
  15611. session_verifier_session = session;
  15612. return SSLVerifierResponse::NoDecisionMade;
  15613. });
  15614. auto res = cli.Get("/test");
  15615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15616. EXPECT_NE(nullptr, verifier_session);
  15617. EXPECT_EQ(session_verifier_session, verifier_session);
  15618. }
  15619. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15620. using httplib::tls::TlsError;
  15621. // Test that verify_error_to_string returns empty for success
  15622. std::string success_str = TlsError::verify_error_to_string(0);
  15623. EXPECT_TRUE(success_str.empty());
  15624. // Test that verify_error_to_string returns non-empty for error codes
  15625. // Using a common error code (certificate expired)
  15626. std::string error_str =
  15627. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15628. EXPECT_FALSE(error_str.empty());
  15629. }
  15630. TEST(SessionVerifierTest, CertificateAccepted) {
  15631. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15632. ASSERT_TRUE(svr.is_valid());
  15633. svr.Get("/test", [](const Request &, Response &res) {
  15634. res.set_content("ok", "text/plain");
  15635. });
  15636. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15637. auto se = detail::scope_exit([&] {
  15638. svr.stop();
  15639. t.join();
  15640. });
  15641. svr.wait_until_ready();
  15642. SSLClient cli(HOST, PORT);
  15643. cli.enable_server_certificate_verification(false);
  15644. cli.set_connection_timeout(30);
  15645. bool callback_called = false;
  15646. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15647. EXPECT_NE(session, nullptr);
  15648. callback_called = true;
  15649. return SSLVerifierResponse::CertificateAccepted;
  15650. });
  15651. auto res = cli.Get("/test");
  15652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15653. EXPECT_EQ(200, res->status);
  15654. EXPECT_TRUE(callback_called);
  15655. }
  15656. TEST(SessionVerifierTest, CertificateRejected) {
  15657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15658. ASSERT_TRUE(svr.is_valid());
  15659. svr.Get("/test", [](const Request &, Response &res) {
  15660. res.set_content("ok", "text/plain");
  15661. });
  15662. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15663. auto se = detail::scope_exit([&] {
  15664. svr.stop();
  15665. t.join();
  15666. });
  15667. svr.wait_until_ready();
  15668. SSLClient cli(HOST, PORT);
  15669. cli.enable_server_certificate_verification(false);
  15670. cli.set_connection_timeout(30);
  15671. bool callback_called = false;
  15672. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15673. EXPECT_NE(session, nullptr);
  15674. callback_called = true;
  15675. return SSLVerifierResponse::CertificateRejected;
  15676. });
  15677. auto res = cli.Get("/test");
  15678. EXPECT_FALSE(res);
  15679. EXPECT_TRUE(callback_called);
  15680. }
  15681. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15683. ASSERT_TRUE(svr.is_valid());
  15684. svr.Get("/test", [](const Request &, Response &res) {
  15685. res.set_content("ok", "text/plain");
  15686. });
  15687. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15688. auto se = detail::scope_exit([&] {
  15689. svr.stop();
  15690. t.join();
  15691. });
  15692. svr.wait_until_ready();
  15693. // NoDecisionMade with verification disabled should succeed (no default check)
  15694. SSLClient cli(HOST, PORT);
  15695. cli.enable_server_certificate_verification(false);
  15696. cli.set_connection_timeout(30);
  15697. bool callback_called = false;
  15698. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15699. EXPECT_NE(session, nullptr);
  15700. callback_called = true;
  15701. return SSLVerifierResponse::NoDecisionMade;
  15702. });
  15703. auto res = cli.Get("/test");
  15704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15705. EXPECT_EQ(200, res->status);
  15706. EXPECT_TRUE(callback_called);
  15707. }
  15708. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15710. ASSERT_TRUE(svr.is_valid());
  15711. svr.Get("/test", [](const Request &, Response &res) {
  15712. res.set_content("ok", "text/plain");
  15713. });
  15714. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15715. auto se = detail::scope_exit([&] {
  15716. svr.stop();
  15717. t.join();
  15718. });
  15719. svr.wait_until_ready();
  15720. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15721. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15722. // so we only check that the request fails, not whether the callback was
  15723. // called.
  15724. SSLClient cli(HOST, PORT);
  15725. cli.enable_server_certificate_verification(true);
  15726. cli.set_connection_timeout(30);
  15727. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15728. EXPECT_NE(session, nullptr);
  15729. return SSLVerifierResponse::NoDecisionMade;
  15730. });
  15731. auto res = cli.Get("/test");
  15732. EXPECT_FALSE(res);
  15733. }
  15734. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15735. // Test SSL server using PemMemory constructor with client CA certificates
  15736. // Read PEM files
  15737. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15738. read_file(SERVER_CERT_FILE, server_cert_pem);
  15739. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15740. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15741. // Create SSLServer with PemMemory constructor including client CA
  15742. SSLServer::PemMemory server_pem = {
  15743. server_cert_pem.c_str(),
  15744. server_cert_pem.size(),
  15745. server_key_pem.c_str(),
  15746. server_key_pem.size(),
  15747. client_ca_pem.c_str(),
  15748. client_ca_pem.size(),
  15749. nullptr // no password for server key
  15750. };
  15751. SSLServer svr(server_pem);
  15752. ASSERT_TRUE(svr.is_valid());
  15753. // No SSL error should be recorded for valid setup
  15754. EXPECT_EQ(0, svr.ssl_last_error());
  15755. // Set up server endpoints
  15756. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15757. res.set_content("ok", "text/plain");
  15758. });
  15759. // Start server in a thread
  15760. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15761. svr.wait_until_ready();
  15762. // Connect with client certificate (using constructor with paths)
  15763. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15764. cli.enable_server_certificate_verification(false);
  15765. auto res = cli.Get("/test-pem-ca");
  15766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15767. EXPECT_EQ(200, res->status);
  15768. EXPECT_EQ("ok", res->body);
  15769. svr.stop();
  15770. server_thread.join();
  15771. }
  15772. #endif
  15773. #ifdef _WIN32
  15774. TEST(CleanupTest, WSACleanup) {
  15775. int ret = WSACleanup();
  15776. ASSERT_EQ(0, ret);
  15777. }
  15778. #endif
  15779. #ifndef CPPHTTPLIB_SSL_ENABLED
  15780. TEST(NoSSLSupport, SimpleInterface) {
  15781. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15782. }
  15783. #endif
  15784. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15785. TEST(InvalidScheme, SimpleInterface) {
  15786. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15787. }
  15788. #endif
  15789. TEST(NoScheme, SimpleInterface) {
  15790. Client cli("yahoo.com:80");
  15791. ASSERT_TRUE(cli.is_valid());
  15792. }
  15793. TEST(SendAPI, SimpleInterface_Online) {
  15794. Client cli("http://yahoo.com");
  15795. Request req;
  15796. req.method = "GET";
  15797. req.path = "/";
  15798. auto res = cli.send(req);
  15799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15800. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15801. }
  15802. TEST(SendAPI, WithParamsInRequest) {
  15803. Server svr;
  15804. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15805. EXPECT_TRUE(req.has_param("test"));
  15806. EXPECT_EQ("test_value", req.get_param_value("test"));
  15807. });
  15808. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15809. auto se = detail::scope_exit([&] {
  15810. svr.stop();
  15811. t.join();
  15812. ASSERT_FALSE(svr.is_running());
  15813. });
  15814. svr.wait_until_ready();
  15815. Client cli(HOST, PORT);
  15816. {
  15817. Request req;
  15818. req.method = "GET";
  15819. req.path = "/";
  15820. req.params.emplace("test", "test_value");
  15821. auto res = cli.send(req);
  15822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15823. }
  15824. {
  15825. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15827. }
  15828. }
  15829. TEST(ClientImplMethods, GetSocketTest) {
  15830. httplib::Server svr;
  15831. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15832. res.status = StatusCode::OK_200;
  15833. });
  15834. auto port = svr.bind_to_any_port("127.0.0.1");
  15835. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15836. auto se = detail::scope_exit([&] {
  15837. svr.stop();
  15838. thread.join();
  15839. ASSERT_FALSE(svr.is_running());
  15840. });
  15841. svr.wait_until_ready();
  15842. {
  15843. httplib::Client cli("127.0.0.1", port);
  15844. cli.set_keep_alive(true);
  15845. // Use the behavior of cpp-httplib of opening the connection
  15846. // only when the first request happens. If that changes,
  15847. // this test would be obsolete.
  15848. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15849. // This also implicitly tests the server. But other tests would fail much
  15850. // earlier than this one to be considered.
  15851. auto res = cli.Get("/");
  15852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15853. EXPECT_EQ(StatusCode::OK_200, res->status);
  15854. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15855. }
  15856. }
  15857. #ifdef CPPHTTPLIB_SSL_ENABLED
  15858. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15859. Client cli("http://yahoo.com");
  15860. auto res = cli.Get("/");
  15861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15862. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15863. cli.set_follow_location(true);
  15864. res = cli.Get("/");
  15865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15866. EXPECT_EQ(StatusCode::OK_200, res->status);
  15867. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15868. }
  15869. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15870. Client cli("https://yahoo.com");
  15871. auto res = cli.Get("/");
  15872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15873. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15874. cli.set_follow_location(true);
  15875. res = cli.Get("/");
  15876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15877. EXPECT_EQ(StatusCode::OK_200, res->status);
  15878. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15879. }
  15880. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15881. Client cli("https://yahoo.com");
  15882. auto res = cli.Get("/");
  15883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15884. ASSERT_FALSE(!res);
  15885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15886. ASSERT_FALSE(res == nullptr);
  15887. ASSERT_TRUE(res != nullptr);
  15888. EXPECT_EQ(Error::Success, res.error());
  15889. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15890. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15891. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15892. cli.set_follow_location(true);
  15893. res = cli.Get("/");
  15894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15895. EXPECT_EQ(Error::Success, res.error());
  15896. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15897. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15898. EXPECT_EQ(StatusCode::OK_200, res->status);
  15899. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15900. }
  15901. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15902. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15903. Client cli("https://cdnjs.cloudflare.com");
  15904. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15905. Headers{{"Accept-Encoding", "br"}});
  15906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15907. EXPECT_EQ(StatusCode::OK_200, res->status);
  15908. EXPECT_EQ(287630U, res->body.size());
  15909. EXPECT_EQ("application/javascript; charset=utf-8",
  15910. res->get_header_value("Content-Type"));
  15911. }
  15912. #endif
  15913. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15914. #undef REDIR_HOST // Silence compiler warning
  15915. #define REDIR_HOST "https://httpbingo.org"
  15916. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15917. Client cli(REDIR_HOST);
  15918. cli.set_follow_location(true);
  15919. auto res = retry_service_failures([&] {
  15920. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15921. });
  15922. SKIP_ON_SERVICE_FAILURE(res);
  15923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15924. EXPECT_EQ(StatusCode::OK_200, res->status);
  15925. }
  15926. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15927. Client cli(REDIR_HOST);
  15928. cli.set_follow_location(true);
  15929. Params params;
  15930. params.emplace("url", "http://example.com");
  15931. params.emplace("status_code", "302");
  15932. auto res = retry_service_failures(
  15933. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  15934. SKIP_ON_SERVICE_FAILURE(res);
  15935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15936. EXPECT_EQ(StatusCode::OK_200, res->status);
  15937. }
  15938. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15939. Client cli(REDIR_HOST);
  15940. cli.set_follow_location(true);
  15941. Params params;
  15942. params.emplace("url", "http://example.com");
  15943. auto res = retry_service_failures([&] {
  15944. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15945. });
  15946. SKIP_ON_SERVICE_FAILURE(res);
  15947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15948. EXPECT_EQ(StatusCode::OK_200, res->status);
  15949. }
  15950. TEST(HttpToHttpsRedirectTest, CertFile) {
  15951. auto ssl_port = PORT + 1;
  15952. Server svr;
  15953. ASSERT_TRUE(svr.is_valid());
  15954. svr.Get("/index", [&](const Request &, Response &res) {
  15955. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15956. "/index");
  15957. svr.stop();
  15958. });
  15959. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15960. ASSERT_TRUE(ssl_svr.is_valid());
  15961. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15962. res.set_content("test", "text/plain");
  15963. ssl_svr.stop();
  15964. });
  15965. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15966. thread t2 =
  15967. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15968. auto se = detail::scope_exit([&] {
  15969. t2.join();
  15970. t.join();
  15971. ASSERT_FALSE(svr.is_running());
  15972. });
  15973. svr.wait_until_ready();
  15974. ssl_svr.wait_until_ready();
  15975. Client cli("127.0.0.1", PORT);
  15976. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15977. cli.enable_server_certificate_verification(true);
  15978. cli.set_follow_location(true);
  15979. cli.set_connection_timeout(30);
  15980. auto res = cli.Get("/index");
  15981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15982. ASSERT_EQ(StatusCode::OK_200, res->status);
  15983. }
  15984. TEST(UppercaseSchemeTest, UsesTLS) {
  15985. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15986. ASSERT_TRUE(ssl_svr.is_valid());
  15987. ssl_svr.Get("/index", [](const Request &, Response &res) {
  15988. res.set_content("test", "text/plain");
  15989. });
  15990. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  15991. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  15992. Server svr;
  15993. svr.Get("/index", [&](const Request &, Response &res) {
  15994. res.set_redirect(https_url + "/index");
  15995. });
  15996. auto port = svr.bind_to_any_port("127.0.0.1");
  15997. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  15998. auto t2 = thread([&] { svr.listen_after_bind(); });
  15999. auto se = detail::scope_exit([&] {
  16000. svr.stop();
  16001. ssl_svr.stop();
  16002. t2.join();
  16003. t.join();
  16004. });
  16005. ssl_svr.wait_until_ready();
  16006. svr.wait_until_ready();
  16007. {
  16008. Client cli(https_url);
  16009. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16010. auto res = cli.Get("/index");
  16011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16012. EXPECT_EQ("test", res->body);
  16013. }
  16014. {
  16015. Client cli("127.0.0.1", port);
  16016. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16017. cli.set_follow_location(true);
  16018. auto res = cli.Get("/index");
  16019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16020. EXPECT_EQ("test", res->body);
  16021. }
  16022. }
  16023. TEST(SSLClientRedirectTest, CertFile) {
  16024. auto ssl_port = PORT + 1;
  16025. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16026. ASSERT_TRUE(ssl_svr1.is_valid());
  16027. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16028. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16029. "/index");
  16030. ssl_svr1.stop();
  16031. });
  16032. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16033. ASSERT_TRUE(ssl_svr2.is_valid());
  16034. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16035. res.set_content("test", "text/plain");
  16036. ssl_svr2.stop();
  16037. });
  16038. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16039. thread t2 =
  16040. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16041. auto se = detail::scope_exit([&] {
  16042. t2.join();
  16043. t.join();
  16044. ASSERT_FALSE(ssl_svr1.is_running());
  16045. });
  16046. ssl_svr1.wait_until_ready();
  16047. ssl_svr2.wait_until_ready();
  16048. SSLClient cli("127.0.0.1", PORT);
  16049. std::string cert;
  16050. read_file(SERVER_CERT2_FILE, cert);
  16051. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16052. cli.enable_server_certificate_verification(true);
  16053. cli.set_follow_location(true);
  16054. cli.set_connection_timeout(30);
  16055. auto res = cli.Get("/index");
  16056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16057. ASSERT_EQ(StatusCode::OK_200, res->status);
  16058. }
  16059. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16060. // another port, so the client follows it with a new client.
  16061. static Result GetThroughTlsRedirectToDifferentPort(
  16062. const std::function<void(SSLClient &)> &setup,
  16063. const char *target_cert = SERVER_CERT2_FILE,
  16064. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16065. auto ssl_port = PORT + 1;
  16066. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16067. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16068. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16069. "/index");
  16070. });
  16071. SSLServer ssl_svr2(target_cert, target_key);
  16072. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16073. res.set_content("test", "text/plain");
  16074. });
  16075. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16076. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16077. auto se = detail::scope_exit([&] {
  16078. ssl_svr2.stop();
  16079. ssl_svr1.stop();
  16080. t2.join();
  16081. t.join();
  16082. });
  16083. ssl_svr1.wait_until_ready();
  16084. ssl_svr2.wait_until_ready();
  16085. SSLClient cli("127.0.0.1", PORT);
  16086. cli.set_follow_location(true);
  16087. cli.set_connection_timeout(30);
  16088. setup(cli);
  16089. return cli.Get("/index");
  16090. }
  16091. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16092. auto calls = 0;
  16093. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16094. cli.enable_server_certificate_verification(false);
  16095. // Accept the first server only.
  16096. cli.set_session_verifier([&](tls::session_t) {
  16097. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16098. : SSLVerifierResponse::CertificateRejected;
  16099. });
  16100. });
  16101. ASSERT_FALSE(res);
  16102. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16103. EXPECT_EQ(2, calls);
  16104. }
  16105. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16106. std::string pinned;
  16107. auto res = GetThroughTlsRedirectToDifferentPort(
  16108. [&](SSLClient &cli) {
  16109. cli.enable_server_certificate_verification(false);
  16110. // Pin the first certificate seen.
  16111. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16112. if (pinned.empty()) { pinned = ctx.serial(); }
  16113. return ctx.serial() == pinned;
  16114. });
  16115. },
  16116. // A certificate other than the first server's.
  16117. SERVER_CERT_FILE);
  16118. EXPECT_FALSE(res);
  16119. EXPECT_FALSE(pinned.empty());
  16120. }
  16121. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16122. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16123. std::string cert;
  16124. read_file(SERVER_CERT2_FILE, cert);
  16125. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16126. });
  16127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16128. EXPECT_EQ(StatusCode::OK_200, res->status);
  16129. }
  16130. // The target's certificate is signed by the root CA, which the first server's
  16131. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16132. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16133. auto res = GetThroughTlsRedirectToDifferentPort(
  16134. [](SSLClient &cli) {
  16135. std::string root_ca, cert;
  16136. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16137. read_file(SERVER_CERT2_FILE, cert);
  16138. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16139. cli.load_ca_cert_store(cert.data(), cert.size());
  16140. cli.enable_server_hostname_verification(false);
  16141. },
  16142. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16144. EXPECT_EQ(StatusCode::OK_200, res->status);
  16145. }
  16146. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16147. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16148. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16149. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16150. auto res = GetThroughTlsRedirectToDifferentPort(
  16151. [](SSLClient &cli) {
  16152. std::string root_ca, cert;
  16153. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16154. read_file(SERVER_CERT2_FILE, cert);
  16155. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16156. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16157. cli.enable_server_hostname_verification(false);
  16158. },
  16159. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16160. ASSERT_FALSE(res);
  16161. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16162. }
  16163. #endif
  16164. #endif
  16165. #ifdef CPPHTTPLIB_SSL_ENABLED
  16166. // Test that set_ca_cert_store() skips system certs (consistent with
  16167. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16168. // should be trusted - system certs should NOT be loaded.
  16169. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16170. // Load a specific cert that is NOT a system CA cert
  16171. std::string cert;
  16172. read_file(SERVER_CERT2_FILE, cert);
  16173. SSLClient cli("google.com");
  16174. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16175. cli.enable_server_certificate_verification(true);
  16176. // This should FAIL because:
  16177. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16178. // 2. System certs should NOT be loaded when custom store is set
  16179. // If system certs WERE loaded, this would succeed
  16180. auto res = cli.Get("/");
  16181. ASSERT_FALSE(res);
  16182. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16183. }
  16184. // Same as above, but through the native store handle path. Regression test:
  16185. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16186. // merged system certs into the user-provided store.
  16187. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16188. std::string cert;
  16189. read_file(SERVER_CERT2_FILE, cert);
  16190. SSLClient cli("google.com");
  16191. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16192. cli.enable_server_certificate_verification(true);
  16193. auto res = cli.Get("/");
  16194. ASSERT_FALSE(res);
  16195. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16196. }
  16197. // A custom store set via the native handle must still verify a server whose
  16198. // cert it does contain.
  16199. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16200. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16201. ASSERT_TRUE(svr.is_valid());
  16202. svr.Get("/test", [&](const Request &, Response &res) {
  16203. res.set_content("test", "text/plain");
  16204. });
  16205. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16206. auto se = detail::scope_exit([&] {
  16207. svr.stop();
  16208. t.join();
  16209. ASSERT_FALSE(svr.is_running());
  16210. });
  16211. svr.wait_until_ready();
  16212. SSLClient cli("127.0.0.1", PORT);
  16213. std::string cert;
  16214. read_file(SERVER_CERT2_FILE, cert);
  16215. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16216. cli.enable_server_certificate_verification(true);
  16217. cli.set_connection_timeout(30);
  16218. auto res = cli.Get("/test");
  16219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16220. ASSERT_EQ(StatusCode::OK_200, res->status);
  16221. }
  16222. // CA certs loaded through the universal Client must be transferred to the
  16223. // client created internally for following an HTTPS redirect. Regression test:
  16224. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16225. // the CA data for redirect transfer.
  16226. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16227. auto ssl_port = PORT + 1;
  16228. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16229. ASSERT_TRUE(ssl_svr1.is_valid());
  16230. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16231. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16232. "/index");
  16233. });
  16234. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16235. ASSERT_TRUE(ssl_svr2.is_valid());
  16236. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16237. res.set_content("test", "text/plain");
  16238. });
  16239. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16240. thread t2 =
  16241. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16242. auto se = detail::scope_exit([&] {
  16243. ssl_svr2.stop();
  16244. ssl_svr1.stop();
  16245. t2.join();
  16246. t.join();
  16247. ASSERT_FALSE(ssl_svr1.is_running());
  16248. });
  16249. ssl_svr1.wait_until_ready();
  16250. ssl_svr2.wait_until_ready();
  16251. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16252. std::string cert;
  16253. read_file(SERVER_CERT2_FILE, cert);
  16254. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16255. cli.enable_server_certificate_verification(true);
  16256. cli.set_follow_location(true);
  16257. cli.set_connection_timeout(30);
  16258. auto res = cli.Get("/index");
  16259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16260. ASSERT_EQ(StatusCode::OK_200, res->status);
  16261. }
  16262. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16263. // so a host signed by a system CA verifies even though a custom CA is set
  16264. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16265. std::string cert;
  16266. read_file(SERVER_CERT2_FILE, cert);
  16267. SSLClient cli("google.com");
  16268. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16269. cli.enable_system_ca(true);
  16270. cli.enable_server_certificate_verification(true);
  16271. auto res = cli.Get("/");
  16272. // Any status: Google may redirect or rate-limit CI runners.
  16273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16274. }
  16275. // The custom CA remains effective when combined with the system CA
  16276. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16277. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16278. ASSERT_TRUE(svr.is_valid());
  16279. svr.Get("/test", [&](const Request &, Response &res) {
  16280. res.set_content("test", "text/plain");
  16281. });
  16282. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16283. auto se = detail::scope_exit([&] {
  16284. svr.stop();
  16285. t.join();
  16286. ASSERT_FALSE(svr.is_running());
  16287. });
  16288. svr.wait_until_ready();
  16289. SSLClient cli("127.0.0.1", PORT);
  16290. std::string cert;
  16291. read_file(SERVER_CERT2_FILE, cert);
  16292. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16293. cli.enable_system_ca(true);
  16294. cli.enable_server_certificate_verification(true);
  16295. cli.set_connection_timeout(30);
  16296. auto res = cli.Get("/test");
  16297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16298. ASSERT_EQ(StatusCode::OK_200, res->status);
  16299. }
  16300. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16301. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16302. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16303. static CFDictionaryRef
  16304. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16305. const SecTrustSettingsResult *result) {
  16306. auto constraint =
  16307. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16308. &kCFTypeDictionaryValueCallBacks);
  16309. if (policy) {
  16310. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16311. }
  16312. if (policy_string) {
  16313. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16314. kCFStringEncodingUTF8);
  16315. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16316. CFRelease(str);
  16317. }
  16318. if (result) {
  16319. auto number_value = static_cast<SInt32>(*result);
  16320. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16321. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16322. CFRelease(number);
  16323. }
  16324. return constraint;
  16325. }
  16326. static SecTrustSettingsResult
  16327. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16328. auto trust_settings =
  16329. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16330. for (auto constraint : constraints) {
  16331. CFArrayAppendValue(trust_settings, constraint);
  16332. CFRelease(constraint);
  16333. }
  16334. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16335. CFRelease(trust_settings);
  16336. return result;
  16337. }
  16338. // The system CA loader takes a Keychain certificate as a trusted root only
  16339. // when its Trust Settings say so for SSL, not merely because it has some.
  16340. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16341. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16342. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16343. const auto deny = kSecTrustSettingsResultDeny;
  16344. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16345. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16346. auto x509_policy = SecPolicyCreateBasicX509();
  16347. // "Always Trust", which stores no constraint at all
  16348. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16349. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16350. ssl_trust_settings_result(
  16351. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16352. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16353. ssl_trust_settings_result(
  16354. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16355. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16356. ssl_trust_settings_result(
  16357. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16358. // "Never Trust", for everything or for SSL
  16359. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16360. ssl_trust_settings_result(
  16361. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16362. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16363. ssl_trust_settings_result(
  16364. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16365. // Trusted for another policy, for one host, or not at all
  16366. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16367. ssl_trust_settings_result(
  16368. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16369. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16370. ssl_trust_settings_result({make_usage_constraint(
  16371. ssl_policy, "www.example.com", &trust_root)}));
  16372. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16373. ssl_trust_settings_result(
  16374. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16375. // The first constraint that applies to SSL decides
  16376. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16377. ssl_trust_settings_result(
  16378. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16379. make_usage_constraint(nullptr, nullptr, &deny)}));
  16380. CFRelease(x509_policy);
  16381. CFRelease(ssl_policy);
  16382. }
  16383. #endif
  16384. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16385. // skip chain verification entirely (only the certificate identity was
  16386. // checked), so a server presenting an untrusted certificate with a matching
  16387. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16388. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16389. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16390. ASSERT_TRUE(svr.is_valid());
  16391. svr.Get("/test", [&](const Request &, Response &res) {
  16392. res.set_content("test", "text/plain");
  16393. });
  16394. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16395. auto se = detail::scope_exit([&] {
  16396. svr.stop();
  16397. t.join();
  16398. ASSERT_FALSE(svr.is_running());
  16399. });
  16400. svr.wait_until_ready();
  16401. SSLClient cli("127.0.0.1", PORT);
  16402. std::string cert;
  16403. // A trusted CA that did not sign the server certificate. The server cert
  16404. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16405. // this connection.
  16406. read_file(CLIENT_CA_CERT_FILE, cert);
  16407. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16408. cli.enable_server_certificate_verification(true);
  16409. cli.set_connection_timeout(30);
  16410. auto res = cli.Get("/test");
  16411. ASSERT_FALSE(res);
  16412. }
  16413. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16414. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16415. // CA that failed to come through fails verification instead of trusting them.
  16416. // (wolfSSL does not list the system CAs it loaded.)
  16417. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16418. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16419. ASSERT_TRUE(svr.is_valid());
  16420. auto port = svr.bind_to_any_port("127.0.0.1");
  16421. ASSERT_LT(0, port);
  16422. thread t = thread([&] { svr.listen_after_bind(); });
  16423. auto se = detail::scope_exit([&] {
  16424. svr.stop();
  16425. t.join();
  16426. ASSERT_FALSE(svr.is_running());
  16427. });
  16428. svr.wait_until_ready();
  16429. // The CAs a client trusts once its first request has loaded them
  16430. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16431. Client cli("https://127.0.0.1:" + std::to_string(port));
  16432. setup(cli);
  16433. cli.Get("/");
  16434. return tls::get_ca_names(cli.tls_context()).size();
  16435. };
  16436. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16437. EXPECT_EQ(0u,
  16438. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16439. }
  16440. #endif
  16441. // A TLS setting changed between requests applies to the next one, not just to
  16442. // the next connection
  16443. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16444. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16445. ASSERT_TRUE(svr.is_valid());
  16446. svr.Get("/", [](const Request &req, Response &res) {
  16447. res.set_content(std::to_string(req.remote_port), "text/plain");
  16448. });
  16449. auto port = svr.bind_to_any_port("127.0.0.1");
  16450. ASSERT_LT(0, port);
  16451. thread t = thread([&] { svr.listen_after_bind(); });
  16452. auto se = detail::scope_exit([&] {
  16453. svr.stop();
  16454. t.join();
  16455. ASSERT_FALSE(svr.is_running());
  16456. });
  16457. svr.wait_until_ready();
  16458. SSLClient cli("127.0.0.1", port);
  16459. cli.set_keep_alive(true);
  16460. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16461. cli.enable_server_certificate_verification(false);
  16462. // The port the request went out from, so a new one means a new connection
  16463. auto client_port = [&] {
  16464. auto res = cli.Get("/");
  16465. return res ? res->body : std::string();
  16466. };
  16467. auto last = client_port();
  16468. ASSERT_FALSE(last.empty());
  16469. // Setting a value it already has keeps the connection
  16470. cli.enable_server_certificate_verification(false);
  16471. cli.enable_server_hostname_verification(true);
  16472. EXPECT_EQ(last, client_port());
  16473. cli.enable_server_certificate_verification(true);
  16474. auto res = cli.Get("/");
  16475. EXPECT_FALSE(res);
  16476. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16477. std::string ca;
  16478. read_file(SERVER_CERT2_FILE, ca);
  16479. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16480. last = client_port();
  16481. ASSERT_FALSE(last.empty());
  16482. std::vector<std::function<void()>> setters = {
  16483. [&] { cli.enable_server_hostname_verification(false); },
  16484. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16485. [&] {
  16486. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16487. },
  16488. [&] {
  16489. cli.set_server_certificate_verifier(
  16490. [](const tls::VerifyContext &) { return true; });
  16491. },
  16492. [&] {
  16493. cli.set_session_verifier(
  16494. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16495. },
  16496. };
  16497. for (const auto &setter : setters) {
  16498. setter();
  16499. auto next = client_port();
  16500. ASSERT_FALSE(next.empty());
  16501. EXPECT_NE(last, next);
  16502. last = next;
  16503. }
  16504. cli.set_session_verifier(
  16505. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16506. auto handle = cli.open_stream("GET", "/");
  16507. EXPECT_FALSE(handle.is_valid());
  16508. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16509. }
  16510. // A PEM given to create_ca_store() needs no NUL after it
  16511. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16512. std::string pem;
  16513. read_file(SERVER_CERT2_FILE, pem);
  16514. auto buf = pem + "X";
  16515. auto store = tls::create_ca_store(buf.data(), pem.size());
  16516. EXPECT_TRUE(store != nullptr);
  16517. SSLClient cli("localhost");
  16518. cli.set_ca_cert_store(store);
  16519. }
  16520. // enable_system_ca(false) prevents system CA loading entirely
  16521. TEST(SSLClientTest, DisableSystemCa_Online) {
  16522. SSLClient cli("google.com");
  16523. cli.enable_system_ca(false);
  16524. cli.enable_server_certificate_verification(true);
  16525. auto res = cli.Get("/");
  16526. ASSERT_FALSE(res);
  16527. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16528. // itself when the CA chain is empty
  16529. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16530. res.error() == Error::SSLConnection);
  16531. }
  16532. // The universal Client forwards enable_system_ca()
  16533. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16534. std::string cert;
  16535. read_file(SERVER_CERT2_FILE, cert);
  16536. Client cli("https://google.com");
  16537. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16538. cli.enable_system_ca(true);
  16539. cli.enable_server_certificate_verification(true);
  16540. auto res = cli.Get("/");
  16541. // Any status: Google may redirect or rate-limit CI runners.
  16542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16543. }
  16544. // The system CA policy must carry over to the client created internally for
  16545. // following a cross-host HTTPS redirect
  16546. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16547. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16548. ASSERT_TRUE(svr.is_valid());
  16549. svr.Get("/index", [&](const Request &, Response &res) {
  16550. res.set_redirect("https://www.google.com/");
  16551. });
  16552. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16553. auto se = detail::scope_exit([&] {
  16554. svr.stop();
  16555. t.join();
  16556. ASSERT_FALSE(svr.is_running());
  16557. });
  16558. svr.wait_until_ready();
  16559. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16560. std::string cert;
  16561. read_file(SERVER_CERT2_FILE, cert);
  16562. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16563. cli.enable_system_ca(true);
  16564. cli.enable_server_certificate_verification(true);
  16565. cli.set_follow_location(true);
  16566. cli.set_connection_timeout(30);
  16567. // Receiving any response proves the redirect client completed the TLS
  16568. // handshake with a system-CA-signed host
  16569. auto res = cli.Get("/index");
  16570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16571. }
  16572. TEST(MultipartFormDataTest, LargeData) {
  16573. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16574. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16575. const ContentReader &content_reader) {
  16576. if (req.is_multipart_form_data()) {
  16577. std::vector<FormData> items;
  16578. content_reader(
  16579. [&](const FormData &file) {
  16580. items.push_back(file);
  16581. return true;
  16582. },
  16583. [&](const char *data, size_t data_length) {
  16584. items.back().content.append(data, data_length);
  16585. return true;
  16586. });
  16587. EXPECT_TRUE(std::string(items[0].name) == "document");
  16588. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16589. EXPECT_TRUE(items[0].filename == "2MB_data");
  16590. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16591. EXPECT_TRUE(items[1].name == "hello");
  16592. EXPECT_TRUE(items[1].content == "world");
  16593. EXPECT_TRUE(items[1].filename == "");
  16594. EXPECT_TRUE(items[1].content_type == "");
  16595. } else {
  16596. std::string body;
  16597. content_reader([&](const char *data, size_t data_length) {
  16598. body.append(data, data_length);
  16599. return true;
  16600. });
  16601. }
  16602. });
  16603. auto port = svr.bind_to_any_port(HOST);
  16604. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16605. auto se = detail::scope_exit([&] {
  16606. svr.stop();
  16607. t.join();
  16608. ASSERT_FALSE(svr.is_running());
  16609. });
  16610. svr.wait_until_ready();
  16611. {
  16612. std::string data(1024 * 1024 * 2, '.');
  16613. std::stringstream buffer;
  16614. buffer << data;
  16615. SSLClient cli(HOST, port);
  16616. cli.enable_server_certificate_verification(false);
  16617. UploadFormDataItems items{
  16618. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16619. {"hello", "world", "", ""},
  16620. };
  16621. auto res = cli.Post("/post", items);
  16622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16623. ASSERT_EQ(StatusCode::OK_200, res->status);
  16624. }
  16625. }
  16626. TEST(MultipartFormDataTest, DataProviderItems) {
  16627. std::random_device seed_gen;
  16628. std::mt19937 random(seed_gen());
  16629. std::string rand1;
  16630. rand1.resize(1000);
  16631. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16632. std::string rand2;
  16633. rand2.resize(3000);
  16634. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16636. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16637. const ContentReader &content_reader) {
  16638. ASSERT_FALSE(req.is_multipart_form_data());
  16639. std::string body;
  16640. content_reader([&](const char *data, size_t data_length) {
  16641. body.append(data, data_length);
  16642. return true;
  16643. });
  16644. EXPECT_EQ(body, "");
  16645. });
  16646. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16647. const ContentReader &content_reader) {
  16648. ASSERT_TRUE(req.is_multipart_form_data());
  16649. std::vector<FormData> items;
  16650. content_reader(
  16651. [&](const FormData &file) {
  16652. items.push_back(file);
  16653. return true;
  16654. },
  16655. [&](const char *data, size_t data_length) {
  16656. items.back().content.append(data, data_length);
  16657. return true;
  16658. });
  16659. ASSERT_TRUE(items.size() == 2);
  16660. EXPECT_EQ(std::string(items[0].name), "name1");
  16661. EXPECT_EQ(items[0].content, "Testing123");
  16662. EXPECT_EQ(items[0].filename, "filename1");
  16663. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16664. EXPECT_EQ(items[1].name, "name2");
  16665. EXPECT_EQ(items[1].content, "Testing456");
  16666. EXPECT_EQ(items[1].filename, "");
  16667. EXPECT_EQ(items[1].content_type, "");
  16668. });
  16669. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16670. const ContentReader &content_reader) {
  16671. ASSERT_TRUE(req.is_multipart_form_data());
  16672. std::vector<FormData> items;
  16673. content_reader(
  16674. [&](const FormData &file) {
  16675. items.push_back(file);
  16676. return true;
  16677. },
  16678. [&](const char *data, size_t data_length) {
  16679. items.back().content.append(data, data_length);
  16680. return true;
  16681. });
  16682. ASSERT_TRUE(items.size() == 2);
  16683. EXPECT_EQ(items[0].name, "name3");
  16684. EXPECT_EQ(items[0].content, rand1);
  16685. EXPECT_EQ(items[0].filename, "filename3");
  16686. EXPECT_EQ(items[0].content_type, "");
  16687. EXPECT_EQ(items[1].name, "name4");
  16688. EXPECT_EQ(items[1].content, rand2);
  16689. EXPECT_EQ(items[1].filename, "filename4");
  16690. EXPECT_EQ(items[1].content_type, "");
  16691. });
  16692. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16693. const ContentReader &content_reader) {
  16694. ASSERT_TRUE(req.is_multipart_form_data());
  16695. std::vector<FormData> items;
  16696. content_reader(
  16697. [&](const FormData &file) {
  16698. items.push_back(file);
  16699. return true;
  16700. },
  16701. [&](const char *data, size_t data_length) {
  16702. items.back().content.append(data, data_length);
  16703. return true;
  16704. });
  16705. ASSERT_TRUE(items.size() == 4);
  16706. EXPECT_EQ(std::string(items[0].name), "name1");
  16707. EXPECT_EQ(items[0].content, "Testing123");
  16708. EXPECT_EQ(items[0].filename, "filename1");
  16709. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16710. EXPECT_EQ(items[1].name, "name2");
  16711. EXPECT_EQ(items[1].content, "Testing456");
  16712. EXPECT_EQ(items[1].filename, "");
  16713. EXPECT_EQ(items[1].content_type, "");
  16714. EXPECT_EQ(items[2].name, "name3");
  16715. EXPECT_EQ(items[2].content, rand1);
  16716. EXPECT_EQ(items[2].filename, "filename3");
  16717. EXPECT_EQ(items[2].content_type, "");
  16718. EXPECT_EQ(items[3].name, "name4");
  16719. EXPECT_EQ(items[3].content, rand2);
  16720. EXPECT_EQ(items[3].filename, "filename4");
  16721. EXPECT_EQ(items[3].content_type, "");
  16722. });
  16723. auto port = svr.bind_to_any_port("localhost");
  16724. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16725. auto se = detail::scope_exit([&] {
  16726. svr.stop();
  16727. t.join();
  16728. ASSERT_FALSE(svr.is_running());
  16729. });
  16730. svr.wait_until_ready();
  16731. {
  16732. SSLClient cli("localhost", port);
  16733. cli.enable_server_certificate_verification(false);
  16734. UploadFormDataItems items{
  16735. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16736. {"name2", "Testing456", "", ""}, // not a file
  16737. };
  16738. {
  16739. auto res = cli.Post("/post-none", {}, {}, {});
  16740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16741. ASSERT_EQ(StatusCode::OK_200, res->status);
  16742. }
  16743. FormDataProviderItems providers;
  16744. {
  16745. auto res =
  16746. cli.Post("/post-items", {}, items, providers); // empty providers
  16747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16748. ASSERT_EQ(StatusCode::OK_200, res->status);
  16749. }
  16750. providers.push_back({"name3",
  16751. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16752. // test the offset is given correctly at each step
  16753. if (!offset)
  16754. sink.os.write(rand1.data(), 30);
  16755. else if (offset == 30)
  16756. sink.os.write(rand1.data() + 30, 300);
  16757. else if (offset == 330)
  16758. sink.os.write(rand1.data() + 330, 670);
  16759. else if (offset == rand1.size())
  16760. sink.done();
  16761. return true;
  16762. },
  16763. "filename3",
  16764. {}});
  16765. providers.push_back({"name4",
  16766. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16767. // test the offset is given correctly at each step
  16768. if (!offset)
  16769. sink.os.write(rand2.data(), 2000);
  16770. else if (offset == 2000)
  16771. sink.os.write(rand2.data() + 2000, 1);
  16772. else if (offset == 2001)
  16773. sink.os.write(rand2.data() + 2001, 999);
  16774. else if (offset == rand2.size())
  16775. sink.done();
  16776. return true;
  16777. },
  16778. "filename4",
  16779. {}});
  16780. {
  16781. auto res = cli.Post("/post-providers", {}, {}, providers);
  16782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16783. ASSERT_EQ(StatusCode::OK_200, res->status);
  16784. }
  16785. {
  16786. auto res = cli.Post("/post-both", {}, items, providers);
  16787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16788. ASSERT_EQ(StatusCode::OK_200, res->status);
  16789. }
  16790. }
  16791. }
  16792. TEST(MultipartFormDataTest, BadHeader) {
  16793. Server svr;
  16794. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16795. res.set_content("ok", "text/plain");
  16796. });
  16797. thread t = thread([&] { svr.listen(HOST, PORT); });
  16798. auto se = detail::scope_exit([&] {
  16799. svr.stop();
  16800. t.join();
  16801. ASSERT_FALSE(svr.is_running());
  16802. });
  16803. svr.wait_until_ready();
  16804. const std::string body =
  16805. "This is the preamble. It is to be ignored, though it\r\n"
  16806. "is a handy place for composition agents to include an\r\n"
  16807. "explanatory note to non-MIME conformant readers.\r\n"
  16808. "\r\n"
  16809. "\r\n"
  16810. "--simple boundary\r\n"
  16811. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16812. ": BAD...\r\n"
  16813. "\r\n"
  16814. "value1\r\n"
  16815. "--simple boundary\r\n"
  16816. "Content-Disposition: form-data; name=\"field2\"; "
  16817. "filename=\"example.txt\"\r\n"
  16818. "\r\n"
  16819. "value2\r\n"
  16820. "--simple boundary--\r\n"
  16821. "This is the epilogue. It is also to be ignored.\r\n";
  16822. std::string content_type =
  16823. R"(multipart/form-data; boundary="simple boundary")";
  16824. Client cli(HOST, PORT);
  16825. auto res = cli.Post("/post", body, content_type.c_str());
  16826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16827. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16828. }
  16829. TEST(MultipartFormDataTest, WithPreamble) {
  16830. Server svr;
  16831. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16832. res.set_content("ok", "text/plain");
  16833. });
  16834. thread t = thread([&] { svr.listen(HOST, PORT); });
  16835. auto se = detail::scope_exit([&] {
  16836. svr.stop();
  16837. t.join();
  16838. ASSERT_FALSE(svr.is_running());
  16839. });
  16840. svr.wait_until_ready();
  16841. const std::string body =
  16842. "This is the preamble. It is to be ignored, though it\r\n"
  16843. "is a handy place for composition agents to include an\r\n"
  16844. "explanatory note to non-MIME conformant readers.\r\n"
  16845. "\r\n"
  16846. "\r\n"
  16847. "--simple boundary\r\n"
  16848. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16849. "\r\n"
  16850. "value1\r\n"
  16851. "--simple boundary\r\n"
  16852. "Content-Disposition: form-data; name=\"field2\"; "
  16853. "filename=\"example.txt\"\r\n"
  16854. "\r\n"
  16855. "value2\r\n"
  16856. "--simple boundary--\r\n"
  16857. "This is the epilogue. It is also to be ignored.\r\n";
  16858. std::string content_type =
  16859. R"(multipart/form-data; boundary="simple boundary")";
  16860. Client cli(HOST, PORT);
  16861. auto res = cli.Post("/post", body, content_type.c_str());
  16862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16863. EXPECT_EQ(StatusCode::OK_200, res->status);
  16864. }
  16865. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16866. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16867. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16868. const ContentReader &content_reader) {
  16869. if (req.is_multipart_form_data()) {
  16870. std::vector<FormData> items;
  16871. content_reader(
  16872. [&](const FormData &file) {
  16873. items.push_back(file);
  16874. return true;
  16875. },
  16876. [&](const char *data, size_t data_length) {
  16877. items.back().content.append(data, data_length);
  16878. return true;
  16879. });
  16880. EXPECT_TRUE(std::string(items[0].name) == "document");
  16881. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16882. EXPECT_TRUE(items[0].filename == "2MB_data");
  16883. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16884. EXPECT_TRUE(items[1].name == "hello");
  16885. EXPECT_TRUE(items[1].content == "world");
  16886. EXPECT_TRUE(items[1].filename == "");
  16887. EXPECT_TRUE(items[1].content_type == "");
  16888. } else {
  16889. std::string body;
  16890. content_reader([&](const char *data, size_t data_length) {
  16891. body.append(data, data_length);
  16892. return true;
  16893. });
  16894. }
  16895. });
  16896. auto port = svr.bind_to_any_port("localhost");
  16897. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16898. auto se = detail::scope_exit([&] {
  16899. svr.stop();
  16900. t.join();
  16901. ASSERT_FALSE(svr.is_running());
  16902. });
  16903. svr.wait_until_ready();
  16904. {
  16905. std::string data(1024 * 1024 * 2, '.');
  16906. std::stringstream buffer;
  16907. buffer << data;
  16908. SSLClient cli("localhost", port);
  16909. cli.enable_server_certificate_verification(false);
  16910. UploadFormDataItems items{
  16911. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16912. {"hello", "world", "", ""},
  16913. };
  16914. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16916. ASSERT_EQ(StatusCode::OK_200, res->status);
  16917. }
  16918. }
  16919. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16920. std::string data(1024 * 1024 * 2, '&');
  16921. std::stringstream buffer;
  16922. buffer << data;
  16923. Client cli("https://localhost:8080");
  16924. UploadFormDataItems items{
  16925. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16926. {"hello", "world", "", ""},
  16927. };
  16928. for (const char &c : " \t\r\n") {
  16929. auto res =
  16930. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16931. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16932. ASSERT_FALSE(res);
  16933. }
  16934. }
  16935. TEST(MultipartFormDataTest, PutFormData) {
  16936. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16937. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16938. const ContentReader &content_reader) {
  16939. if (req.is_multipart_form_data()) {
  16940. std::vector<FormData> items;
  16941. content_reader(
  16942. [&](const FormData &file) {
  16943. items.push_back(file);
  16944. return true;
  16945. },
  16946. [&](const char *data, size_t data_length) {
  16947. items.back().content.append(data, data_length);
  16948. return true;
  16949. });
  16950. EXPECT_TRUE(std::string(items[0].name) == "document");
  16951. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16952. EXPECT_TRUE(items[0].filename == "2MB_data");
  16953. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16954. EXPECT_TRUE(items[1].name == "hello");
  16955. EXPECT_TRUE(items[1].content == "world");
  16956. EXPECT_TRUE(items[1].filename == "");
  16957. EXPECT_TRUE(items[1].content_type == "");
  16958. } else {
  16959. std::string body;
  16960. content_reader([&](const char *data, size_t data_length) {
  16961. body.append(data, data_length);
  16962. return true;
  16963. });
  16964. }
  16965. });
  16966. auto port = svr.bind_to_any_port("localhost");
  16967. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16968. auto se = detail::scope_exit([&] {
  16969. svr.stop();
  16970. t.join();
  16971. ASSERT_FALSE(svr.is_running());
  16972. });
  16973. svr.wait_until_ready();
  16974. {
  16975. std::string data(1024 * 1024 * 2, '&');
  16976. std::stringstream buffer;
  16977. buffer << data;
  16978. SSLClient cli("localhost", port);
  16979. cli.enable_server_certificate_verification(false);
  16980. UploadFormDataItems items{
  16981. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16982. {"hello", "world", "", ""},
  16983. };
  16984. auto res = cli.Put("/put", items);
  16985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16986. ASSERT_EQ(StatusCode::OK_200, res->status);
  16987. }
  16988. }
  16989. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16990. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16991. svr.Put("/put_customboundary",
  16992. [&](const Request &req, const Response & /*res*/,
  16993. const ContentReader &content_reader) {
  16994. if (req.is_multipart_form_data()) {
  16995. std::vector<FormData> items;
  16996. content_reader(
  16997. [&](const FormData &file) {
  16998. items.push_back(file);
  16999. return true;
  17000. },
  17001. [&](const char *data, size_t data_length) {
  17002. items.back().content.append(data, data_length);
  17003. return true;
  17004. });
  17005. EXPECT_TRUE(std::string(items[0].name) == "document");
  17006. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17007. EXPECT_TRUE(items[0].filename == "2MB_data");
  17008. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17009. EXPECT_TRUE(items[1].name == "hello");
  17010. EXPECT_TRUE(items[1].content == "world");
  17011. EXPECT_TRUE(items[1].filename == "");
  17012. EXPECT_TRUE(items[1].content_type == "");
  17013. } else {
  17014. std::string body;
  17015. content_reader([&](const char *data, size_t data_length) {
  17016. body.append(data, data_length);
  17017. return true;
  17018. });
  17019. }
  17020. });
  17021. auto port = svr.bind_to_any_port("localhost");
  17022. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17023. auto se = detail::scope_exit([&] {
  17024. svr.stop();
  17025. t.join();
  17026. ASSERT_FALSE(svr.is_running());
  17027. });
  17028. svr.wait_until_ready();
  17029. {
  17030. std::string data(1024 * 1024 * 2, '&');
  17031. std::stringstream buffer;
  17032. buffer << data;
  17033. SSLClient cli("localhost", port);
  17034. cli.enable_server_certificate_verification(false);
  17035. UploadFormDataItems items{
  17036. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17037. {"hello", "world", "", ""},
  17038. };
  17039. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17041. ASSERT_EQ(StatusCode::OK_200, res->status);
  17042. }
  17043. }
  17044. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17045. std::string data(1024 * 1024 * 2, '&');
  17046. std::stringstream buffer;
  17047. buffer << data;
  17048. Client cli("https://localhost:8080");
  17049. cli.enable_server_certificate_verification(false);
  17050. UploadFormDataItems items{
  17051. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17052. {"hello", "world", "", ""},
  17053. };
  17054. for (const char &c : " \t\r\n") {
  17055. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17056. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17057. ASSERT_FALSE(res);
  17058. }
  17059. }
  17060. TEST(MultipartFormDataTest, AlternateFilename) {
  17061. auto handled = false;
  17062. Server svr;
  17063. svr.Post("/test", [&](const Request &req, Response &res) {
  17064. ASSERT_EQ(2u, req.form.files.size());
  17065. ASSERT_EQ(1u, req.form.fields.size());
  17066. // Test files
  17067. const auto &file1 = req.form.get_file("file1");
  17068. ASSERT_EQ("file1", file1.name);
  17069. ASSERT_EQ("A.txt", file1.filename);
  17070. ASSERT_EQ("text/plain", file1.content_type);
  17071. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17072. const auto &file2 = req.form.get_file("file2");
  17073. ASSERT_EQ("file2", file2.name);
  17074. ASSERT_EQ("a.html", file2.filename);
  17075. ASSERT_EQ("text/html", file2.content_type);
  17076. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17077. file2.content);
  17078. // Test text field
  17079. const auto &text = req.form.get_field("text");
  17080. ASSERT_EQ("text default", text);
  17081. res.set_content("ok", "text/plain");
  17082. handled = true;
  17083. });
  17084. thread t = thread([&] { svr.listen(HOST, PORT); });
  17085. auto se = detail::scope_exit([&] {
  17086. svr.stop();
  17087. t.join();
  17088. ASSERT_FALSE(svr.is_running());
  17089. ASSERT_TRUE(handled);
  17090. });
  17091. svr.wait_until_ready();
  17092. auto req = "POST /test HTTP/1.1\r\n"
  17093. "Host: localhost\r\n"
  17094. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17095. "Content-Length: 399\r\n"
  17096. "\r\n"
  17097. "----------\r\n"
  17098. "Content-Disposition: form-data; name=\"text\"\r\n"
  17099. "\r\n"
  17100. "text default\r\n"
  17101. "----------\r\n"
  17102. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17103. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17104. "Content-Type: text/plain\r\n"
  17105. "\r\n"
  17106. "Content of a.txt.\r\n"
  17107. "\r\n"
  17108. "----------\r\n"
  17109. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17110. "\"a.html\"\r\n"
  17111. "Content-Type: text/html\r\n"
  17112. "\r\n"
  17113. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17114. "\r\n"
  17115. "------------\r\n";
  17116. ASSERT_TRUE(send_request(1, req));
  17117. }
  17118. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17119. auto handled = false;
  17120. Server svr;
  17121. svr.Post("/test", [&](const Request &req, Response &res) {
  17122. // Case-insensitive "utf-8''" prefix with a long value
  17123. const auto &file = req.form.get_file("file1");
  17124. ASSERT_EQ("file1", file.name);
  17125. // 8000 chars exercises both the Content-Disposition parser and the
  17126. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17127. // Prior to the fix, std::regex_match on this header would cause O(N)
  17128. // stack recursion in libstdc++, leading to SIGSEGV.
  17129. std::string expected_filename(8000, 'A');
  17130. ASSERT_EQ(expected_filename, file.filename);
  17131. res.set_content("ok", "text/plain");
  17132. handled = true;
  17133. });
  17134. thread t = thread([&] { svr.listen(HOST, PORT); });
  17135. auto se = detail::scope_exit([&] {
  17136. svr.stop();
  17137. t.join();
  17138. ASSERT_FALSE(svr.is_running());
  17139. ASSERT_TRUE(handled);
  17140. });
  17141. svr.wait_until_ready();
  17142. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17143. // Regression test for GHSA-qq6v-r583-3h69
  17144. std::string long_filename(8000, 'A');
  17145. std::string body = "----------\r\n"
  17146. "Content-Disposition: form-data; name=\"file1\"; "
  17147. "filename*=\"Utf-8''" +
  17148. long_filename +
  17149. "\"\r\n"
  17150. "\r\n"
  17151. "hello\r\n"
  17152. "------------\r\n";
  17153. auto req = "POST /test HTTP/1.1\r\n"
  17154. "Host: localhost\r\n"
  17155. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17156. "Content-Length: " +
  17157. std::to_string(body.size()) + "\r\n\r\n" + body;
  17158. ASSERT_TRUE(send_request(1, req));
  17159. }
  17160. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17161. auto handled = false;
  17162. Server svr;
  17163. svr.Post("/test", [&](const Request &req, Response &) {
  17164. ASSERT_EQ(2u, req.form.fields.size());
  17165. const auto &text1 = req.form.get_field("text1");
  17166. ASSERT_EQ("text1", text1);
  17167. const auto &text2 = req.form.get_field("text2");
  17168. ASSERT_EQ("text2", text2);
  17169. handled = true;
  17170. });
  17171. thread t = thread([&] { svr.listen(HOST, PORT); });
  17172. auto se = detail::scope_exit([&] {
  17173. svr.stop();
  17174. t.join();
  17175. ASSERT_FALSE(svr.is_running());
  17176. ASSERT_TRUE(handled);
  17177. });
  17178. svr.wait_until_ready();
  17179. auto req = "POST /test HTTP/1.1\r\n"
  17180. "Host: localhost\r\n"
  17181. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17182. "Content-Length: 146\r\n"
  17183. "\r\n----------\r\n"
  17184. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17185. "\r\n"
  17186. "text1"
  17187. "\r\n----------\r\n"
  17188. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17189. "\r\n"
  17190. "text2"
  17191. "\r\n------------";
  17192. std::string response;
  17193. ASSERT_TRUE(send_request(1, req, &response));
  17194. ASSERT_EQ("200", response.substr(9, 3));
  17195. }
  17196. TEST(MultipartFormDataTest, ContentLength) {
  17197. auto handled = false;
  17198. Server svr;
  17199. svr.Post("/test", [&](const Request &req, Response &) {
  17200. ASSERT_EQ(2u, req.form.fields.size());
  17201. const auto &text1 = req.form.get_field("text1");
  17202. ASSERT_EQ("text1", text1);
  17203. const auto &text2 = req.form.get_field("text2");
  17204. ASSERT_EQ("text2", text2);
  17205. handled = true;
  17206. });
  17207. thread t = thread([&] { svr.listen(HOST, PORT); });
  17208. auto se = detail::scope_exit([&] {
  17209. svr.stop();
  17210. t.join();
  17211. ASSERT_FALSE(svr.is_running());
  17212. ASSERT_TRUE(handled);
  17213. });
  17214. svr.wait_until_ready();
  17215. auto req = "POST /test HTTP/1.1\r\n"
  17216. "Host: localhost\r\n"
  17217. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17218. "Content-Length: 167\r\n"
  17219. "\r\n----------\r\n"
  17220. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17221. "Content-Length: 5\r\n"
  17222. "\r\n"
  17223. "text1"
  17224. "\r\n----------\r\n"
  17225. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17226. "\r\n"
  17227. "text2"
  17228. "\r\n------------\r\n";
  17229. std::string response;
  17230. ASSERT_TRUE(send_request(1, req, &response));
  17231. ASSERT_EQ("200", response.substr(9, 3));
  17232. }
  17233. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17234. auto handled = false;
  17235. Server svr;
  17236. svr.Post("/test", [&](const Request &req, Response &) {
  17237. ASSERT_EQ(2u, req.form.fields.size());
  17238. const auto &text1 = req.form.get_field("text1");
  17239. ASSERT_EQ("text1", text1);
  17240. // TODO: Add header access for text fields if needed
  17241. const auto &text2 = req.form.get_field("text2");
  17242. ASSERT_EQ("text2", text2);
  17243. // TODO: Header access for text fields needs to be implemented
  17244. // auto &headers = it->second.headers;
  17245. // ASSERT_EQ(3U, headers.size());
  17246. // auto custom_header = headers.find("x-whatever");
  17247. // ASSERT_TRUE(custom_header != headers.end());
  17248. // ASSERT_NE("customvalue", custom_header->second);
  17249. // ASSERT_EQ("CustomValue", custom_header->second);
  17250. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17251. handled = true;
  17252. });
  17253. thread t = thread([&] { svr.listen(HOST, PORT); });
  17254. auto se = detail::scope_exit([&] {
  17255. svr.stop();
  17256. t.join();
  17257. ASSERT_FALSE(svr.is_running());
  17258. ASSERT_TRUE(handled);
  17259. });
  17260. svr.wait_until_ready();
  17261. auto req = "POST /test HTTP/1.1\r\n"
  17262. "Host: localhost\r\n"
  17263. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17264. "Content-Length: 232\r\n"
  17265. "\r\n----------\r\n"
  17266. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17267. "Content-Length: 5\r\n"
  17268. "X-Test: 1\r\n"
  17269. "\r\n"
  17270. "text1"
  17271. "\r\n----------\r\n"
  17272. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17273. "Content-Type: text/plain\r\n"
  17274. "X-Whatever: CustomValue\r\n"
  17275. "\r\n"
  17276. "text2"
  17277. "\r\n------------\r\n"
  17278. "That should be disregarded. Not even read";
  17279. std::string response;
  17280. ASSERT_TRUE(send_request(1, req, &response));
  17281. ASSERT_EQ("200", response.substr(9, 3));
  17282. }
  17283. TEST(MultipartFormDataTest, LargeHeader) {
  17284. auto handled = false;
  17285. Server svr;
  17286. svr.Post("/test", [&](const Request &req, Response &) {
  17287. ASSERT_EQ(1u, req.form.fields.size());
  17288. const auto &text = req.form.get_field("name1");
  17289. ASSERT_EQ("text1", text);
  17290. handled = true;
  17291. });
  17292. thread t = thread([&] { svr.listen(HOST, PORT); });
  17293. auto se = detail::scope_exit([&] {
  17294. svr.stop();
  17295. t.join();
  17296. ASSERT_FALSE(svr.is_running());
  17297. ASSERT_TRUE(handled);
  17298. });
  17299. svr.wait_until_ready();
  17300. auto boundary = std::string("cpp-httplib-multipart-data");
  17301. std::string content = "--" + boundary +
  17302. "\r\n"
  17303. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17304. "\r\n"
  17305. "text1\r\n"
  17306. "--" +
  17307. boundary + "--\r\n";
  17308. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17309. "Host: localhost\r\n"
  17310. "Content-Type: multipart/form-data;boundary=" +
  17311. boundary +
  17312. "\r\n"
  17313. "Content-Length: " +
  17314. std::to_string(content.size()) +
  17315. "\r\n"
  17316. "Dummy-Header: ";
  17317. std::string header_suffix = "\r\n"
  17318. "\r\n";
  17319. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17320. size_t header_dummy_size =
  17321. read_buff_size -
  17322. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17323. auto header_dummy = std::string(header_dummy_size, '@');
  17324. auto req = header_prefix + header_dummy + header_suffix + content;
  17325. std::string response;
  17326. ASSERT_TRUE(send_request(1, req, &response));
  17327. ASSERT_EQ("200", response.substr(9, 3));
  17328. }
  17329. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17330. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17331. // (not chunked Transfer-Encoding) after the streaming refactor.
  17332. auto handled = false;
  17333. Server svr;
  17334. svr.Post("/upload", [&](const Request &req, Response &res) {
  17335. auto cl_it = req.headers.find("Content-Length");
  17336. EXPECT_TRUE(cl_it != req.headers.end());
  17337. auto te_it = req.headers.find("Transfer-Encoding");
  17338. EXPECT_TRUE(te_it == req.headers.end());
  17339. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17340. res.set_content("ok", "text/plain");
  17341. handled = true;
  17342. });
  17343. auto port = svr.bind_to_any_port(HOST);
  17344. auto t = thread([&] { svr.listen_after_bind(); });
  17345. auto se = detail::scope_exit([&] {
  17346. svr.stop();
  17347. t.join();
  17348. ASSERT_FALSE(svr.is_running());
  17349. ASSERT_TRUE(handled);
  17350. });
  17351. svr.wait_until_ready();
  17352. UploadFormDataItems items = {
  17353. {"field1", "hello", "", "text/plain"},
  17354. {"file1", "world", "test.txt", "application/octet-stream"},
  17355. };
  17356. Client cli(HOST, port);
  17357. auto res = cli.Post("/upload", {}, items);
  17358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17359. EXPECT_EQ(StatusCode::OK_200, res->status);
  17360. }
  17361. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17362. // Verify that make_multipart_content_provider coalesces many small segments
  17363. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17364. constexpr size_t kItemCount = 1000;
  17365. UploadFormDataItems items;
  17366. items.reserve(kItemCount);
  17367. for (size_t i = 0; i < kItemCount; i++) {
  17368. items.push_back(
  17369. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17370. }
  17371. const std::string boundary = "----test-boundary";
  17372. auto content_length = detail::get_multipart_content_length(items, boundary);
  17373. auto provider = detail::make_multipart_content_provider(items, boundary);
  17374. // Drive the provider the same way write_content_with_progress does
  17375. size_t write_count = 0;
  17376. size_t total_bytes = 0;
  17377. DataSink sink;
  17378. size_t offset = 0;
  17379. sink.write = [&](const char *d, size_t l) -> bool {
  17380. (void)d;
  17381. write_count++;
  17382. total_bytes += l;
  17383. offset += l;
  17384. return true;
  17385. };
  17386. sink.is_writable = []() -> bool { return true; };
  17387. while (offset < content_length) {
  17388. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17389. }
  17390. EXPECT_EQ(content_length, total_bytes);
  17391. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17392. // With buffering into 64KB blocks, write_count should be much smaller.
  17393. auto segment_count = 3 * kItemCount + 1;
  17394. EXPECT_LT(write_count, segment_count / 10);
  17395. }
  17396. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17397. // Integration test: send many UploadFormDataItems and verify the server
  17398. // receives all of them correctly (#2410).
  17399. constexpr size_t kItemCount = 500;
  17400. auto handled = false;
  17401. Server svr;
  17402. svr.Post("/upload", [&](const Request &req, Response &res) {
  17403. EXPECT_EQ(kItemCount, req.form.fields.size());
  17404. for (size_t i = 0; i < kItemCount; i++) {
  17405. auto key = "field" + std::to_string(i);
  17406. auto val = "value" + std::to_string(i);
  17407. auto it = req.form.fields.find(key);
  17408. if (it != req.form.fields.end()) {
  17409. EXPECT_EQ(val, it->second.content);
  17410. } else {
  17411. ADD_FAILURE() << "Missing field: " << key;
  17412. }
  17413. }
  17414. res.set_content("ok", "text/plain");
  17415. handled = true;
  17416. });
  17417. auto port = svr.bind_to_any_port(HOST);
  17418. auto t = thread([&] { svr.listen_after_bind(); });
  17419. auto se = detail::scope_exit([&] {
  17420. svr.stop();
  17421. t.join();
  17422. ASSERT_FALSE(svr.is_running());
  17423. ASSERT_TRUE(handled);
  17424. });
  17425. svr.wait_until_ready();
  17426. UploadFormDataItems items;
  17427. items.reserve(kItemCount);
  17428. for (size_t i = 0; i < kItemCount; i++) {
  17429. items.push_back(
  17430. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17431. }
  17432. Client cli(HOST, port);
  17433. auto res = cli.Post("/upload", items);
  17434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17435. EXPECT_EQ(StatusCode::OK_200, res->status);
  17436. }
  17437. TEST(MultipartFormDataTest, MakeFileProvider) {
  17438. // Verify make_file_provider sends a file's contents correctly.
  17439. const std::string file_content(4096, 'Z');
  17440. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17441. {
  17442. std::ofstream ofs(tmp_path, std::ios::binary);
  17443. ofs.write(file_content.data(),
  17444. static_cast<std::streamsize>(file_content.size()));
  17445. }
  17446. auto handled = false;
  17447. Server svr;
  17448. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17449. const ContentReader &content_reader) {
  17450. ASSERT_TRUE(req.is_multipart_form_data());
  17451. std::vector<FormData> items;
  17452. content_reader(
  17453. [&](const FormData &file) {
  17454. items.push_back(file);
  17455. return true;
  17456. },
  17457. [&](const char *data, size_t data_length) {
  17458. items.back().content.append(data, data_length);
  17459. return true;
  17460. });
  17461. ASSERT_EQ(1u, items.size());
  17462. EXPECT_EQ("myfile", items[0].name);
  17463. EXPECT_EQ("data.bin", items[0].filename);
  17464. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17465. EXPECT_EQ(file_content, items[0].content);
  17466. handled = true;
  17467. });
  17468. auto port = svr.bind_to_any_port(HOST);
  17469. auto t = thread([&] { svr.listen_after_bind(); });
  17470. auto se = detail::scope_exit([&] {
  17471. svr.stop();
  17472. t.join();
  17473. ASSERT_FALSE(svr.is_running());
  17474. ASSERT_TRUE(handled);
  17475. std::remove(tmp_path.c_str());
  17476. });
  17477. svr.wait_until_ready();
  17478. FormDataProviderItems providers;
  17479. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17480. "application/octet-stream"));
  17481. Client cli(HOST, port);
  17482. auto res = cli.Post("/upload", {}, {}, providers);
  17483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17484. EXPECT_EQ(StatusCode::OK_200, res->status);
  17485. }
  17486. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17487. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17488. // (100) headers is rejected with a 400 Bad Request response.
  17489. Server svr;
  17490. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17491. res.set_content("ok", "text/plain");
  17492. });
  17493. thread t = thread([&] { svr.listen(HOST, PORT); });
  17494. auto se = detail::scope_exit([&] {
  17495. svr.stop();
  17496. t.join();
  17497. ASSERT_FALSE(svr.is_running());
  17498. });
  17499. svr.wait_until_ready();
  17500. // Build a multipart part with 101 custom headers (exceeding
  17501. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17502. std::stringstream body;
  17503. body << "--simpleboundary\r\n"
  17504. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17505. for (int i = 0; i < 101; i++) {
  17506. body << "X-Custom-Header-" << i << ": value\r\n";
  17507. }
  17508. body << "\r\n"
  17509. << "value1\r\n"
  17510. << "--simpleboundary--\r\n";
  17511. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17512. Client cli(HOST, PORT);
  17513. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17515. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17516. }
  17517. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17518. // A body that never contains the declared boundary must not be accumulated
  17519. // while the parser waits for it. Buffering it would also make every read
  17520. // rescan everything seen so far, which is quadratic in the body size.
  17521. Server svr;
  17522. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17523. res.set_content("ok", "text/plain");
  17524. });
  17525. auto port = svr.bind_to_any_port(HOST);
  17526. thread t = thread([&] { svr.listen_after_bind(); });
  17527. auto se = detail::scope_exit([&] {
  17528. svr.stop();
  17529. t.join();
  17530. ASSERT_FALSE(svr.is_running());
  17531. });
  17532. svr.wait_until_ready();
  17533. Client cli(HOST, port);
  17534. cli.set_read_timeout(60, 0);
  17535. cli.set_write_timeout(60, 0);
  17536. // '-' is the worst case: it matches the first character of the boundary, so
  17537. // every position has to be checked against it.
  17538. auto post_dashes = [&](size_t size) {
  17539. const std::string body(size, '-');
  17540. auto start = std::chrono::steady_clock::now();
  17541. auto res =
  17542. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17543. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17544. std::chrono::steady_clock::now() - start)
  17545. .count();
  17546. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17547. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17548. return ms;
  17549. };
  17550. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17551. // Windows.
  17552. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17553. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17554. // Comparing the two sizes rather than checking an absolute duration keeps
  17555. // this meaningful across build types and CI load, both of which move the
  17556. // absolute numbers by more than an order of magnitude. Four times the bytes
  17557. // costs about four times the time when parsing is linear, and about sixteen
  17558. // times when the body is buffered and rescanned.
  17559. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17560. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17561. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17562. << "ms, which suggests the body is being buffered and rescanned";
  17563. }
  17564. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17565. // A boundary can only be followed by CRLF or by "--", so anything else is
  17566. // malformed no matter what comes next. The parser must say so right away
  17567. // instead of buffering the rest of the declared body.
  17568. Server svr;
  17569. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17570. res.set_content("ok", "text/plain");
  17571. });
  17572. auto port = svr.bind_to_any_port(HOST);
  17573. thread t = thread([&] { svr.listen_after_bind(); });
  17574. auto se = detail::scope_exit([&] {
  17575. svr.stop();
  17576. t.join();
  17577. ASSERT_FALSE(svr.is_running());
  17578. });
  17579. svr.wait_until_ready();
  17580. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17581. // buffers instead of failing would still be waiting for the remaining bytes.
  17582. const std::string body = "--zzzz\r\n"
  17583. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17584. "\r\n"
  17585. "text1"
  17586. "\r\n--zzzzXX";
  17587. const std::string req = "POST /post HTTP/1.1\r\n"
  17588. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17589. "Content-Length: 1048576\r\n"
  17590. "\r\n" +
  17591. body;
  17592. std::string response;
  17593. ASSERT_TRUE(send_request(3, req, &response, port));
  17594. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17595. EXPECT_EQ("400", response.substr(9, 3));
  17596. }
  17597. // Posts a multipart body split into two writes, so that the server sees the
  17598. // split at whatever offset the caller chose, and expects the single "text1"
  17599. // field to come through.
  17600. static void expect_split_multipart_ok(const std::string &body1,
  17601. const std::string &body2) {
  17602. auto handled = false;
  17603. Server svr;
  17604. svr.Post("/post", [&](const Request &req, Response &) {
  17605. EXPECT_EQ(1u, req.form.fields.size());
  17606. EXPECT_EQ("text1", req.form.get_field("text1"));
  17607. handled = true;
  17608. });
  17609. auto port = svr.bind_to_any_port(HOST);
  17610. thread t = thread([&] { svr.listen_after_bind(); });
  17611. auto se = detail::scope_exit([&] {
  17612. svr.stop();
  17613. t.join();
  17614. ASSERT_FALSE(svr.is_running());
  17615. ASSERT_TRUE(handled);
  17616. });
  17617. svr.wait_until_ready();
  17618. // "Connection: close" makes the server close once it has answered, so the
  17619. // response drain ends immediately instead of idling until the read timeout.
  17620. const std::string head =
  17621. "POST /post HTTP/1.1\r\n"
  17622. "Host: localhost\r\n"
  17623. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17624. "Connection: close\r\n"
  17625. "Content-Length: " +
  17626. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17627. std::string response;
  17628. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17629. ASSERT_GE(response.size(), 12u) << "no response";
  17630. EXPECT_EQ("200", response.substr(9, 3));
  17631. }
  17632. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17633. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17634. // ignored, including when it does not arrive in the same read as the
  17635. // close-delimiter itself.
  17636. expect_split_multipart_ok("--zzzz\r\n"
  17637. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17638. "\r\n"
  17639. "text1"
  17640. "\r\n--zzzz--",
  17641. "\r\nthis epilogue must be ignored\r\n");
  17642. }
  17643. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17644. // The initial boundary may be preceded by a preamble of any length and may
  17645. // straddle a read boundary. Discarding data while waiting for it must not
  17646. // throw away a partial boundary sitting at the end of the buffer.
  17647. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17648. "zz\r\n"
  17649. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17650. "\r\n"
  17651. "text1"
  17652. "\r\n--zzzz--\r\n");
  17653. }
  17654. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17655. // The received boundary was only checked for being non-empty, so it could be
  17656. // as long as a header is allowed to be. The parser scans the body for
  17657. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17658. // costs a nearly full comparison at nearly every position, making the
  17659. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17660. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17661. Server svr;
  17662. svr.Post("/post", [](const Request &req, Response &res) {
  17663. EXPECT_EQ(1u, req.form.fields.size());
  17664. EXPECT_EQ("text1", req.form.get_field("text1"));
  17665. res.set_content("ok", "text/plain");
  17666. });
  17667. auto port = svr.bind_to_any_port(HOST);
  17668. thread t = thread([&] { svr.listen_after_bind(); });
  17669. auto se = detail::scope_exit([&] {
  17670. svr.stop();
  17671. t.join();
  17672. ASSERT_FALSE(svr.is_running());
  17673. });
  17674. svr.wait_until_ready();
  17675. Client cli(HOST, port);
  17676. auto post_with_boundary_of_length = [&](size_t len) {
  17677. const std::string boundary(len, 'a');
  17678. const std::string body =
  17679. "--" + boundary +
  17680. "\r\n"
  17681. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17682. "\r\n"
  17683. "text1"
  17684. "\r\n--" +
  17685. boundary + "--\r\n";
  17686. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17687. };
  17688. auto res = post_with_boundary_of_length(70);
  17689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17690. EXPECT_EQ(StatusCode::OK_200, res->status);
  17691. res = post_with_boundary_of_length(71);
  17692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17693. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17694. }
  17695. TEST(MakeFileBodyTest, Basic) {
  17696. const std::string file_content(4096, 'Z');
  17697. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17698. {
  17699. std::ofstream ofs(tmp_path, std::ios::binary);
  17700. ofs.write(file_content.data(),
  17701. static_cast<std::streamsize>(file_content.size()));
  17702. }
  17703. auto handled = false;
  17704. Server svr;
  17705. svr.Post("/upload", [&](const Request &req, Response &res) {
  17706. EXPECT_EQ(file_content, req.body);
  17707. handled = true;
  17708. res.status = StatusCode::OK_200;
  17709. });
  17710. auto port = svr.bind_to_any_port(HOST);
  17711. auto t = thread([&] { svr.listen_after_bind(); });
  17712. auto se = detail::scope_exit([&] {
  17713. svr.stop();
  17714. t.join();
  17715. ASSERT_FALSE(svr.is_running());
  17716. ASSERT_TRUE(handled);
  17717. std::remove(tmp_path.c_str());
  17718. });
  17719. svr.wait_until_ready();
  17720. auto fb = make_file_body(tmp_path);
  17721. ASSERT_GT(fb.first, 0u);
  17722. Client cli(HOST, port);
  17723. auto res =
  17724. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17726. EXPECT_EQ(StatusCode::OK_200, res->status);
  17727. }
  17728. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17729. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17730. {
  17731. std::ofstream ofs(path, std::ios::binary);
  17732. const std::string content(100, 'A');
  17733. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17734. }
  17735. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17736. auto body = make_file_body(path);
  17737. ASSERT_EQ(100u, body.first);
  17738. ASSERT_TRUE(static_cast<bool>(body.second));
  17739. // Rewritten shorter after its length was measured - and, on a server, after
  17740. // that length has already gone out as Content-Length.
  17741. {
  17742. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17743. const std::string content(10, 'A');
  17744. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17745. }
  17746. std::string written;
  17747. DataSink sink;
  17748. sink.write = [&](const char *d, size_t l) {
  17749. written.append(d, l);
  17750. return true;
  17751. };
  17752. // The provider has to report failure. write_content_with_progress() advances
  17753. // its offset only by what was written, so a provider that returns true
  17754. // without completing the length it promised is called again straight away,
  17755. // and again.
  17756. EXPECT_FALSE(body.second(0, body.first, sink));
  17757. EXPECT_EQ(std::string(10, 'A'), written);
  17758. }
  17759. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17760. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17761. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17762. {
  17763. std::ofstream ofs(path, std::ios::binary);
  17764. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17765. }
  17766. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17767. auto body = make_file_body(path);
  17768. ASSERT_EQ(content.size(), body.first);
  17769. ASSERT_TRUE(static_cast<bool>(body.second));
  17770. std::string written;
  17771. DataSink sink;
  17772. sink.write = [&](const char *d, size_t l) {
  17773. written.append(d, l);
  17774. return true;
  17775. };
  17776. EXPECT_TRUE(body.second(0, body.first, sink));
  17777. EXPECT_EQ(content, written);
  17778. }
  17779. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17780. static constexpr unsigned int number_of_tasks{1000000};
  17781. std::atomic_uint count{0};
  17782. std::unique_ptr<TaskQueue> task_queue{
  17783. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17784. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17785. auto queued = task_queue->enqueue(
  17786. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17787. EXPECT_TRUE(queued);
  17788. }
  17789. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17790. task_queue->shutdown();
  17791. #else
  17792. EXPECT_NO_THROW(task_queue->shutdown());
  17793. #endif
  17794. EXPECT_EQ(number_of_tasks, count.load());
  17795. }
  17796. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17797. static constexpr unsigned int number_of_tasks{1000000};
  17798. static constexpr unsigned int qlimit{2};
  17799. unsigned int queued_count{0};
  17800. std::atomic_uint count{0};
  17801. std::unique_ptr<TaskQueue> task_queue{
  17802. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17803. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17804. if (task_queue->enqueue(
  17805. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17806. queued_count++;
  17807. }
  17808. }
  17809. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17810. task_queue->shutdown();
  17811. #else
  17812. EXPECT_NO_THROW(task_queue->shutdown());
  17813. #endif
  17814. EXPECT_EQ(queued_count, count.load());
  17815. EXPECT_TRUE(queued_count <= number_of_tasks);
  17816. EXPECT_TRUE(queued_count >= qlimit);
  17817. }
  17818. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17819. // Use a short idle timeout so a dynamic thread spawns, times out and
  17820. // exits during the test, and the pool keeps working afterwards.
  17821. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17822. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17823. /*idle_timeout_sec=*/1}};
  17824. std::atomic_uint count{0};
  17825. std::condition_variable cv;
  17826. std::mutex mtx;
  17827. bool release = false;
  17828. // Block the base thread so the second task spawns a dynamic thread.
  17829. EXPECT_TRUE(task_queue->enqueue([&] {
  17830. std::unique_lock<std::mutex> lock(mtx);
  17831. while (!release) {
  17832. cv.wait(lock);
  17833. }
  17834. count++;
  17835. }));
  17836. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17837. // Let the dynamic thread finish its task and exceed the idle timeout.
  17838. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17839. {
  17840. std::unique_lock<std::mutex> lock(mtx);
  17841. release = true;
  17842. }
  17843. cv.notify_all();
  17844. // The pool must still accept and run tasks after the dynamic thread exited.
  17845. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17846. task_queue->shutdown();
  17847. EXPECT_EQ(3u, count.load());
  17848. }
  17849. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17850. static constexpr size_t number_of_tasks{32};
  17851. std::unique_ptr<TaskQueue> task_queue{
  17852. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17853. // Let the base threads go idle so the burst below finds them waiting.
  17854. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17855. std::mutex mtx;
  17856. std::condition_variable cv;
  17857. size_t running = 0;
  17858. bool release = false;
  17859. for (size_t i = 0; i < number_of_tasks; i++) {
  17860. EXPECT_TRUE(task_queue->enqueue([&] {
  17861. std::unique_lock<std::mutex> lock(mtx);
  17862. running++;
  17863. cv.notify_all();
  17864. cv.wait(lock, [&] { return release; });
  17865. }));
  17866. }
  17867. {
  17868. std::unique_lock<std::mutex> lock(mtx);
  17869. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17870. [&] { return running == number_of_tasks; }));
  17871. release = true;
  17872. }
  17873. cv.notify_all();
  17874. task_queue->shutdown();
  17875. }
  17876. TEST(TaskQueueTest, MaxQueuedRequests) {
  17877. static constexpr unsigned int qlimit{3};
  17878. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17879. std::condition_variable sem_cv;
  17880. std::mutex sem_mtx;
  17881. int credits = 0;
  17882. bool queued;
  17883. /* Fill up the queue with tasks that will block until we give them credits to
  17884. * complete. */
  17885. for (unsigned int n = 0; n <= qlimit;) {
  17886. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17887. std::unique_lock<std::mutex> lock(sem_mtx);
  17888. while (credits <= 0) {
  17889. sem_cv.wait(lock);
  17890. }
  17891. /* Consume the credit and signal the test code if they are all gone. */
  17892. if (--credits == 0) { sem_cv.notify_one(); }
  17893. });
  17894. if (n < qlimit) {
  17895. /* The first qlimit enqueues must succeed. */
  17896. EXPECT_TRUE(queued);
  17897. } else {
  17898. /* The last one will succeed only when the worker thread
  17899. * starts and dequeues the first blocking task. Although
  17900. * not necessary for the correctness of this test, we sleep for
  17901. * a short while to avoid busy waiting. */
  17902. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17903. }
  17904. if (queued) { n++; }
  17905. }
  17906. /* Further enqueues must fail since the queue is full. */
  17907. for (auto i = 0; i < 4; i++) {
  17908. queued = task_queue->enqueue([] {});
  17909. EXPECT_FALSE(queued);
  17910. }
  17911. /* Give the credits to allow the previous tasks to complete. */
  17912. {
  17913. std::unique_lock<std::mutex> lock(sem_mtx);
  17914. credits += qlimit + 1;
  17915. }
  17916. sem_cv.notify_all();
  17917. /* Wait for all the credits to be consumed. */
  17918. {
  17919. std::unique_lock<std::mutex> lock(sem_mtx);
  17920. while (credits > 0) {
  17921. sem_cv.wait(lock);
  17922. }
  17923. }
  17924. /* Check that we are able again to enqueue at least qlimit tasks. */
  17925. for (unsigned int i = 0; i < qlimit; i++) {
  17926. queued = task_queue->enqueue([] {});
  17927. EXPECT_TRUE(queued);
  17928. }
  17929. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17930. task_queue->shutdown();
  17931. #else
  17932. EXPECT_NO_THROW(task_queue->shutdown());
  17933. #endif
  17934. }
  17935. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17936. Server svr;
  17937. std::string method;
  17938. std::string body;
  17939. auto has_content_length = false;
  17940. auto has_transfer_encoding = false;
  17941. std::atomic<int> bad_requests{0};
  17942. // Leftover body bytes get parsed as a malformed request and answered with
  17943. // 400
  17944. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17945. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17946. });
  17947. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17948. res.set_redirect("/down", StatusCode::SeeOther_303);
  17949. });
  17950. svr.Get("/down", [&](const Request &req, Response &res) {
  17951. method = req.method;
  17952. body = req.body;
  17953. has_content_length = req.has_header("Content-Length");
  17954. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17955. res.set_content("ok", "text/plain");
  17956. });
  17957. auto port = svr.bind_to_any_port(HOST);
  17958. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17959. auto se = detail::scope_exit([&] {
  17960. svr.stop();
  17961. thread.join();
  17962. ASSERT_FALSE(svr.is_running());
  17963. });
  17964. svr.wait_until_ready();
  17965. const std::string payload = "SECRET-BODY";
  17966. auto check = [&](Client &cli, const Result &res) {
  17967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17968. EXPECT_EQ(StatusCode::OK_200, res->status);
  17969. EXPECT_EQ("ok", res->body);
  17970. EXPECT_EQ("GET", method);
  17971. EXPECT_TRUE(body.empty());
  17972. EXPECT_FALSE(has_content_length);
  17973. EXPECT_FALSE(has_transfer_encoding);
  17974. // Nothing of the original body may be left on the connection
  17975. auto res2 = cli.Get("/down");
  17976. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17977. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17978. EXPECT_EQ("ok", res2->body);
  17979. EXPECT_EQ(0, bad_requests);
  17980. };
  17981. // With content length
  17982. {
  17983. Client cli(HOST, port);
  17984. cli.set_keep_alive(true);
  17985. cli.set_follow_location(true);
  17986. auto res = cli.Post(
  17987. "/up", payload.size(),
  17988. [&](size_t offset, size_t length, DataSink &sink) {
  17989. return sink.write(payload.data() + offset, length);
  17990. },
  17991. "text/plain");
  17992. check(cli, res);
  17993. }
  17994. // Without content length (chunked)
  17995. {
  17996. Client cli(HOST, port);
  17997. cli.set_keep_alive(true);
  17998. cli.set_follow_location(true);
  17999. auto res = cli.Post(
  18000. "/up",
  18001. [&](size_t /*offset*/, DataSink &sink) {
  18002. sink.write(payload.data(), payload.size());
  18003. sink.done();
  18004. return true;
  18005. },
  18006. "text/plain");
  18007. check(cli, res);
  18008. }
  18009. }
  18010. TEST(RedirectTest, LocationPathIsNotDecoded) {
  18011. Server svr;
  18012. std::string target;
  18013. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  18014. // Echo the still-encoded name back in the Location
  18015. const std::string prefix = "/start/";
  18016. res.status = StatusCode::Found_302;
  18017. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  18018. });
  18019. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  18020. target = req.target;
  18021. res.set_content("ok", "text/plain");
  18022. });
  18023. auto port = svr.bind_to_any_port(HOST);
  18024. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18025. auto se = detail::scope_exit([&] {
  18026. svr.stop();
  18027. thread.join();
  18028. ASSERT_FALSE(svr.is_running());
  18029. });
  18030. svr.wait_until_ready();
  18031. // Decoding the Location path would turn the first four into a path
  18032. // separator, a query delimiter, a fragment delimiter and a different
  18033. // percent-encoded octet. The rest must keep reaching the server as they are.
  18034. const std::vector<std::string> names = {
  18035. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  18036. };
  18037. for (auto path_encode : {true, false}) {
  18038. Client cli(HOST, port);
  18039. cli.set_follow_location(true);
  18040. cli.set_path_encode(path_encode);
  18041. for (const auto &name : names) {
  18042. target.clear();
  18043. auto res = cli.Get("/start/" + name);
  18044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18045. EXPECT_EQ(StatusCode::OK_200, res->status);
  18046. EXPECT_EQ("/dest/" + name, target);
  18047. }
  18048. }
  18049. }
  18050. TEST(RedirectTest, NotModifiedIsReturned) {
  18051. Server svr;
  18052. svr.Get("/cached", [](const Request &, Response &res) {
  18053. res.status = StatusCode::NotModified_304;
  18054. });
  18055. auto port = svr.bind_to_any_port(HOST);
  18056. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18057. auto se = detail::scope_exit([&] {
  18058. svr.stop();
  18059. thread.join();
  18060. ASSERT_FALSE(svr.is_running());
  18061. });
  18062. svr.wait_until_ready();
  18063. Client cli(HOST, port);
  18064. cli.set_follow_location(true);
  18065. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18067. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18068. }
  18069. TEST(RedirectTest, NoLocationIsReturned) {
  18070. Server svr;
  18071. svr.Get("/no-location", [](const Request &, Response &res) {
  18072. res.status = StatusCode::Found_302;
  18073. res.set_content("no location", "text/plain");
  18074. });
  18075. auto port = svr.bind_to_any_port(HOST);
  18076. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18077. auto se = detail::scope_exit([&] {
  18078. svr.stop();
  18079. thread.join();
  18080. ASSERT_FALSE(svr.is_running());
  18081. });
  18082. svr.wait_until_ready();
  18083. Client cli(HOST, port);
  18084. cli.set_follow_location(true);
  18085. auto res = cli.Get("/no-location");
  18086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18087. EXPECT_EQ(StatusCode::Found_302, res->status);
  18088. EXPECT_EQ("no location", res->body);
  18089. // The callbacks see the body of the response that is returned
  18090. auto handler_called = false;
  18091. auto progress_called = false;
  18092. std::string body;
  18093. auto res2 = cli.Get(
  18094. "/no-location",
  18095. [&](const Response &) {
  18096. handler_called = true;
  18097. return true;
  18098. },
  18099. [&](const char *data, size_t data_length) {
  18100. body.append(data, data_length);
  18101. return true;
  18102. },
  18103. [&](size_t, size_t) {
  18104. progress_called = true;
  18105. return true;
  18106. });
  18107. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18108. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18109. EXPECT_TRUE(handler_called);
  18110. EXPECT_TRUE(progress_called);
  18111. EXPECT_EQ("no location", body);
  18112. }
  18113. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18114. Server svr;
  18115. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18116. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18117. });
  18118. svr.Get("/hello", [](const Request &req, Response &res) {
  18119. res.set_content(req.get_param_value("key"), "text/plain");
  18120. });
  18121. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18122. auto se = detail::scope_exit([&] {
  18123. svr.stop();
  18124. thread.join();
  18125. ASSERT_FALSE(svr.is_running());
  18126. });
  18127. svr.wait_until_ready();
  18128. {
  18129. Client cli(HOST, PORT);
  18130. cli.set_follow_location(true);
  18131. auto res = cli.Get("/");
  18132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18133. EXPECT_EQ(StatusCode::OK_200, res->status);
  18134. EXPECT_EQ("val&key2=val2", res->body);
  18135. }
  18136. }
  18137. #endif
  18138. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18139. Server svr;
  18140. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18141. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18142. });
  18143. svr.Get("/hello", [](const Request &req, Response &res) {
  18144. res.set_content(req.get_param_value("key"), "text/plain");
  18145. });
  18146. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18147. auto se = detail::scope_exit([&] {
  18148. svr.stop();
  18149. thread.join();
  18150. ASSERT_FALSE(svr.is_running());
  18151. });
  18152. svr.wait_until_ready();
  18153. {
  18154. Client cli(HOST, PORT);
  18155. cli.set_follow_location(true);
  18156. auto res = cli.Get("/");
  18157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18158. EXPECT_EQ(StatusCode::OK_200, res->status);
  18159. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18160. }
  18161. }
  18162. TEST(RedirectTest, RedirectWithPlusInPath) {
  18163. Server svr;
  18164. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18165. res.set_redirect("/a+b");
  18166. });
  18167. // Route pattern uses regex; escape + as \\+
  18168. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18169. res.set_content(req.path, "text/plain");
  18170. });
  18171. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18172. auto se = detail::scope_exit([&] {
  18173. svr.stop();
  18174. thread.join();
  18175. ASSERT_FALSE(svr.is_running());
  18176. });
  18177. svr.wait_until_ready();
  18178. {
  18179. Client cli(HOST, PORT);
  18180. cli.set_follow_location(true);
  18181. auto res = cli.Get("/");
  18182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18183. EXPECT_EQ(StatusCode::OK_200, res->status);
  18184. EXPECT_EQ("/a+b", res->body);
  18185. }
  18186. }
  18187. TEST(RedirectTest, ResolveRelativeLocation) {
  18188. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18189. const std::vector<std::pair<std::string, std::string>> cases = {
  18190. {"g", "/b/c/g"},
  18191. {"./g", "/b/c/g"},
  18192. {"g/", "/b/c/g/"},
  18193. {"?y", "/b/c/d;p?y"},
  18194. {"g?y", "/b/c/g?y"},
  18195. {"#s", "/b/c/d;p?q#s"},
  18196. {"g#s", "/b/c/g#s"},
  18197. {"g?y#s", "/b/c/g?y#s"},
  18198. {";x", "/b/c/;x"},
  18199. {"g;x", "/b/c/g;x"},
  18200. {".", "/b/c/"},
  18201. {"./", "/b/c/"},
  18202. {"..", "/b/"},
  18203. {"../", "/b/"},
  18204. {"../g", "/b/g"},
  18205. {"../..", "/"},
  18206. {"../../", "/"},
  18207. {"../../g", "/g"},
  18208. {"../../../g", "/g"},
  18209. {"g.", "/b/c/g."},
  18210. {".g", "/b/c/.g"},
  18211. {"g..", "/b/c/g.."},
  18212. {"..g", "/b/c/..g"},
  18213. {"./../g", "/b/g"},
  18214. {"./g/.", "/b/c/g/"},
  18215. {"g/./h", "/b/c/g/h"},
  18216. {"g/../h", "/b/c/h"},
  18217. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18218. {"g;x=1/../y", "/b/c/y"},
  18219. {"g?y/./x", "/b/c/g?y/./x"},
  18220. {"g#s/../x", "/b/c/g#s/../x"},
  18221. // Not relative-path references, so left for parse_url.
  18222. {"/g", "/g"},
  18223. {"//g", "//g"},
  18224. {"http://g/x", "http://g/x"},
  18225. {"g:h", "g:h"},
  18226. };
  18227. for (const auto &c : cases) {
  18228. EXPECT_EQ(c.second,
  18229. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18230. << c.first;
  18231. }
  18232. // A result starting with "//" is still a path, not a network-path reference
  18233. EXPECT_EQ("/.//g",
  18234. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18235. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18236. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18237. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18238. }
  18239. TEST(RedirectTest, RemoveDotSegments) {
  18240. // RFC 3986 section 5.2.4
  18241. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18242. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18243. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18244. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18245. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18246. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18247. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18248. }
  18249. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18250. Server svr;
  18251. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18252. res.set_redirect("/dir/../target?x=1");
  18253. });
  18254. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18255. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18256. "/dir/./../target");
  18257. });
  18258. svr.Get("/target", [](const Request &req, Response &res) {
  18259. res.set_content(req.path, "text/plain");
  18260. });
  18261. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18262. auto se = detail::scope_exit([&] {
  18263. svr.stop();
  18264. th.join();
  18265. ASSERT_FALSE(svr.is_running());
  18266. });
  18267. svr.wait_until_ready();
  18268. Client cli("localhost", PORT);
  18269. cli.set_follow_location(true);
  18270. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18271. auto res = cli.Get(path);
  18272. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18273. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18274. EXPECT_EQ("/target", res->body) << path;
  18275. }
  18276. }
  18277. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18278. Server svr;
  18279. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18280. res.set_redirect(req.get_param_value("to"));
  18281. });
  18282. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18283. res.set_content(req.target, "text/plain");
  18284. });
  18285. svr.Get("/other", [](const Request &req, Response &res) {
  18286. res.set_content(req.target, "text/plain");
  18287. });
  18288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18289. auto se = detail::scope_exit([&] {
  18290. svr.stop();
  18291. thread.join();
  18292. ASSERT_FALSE(svr.is_running());
  18293. });
  18294. svr.wait_until_ready();
  18295. const std::vector<std::pair<std::string, std::string>> cases = {
  18296. {"next", "/dir/next"},
  18297. {"./next?x=1", "/dir/next?x=1"},
  18298. {"../other", "/other"},
  18299. };
  18300. for (const auto &c : cases) {
  18301. Client cli(HOST, PORT);
  18302. cli.set_follow_location(true);
  18303. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18304. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18305. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18306. EXPECT_EQ(c.second, res->body) << c.first;
  18307. }
  18308. }
  18309. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18310. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18311. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18312. Server other;
  18313. std::atomic<int> other_hits{0};
  18314. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18315. other_hits++;
  18316. res.set_content("other", "text/plain");
  18317. });
  18318. auto other_port = other.bind_to_any_port("127.0.0.1");
  18319. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18320. Server svr;
  18321. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18322. res.set_redirect(req.get_param_value("to"));
  18323. });
  18324. svr.Get(".*", [](const Request &req, Response &res) {
  18325. res.set_content(req.path, "text/plain");
  18326. });
  18327. auto port = svr.bind_to_any_port(HOST);
  18328. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18329. auto se = detail::scope_exit([&] {
  18330. svr.stop();
  18331. thread.join();
  18332. other.stop();
  18333. other_thread.join();
  18334. ASSERT_FALSE(svr.is_running());
  18335. ASSERT_FALSE(other.is_running());
  18336. });
  18337. svr.wait_until_ready();
  18338. other.wait_until_ready();
  18339. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18340. for (const auto &to :
  18341. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18342. Client cli(HOST, port);
  18343. cli.set_follow_location(true);
  18344. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18345. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18346. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18347. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18348. }
  18349. EXPECT_EQ(0, other_hits.load());
  18350. }
  18351. #ifdef CPPHTTPLIB_SSL_ENABLED
  18352. TEST(RedirectTest, Issue2185_Online) {
  18353. SSLClient client("github.com");
  18354. client.set_follow_location(true);
  18355. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18356. "Coollab-Windows.zip");
  18357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18358. EXPECT_EQ(StatusCode::OK_200, res->status);
  18359. EXPECT_EQ(9920427U, res->body.size());
  18360. }
  18361. #endif
  18362. TEST(VulnerabilityTest, CRLFInjection) {
  18363. Server svr;
  18364. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18365. res.set_content("Hello 1", "text/plain");
  18366. });
  18367. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18368. res.set_content("Hello 2", "text/plain");
  18369. });
  18370. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18371. res.set_content("Hello 3", "text/plain");
  18372. });
  18373. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18374. res.set_content("Hello 4", "text/plain");
  18375. });
  18376. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18377. for (const auto &x : req.headers) {
  18378. auto key = x.first;
  18379. EXPECT_STRNE("evil", key.c_str());
  18380. }
  18381. });
  18382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18383. auto se = detail::scope_exit([&] {
  18384. svr.stop();
  18385. thread.join();
  18386. ASSERT_FALSE(svr.is_running());
  18387. });
  18388. svr.wait_until_ready();
  18389. {
  18390. Client cli(HOST, PORT);
  18391. cli.Post("/test1", "A=B",
  18392. "application/x-www-form-urlencoded\r\nevil: hello1");
  18393. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18394. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18395. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18396. }
  18397. }
  18398. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18399. auto server_thread = std::thread([] {
  18400. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18401. default_socket_options(srv);
  18402. sockaddr_in addr{};
  18403. addr.sin_family = AF_INET;
  18404. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18405. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18406. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18407. ::listen(srv, 1);
  18408. sockaddr_in cli_addr{};
  18409. socklen_t cli_len = sizeof(cli_addr);
  18410. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18411. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18412. std::string buf_all;
  18413. char buf[2048];
  18414. ssize_t n;
  18415. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18416. buf_all.append(buf, static_cast<size_t>(n));
  18417. size_t pos;
  18418. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18419. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18420. auto e = request_block.find("\r\n");
  18421. if (e != std::string::npos) {
  18422. auto request_line = request_block.substr(0, e);
  18423. std::string msg =
  18424. "CRLF injection detected in request line: '" + request_line + "'";
  18425. EXPECT_FALSE(true) << msg;
  18426. }
  18427. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18428. ::send(cli,
  18429. #ifdef _WIN32
  18430. static_cast<const char *>(resp.c_str()),
  18431. static_cast<int>(resp.size()),
  18432. #else
  18433. resp.c_str(), resp.size(),
  18434. #endif
  18435. 0);
  18436. buf_all.erase(0, pos + 4);
  18437. }
  18438. }
  18439. detail::close_socket(cli);
  18440. detail::close_socket(srv);
  18441. });
  18442. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18443. auto cli = Client("127.0.0.1", PORT + 1);
  18444. auto headers = Headers{
  18445. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18446. {"Connection", "keep-alive"}};
  18447. auto res = cli.Get("/hi", headers);
  18448. EXPECT_FALSE(res);
  18449. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18450. server_thread.join();
  18451. }
  18452. // A request rejected before any byte reaches the socket must fail right away
  18453. // instead of waiting for a response the server will never send.
  18454. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18455. // The kernel completes the TCP handshake from the listen backlog, so the
  18456. // client connects, but nothing ever reads, responds or closes.
  18457. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18458. default_socket_options(srv);
  18459. sockaddr_in addr{};
  18460. addr.sin_family = AF_INET;
  18461. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18462. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18463. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18464. ASSERT_EQ(0, ::listen(srv, 8));
  18465. auto cli = Client("127.0.0.1", PORT + 1);
  18466. cli.set_read_timeout(10, 0);
  18467. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18468. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18469. std::chrono::steady_clock::now() - start)
  18470. .count();
  18471. };
  18472. {
  18473. Request req;
  18474. req.method = "GE T";
  18475. req.path = "/";
  18476. auto start = std::chrono::steady_clock::now();
  18477. auto res = cli.send(req);
  18478. EXPECT_FALSE(res);
  18479. EXPECT_EQ(Error::Write, res.error());
  18480. EXPECT_LT(elapsed_ms(start), 1000);
  18481. }
  18482. {
  18483. auto start = std::chrono::steady_clock::now();
  18484. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18485. EXPECT_FALSE(res);
  18486. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18487. EXPECT_LT(elapsed_ms(start), 1000);
  18488. }
  18489. EXPECT_FALSE(cli.is_socket_open());
  18490. detail::close_socket(srv);
  18491. }
  18492. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18493. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18494. default_socket_options(srv);
  18495. sockaddr_in addr{};
  18496. addr.sin_family = AF_INET;
  18497. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18498. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18499. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18500. ASSERT_EQ(0, ::listen(srv, 1));
  18501. std::string received;
  18502. auto server_thread = std::thread([&] {
  18503. auto sock = ::accept(srv, nullptr, nullptr);
  18504. if (sock == INVALID_SOCKET) { return; }
  18505. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18506. char buf[2048];
  18507. ssize_t n;
  18508. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18509. received.append(buf, static_cast<size_t>(n));
  18510. }
  18511. detail::close_socket(sock);
  18512. });
  18513. {
  18514. auto cli = Client("127.0.0.1", PORT + 1);
  18515. // "Z" sorts after the default headers, so writing straight to the socket
  18516. // would have sent the request line and those headers before the rejection.
  18517. auto handle =
  18518. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18519. EXPECT_FALSE(handle.is_valid());
  18520. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18521. }
  18522. server_thread.join();
  18523. detail::close_socket(srv);
  18524. EXPECT_TRUE(received.empty()) << received;
  18525. }
  18526. TEST(PathParamsTest, StaticMatch) {
  18527. const auto pattern = "/users/all";
  18528. detail::PathParamsMatcher matcher(pattern);
  18529. Request request;
  18530. request.path = "/users/all";
  18531. ASSERT_TRUE(matcher.match(request));
  18532. std::unordered_map<std::string, std::string> expected_params = {};
  18533. EXPECT_EQ(request.path_params, expected_params);
  18534. }
  18535. TEST(PathParamsTest, StaticMismatch) {
  18536. const auto pattern = "/users/all";
  18537. detail::PathParamsMatcher matcher(pattern);
  18538. Request request;
  18539. request.path = "/users/1";
  18540. ASSERT_FALSE(matcher.match(request));
  18541. }
  18542. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18543. const auto pattern = "/users/:id/subscriptions";
  18544. detail::PathParamsMatcher matcher(pattern);
  18545. Request request;
  18546. request.path = "/users/42/subscriptions";
  18547. ASSERT_TRUE(matcher.match(request));
  18548. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18549. EXPECT_EQ(request.path_params, expected_params);
  18550. }
  18551. TEST(PathParamsTest, SingleParamInTheEnd) {
  18552. const auto pattern = "/users/:id";
  18553. detail::PathParamsMatcher matcher(pattern);
  18554. Request request;
  18555. request.path = "/users/24";
  18556. ASSERT_TRUE(matcher.match(request));
  18557. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18558. EXPECT_EQ(request.path_params, expected_params);
  18559. }
  18560. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18561. const auto pattern = "/users/:id/";
  18562. detail::PathParamsMatcher matcher(pattern);
  18563. Request request;
  18564. request.path = "/users/42/";
  18565. ASSERT_TRUE(matcher.match(request));
  18566. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18567. EXPECT_EQ(request.path_params, expected_params);
  18568. }
  18569. TEST(PathParamsTest, EmptyParam) {
  18570. const auto pattern = "/users/:id/";
  18571. detail::PathParamsMatcher matcher(pattern);
  18572. Request request;
  18573. request.path = "/users//";
  18574. ASSERT_TRUE(matcher.match(request));
  18575. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18576. EXPECT_EQ(request.path_params, expected_params);
  18577. }
  18578. TEST(PathParamsTest, FragmentMismatch) {
  18579. const auto pattern = "/users/:id/";
  18580. detail::PathParamsMatcher matcher(pattern);
  18581. Request request;
  18582. request.path = "/admins/24/";
  18583. ASSERT_FALSE(matcher.match(request));
  18584. }
  18585. TEST(PathParamsTest, ExtraFragments) {
  18586. const auto pattern = "/users/:id";
  18587. detail::PathParamsMatcher matcher(pattern);
  18588. Request request;
  18589. request.path = "/users/42/subscriptions";
  18590. ASSERT_FALSE(matcher.match(request));
  18591. }
  18592. TEST(PathParamsTest, MissingTrailingParam) {
  18593. const auto pattern = "/users/:id";
  18594. detail::PathParamsMatcher matcher(pattern);
  18595. Request request;
  18596. request.path = "/users";
  18597. ASSERT_FALSE(matcher.match(request));
  18598. }
  18599. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18600. const auto pattern = "/users/:id/subscriptions";
  18601. detail::PathParamsMatcher matcher(pattern);
  18602. Request request;
  18603. request.path = "/users/subscriptions";
  18604. ASSERT_FALSE(matcher.match(request));
  18605. }
  18606. TEST(PathParamsTest, MultipleParams) {
  18607. const auto pattern = "/users/:userid/subscriptions/:subid";
  18608. detail::PathParamsMatcher matcher(pattern);
  18609. Request request;
  18610. request.path = "/users/42/subscriptions/2";
  18611. ASSERT_TRUE(matcher.match(request));
  18612. std::unordered_map<std::string, std::string> expected_params = {
  18613. {"userid", "42"}, {"subid", "2"}};
  18614. EXPECT_EQ(request.path_params, expected_params);
  18615. }
  18616. TEST(PathParamsTest, SequenceOfParams) {
  18617. const auto pattern = "/values/:x/:y/:z";
  18618. detail::PathParamsMatcher matcher(pattern);
  18619. Request request;
  18620. request.path = "/values/1/2/3";
  18621. ASSERT_TRUE(matcher.match(request));
  18622. std::unordered_map<std::string, std::string> expected_params = {
  18623. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18624. EXPECT_EQ(request.path_params, expected_params);
  18625. }
  18626. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18627. const auto pattern = "/prefix:suffix";
  18628. detail::PathParamsMatcher matcher(pattern);
  18629. Request request;
  18630. request.path = "/prefix:suffix";
  18631. ASSERT_TRUE(matcher.match(request));
  18632. const std::unordered_map<std::string, std::string> expected_params = {};
  18633. EXPECT_EQ(request.path_params, expected_params);
  18634. }
  18635. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18636. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18637. // calling thread's stack on a long enough path for a quantified pattern;
  18638. // RegexMatcher must refuse to run regex matching on paths beyond
  18639. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18640. detail::RegexMatcher matcher("/files/(.*)");
  18641. Request within_limit;
  18642. within_limit.path = "/files/" + std::string(10, 'A');
  18643. EXPECT_TRUE(matcher.match(within_limit));
  18644. Request over_limit;
  18645. over_limit.path =
  18646. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18647. EXPECT_FALSE(matcher.match(over_limit));
  18648. }
  18649. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18650. Server svr;
  18651. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18652. res.set_content("ok", "text/plain");
  18653. });
  18654. auto port = svr.bind_to_any_port(HOST);
  18655. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18656. auto se = detail::scope_exit([&] {
  18657. svr.stop();
  18658. thread.join();
  18659. ASSERT_FALSE(svr.is_running());
  18660. });
  18661. svr.wait_until_ready();
  18662. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18663. // request URI limit; this used to be able to crash the process.
  18664. std::string path =
  18665. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18666. std::string req = "GET " + path +
  18667. " HTTP/1.1\r\n"
  18668. "Host: " +
  18669. std::string(HOST) + ":" + std::to_string(port) +
  18670. "\r\n"
  18671. "Connection: close\r\n"
  18672. "\r\n";
  18673. std::string response;
  18674. ASSERT_TRUE(send_request(5, req, &response, port));
  18675. EXPECT_NE(std::string::npos, response.find("404"));
  18676. }
  18677. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18678. Server svr;
  18679. auto handler = [](const Request & /*req*/, Response &res) {
  18680. res.set_content("hit", "text/plain");
  18681. };
  18682. // No regex metacharacter, so this one is compared literally
  18683. svr.Get("/literal/route", handler);
  18684. // '.' is a regex metacharacter, so this one must keep regex semantics
  18685. svr.Get("/a.c", handler);
  18686. auto port = svr.bind_to_any_port(HOST);
  18687. std::thread t([&]() { svr.listen_after_bind(); });
  18688. auto se = detail::scope_exit([&] {
  18689. svr.stop();
  18690. t.join();
  18691. ASSERT_FALSE(svr.is_running());
  18692. });
  18693. svr.wait_until_ready();
  18694. Client cli(HOST, port);
  18695. struct {
  18696. const char *path;
  18697. int status;
  18698. } cases[] = {
  18699. {"/literal/route", StatusCode::OK_200},
  18700. {"/literal/routes", StatusCode::NotFound_404},
  18701. {"/literal/rout", StatusCode::NotFound_404},
  18702. {"/abc", StatusCode::OK_200},
  18703. {"/a.c", StatusCode::OK_200},
  18704. };
  18705. for (const auto &x : cases) {
  18706. auto res = cli.Get(x.path);
  18707. ASSERT_TRUE(res) << x.path;
  18708. EXPECT_EQ(x.status, res->status) << x.path;
  18709. }
  18710. }
  18711. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18712. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18713. // from exhausting the stack, so it must only constrain routes that actually
  18714. // run a regular expression. A literal route is matched by comparison and
  18715. // stays usable at any length.
  18716. Server svr;
  18717. const std::string pattern =
  18718. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18719. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18720. res.set_content("hit", "text/plain");
  18721. });
  18722. auto port = svr.bind_to_any_port(HOST);
  18723. std::thread t([&]() { svr.listen_after_bind(); });
  18724. auto se = detail::scope_exit([&] {
  18725. svr.stop();
  18726. t.join();
  18727. ASSERT_FALSE(svr.is_running());
  18728. });
  18729. svr.wait_until_ready();
  18730. Client cli(HOST, port);
  18731. auto res = cli.Get(pattern);
  18732. ASSERT_TRUE(res);
  18733. EXPECT_EQ(StatusCode::OK_200, res->status);
  18734. }
  18735. TEST(ParseUrlTest, VariousPatterns) {
  18736. {
  18737. detail::UrlComponents uc;
  18738. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18739. EXPECT_EQ("http", uc.scheme);
  18740. EXPECT_EQ("example.com", uc.host);
  18741. EXPECT_EQ("8080", uc.port);
  18742. EXPECT_EQ("/path", uc.path);
  18743. EXPECT_EQ("?q=1", uc.query);
  18744. }
  18745. {
  18746. detail::UrlComponents uc;
  18747. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18748. EXPECT_EQ("https", uc.scheme);
  18749. EXPECT_EQ("example.com", uc.host);
  18750. EXPECT_TRUE(uc.port.empty());
  18751. EXPECT_EQ("/path", uc.path);
  18752. }
  18753. {
  18754. detail::UrlComponents uc;
  18755. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18756. EXPECT_EQ("::1", uc.host);
  18757. EXPECT_EQ("8080", uc.port);
  18758. EXPECT_EQ("/path", uc.path);
  18759. }
  18760. {
  18761. detail::UrlComponents uc;
  18762. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18763. }
  18764. {
  18765. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18766. // the path while the connection still targets the bracketed host.
  18767. detail::UrlComponents uc;
  18768. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18769. }
  18770. {
  18771. detail::UrlComponents uc;
  18772. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18773. }
  18774. {
  18775. detail::UrlComponents uc;
  18776. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18777. EXPECT_EQ("::1", uc.host);
  18778. EXPECT_TRUE(uc.port.empty());
  18779. EXPECT_EQ("/path", uc.path);
  18780. }
  18781. {
  18782. detail::UrlComponents uc;
  18783. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18784. EXPECT_TRUE(uc.scheme.empty());
  18785. EXPECT_EQ("example.com", uc.host);
  18786. EXPECT_EQ("/path", uc.path);
  18787. EXPECT_EQ("?q=1", uc.query);
  18788. }
  18789. {
  18790. detail::UrlComponents uc;
  18791. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18792. EXPECT_TRUE(uc.host.empty());
  18793. EXPECT_EQ("/path", uc.path);
  18794. EXPECT_EQ("?q=1", uc.query);
  18795. }
  18796. {
  18797. detail::UrlComponents uc;
  18798. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18799. EXPECT_EQ("example.com", uc.host);
  18800. EXPECT_EQ("8080", uc.port);
  18801. }
  18802. {
  18803. // Unix socket path — must not be parsed as host
  18804. detail::UrlComponents uc;
  18805. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18806. EXPECT_TRUE(uc.host.empty());
  18807. }
  18808. {
  18809. detail::UrlComponents uc;
  18810. ASSERT_TRUE(detail::parse_url("", uc));
  18811. EXPECT_TRUE(uc.host.empty());
  18812. EXPECT_TRUE(uc.path.empty());
  18813. }
  18814. {
  18815. detail::UrlComponents uc;
  18816. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18817. EXPECT_EQ("http", uc.scheme);
  18818. }
  18819. {
  18820. detail::UrlComponents uc;
  18821. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18822. }
  18823. {
  18824. // Accepted by parse_url; callers restrict to http/https
  18825. detail::UrlComponents uc;
  18826. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18827. EXPECT_EQ("ftp", uc.scheme);
  18828. }
  18829. {
  18830. detail::UrlComponents uc;
  18831. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18832. }
  18833. {
  18834. detail::UrlComponents uc;
  18835. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18836. }
  18837. }
  18838. TEST(ParseUrlTest, FragmentHandling) {
  18839. {
  18840. detail::UrlComponents uc;
  18841. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18842. EXPECT_EQ("/path", uc.path);
  18843. EXPECT_TRUE(uc.query.empty());
  18844. }
  18845. {
  18846. detail::UrlComponents uc;
  18847. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18848. EXPECT_TRUE(uc.path.empty());
  18849. EXPECT_TRUE(uc.query.empty());
  18850. }
  18851. }
  18852. TEST(ParseUrlTest, UserinfoHandling) {
  18853. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18854. // parsers would see evil.com as the host.
  18855. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18856. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18857. for (auto url : urls) {
  18858. detail::UrlComponents uc;
  18859. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18860. }
  18861. }
  18862. TEST(ParseUrlTest, IPv6EdgeCases) {
  18863. {
  18864. detail::UrlComponents uc;
  18865. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18866. EXPECT_TRUE(uc.scheme.empty());
  18867. EXPECT_EQ("::1", uc.host);
  18868. EXPECT_EQ("8080", uc.port);
  18869. }
  18870. {
  18871. // Zone ID '%25' is not in [a-fA-F0-9:]
  18872. detail::UrlComponents uc;
  18873. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18874. }
  18875. }
  18876. TEST(ParseUrlTest, SchemeEdgeCases) {
  18877. {
  18878. detail::UrlComponents uc;
  18879. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18880. }
  18881. {
  18882. detail::UrlComponents uc;
  18883. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18884. }
  18885. {
  18886. detail::UrlComponents uc;
  18887. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18888. }
  18889. {
  18890. detail::UrlComponents uc;
  18891. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18892. EXPECT_EQ("https", uc.scheme);
  18893. }
  18894. }
  18895. TEST(ParseUrlTest, PortEdgeCases) {
  18896. {
  18897. detail::UrlComponents uc;
  18898. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18899. EXPECT_TRUE(uc.port.empty());
  18900. EXPECT_EQ("/path", uc.path);
  18901. }
  18902. {
  18903. // parse_url accepts any port string; validation is done by parse_port
  18904. detail::UrlComponents uc;
  18905. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18906. EXPECT_EQ("abc", uc.port);
  18907. }
  18908. }
  18909. TEST(ParseUrlTest, WebSocketPatterns) {
  18910. {
  18911. detail::UrlComponents uc;
  18912. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18913. EXPECT_EQ("ws", uc.scheme);
  18914. EXPECT_EQ("echo.example.com", uc.host);
  18915. EXPECT_EQ("8080", uc.port);
  18916. EXPECT_EQ("/ws", uc.path);
  18917. }
  18918. {
  18919. detail::UrlComponents uc;
  18920. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18921. EXPECT_EQ("wss", uc.scheme);
  18922. EXPECT_EQ("echo.example.com", uc.host);
  18923. EXPECT_TRUE(uc.port.empty());
  18924. EXPECT_EQ("/ws", uc.path);
  18925. }
  18926. }
  18927. TEST(ParseUrlTest, QueryOnly) {
  18928. detail::UrlComponents uc;
  18929. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18930. EXPECT_TRUE(uc.host.empty());
  18931. EXPECT_TRUE(uc.path.empty());
  18932. EXPECT_EQ("?q=1&r=2", uc.query);
  18933. }
  18934. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18935. detail::UrlComponents uc;
  18936. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18937. EXPECT_TRUE(uc.scheme.empty());
  18938. EXPECT_EQ("example.com", uc.host);
  18939. EXPECT_EQ("443", uc.port);
  18940. EXPECT_EQ("/path", uc.path);
  18941. }
  18942. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18943. // If ipv6 regex working, regex match codepath is taken.
  18944. // else port will default to 80 in Client impl
  18945. int clientImplMagicPort = 80;
  18946. int port = 4321;
  18947. // above ports must be different to avoid false negative
  18948. EXPECT_NE(clientImplMagicPort, port);
  18949. std::string ipV6TestURL = "http://[ff06::c3]";
  18950. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18951. CLIENT_PRIVATE_KEY_FILE);
  18952. EXPECT_EQ(cli.port(), port);
  18953. }
  18954. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18955. auto file_path = "./www/dir/index.html";
  18956. auto dir_path = "./www/dir";
  18957. detail::FileStat stat_file(file_path);
  18958. EXPECT_TRUE(stat_file.is_file());
  18959. EXPECT_FALSE(stat_file.is_dir());
  18960. detail::FileStat stat_dir(dir_path);
  18961. EXPECT_FALSE(stat_dir.is_file());
  18962. EXPECT_TRUE(stat_dir.is_dir());
  18963. }
  18964. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18965. // IPv4 with default HTTP port (80)
  18966. EXPECT_EQ("example.com",
  18967. detail::make_host_and_port_string("example.com", 80, false));
  18968. // IPv4 with default HTTPS port (443)
  18969. EXPECT_EQ("example.com",
  18970. detail::make_host_and_port_string("example.com", 443, true));
  18971. // IPv4 with non-default HTTP port
  18972. EXPECT_EQ("example.com:8080",
  18973. detail::make_host_and_port_string("example.com", 8080, false));
  18974. // IPv4 with non-default HTTPS port
  18975. EXPECT_EQ("example.com:8443",
  18976. detail::make_host_and_port_string("example.com", 8443, true));
  18977. // IPv6 with default HTTP port (80)
  18978. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18979. // IPv6 with default HTTPS port (443)
  18980. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18981. // IPv6 with non-default HTTP port
  18982. EXPECT_EQ("[::1]:8080",
  18983. detail::make_host_and_port_string("::1", 8080, false));
  18984. // IPv6 with non-default HTTPS port
  18985. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18986. // IPv6 full address with default port
  18987. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18988. detail::make_host_and_port_string(
  18989. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18990. // IPv6 full address with non-default port
  18991. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18992. detail::make_host_and_port_string(
  18993. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18994. // IPv6 localhost with non-default port
  18995. EXPECT_EQ("[::1]:3000",
  18996. detail::make_host_and_port_string("::1", 3000, false));
  18997. // IPv6 with zone ID (link-local address) with default port
  18998. EXPECT_EQ("[fe80::1%eth0]",
  18999. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  19000. // IPv6 with zone ID (link-local address) with non-default port
  19001. EXPECT_EQ("[fe80::1%eth0]:8080",
  19002. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  19003. // Edge case: Port 443 with is_ssl=false (should add port)
  19004. EXPECT_EQ("example.com:443",
  19005. detail::make_host_and_port_string("example.com", 443, false));
  19006. // Edge case: Port 80 with is_ssl=true (should add port)
  19007. EXPECT_EQ("example.com:80",
  19008. detail::make_host_and_port_string("example.com", 80, true));
  19009. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  19010. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  19011. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  19012. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  19013. // Security fix: Already bracketed IPv6 should not get double brackets
  19014. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  19015. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  19016. EXPECT_EQ("[::1]:8080",
  19017. detail::make_host_and_port_string("[::1]", 8080, false));
  19018. EXPECT_EQ("[2001:db8::1]:8080",
  19019. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  19020. EXPECT_EQ("[fe80::1%eth0]",
  19021. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  19022. EXPECT_EQ("[fe80::1%eth0]:8080",
  19023. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  19024. // Edge case: Empty host (should return as-is)
  19025. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  19026. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  19027. // This is a known limitation but shouldn't crash
  19028. EXPECT_EQ("[host:name]",
  19029. detail::make_host_and_port_string("host:name", 80, false));
  19030. // Port number edge cases (no validation, but should not crash)
  19031. EXPECT_EQ("example.com:0",
  19032. detail::make_host_and_port_string("example.com", 0, false));
  19033. EXPECT_EQ("example.com:-1",
  19034. detail::make_host_and_port_string("example.com", -1, false));
  19035. EXPECT_EQ("example.com:65535",
  19036. detail::make_host_and_port_string("example.com", 65535, false));
  19037. EXPECT_EQ("example.com:65536",
  19038. detail::make_host_and_port_string("example.com", 65536, false));
  19039. }
  19040. namespace httplib {
  19041. namespace detail {
  19042. std::string
  19043. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19044. const std::string &host, int port);
  19045. } // namespace detail
  19046. } // namespace httplib
  19047. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19048. std::map<std::string, std::string> addr_map = {
  19049. {"ipv4.example", "192.0.2.10"},
  19050. {"ipv6.example", "2001:db8::1"},
  19051. {"name.example", "internal.example.lan"},
  19052. {"empty.example", ""}};
  19053. EXPECT_EQ("192.0.2.10:443",
  19054. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19055. EXPECT_EQ("[2001:db8::1]:443",
  19056. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19057. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19058. addr_map, "name.example", 8443));
  19059. // An empty or absent mapping keeps the hostname as the target
  19060. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19061. addr_map, "empty.example", 443));
  19062. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19063. addr_map, "other.example", 443));
  19064. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19065. }
  19066. #ifdef CPPHTTPLIB_SSL_ENABLED
  19067. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19068. httplib::SSLClient cli("roblox.com", 443);
  19069. cli.set_follow_location(true);
  19070. auto res = cli.Get("/");
  19071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19072. EXPECT_EQ(StatusCode::OK_200, res->status);
  19073. }
  19074. #endif
  19075. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19076. Server svr;
  19077. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19078. EXPECT_EQ(res.status, 400);
  19079. });
  19080. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19081. auto se = detail::scope_exit([&] {
  19082. svr.stop();
  19083. thread.join();
  19084. ASSERT_FALSE(svr.is_running());
  19085. });
  19086. svr.wait_until_ready();
  19087. Client cli(HOST, PORT);
  19088. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19089. }
  19090. TEST(InvalidHeaderCharsTest, is_field_name) {
  19091. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19092. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19093. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19094. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19095. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19096. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19097. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19098. EXPECT_FALSE(detail::fields::is_field_name(""));
  19099. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19100. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19101. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19102. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19103. }
  19104. TEST(InvalidHeaderCharsTest, is_field_value) {
  19105. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19106. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19107. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19108. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19109. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19110. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19111. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19112. EXPECT_TRUE(detail::fields::is_field_value(""));
  19113. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19114. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19115. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19116. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19117. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19118. }
  19119. TEST(InvalidHeaderCharsTest, OnServer) {
  19120. Server svr;
  19121. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19122. std::string header = "Not Set";
  19123. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19124. res.set_header(header, "value");
  19125. res.set_content("Page Content Page Content", "text/plain");
  19126. });
  19127. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19128. std::string header = "Not Set";
  19129. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19130. res.set_header("X-Test", header);
  19131. res.set_content("Page Content Page Content", "text/plain");
  19132. });
  19133. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19134. auto se = detail::scope_exit([&] {
  19135. svr.stop();
  19136. thread.join();
  19137. ASSERT_FALSE(svr.is_running());
  19138. });
  19139. svr.wait_until_ready();
  19140. Client cli(HOST, PORT);
  19141. {
  19142. auto res = cli.Get(
  19143. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19145. EXPECT_EQ("Page Content Page Content", res->body);
  19146. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19147. }
  19148. {
  19149. auto res = cli.Get(
  19150. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19152. EXPECT_EQ("Page Content Page Content", res->body);
  19153. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19154. }
  19155. }
  19156. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19157. auto handled = false;
  19158. Server svr;
  19159. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19160. thread t = thread([&] { svr.listen(HOST, PORT); });
  19161. auto se = detail::scope_exit([&] {
  19162. svr.stop();
  19163. t.join();
  19164. ASSERT_FALSE(svr.is_running());
  19165. ASSERT_FALSE(handled);
  19166. });
  19167. svr.wait_until_ready();
  19168. auto req = "POST /test HTTP/1.1\r\n"
  19169. "Content-Length: x\r\n"
  19170. "\r\n";
  19171. std::string response;
  19172. ASSERT_TRUE(send_request(1, req, &response));
  19173. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19174. response.substr(0, response.find("\r\n")));
  19175. }
  19176. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19177. // case-insensitive, and a server that receives a 100-continue expectation in
  19178. // an HTTP/1.0 request MUST ignore it.
  19179. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19180. std::string response;
  19181. ASSERT_TRUE(send_request(1, req, &response, port));
  19182. *got_100 = response.find("100 Continue") != std::string::npos;
  19183. }
  19184. class ExpectTokenTest : public ::testing::Test {
  19185. protected:
  19186. void SetUp() override {
  19187. svr_.Post("/p", [](const Request &, Response &res) {
  19188. res.set_content("ok", "text/plain");
  19189. });
  19190. port_ = svr_.bind_to_any_port(HOST);
  19191. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19192. svr_.wait_until_ready();
  19193. }
  19194. void TearDown() override {
  19195. svr_.stop();
  19196. if (thread_.joinable()) { thread_.join(); }
  19197. }
  19198. std::string request(const char *version, const char *expect_value) const {
  19199. return std::string("POST /p ") + version +
  19200. "\r\n"
  19201. "Host: localhost\r\n"
  19202. "Content-Length: 2\r\n"
  19203. "Connection: close\r\n"
  19204. "Expect: " +
  19205. expect_value +
  19206. "\r\n"
  19207. "\r\n"
  19208. "hi";
  19209. }
  19210. Server svr_;
  19211. int port_ = 0;
  19212. thread thread_;
  19213. };
  19214. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19215. bool got_100 = false;
  19216. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19217. EXPECT_TRUE(got_100);
  19218. }
  19219. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19220. bool got_100 = true;
  19221. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19222. EXPECT_FALSE(got_100);
  19223. }
  19224. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19225. bool got_100 = false;
  19226. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19227. EXPECT_TRUE(got_100);
  19228. }
  19229. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19230. bool got_100 = false;
  19231. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19232. EXPECT_TRUE(got_100);
  19233. }
  19234. // `100 Continue` is sent only when the server starts reading the body, so a
  19235. // request rejected before that never invites the client to send it. The
  19236. // requests below carry the expectation but withhold the body, as a client
  19237. // waiting for `100 Continue` would.
  19238. // A POST that expects `100 Continue` and withholds its two-byte body.
  19239. static std::string expect_headers_only(const std::string &path) {
  19240. return "POST " + path +
  19241. " HTTP/1.1\r\n"
  19242. "Host: localhost\r\n"
  19243. "Content-Length: 2\r\n"
  19244. "Expect: 100-continue\r\n"
  19245. "\r\n";
  19246. }
  19247. class ExpectLazyContinueTest : public ::testing::Test {
  19248. protected:
  19249. void SetUp() override {
  19250. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19251. if (req.path == "/pre-routing") {
  19252. res.status = StatusCode::Unauthorized_401;
  19253. return Server::HandlerResponse::Handled;
  19254. }
  19255. return Server::HandlerResponse::Unhandled;
  19256. });
  19257. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19258. if (req.matched_route == "/pre-request") {
  19259. res.status = StatusCode::Forbidden_403;
  19260. return Server::HandlerResponse::Handled;
  19261. }
  19262. return Server::HandlerResponse::Unhandled;
  19263. });
  19264. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19265. res.set_content("ok", "text/plain");
  19266. });
  19267. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19268. res.set_content("ok", "text/plain");
  19269. });
  19270. svr_.Post("/reader-used", [](const Request &, Response &res,
  19271. const ContentReader &content_reader) {
  19272. std::string body;
  19273. content_reader([&](const char *data, size_t len) {
  19274. body.append(data, len);
  19275. return true;
  19276. });
  19277. res.set_content(body, "text/plain");
  19278. });
  19279. svr_.Post("/reader-unused",
  19280. [](const Request &, Response &res, const ContentReader &) {
  19281. res.set_content("ignored", "text/plain");
  19282. });
  19283. port_ = svr_.bind_to_any_port(HOST);
  19284. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19285. svr_.wait_until_ready();
  19286. }
  19287. void TearDown() override {
  19288. svr_.stop();
  19289. if (thread_.joinable()) { thread_.join(); }
  19290. }
  19291. // Sends `req` and reads until the server closes the connection. Returns
  19292. // false if the read had to wait for the client-side timeout instead.
  19293. bool send_until_closed(const std::string &req, std::string *resp) const {
  19294. auto start = std::chrono::steady_clock::now();
  19295. if (!send_request(3, req, resp, port_)) { return false; }
  19296. auto elapsed = std::chrono::steady_clock::now() - start;
  19297. return elapsed < std::chrono::seconds(2);
  19298. }
  19299. // The final response comes without `100 Continue`, and the server closes
  19300. // the connection since the body may or may not follow.
  19301. void expect_final_without_interim(const std::string &path,
  19302. const char *status_line) const {
  19303. std::string resp;
  19304. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19305. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19306. EXPECT_EQ(0u, resp.find(status_line));
  19307. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19308. }
  19309. Server svr_;
  19310. int port_ = 0;
  19311. thread thread_;
  19312. };
  19313. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19314. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19315. }
  19316. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19317. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19318. }
  19319. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19320. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19321. }
  19322. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19323. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19324. }
  19325. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19326. // The body follows once `100 Continue` has had time to arrive.
  19327. auto req = expect_headers_only("/reader-used");
  19328. req.insert(req.size() - 2, "Connection: close\r\n");
  19329. std::string resp;
  19330. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19331. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19332. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19333. EXPECT_NE(std::string::npos, resp.find("hi"));
  19334. }
  19335. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19336. // Large enough for the client to add `Expect: 100-continue` itself.
  19337. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19338. std::atomic<bool> body_sent{false};
  19339. Client cli(HOST, port_);
  19340. auto res = cli.Post(
  19341. "/pre-request", length,
  19342. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19343. body_sent = true;
  19344. std::string chunk(len, 'x');
  19345. sink.write(chunk.data(), chunk.size());
  19346. return true;
  19347. },
  19348. "application/octet-stream");
  19349. ASSERT_TRUE(res);
  19350. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19351. EXPECT_FALSE(body_sent);
  19352. }
  19353. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19354. Server svr;
  19355. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19356. return StatusCode::ExpectationFailed_417;
  19357. });
  19358. svr.Post("/p", [](const Request &, Response &res) {
  19359. res.set_content("ok", "text/plain");
  19360. });
  19361. auto port = svr.bind_to_any_port(HOST);
  19362. thread t = thread([&] { svr.listen_after_bind(); });
  19363. auto se = detail::scope_exit([&] {
  19364. svr.stop();
  19365. t.join();
  19366. });
  19367. svr.wait_until_ready();
  19368. std::string resp;
  19369. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19370. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19371. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19372. // Exactly one response: the route handler must not run after the 417.
  19373. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19374. }
  19375. #ifndef _WIN32
  19376. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19377. static constexpr char reject[] = "Unauthorized";
  19378. static constexpr char accept[] = "Upload accepted";
  19379. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19380. Server svr;
  19381. svr.set_expect_100_continue_handler(
  19382. [](const Request & /*req*/, Response &res) {
  19383. res.status = StatusCode::Unauthorized_401;
  19384. res.set_content(reject, "text/plain");
  19385. return res.status;
  19386. });
  19387. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19388. res.set_content(accept, "text/plain");
  19389. });
  19390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19391. auto se = detail::scope_exit([&] {
  19392. svr.stop();
  19393. thread.join();
  19394. ASSERT_FALSE(svr.is_running());
  19395. });
  19396. svr.wait_until_ready();
  19397. {
  19398. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19399. curl_easy_init(), &curl_easy_cleanup};
  19400. ASSERT_NE(curl, nullptr);
  19401. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19402. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19403. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19404. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19405. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19406. &curl_slist_free_all};
  19407. ASSERT_NE(list, nullptr);
  19408. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19409. struct read_data {
  19410. uint64_t read_size;
  19411. uint64_t total_size;
  19412. } data = {0, total_size};
  19413. using read_callback_t =
  19414. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19415. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19416. void *userdata) -> size_t {
  19417. read_data *d = (read_data *)userdata;
  19418. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19419. std::fill_n(ptr, size * nmemb, 'A');
  19420. d->read_size += size * nmemb;
  19421. return size * nmemb;
  19422. };
  19423. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19424. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19425. std::vector<char> buffer;
  19426. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19427. using write_callback_t =
  19428. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19429. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19430. void *userdata) -> size_t {
  19431. std::vector<char> *buf = (std::vector<char> *)userdata;
  19432. buf->reserve(buf->size() + size * nmemb + 1);
  19433. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19434. return size * nmemb;
  19435. };
  19436. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19437. {
  19438. const auto res = curl_easy_perform(curl.get());
  19439. ASSERT_EQ(res, CURLE_OK);
  19440. }
  19441. {
  19442. auto response_code = long{};
  19443. const auto res =
  19444. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19445. ASSERT_EQ(res, CURLE_OK);
  19446. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19447. }
  19448. {
  19449. auto dl = curl_off_t{};
  19450. const auto res =
  19451. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19452. ASSERT_EQ(res, CURLE_OK);
  19453. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19454. }
  19455. {
  19456. buffer.push_back('\0');
  19457. ASSERT_STRCASEEQ(buffer.data(), reject);
  19458. }
  19459. }
  19460. }
  19461. #endif
  19462. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19463. // Regression test for #2458.
  19464. //
  19465. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19466. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19467. // ticket can make the client socket spuriously readable during the
  19468. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19469. // the client withholds the body and then blocks reading a response that never
  19470. // comes, failing with `Failed to read connection`.
  19471. //
  19472. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19473. // within the timeout. This raw OpenSSL server deliberately never sends
  19474. // `100 Continue`; the client must still deliver the body and receive 200.
  19475. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19476. signal(SIGPIPE, SIG_IGN);
  19477. const auto port = PORT + 4;
  19478. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19479. ASSERT_NE(srv, INVALID_SOCKET);
  19480. int opt = 1;
  19481. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19482. sockaddr_in addr{};
  19483. addr.sin_family = AF_INET;
  19484. addr.sin_port = htons(static_cast<uint16_t>(port));
  19485. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19486. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19487. ASSERT_EQ(0, ::listen(srv, 1));
  19488. std::atomic<size_t> server_body_bytes{0};
  19489. auto server_thread = std::thread([&] {
  19490. sockaddr_in cli_addr{};
  19491. socklen_t cli_len = sizeof(cli_addr);
  19492. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19493. if (cli == INVALID_SOCKET) { return; }
  19494. // Bound the lifetime of the server side so a buggy client (which never
  19495. // sends the body) cannot make this thread block forever on join.
  19496. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19497. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19498. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19499. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19500. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19501. SSL *ssl = SSL_new(ctx);
  19502. SSL_set_fd(ssl, static_cast<int>(cli));
  19503. if (SSL_accept(ssl) > 0) {
  19504. // Read the request headers. Reading here also flushes the TLS 1.3
  19505. // session tickets to the client. Deliberately do NOT send
  19506. // `100 Continue`.
  19507. std::string buf;
  19508. char tmp[1024];
  19509. while (buf.find("\r\n\r\n") == std::string::npos) {
  19510. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19511. if (n <= 0) { break; }
  19512. buf.append(tmp, static_cast<size_t>(n));
  19513. }
  19514. // A correct client sends the body now; count what arrives.
  19515. auto pos = buf.find("\r\n\r\n");
  19516. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19517. while (body < 4096) {
  19518. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19519. if (n <= 0) { break; }
  19520. body += static_cast<size_t>(n);
  19521. }
  19522. server_body_bytes = body;
  19523. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19524. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19525. SSL_shutdown(ssl);
  19526. }
  19527. SSL_free(ssl);
  19528. detail::close_socket(cli);
  19529. SSL_CTX_free(ctx);
  19530. });
  19531. auto se = detail::scope_exit([&] {
  19532. server_thread.join();
  19533. detail::close_socket(srv);
  19534. });
  19535. SSLClient cli("127.0.0.1", port);
  19536. cli.enable_server_certificate_verification(false);
  19537. cli.set_connection_timeout(5, 0);
  19538. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19539. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19540. std::string body(4096, 'A');
  19541. auto res = cli.Put("/api/test", body, "application/json");
  19542. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19543. EXPECT_EQ(StatusCode::OK_200, res->status);
  19544. EXPECT_EQ(body.size(), server_body_bytes.load());
  19545. }
  19546. #endif
  19547. template <typename S, typename C>
  19548. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19549. svr.Get("/stream", [&](const Request &, Response &res) {
  19550. auto data = new std::string("01234567890123456789");
  19551. res.set_content_provider(
  19552. data->size(), "text/plain",
  19553. [&, data](size_t offset, size_t length, DataSink &sink) {
  19554. const size_t DATA_CHUNK_SIZE = 4;
  19555. const auto &d = *data;
  19556. std::this_thread::sleep_for(std::chrono::seconds(1));
  19557. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19558. return true;
  19559. },
  19560. [data](bool success) {
  19561. EXPECT_FALSE(success);
  19562. delete data;
  19563. });
  19564. });
  19565. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19566. auto i = new size_t(0);
  19567. res.set_content_provider(
  19568. "text/plain",
  19569. [i](size_t, DataSink &sink) {
  19570. if (*i < 5) {
  19571. std::this_thread::sleep_for(std::chrono::seconds(1));
  19572. sink.write("abcd", 4);
  19573. (*i)++;
  19574. } else {
  19575. sink.done();
  19576. }
  19577. return true;
  19578. },
  19579. [i](bool success) {
  19580. EXPECT_FALSE(success);
  19581. delete i;
  19582. });
  19583. });
  19584. svr.Get("/chunked", [&](const Request &, Response &res) {
  19585. auto i = new size_t(0);
  19586. res.set_chunked_content_provider(
  19587. "text/plain",
  19588. [i](size_t, DataSink &sink) {
  19589. if (*i < 5) {
  19590. std::this_thread::sleep_for(std::chrono::seconds(1));
  19591. sink.os << "abcd";
  19592. (*i)++;
  19593. } else {
  19594. sink.done();
  19595. }
  19596. return true;
  19597. },
  19598. [i](bool success) {
  19599. EXPECT_FALSE(success);
  19600. delete i;
  19601. });
  19602. });
  19603. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19604. auto se = detail::scope_exit([&] {
  19605. svr.stop();
  19606. listen_thread.join();
  19607. ASSERT_FALSE(svr.is_running());
  19608. });
  19609. svr.wait_until_ready();
  19610. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19611. {
  19612. auto start = std::chrono::steady_clock::now();
  19613. auto res = cli.Get("/stream");
  19614. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19615. std::chrono::steady_clock::now() - start)
  19616. .count();
  19617. ASSERT_FALSE(res);
  19618. EXPECT_EQ(Error::Read, res.error());
  19619. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19620. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19621. }
  19622. {
  19623. auto start = std::chrono::steady_clock::now();
  19624. auto res = cli.Get("/stream_without_length");
  19625. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19626. std::chrono::steady_clock::now() - start)
  19627. .count();
  19628. ASSERT_FALSE(res);
  19629. EXPECT_EQ(Error::Read, res.error());
  19630. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19631. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19632. }
  19633. {
  19634. auto start = std::chrono::steady_clock::now();
  19635. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19636. EXPECT_EQ("abcd", string(data, data_length));
  19637. return true;
  19638. });
  19639. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19640. std::chrono::steady_clock::now() - start)
  19641. .count();
  19642. ASSERT_FALSE(res);
  19643. EXPECT_EQ(Error::Read, res.error());
  19644. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19645. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19646. }
  19647. }
  19648. TEST(MaxTimeoutTest, ContentStream) {
  19649. time_t timeout = 2000;
  19650. time_t threshold = 200;
  19651. Server svr;
  19652. Client cli("localhost", PORT);
  19653. max_timeout_test(svr, cli, timeout, threshold);
  19654. }
  19655. #ifdef CPPHTTPLIB_SSL_ENABLED
  19656. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19657. time_t timeout = 2000;
  19658. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19660. SSLClient cli("localhost", PORT);
  19661. cli.enable_server_certificate_verification(false);
  19662. max_timeout_test(svr, cli, timeout, threshold);
  19663. }
  19664. #endif
  19665. class EventDispatcher {
  19666. public:
  19667. EventDispatcher() {}
  19668. bool wait_event(DataSink *sink) {
  19669. unique_lock<mutex> lk(m_);
  19670. int id = id_;
  19671. // Wait with timeout to prevent hanging if client disconnects
  19672. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19673. [&] { return cid_ == id; })) {
  19674. return false; // Timeout occurred
  19675. }
  19676. sink->write(message_.data(), message_.size());
  19677. return true;
  19678. }
  19679. void send_event(const string &message) {
  19680. lock_guard<mutex> lk(m_);
  19681. cid_ = id_++;
  19682. message_ = message;
  19683. cv_.notify_all();
  19684. }
  19685. private:
  19686. mutex m_;
  19687. condition_variable cv_;
  19688. atomic_int id_{0};
  19689. atomic_int cid_{-1};
  19690. string message_;
  19691. };
  19692. TEST(ClientInThreadTest, Issue2068) {
  19693. EventDispatcher ed;
  19694. Server svr;
  19695. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19696. res.set_chunked_content_provider("text/event-stream",
  19697. [&](size_t /*offset*/, DataSink &sink) {
  19698. return ed.wait_event(&sink);
  19699. });
  19700. });
  19701. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19702. svr.wait_until_ready();
  19703. thread event_thread([&] {
  19704. int id = 0;
  19705. while (svr.is_running()) {
  19706. this_thread::sleep_for(chrono::milliseconds(500));
  19707. std::stringstream ss;
  19708. ss << "data: " << id << "\n\n";
  19709. ed.send_event(ss.str());
  19710. id++;
  19711. }
  19712. });
  19713. auto se = detail::scope_exit([&] {
  19714. svr.stop();
  19715. listen_thread.join();
  19716. event_thread.join();
  19717. ASSERT_FALSE(svr.is_running());
  19718. });
  19719. {
  19720. auto client = detail::make_unique<Client>(HOST, PORT);
  19721. client->set_read_timeout(std::chrono::minutes(10));
  19722. std::atomic<bool> stop{false};
  19723. std::thread t([&] {
  19724. client->Get("/event1",
  19725. [&](const char *, size_t) -> bool { return !stop; });
  19726. });
  19727. std::this_thread::sleep_for(std::chrono::seconds(2));
  19728. stop = true;
  19729. client->stop();
  19730. t.join();
  19731. // Reset client after thread has finished
  19732. client.reset();
  19733. }
  19734. }
  19735. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19736. auto handled = false;
  19737. Server svr;
  19738. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19739. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19740. auto se = detail::scope_exit([&] {
  19741. svr.stop();
  19742. t.join();
  19743. ASSERT_FALSE(svr.is_running());
  19744. ASSERT_FALSE(handled);
  19745. });
  19746. svr.wait_until_ready();
  19747. // Two Content-Length headers with different values — must be rejected
  19748. auto req = "POST /test HTTP/1.1\r\n"
  19749. "Content-Length: 5\r\n"
  19750. "Content-Length: 10\r\n"
  19751. "\r\n"
  19752. "hello";
  19753. std::string response;
  19754. ASSERT_TRUE(send_request(1, req, &response));
  19755. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19756. response.substr(0, response.find("\r\n")));
  19757. }
  19758. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19759. auto handled = false;
  19760. Server svr;
  19761. svr.Post("/test", [&](const Request &, Response &res) {
  19762. handled = true;
  19763. res.set_content("ok", "text/plain");
  19764. });
  19765. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19766. auto se = detail::scope_exit([&] {
  19767. svr.stop();
  19768. t.join();
  19769. ASSERT_FALSE(svr.is_running());
  19770. ASSERT_TRUE(handled);
  19771. });
  19772. svr.wait_until_ready();
  19773. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19774. auto req = "POST /test HTTP/1.1\r\n"
  19775. "Host: localhost\r\n"
  19776. "Content-Length: 5\r\n"
  19777. "Content-Length: 5\r\n"
  19778. "\r\n"
  19779. "hello";
  19780. std::string response;
  19781. ASSERT_TRUE(send_request(1, req, &response));
  19782. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19783. }
  19784. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19785. Server svr;
  19786. svr.Get("/test", [](const Request &, Response &res) {
  19787. res.set_content("ok", "text/plain");
  19788. });
  19789. auto port = svr.bind_to_any_port(HOST);
  19790. thread t = thread([&] { svr.listen_after_bind(); });
  19791. auto se = detail::scope_exit([&] {
  19792. svr.stop();
  19793. t.join();
  19794. ASSERT_FALSE(svr.is_running());
  19795. });
  19796. svr.wait_until_ready();
  19797. auto status_line = [&](const std::string &host_lines) {
  19798. std::string res;
  19799. send_request(
  19800. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19801. &res, port);
  19802. return res.substr(0, res.find("\r\n"));
  19803. };
  19804. const char *accepted[] = {
  19805. "Host: localhost\r\n",
  19806. "Host: a.example:8080\r\n",
  19807. "Host: my_service\r\n",
  19808. "Host: [::1]:8080\r\n",
  19809. "Host: [fe80::1%25eth0]\r\n",
  19810. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19811. };
  19812. for (auto host_lines : accepted) {
  19813. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19814. }
  19815. const char *rejected[] = {
  19816. "Host: a.example\r\nHost: b.example\r\n",
  19817. "Host: a.example\r\nHost: a.example\r\n",
  19818. "Host: a@b.example\r\n",
  19819. "Host: a.example/b\r\n",
  19820. "Host: a.example\\b\r\n",
  19821. "Host: a.example?b\r\n",
  19822. "Host: a.example#b\r\n",
  19823. "Host: a.example b.example\r\n",
  19824. };
  19825. for (auto host_lines : rejected) {
  19826. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19827. << host_lines;
  19828. }
  19829. }
  19830. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19831. Server svr;
  19832. svr.Get("/", [](const Request &req, Response &res) {
  19833. EXPECT_EQ(2U, req.trailers.size());
  19834. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19835. // Denied
  19836. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19837. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19838. // Accepted
  19839. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19840. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19841. EXPECT_TRUE(req.has_trailer("X-World"));
  19842. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19843. res.set_content("ok", "text/plain");
  19844. });
  19845. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19846. auto se = detail::scope_exit([&] {
  19847. svr.stop();
  19848. t.join();
  19849. ASSERT_FALSE(svr.is_running());
  19850. });
  19851. svr.wait_until_ready();
  19852. const std::string req = "GET / HTTP/1.1\r\n"
  19853. "Transfer-Encoding: chunked\r\n"
  19854. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19855. "\r\n"
  19856. "0\r\n"
  19857. "Content-Length: 10\r\n"
  19858. "Host: internal.local\r\n"
  19859. "Content-Type: malicious/content\r\n"
  19860. "Cookie: any\r\n"
  19861. "Set-Cookie: any\r\n"
  19862. "X-Forwarded-For: attacker.com\r\n"
  19863. "X-Real-Ip: 1.1.1.1\r\n"
  19864. "X-Hello: hello\r\n"
  19865. "X-World: world\r\n"
  19866. "\r\n";
  19867. std::string res;
  19868. ASSERT_TRUE(send_request(1, req, &res));
  19869. }
  19870. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19871. // several field lines, and the combined value is what has to be parsed. A
  19872. // Trailer field split across lines therefore declares every name it lists;
  19873. // reading only the first line silently drops the trailers the later lines
  19874. // declare. The prohibited-trailer filter still applies to every line.
  19875. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19876. Server svr;
  19877. size_t observed_trailer_count = 0;
  19878. std::string observed_hello;
  19879. std::string observed_world;
  19880. bool observed_content_length = true;
  19881. svr.Get("/", [&](const Request &req, Response &res) {
  19882. observed_trailer_count = req.trailers.size();
  19883. observed_hello = req.get_trailer_value("X-Hello");
  19884. observed_world = req.get_trailer_value("X-World");
  19885. observed_content_length = req.has_trailer("Content-Length");
  19886. res.set_content("ok", "text/plain");
  19887. });
  19888. auto port = svr.bind_to_any_port(HOST);
  19889. thread t = thread([&]() { svr.listen_after_bind(); });
  19890. auto se = detail::scope_exit([&] {
  19891. svr.stop();
  19892. t.join();
  19893. ASSERT_FALSE(svr.is_running());
  19894. });
  19895. svr.wait_until_ready();
  19896. const std::string req = "GET / HTTP/1.1\r\n"
  19897. "Host: localhost\r\n"
  19898. "Transfer-Encoding: chunked\r\n"
  19899. "Trailer: X-Hello\r\n"
  19900. "Trailer: X-World, Content-Length\r\n"
  19901. "\r\n"
  19902. "0\r\n"
  19903. "X-Hello: hello\r\n"
  19904. "X-World: world\r\n"
  19905. "Content-Length: 10\r\n"
  19906. "\r\n";
  19907. std::string res;
  19908. ASSERT_TRUE(send_request(1, req, &res, port));
  19909. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19910. // Accepted: both field lines contribute to the declared set
  19911. EXPECT_EQ(2U, observed_trailer_count);
  19912. EXPECT_EQ(observed_hello, "hello");
  19913. EXPECT_EQ(observed_world, "world");
  19914. // Denied: a prohibited name stays prohibited on a later field line
  19915. EXPECT_FALSE(observed_content_length);
  19916. }
  19917. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19918. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19919. // unbounded run of fields that are never declared, because the counter would
  19920. // only advance for declared fields.
  19921. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19922. Server svr;
  19923. bool handler_called = false;
  19924. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19925. handler_called = true;
  19926. res.set_content("ok", "text/plain");
  19927. });
  19928. auto port = svr.bind_to_any_port(HOST);
  19929. thread t = thread([&]() { svr.listen_after_bind(); });
  19930. auto se = detail::scope_exit([&] {
  19931. svr.stop();
  19932. t.join();
  19933. ASSERT_FALSE(svr.is_running());
  19934. });
  19935. svr.wait_until_ready();
  19936. // Declare nothing, then send far more undeclared trailer fields than the
  19937. // header-count limit. Parsing must stop and reject the request rather than
  19938. // read every line.
  19939. std::string req = "GET / HTTP/1.1\r\n"
  19940. "Transfer-Encoding: chunked\r\n"
  19941. "\r\n"
  19942. "0\r\n";
  19943. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19944. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19945. }
  19946. req += "\r\n";
  19947. std::string res;
  19948. ASSERT_TRUE(send_request(1, req, &res, port));
  19949. // The request is rejected before the handler runs.
  19950. EXPECT_FALSE(handler_called);
  19951. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19952. }
  19953. // The set of declared trailer names is capped so a peer cannot grow it without
  19954. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19955. // declared past the cap is not honored, even if the field is actually sent.
  19956. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19957. Server svr;
  19958. // One name inside the cap and one past it, so the test tracks the cap rather
  19959. // than a fixed count.
  19960. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19961. const std::string within_cap_name = "X-T-0";
  19962. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19963. bool observed_within_cap = false;
  19964. bool observed_past_cap = false;
  19965. svr.Get("/", [&](const Request &req, Response &res) {
  19966. observed_within_cap = req.has_trailer(within_cap_name);
  19967. observed_past_cap = req.has_trailer(past_cap_name);
  19968. res.set_content("ok", "text/plain");
  19969. });
  19970. auto port = svr.bind_to_any_port(HOST);
  19971. thread t = thread([&]() { svr.listen_after_bind(); });
  19972. auto se = detail::scope_exit([&] {
  19973. svr.stop();
  19974. t.join();
  19975. ASSERT_FALSE(svr.is_running());
  19976. });
  19977. svr.wait_until_ready();
  19978. // Declare more trailer names than the cap in a single Trailer field, then
  19979. // actually send the first (within the cap) and the last (past it).
  19980. std::string trailer_decl = "Trailer: ";
  19981. for (int i = 0; i < declared_count; i++) {
  19982. if (i != 0) { trailer_decl += ", "; }
  19983. trailer_decl += "X-T-" + std::to_string(i);
  19984. }
  19985. trailer_decl += "\r\n";
  19986. const std::string req = "GET / HTTP/1.1\r\n"
  19987. "Host: localhost\r\n"
  19988. "Transfer-Encoding: chunked\r\n" +
  19989. trailer_decl +
  19990. "\r\n"
  19991. "0\r\n" +
  19992. within_cap_name + ": a\r\n" + past_cap_name +
  19993. ": b\r\n"
  19994. "\r\n";
  19995. std::string res;
  19996. ASSERT_TRUE(send_request(1, req, &res, port));
  19997. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19998. // A name within the cap is honored; one declared past the cap is dropped.
  19999. EXPECT_TRUE(observed_within_cap);
  20000. EXPECT_FALSE(observed_past_cap);
  20001. }
  20002. // A direct client that is not listed in trusted_proxies must not be able to
  20003. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  20004. // the peer address on the actual TCP connection determines whether the
  20005. // header is honored.
  20006. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  20007. Server svr;
  20008. // Deliberately does NOT include the loopback address the test client
  20009. // actually connects from, so the direct connection is not a trusted proxy.
  20010. svr.set_trusted_proxies({"203.0.113.66"});
  20011. std::string observed_remote_addr;
  20012. svr.Get("/ip", [&](const Request &req, Response &res) {
  20013. observed_remote_addr = req.remote_addr;
  20014. res.set_content("ok", "text/plain");
  20015. });
  20016. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20017. auto se = detail::scope_exit([&] {
  20018. svr.stop();
  20019. t.join();
  20020. ASSERT_FALSE(svr.is_running());
  20021. });
  20022. svr.wait_until_ready();
  20023. Client cli(HOST, PORT);
  20024. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  20025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20026. EXPECT_EQ(StatusCode::OK_200, res->status);
  20027. // The connecting peer is not a trusted proxy, so the spoofed header must be
  20028. // ignored entirely and the real connection-level address retained.
  20029. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20030. observed_remote_addr == "127.0.0.1");
  20031. }
  20032. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  20033. Server svr;
  20034. std::string observed_remote_addr;
  20035. std::string observed_xff;
  20036. svr.Get("/ip", [&](const Request &req, Response &res) {
  20037. observed_remote_addr = req.remote_addr;
  20038. observed_xff = req.get_header_value("X-Forwarded-For");
  20039. res.set_content("ok", "text/plain");
  20040. });
  20041. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20042. auto se = detail::scope_exit([&] {
  20043. svr.stop();
  20044. t.join();
  20045. ASSERT_FALSE(svr.is_running());
  20046. });
  20047. svr.wait_until_ready();
  20048. Client cli(HOST, PORT);
  20049. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20051. EXPECT_EQ(StatusCode::OK_200, res->status);
  20052. EXPECT_EQ(observed_xff, "203.0.113.66");
  20053. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20054. observed_remote_addr == "127.0.0.1");
  20055. }
  20056. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20057. Server svr;
  20058. svr.set_trusted_proxies({"203.0.113.66"});
  20059. std::string observed_remote_addr;
  20060. std::string observed_xff;
  20061. svr.Get("/ip", [&](const Request &req, Response &res) {
  20062. observed_remote_addr = req.remote_addr;
  20063. observed_xff = req.get_header_value("X-Forwarded-For");
  20064. res.set_content("ok", "text/plain");
  20065. });
  20066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20067. auto se = detail::scope_exit([&] {
  20068. svr.stop();
  20069. t.join();
  20070. ASSERT_FALSE(svr.is_running());
  20071. });
  20072. svr.wait_until_ready();
  20073. Client cli(HOST, PORT);
  20074. auto res = cli.Get("/ip");
  20075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20076. EXPECT_EQ(StatusCode::OK_200, res->status);
  20077. EXPECT_EQ(observed_xff, "");
  20078. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20079. observed_remote_addr == "127.0.0.1");
  20080. }
  20081. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20082. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20083. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20084. Server svr;
  20085. svr.set_trusted_proxies({"127.0.0.1"});
  20086. svr.Get("/ip", [](const Request &req, Response &res) {
  20087. res.set_content(req.remote_addr, "text/plain");
  20088. });
  20089. auto port = svr.bind_to_any_port("::");
  20090. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20091. thread t = thread([&] { svr.listen_after_bind(); });
  20092. auto se = detail::scope_exit([&] {
  20093. svr.stop();
  20094. t.join();
  20095. ASSERT_FALSE(svr.is_running());
  20096. });
  20097. svr.wait_until_ready();
  20098. Client cli("127.0.0.1", port);
  20099. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20101. EXPECT_EQ("198.51.100.23", res->body);
  20102. }
  20103. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20104. Server svr;
  20105. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20106. svr.Get("/ip", [](const Request &req, Response &res) {
  20107. res.set_content(req.remote_addr, "text/plain");
  20108. });
  20109. auto port = svr.bind_to_any_port(HOST);
  20110. ASSERT_GT(port, 0);
  20111. thread t = thread([&] { svr.listen_after_bind(); });
  20112. auto se = detail::scope_exit([&] {
  20113. svr.stop();
  20114. t.join();
  20115. ASSERT_FALSE(svr.is_running());
  20116. });
  20117. svr.wait_until_ready();
  20118. Client cli(HOST, port);
  20119. auto res = cli.Get(
  20120. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20122. EXPECT_EQ("198.51.100.23", res->body);
  20123. }
  20124. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20125. Server svr;
  20126. // Include the loopback address the test client actually connects from, so
  20127. // the direct connection itself is recognized as the trusted proxy hop.
  20128. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20129. std::string observed_remote_addr;
  20130. std::string observed_xff;
  20131. svr.Get("/ip", [&](const Request &req, Response &res) {
  20132. observed_remote_addr = req.remote_addr;
  20133. observed_xff = req.get_header_value("X-Forwarded-For");
  20134. res.set_content("ok", "text/plain");
  20135. });
  20136. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20137. auto se = detail::scope_exit([&] {
  20138. svr.stop();
  20139. t.join();
  20140. ASSERT_FALSE(svr.is_running());
  20141. });
  20142. svr.wait_until_ready();
  20143. Client cli(HOST, PORT);
  20144. auto res = cli.Get(
  20145. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20147. EXPECT_EQ(StatusCode::OK_200, res->status);
  20148. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20149. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20150. }
  20151. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20152. Server svr;
  20153. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20154. std::string observed_remote_addr;
  20155. std::string observed_xff;
  20156. svr.Get("/ip", [&](const Request &req, Response &res) {
  20157. observed_remote_addr = req.remote_addr;
  20158. observed_xff = req.get_header_value("X-Forwarded-For");
  20159. res.set_content("ok", "text/plain");
  20160. });
  20161. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20162. auto se = detail::scope_exit([&] {
  20163. svr.stop();
  20164. t.join();
  20165. ASSERT_FALSE(svr.is_running());
  20166. });
  20167. svr.wait_until_ready();
  20168. Client cli(HOST, PORT);
  20169. auto res = cli.Get(
  20170. "/ip",
  20171. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20173. EXPECT_EQ(StatusCode::OK_200, res->status);
  20174. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20175. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20176. }
  20177. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20178. Server svr;
  20179. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20180. std::string observed_remote_addr;
  20181. std::string observed_xff;
  20182. svr.Get("/ip", [&](const Request &req, Response &res) {
  20183. observed_remote_addr = req.remote_addr;
  20184. observed_xff = req.get_header_value("X-Forwarded-For");
  20185. res.set_content("ok", "text/plain");
  20186. });
  20187. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20188. auto se = detail::scope_exit([&] {
  20189. svr.stop();
  20190. t.join();
  20191. ASSERT_FALSE(svr.is_running());
  20192. });
  20193. svr.wait_until_ready();
  20194. Client cli(HOST, PORT);
  20195. auto res = cli.Get(
  20196. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20198. EXPECT_EQ(StatusCode::OK_200, res->status);
  20199. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20200. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20201. // and must not be selected.
  20202. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20203. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20204. }
  20205. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20206. Server svr;
  20207. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20208. std::string observed_remote_addr;
  20209. svr.Get("/ip", [&](const Request &req, Response &res) {
  20210. observed_remote_addr = req.remote_addr;
  20211. res.set_content("ok", "text/plain");
  20212. });
  20213. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20214. auto se = detail::scope_exit([&] {
  20215. svr.stop();
  20216. t.join();
  20217. ASSERT_FALSE(svr.is_running());
  20218. });
  20219. svr.wait_until_ready();
  20220. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20221. // a forged address and the trusted proxy's own address; the forged value must
  20222. // not win over the address the trusted proxy actually recorded.
  20223. Client cli(HOST, PORT);
  20224. auto res = cli.Get(
  20225. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20227. EXPECT_EQ(StatusCode::OK_200, res->status);
  20228. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20229. }
  20230. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20231. Server svr;
  20232. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20233. std::string observed_remote_addr;
  20234. std::string observed_xff;
  20235. svr.Get("/ip", [&](const Request &req, Response &res) {
  20236. observed_remote_addr = req.remote_addr;
  20237. observed_xff = req.get_header_value("X-Forwarded-For");
  20238. res.set_content("ok", "text/plain");
  20239. });
  20240. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20241. auto se = detail::scope_exit([&] {
  20242. svr.stop();
  20243. t.join();
  20244. ASSERT_FALSE(svr.is_running());
  20245. });
  20246. svr.wait_until_ready();
  20247. Client cli(HOST, PORT);
  20248. auto res = cli.Get(
  20249. "/ip",
  20250. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20252. EXPECT_EQ(StatusCode::OK_200, res->status);
  20253. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20254. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20255. }
  20256. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20257. Server svr;
  20258. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20259. std::string observed_remote_addr;
  20260. std::string observed_xff;
  20261. svr.Get("/ip", [&](const Request &req, Response &res) {
  20262. observed_remote_addr = req.remote_addr;
  20263. observed_xff = req.get_header_value("X-Forwarded-For");
  20264. res.set_content("ok", "text/plain");
  20265. });
  20266. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20267. auto se = detail::scope_exit([&] {
  20268. svr.stop();
  20269. t.join();
  20270. ASSERT_FALSE(svr.is_running());
  20271. });
  20272. svr.wait_until_ready();
  20273. std::string raw_req =
  20274. "GET /ip HTTP/1.1\r\n"
  20275. "Host: localhost\r\n"
  20276. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20277. "Connection: close\r\n"
  20278. "\r\n";
  20279. std::string out;
  20280. ASSERT_TRUE(send_request(5, raw_req, &out));
  20281. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20282. // Header parser trims surrounding whitespace of the header value
  20283. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20284. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20285. }
  20286. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20287. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20288. // their own X-Forwarded-For as a separate field line rather than extending the
  20289. // one the client sent, so every occurrence has to be taken into account.
  20290. // Reading only the first one hands back the address the client chose.
  20291. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20292. Server svr;
  20293. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20294. std::string observed_remote_addr;
  20295. size_t observed_xff_count = 0;
  20296. svr.Get("/ip", [&](const Request &req, Response &res) {
  20297. observed_remote_addr = req.remote_addr;
  20298. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20299. res.set_content("ok", "text/plain");
  20300. });
  20301. auto port = svr.bind_to_any_port(HOST);
  20302. thread t = thread([&]() { svr.listen_after_bind(); });
  20303. auto se = detail::scope_exit([&] {
  20304. svr.stop();
  20305. t.join();
  20306. ASSERT_FALSE(svr.is_running());
  20307. });
  20308. svr.wait_until_ready();
  20309. // The client supplies the first field line; the trusted proxy appends the
  20310. // address it observed as a second one.
  20311. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20312. "Host: localhost\r\n"
  20313. "X-Forwarded-For: 1.2.3.4\r\n"
  20314. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20315. "Connection: close\r\n"
  20316. "\r\n";
  20317. std::string out;
  20318. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20319. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20320. EXPECT_EQ(observed_xff_count, 2U);
  20321. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20322. // The same chain spread over one field line per hop derives the same client
  20323. // address, i.e. the split and the comma-joined representations agree.
  20324. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20325. "Host: localhost\r\n"
  20326. "X-Forwarded-For: 1.2.3.4\r\n"
  20327. "X-Forwarded-For: 198.51.100.23\r\n"
  20328. "X-Forwarded-For: 192.0.2.45\r\n"
  20329. "Connection: close\r\n"
  20330. "\r\n";
  20331. out.clear();
  20332. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20333. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20334. EXPECT_EQ(observed_xff_count, 3U);
  20335. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20336. }
  20337. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20338. // crash the server (it used to call front() on an empty vector inside
  20339. // get_client_ip). The connection-level remote address must be retained instead.
  20340. static void run_malformed_xff_test(const std::string &xff_value) {
  20341. Server svr;
  20342. svr.set_trusted_proxies({"192.0.2.45"});
  20343. std::string observed_remote_addr;
  20344. svr.Get("/ip", [&](const Request &req, Response &res) {
  20345. observed_remote_addr = req.remote_addr;
  20346. res.set_content("ok", "text/plain");
  20347. });
  20348. int port = 0;
  20349. thread t = thread([&]() {
  20350. port = svr.bind_to_any_port(HOST);
  20351. svr.listen_after_bind();
  20352. });
  20353. auto se = detail::scope_exit([&] {
  20354. svr.stop();
  20355. t.join();
  20356. ASSERT_FALSE(svr.is_running());
  20357. });
  20358. svr.wait_until_ready();
  20359. Client cli(HOST, port);
  20360. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20362. EXPECT_EQ(StatusCode::OK_200, res->status);
  20363. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20364. observed_remote_addr == "127.0.0.1");
  20365. }
  20366. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20367. run_malformed_xff_test("");
  20368. }
  20369. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20370. run_malformed_xff_test(",");
  20371. }
  20372. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20373. run_malformed_xff_test(", , ,");
  20374. }
  20375. // The same rule applies to Accept: a request whose acceptable types are spread
  20376. // over several field lines must be negotiated against all of them.
  20377. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20378. // case-insensitive connection options. Comparing the whole field value against
  20379. // one option misses a client that sends several of them, and misses every
  20380. // casing but the one written in the comparison.
  20381. //
  20382. // Sends req, reads the response, then reuses the same socket for a second
  20383. // request to find out whether the server kept the connection.
  20384. static void probe_connection_reuse(int port, const std::string &req,
  20385. bool *announced_close, bool *reusable) {
  20386. auto error = Error::Success;
  20387. auto sock = detail::create_client_socket(
  20388. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20389. /*connection_timeout_sec=*/5, 0,
  20390. /*read_timeout_sec=*/1, 0,
  20391. /*write_timeout_sec=*/5, 0, std::string(), error);
  20392. ASSERT_NE(sock, INVALID_SOCKET);
  20393. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20394. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20395. "Host: localhost\r\n"
  20396. "Connection: close\r\n"
  20397. "\r\n";
  20398. std::string first_response;
  20399. std::string second_response;
  20400. detail::process_client_socket(
  20401. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20402. [&](Stream &strm) {
  20403. if (strm.write(req.data(), req.size()) !=
  20404. static_cast<ssize_t>(req.size())) {
  20405. return false;
  20406. }
  20407. char buf[512];
  20408. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20409. // Headers plus the two-byte body of the handler below
  20410. while (reader.getline()) {
  20411. first_response += reader.ptr();
  20412. if (first_response.find("ok") != std::string::npos) { break; }
  20413. }
  20414. if (strm.write(second.data(), second.size()) !=
  20415. static_cast<ssize_t>(second.size())) {
  20416. return true;
  20417. }
  20418. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20419. while (reader2.getline()) {
  20420. second_response += reader2.ptr();
  20421. if (second_response.find("ok") != std::string::npos) { break; }
  20422. }
  20423. return true;
  20424. });
  20425. *announced_close =
  20426. first_response.find("Connection: close") != std::string::npos;
  20427. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20428. }
  20429. class ConnectionTokenTest : public ::testing::Test {
  20430. protected:
  20431. void SetUp() override {
  20432. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20433. res.set_content("ok", "text/plain");
  20434. });
  20435. port_ = svr_.bind_to_any_port(HOST);
  20436. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20437. svr_.wait_until_ready();
  20438. }
  20439. void TearDown() override {
  20440. svr_.stop();
  20441. if (thread_.joinable()) { thread_.join(); }
  20442. }
  20443. Server svr_;
  20444. int port_ = 0;
  20445. thread thread_;
  20446. };
  20447. // "close" alongside another option still closes the connection, and the
  20448. // response says so rather than leaving the peer to discover it.
  20449. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20450. bool announced_close = false;
  20451. bool reusable = true;
  20452. probe_connection_reuse(port_,
  20453. "GET /keepalive HTTP/1.1\r\n"
  20454. "Host: localhost\r\n"
  20455. "Connection: keep-alive, close\r\n"
  20456. "\r\n",
  20457. &announced_close, &reusable);
  20458. EXPECT_TRUE(announced_close);
  20459. EXPECT_FALSE(reusable);
  20460. }
  20461. // "close" split over two field lines is the same list, so it is honored too.
  20462. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20463. bool announced_close = false;
  20464. bool reusable = true;
  20465. probe_connection_reuse(port_,
  20466. "GET /keepalive HTTP/1.1\r\n"
  20467. "Host: localhost\r\n"
  20468. "Connection: keep-alive\r\n"
  20469. "Connection: close\r\n"
  20470. "\r\n",
  20471. &announced_close, &reusable);
  20472. EXPECT_TRUE(announced_close);
  20473. EXPECT_FALSE(reusable);
  20474. }
  20475. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20476. // keep-alive in the spelling everyone actually sends keeps its connection.
  20477. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20478. bool announced_close = false;
  20479. bool reusable = false;
  20480. probe_connection_reuse(port_,
  20481. "GET /keepalive HTTP/1.0\r\n"
  20482. "Host: localhost\r\n"
  20483. "Connection: keep-alive\r\n"
  20484. "\r\n",
  20485. &announced_close, &reusable);
  20486. EXPECT_FALSE(announced_close);
  20487. EXPECT_TRUE(reusable);
  20488. }
  20489. // A token the value merely contains is not the token itself.
  20490. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20491. bool announced_close = false;
  20492. bool reusable = false;
  20493. probe_connection_reuse(port_,
  20494. "GET /keepalive HTTP/1.1\r\n"
  20495. "Host: localhost\r\n"
  20496. "Connection: notclose\r\n"
  20497. "\r\n",
  20498. &announced_close, &reusable);
  20499. EXPECT_FALSE(announced_close);
  20500. EXPECT_TRUE(reusable);
  20501. }
  20502. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20503. Server svr;
  20504. std::vector<std::string> observed_types;
  20505. svr.Get("/", [&](const Request &req, Response &res) {
  20506. observed_types = req.accept_content_types;
  20507. res.set_content("ok", "text/plain");
  20508. });
  20509. auto port = svr.bind_to_any_port(HOST);
  20510. thread t = thread([&]() { svr.listen_after_bind(); });
  20511. auto se = detail::scope_exit([&] {
  20512. svr.stop();
  20513. t.join();
  20514. ASSERT_FALSE(svr.is_running());
  20515. });
  20516. svr.wait_until_ready();
  20517. Client cli(HOST, port);
  20518. Headers headers;
  20519. headers.emplace("Accept", "text/plain;q=0.5");
  20520. headers.emplace("Accept", "application/json");
  20521. auto res = cli.Get("/", headers);
  20522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20523. EXPECT_EQ(StatusCode::OK_200, res->status);
  20524. // Sorted by q-value, so the second field line's type comes first
  20525. ASSERT_EQ(2U, observed_types.size());
  20526. EXPECT_EQ("application/json", observed_types[0]);
  20527. EXPECT_EQ("text/plain", observed_types[1]);
  20528. }
  20529. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20530. // empty field line must not contribute a bare comma to the combined value.
  20531. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20532. Server svr;
  20533. std::vector<std::string> observed_types;
  20534. svr.Get("/", [&](const Request &req, Response &res) {
  20535. observed_types = req.accept_content_types;
  20536. res.set_content("ok", "text/plain");
  20537. });
  20538. auto port = svr.bind_to_any_port(HOST);
  20539. thread t = thread([&]() { svr.listen_after_bind(); });
  20540. auto se = detail::scope_exit([&] {
  20541. svr.stop();
  20542. t.join();
  20543. ASSERT_FALSE(svr.is_running());
  20544. });
  20545. svr.wait_until_ready();
  20546. // Empty first field line, then a real one
  20547. std::string raw_req = "GET / HTTP/1.1\r\n"
  20548. "Host: localhost\r\n"
  20549. "Accept:\r\n"
  20550. "Accept: application/json\r\n"
  20551. "Connection: close\r\n"
  20552. "\r\n";
  20553. std::string out;
  20554. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20555. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20556. ASSERT_EQ(1U, observed_types.size());
  20557. EXPECT_EQ("application/json", observed_types[0]);
  20558. }
  20559. // The skip in get_combined_header_value() is what keeps an empty field line
  20560. // from contributing a bare comma. Only a trailing empty field line exercises
  20561. // it: a leading one is already covered by the "combined is still empty" check,
  20562. // and parse_accept_header() now ignores the empty element either way, so the
  20563. // request-level test above can no longer tell the two apart.
  20564. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20565. Headers headers;
  20566. headers.emplace("Accept", "text/html");
  20567. headers.emplace("Accept", "");
  20568. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20569. headers.clear();
  20570. headers.emplace("Accept", "");
  20571. headers.emplace("Accept", "application/json");
  20572. EXPECT_EQ("application/json",
  20573. detail::get_combined_header_value(headers, "Accept"));
  20574. }
  20575. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20576. // An encoding offered on a later Accept-Encoding field line is still offered.
  20577. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20578. Server svr;
  20579. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20580. res.set_content(std::string(1024, 'x'), "text/plain");
  20581. });
  20582. auto port = svr.bind_to_any_port(HOST);
  20583. thread t = thread([&]() { svr.listen_after_bind(); });
  20584. auto se = detail::scope_exit([&] {
  20585. svr.stop();
  20586. t.join();
  20587. ASSERT_FALSE(svr.is_running());
  20588. });
  20589. svr.wait_until_ready();
  20590. Client cli(HOST, port);
  20591. cli.set_decompress(false);
  20592. Headers headers;
  20593. headers.emplace("Accept-Encoding", "identity");
  20594. headers.emplace("Accept-Encoding", "gzip");
  20595. auto res = cli.Get("/", headers);
  20596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20597. EXPECT_EQ(StatusCode::OK_200, res->status);
  20598. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20599. }
  20600. #endif
  20601. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20602. // Transfer-Encoding is not its body.
  20603. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20604. Server svr;
  20605. svr.set_payload_max_length(8);
  20606. svr.Post("/test", [](const Request &, Response &res) {
  20607. res.set_content("ok", "text/plain");
  20608. });
  20609. auto port = svr.bind_to_any_port(HOST);
  20610. ASSERT_GT(port, 0);
  20611. thread t = thread([&] { svr.listen_after_bind(); });
  20612. auto se = detail::scope_exit([&] {
  20613. svr.stop();
  20614. t.join();
  20615. ASSERT_FALSE(svr.is_running());
  20616. });
  20617. svr.wait_until_ready();
  20618. std::string resp;
  20619. ASSERT_TRUE(send_request(1,
  20620. "POST /test HTTP/1.1\r\n"
  20621. "Host: localhost\r\n"
  20622. "Connection: close\r\n"
  20623. "\r\n" +
  20624. std::string(16, 'X'),
  20625. &resp, port));
  20626. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20627. }
  20628. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20629. Server svr;
  20630. svr.Post("/post", [&](const Request &req, Response &res) {
  20631. res.set_content(req.body, "text/plain");
  20632. });
  20633. svr.Put("/put", [&](const Request &req, Response &res) {
  20634. res.set_content(req.body, "text/plain");
  20635. });
  20636. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20637. res.set_content(req.body, "text/plain");
  20638. });
  20639. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20640. res.set_content(req.body, "text/plain");
  20641. });
  20642. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20643. auto se = detail::scope_exit([&] {
  20644. svr.stop();
  20645. t.join();
  20646. ASSERT_FALSE(svr.is_running());
  20647. });
  20648. svr.wait_until_ready();
  20649. std::string resp;
  20650. // POST without Content-Length
  20651. ASSERT_TRUE(send_request(5,
  20652. "POST /post HTTP/1.1\r\n"
  20653. "Host: localhost\r\n"
  20654. "Connection: close\r\n"
  20655. "\r\n",
  20656. &resp));
  20657. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20658. // PUT without Content-Length
  20659. resp.clear();
  20660. ASSERT_TRUE(send_request(5,
  20661. "PUT /put HTTP/1.1\r\n"
  20662. "Host: localhost\r\n"
  20663. "Connection: close\r\n"
  20664. "\r\n",
  20665. &resp));
  20666. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20667. // PATCH without Content-Length
  20668. resp.clear();
  20669. ASSERT_TRUE(send_request(5,
  20670. "PATCH /patch HTTP/1.1\r\n"
  20671. "Host: localhost\r\n"
  20672. "Connection: close\r\n"
  20673. "\r\n",
  20674. &resp));
  20675. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20676. // DELETE without Content-Length
  20677. resp.clear();
  20678. ASSERT_TRUE(send_request(5,
  20679. "DELETE /delete HTTP/1.1\r\n"
  20680. "Host: localhost\r\n"
  20681. "Connection: close\r\n"
  20682. "\r\n",
  20683. &resp));
  20684. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20685. }
  20686. //==============================================================================
  20687. // open_stream() Tests
  20688. //==============================================================================
  20689. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20690. std::string result;
  20691. char buf[8192];
  20692. ssize_t n;
  20693. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20694. result.append(buf, static_cast<size_t>(n));
  20695. }
  20696. return result;
  20697. }
  20698. // Mock stream for unit tests
  20699. class MockStream : public Stream {
  20700. public:
  20701. std::string data;
  20702. size_t pos = 0;
  20703. ssize_t error_after = -1; // -1 = no error
  20704. explicit MockStream(const std::string &d, ssize_t err = -1)
  20705. : data(d), error_after(err) {}
  20706. bool is_readable() const override { return true; }
  20707. bool wait_readable() const override { return true; }
  20708. bool wait_writable() const override { return true; }
  20709. ssize_t read(char *ptr, size_t size) override {
  20710. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20711. if (pos >= data.size()) return 0;
  20712. size_t limit =
  20713. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20714. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20715. std::memcpy(ptr, data.data() + pos, to_read);
  20716. pos += to_read;
  20717. return static_cast<ssize_t>(to_read);
  20718. }
  20719. ssize_t write(const char *, size_t) override { return -1; }
  20720. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20721. ip = "127.0.0.1";
  20722. port = 0;
  20723. }
  20724. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20725. ip = "127.0.0.1";
  20726. port = 0;
  20727. }
  20728. socket_t socket() const override { return INVALID_SOCKET; }
  20729. time_t duration() const override { return 0; }
  20730. };
  20731. TEST(StreamHandleTest, Basic) {
  20732. ClientImpl::StreamHandle handle;
  20733. EXPECT_FALSE(handle.is_valid());
  20734. handle.response = detail::make_unique<Response>();
  20735. handle.error = Error::Connection;
  20736. EXPECT_FALSE(handle.is_valid());
  20737. handle.error = Error::Success;
  20738. EXPECT_TRUE(handle.is_valid());
  20739. }
  20740. TEST(BodyReaderTest, Basic) {
  20741. MockStream stream("Hello, World!");
  20742. detail::BodyReader reader;
  20743. reader.stream = &stream;
  20744. reader.content_length = 13;
  20745. char buf[32];
  20746. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20747. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20748. EXPECT_TRUE(reader.eof);
  20749. }
  20750. TEST(BodyReaderTest, NoStream) {
  20751. detail::BodyReader reader;
  20752. char buf[32];
  20753. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20754. EXPECT_EQ(Error::Connection, reader.last_error);
  20755. }
  20756. TEST(BodyReaderTest, Error) {
  20757. MockStream stream("Hello, World!", 5);
  20758. detail::BodyReader reader;
  20759. reader.stream = &stream;
  20760. reader.content_length = 13;
  20761. char buf[32];
  20762. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20763. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20764. EXPECT_EQ(Error::Read, reader.last_error);
  20765. }
  20766. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20767. // Mock-based StreamHandle tests relying on private internals are removed.
  20768. class OpenStreamTest : public ::testing::Test {
  20769. protected:
  20770. void SetUp() override {
  20771. svr_.Get("/hello", [](const Request &, Response &res) {
  20772. res.set_content("Hello World!", "text/plain");
  20773. });
  20774. svr_.Get("/large", [](const Request &, Response &res) {
  20775. res.set_content(std::string(10000, 'X'), "text/plain");
  20776. });
  20777. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20778. res.set_content("Hello World!", "image/jpeg");
  20779. res.set_header("Content-Encoding", "UTF-8");
  20780. });
  20781. svr_.Get("/chunked", [](const Request &, Response &res) {
  20782. res.set_chunked_content_provider("text/plain",
  20783. [](size_t offset, DataSink &sink) {
  20784. if (offset < 15) {
  20785. sink.write("chunk", 5);
  20786. return true;
  20787. }
  20788. sink.done();
  20789. return true;
  20790. });
  20791. });
  20792. svr_.Get("/compressible", [](const Request &, Response &res) {
  20793. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20794. DataSink &sink) {
  20795. if (offset < 100 * 1024) {
  20796. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20797. sink.write(chunk.data(), chunk.size());
  20798. return true;
  20799. }
  20800. sink.done();
  20801. return true;
  20802. });
  20803. });
  20804. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20805. [](const Request & /*req*/, Response &res) {
  20806. auto i = new int(0);
  20807. res.set_header("Trailer", "Content-Length, X-Allowed");
  20808. res.set_chunked_content_provider(
  20809. "text/plain",
  20810. [i](size_t /*offset*/, DataSink &sink) {
  20811. switch (*i) {
  20812. case 0: sink.os << "123"; break;
  20813. case 1: sink.os << "456"; break;
  20814. case 2: sink.os << "789"; break;
  20815. case 3: {
  20816. sink.done_with_trailer(
  20817. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20818. } break;
  20819. }
  20820. (*i)++;
  20821. return true;
  20822. },
  20823. [i](bool success) {
  20824. EXPECT_TRUE(success);
  20825. delete i;
  20826. });
  20827. });
  20828. // Echo headers endpoint for header-related tests
  20829. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20830. std::string body;
  20831. for (const auto &h : req.headers) {
  20832. body.append(h.first);
  20833. body.push_back(':');
  20834. body.append(h.second);
  20835. body.push_back('\n');
  20836. }
  20837. res.set_content(body, "text/plain");
  20838. });
  20839. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20840. std::string body;
  20841. for (const auto &h : req.headers) {
  20842. body.append(h.first);
  20843. body.push_back(':');
  20844. body.append(h.second);
  20845. body.push_back('\n');
  20846. }
  20847. res.set_content(body, "text/plain");
  20848. });
  20849. port_ = svr_.bind_to_any_port("127.0.0.1");
  20850. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20851. svr_.wait_until_ready();
  20852. }
  20853. void TearDown() override {
  20854. svr_.stop();
  20855. if (thread_.joinable()) thread_.join();
  20856. }
  20857. Server svr_;
  20858. std::thread thread_;
  20859. int port_ = 0;
  20860. };
  20861. TEST_F(OpenStreamTest, Basic) {
  20862. Client cli("127.0.0.1", port_);
  20863. auto handle = cli.open_stream("GET", "/hello");
  20864. EXPECT_TRUE(handle.is_valid());
  20865. EXPECT_EQ("Hello World!", read_all(handle));
  20866. }
  20867. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20868. Client cli("127.0.0.1", port_);
  20869. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20870. ASSERT_TRUE(handle.is_valid());
  20871. EXPECT_EQ("Hello World!", read_all(handle));
  20872. }
  20873. TEST_F(OpenStreamTest, SmallBuffer) {
  20874. Client cli("127.0.0.1", port_);
  20875. auto handle = cli.open_stream("GET", "/hello");
  20876. std::string result;
  20877. char buf[4];
  20878. ssize_t n;
  20879. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20880. result.append(buf, static_cast<size_t>(n));
  20881. EXPECT_EQ("Hello World!", result);
  20882. }
  20883. TEST_F(OpenStreamTest, DefaultHeaders) {
  20884. Client cli("127.0.0.1", port_);
  20885. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20886. {
  20887. auto handle = cli.open_stream("GET", "/echo-headers");
  20888. ASSERT_TRUE(handle.is_valid());
  20889. auto body = read_all(handle);
  20890. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20891. std::string::npos);
  20892. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20893. std::string::npos);
  20894. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20895. }
  20896. // open_stream POST with body and no explicit content_type should NOT add
  20897. // text/plain Content-Type (behavior differs from non-streaming path), but
  20898. // should include Content-Length
  20899. {
  20900. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20901. ASSERT_TRUE(handle.is_valid());
  20902. auto body = read_all(handle);
  20903. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20904. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20905. }
  20906. // open_stream POST with explicit Content-Type should preserve it
  20907. {
  20908. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20909. {{"Content-Type", "application/custom"}},
  20910. "{}", "application/custom");
  20911. ASSERT_TRUE(handle.is_valid());
  20912. auto body = read_all(handle);
  20913. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20914. }
  20915. // User-specified User-Agent must not be overwritten for stream API
  20916. {
  20917. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20918. {{"User-Agent", "MyAgent/1.2"}});
  20919. ASSERT_TRUE(handle.is_valid());
  20920. auto body = read_all(handle);
  20921. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20922. }
  20923. }
  20924. TEST_F(OpenStreamTest, Large) {
  20925. Client cli("127.0.0.1", port_);
  20926. auto handle = cli.open_stream("GET", "/large");
  20927. EXPECT_EQ(10000u, read_all(handle).size());
  20928. }
  20929. TEST_F(OpenStreamTest, ConnectionError) {
  20930. Client cli("127.0.0.1", 9999);
  20931. auto handle = cli.open_stream("GET", "/hello");
  20932. EXPECT_FALSE(handle.is_valid());
  20933. }
  20934. TEST_F(OpenStreamTest, Chunked) {
  20935. Client cli("127.0.0.1", port_);
  20936. auto handle = cli.open_stream("GET", "/chunked");
  20937. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20938. "Transfer-Encoding") == "chunked");
  20939. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20940. }
  20941. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20942. Client cli("127.0.0.1", port_);
  20943. auto handle =
  20944. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20945. ASSERT_TRUE(handle.is_valid());
  20946. // Consume body to allow trailers to be received/parsed
  20947. auto body = read_all(handle);
  20948. // Explicitly parse trailers (ensure trailers are available for assertion)
  20949. handle.parse_trailers_if_needed();
  20950. EXPECT_EQ(std::string("123456789"), body);
  20951. // The response should include a Trailer header declaring both names
  20952. ASSERT_TRUE(handle.response);
  20953. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20954. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20955. handle.response->get_header_value("Trailer"));
  20956. // Prohibited trailer must not be present
  20957. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20958. // Allowed trailer should be present
  20959. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20960. EXPECT_EQ(std::string("yes"),
  20961. handle.response->get_trailer_value("X-Allowed"));
  20962. // Verify trailers are NOT present as regular headers
  20963. EXPECT_EQ(std::string(""),
  20964. handle.response->get_header_value("Content-Length"));
  20965. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20966. }
  20967. // Accepts one connection on an OS-assigned port, which it hands over through
  20968. // port_promise, reads the request head and sends back response. after_send,
  20969. // if given, runs on the connection before it is closed.
  20970. static std::thread
  20971. serve_single_response(std::promise<int> &port_promise,
  20972. const std::string &response,
  20973. std::function<void(socket_t)> after_send = nullptr) {
  20974. return std::thread([&port_promise, response, after_send] {
  20975. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20976. default_socket_options(srv);
  20977. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20978. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20979. sockaddr_in addr{};
  20980. addr.sin_family = AF_INET;
  20981. addr.sin_port = htons(0); // Let OS assign a free port
  20982. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20983. int opt = 1;
  20984. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20985. #ifdef _WIN32
  20986. reinterpret_cast<const char *>(&opt),
  20987. #else
  20988. &opt,
  20989. #endif
  20990. sizeof(opt));
  20991. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20992. ::listen(srv, 1) != 0) {
  20993. port_promise.set_value(-1);
  20994. detail::close_socket(srv);
  20995. return;
  20996. }
  20997. socklen_t addr_len = sizeof(addr);
  20998. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20999. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21000. sockaddr_in cli_addr{};
  21001. socklen_t cli_len = sizeof(cli_addr);
  21002. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21003. if (cli != INVALID_SOCKET) {
  21004. // Read the complete HTTP request (until the blank line that terminates
  21005. // headers) before sending the response. If the server closes the socket
  21006. // while the client's request data is still unread in the kernel receive
  21007. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  21008. // connection on both sides: it discards the client's receive buffer
  21009. // (which already holds our response) and causes any in-progress write on
  21010. // the client to fail with ECONNRESET. Reading all request data first
  21011. // ensures close() emits a graceful FIN.
  21012. {
  21013. char rbuf[256];
  21014. std::string req;
  21015. while (req.find("\r\n\r\n") == std::string::npos) {
  21016. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  21017. if (n <= 0) { break; }
  21018. req.append(rbuf, static_cast<size_t>(n));
  21019. }
  21020. }
  21021. ::send(cli,
  21022. #ifdef _WIN32
  21023. static_cast<const char *>(response.c_str()),
  21024. static_cast<int>(response.size()),
  21025. #else
  21026. response.c_str(), response.size(),
  21027. #endif
  21028. 0);
  21029. if (after_send) { after_send(cli); }
  21030. detail::close_socket(cli);
  21031. }
  21032. detail::close_socket(srv);
  21033. });
  21034. }
  21035. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  21036. #ifndef _WIN32
  21037. signal(SIGPIPE, SIG_IGN);
  21038. #endif
  21039. std::promise<int> port_promise;
  21040. auto port_future = port_promise.get_future();
  21041. auto server_thread =
  21042. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21043. "Content-Type: text/plain\r\n"
  21044. "Content-Length: not-a-number\r\n"
  21045. "Connection: close\r\n"
  21046. "\r\n"
  21047. "hello");
  21048. auto port = port_future.get();
  21049. ASSERT_GT(port, 0);
  21050. Client cli("127.0.0.1", port);
  21051. auto handle = cli.open_stream("GET", "/");
  21052. EXPECT_FALSE(handle.is_valid());
  21053. server_thread.join();
  21054. }
  21055. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21056. #ifndef _WIN32
  21057. signal(SIGPIPE, SIG_IGN);
  21058. #endif
  21059. std::promise<int> port_promise;
  21060. auto port_future = port_promise.get_future();
  21061. auto server_thread = serve_single_response(
  21062. port_promise, "HTTP/1.1 200 OK\r\n"
  21063. "Content-Type: text/plain\r\n"
  21064. "Content-Length: 99999999999999999999999999\r\n"
  21065. "Connection: close\r\n"
  21066. "\r\n"
  21067. "hello");
  21068. auto port = port_future.get();
  21069. ASSERT_GT(port, 0);
  21070. // Historically std::stoull would throw std::out_of_range here and crash
  21071. // the process, then parsing silently clamped to a bogus framing length and
  21072. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21073. // so the stream fails to open, matching the not-a-number case above. The
  21074. // process still must NOT terminate.
  21075. Client cli("127.0.0.1", port);
  21076. auto handle = cli.open_stream("GET", "/");
  21077. EXPECT_FALSE(handle.is_valid());
  21078. server_thread.join();
  21079. }
  21080. #ifndef _WIN32
  21081. // As above for the body of a streamed request: a send() cut short by the write
  21082. // timeout must not leave the rest of the body unsent.
  21083. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21084. signal(SIGPIPE, SIG_IGN);
  21085. Server svr;
  21086. svr.set_socket_options([](socket_t sock) {
  21087. int size = 8192;
  21088. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21089. reinterpret_cast<const char *>(&size), sizeof(size));
  21090. });
  21091. svr.Post("/size", [](const Request &, Response &res,
  21092. const ContentReader &content_reader) {
  21093. // Outlast the client's write timeout before reading the body.
  21094. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21095. size_t received = 0;
  21096. content_reader([&](const char *, size_t len) {
  21097. received += len;
  21098. return true;
  21099. });
  21100. res.set_content(std::to_string(received), "text/plain");
  21101. });
  21102. auto port = svr.bind_to_any_port(HOST);
  21103. std::thread t([&]() { svr.listen_after_bind(); });
  21104. auto se = detail::scope_exit([&] {
  21105. svr.stop();
  21106. t.join();
  21107. });
  21108. svr.wait_until_ready();
  21109. Client cli(HOST, port);
  21110. cli.set_write_timeout(0, 500000);
  21111. cli.set_socket_options([](socket_t sock) {
  21112. int size = 8192;
  21113. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21114. reinterpret_cast<const char *>(&size), sizeof(size));
  21115. });
  21116. const std::string body(4 * 1024 * 1024, 'A');
  21117. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21118. "application/octet-stream");
  21119. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21120. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21121. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21122. }
  21123. #endif
  21124. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21125. std::promise<void> slow_started;
  21126. auto slow_started_future = slow_started.get_future();
  21127. Server svr;
  21128. svr.Get("/slow", [&](const Request &, Response &res) {
  21129. slow_started.set_value();
  21130. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21131. res.set_content("slow", "text/plain");
  21132. });
  21133. svr.Get("/fast", [](const Request &, Response &res) {
  21134. res.set_content("fast", "text/plain");
  21135. });
  21136. auto port = svr.bind_to_any_port(HOST);
  21137. std::thread t([&]() { svr.listen_after_bind(); });
  21138. auto se = detail::scope_exit([&] {
  21139. svr.stop();
  21140. t.join();
  21141. });
  21142. svr.wait_until_ready();
  21143. Client cli(HOST, port);
  21144. std::string slow_body;
  21145. std::thread slow_thread([&] {
  21146. auto res = cli.Get("/slow");
  21147. if (res) { slow_body = res->body; }
  21148. });
  21149. slow_started_future.wait();
  21150. auto result = stream::Get(cli, "/fast");
  21151. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21152. slow_thread.join();
  21153. EXPECT_EQ("slow", slow_body);
  21154. EXPECT_EQ("fast", fast_body);
  21155. }
  21156. // Serves `response` to the single request `fn` makes with a fresh client.
  21157. template <typename Fn>
  21158. static void with_single_response(const std::string &response, Fn fn) {
  21159. #ifndef _WIN32
  21160. signal(SIGPIPE, SIG_IGN);
  21161. #endif
  21162. std::promise<int> port_promise;
  21163. auto port_future = port_promise.get_future();
  21164. auto server_thread = serve_single_response(port_promise, response);
  21165. auto se = detail::scope_exit([&] { server_thread.join(); });
  21166. auto port = port_future.get();
  21167. ASSERT_GT(port, 0);
  21168. Client cli("127.0.0.1", port);
  21169. fn(cli);
  21170. }
  21171. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21172. // too, also in a build without the decoder for the advertised coding.
  21173. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21174. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21175. const auto response = "HTTP/1.1 200 OK\r\n"
  21176. "Content-Encoding: gzip\r\n"
  21177. "Content-Length: " +
  21178. std::to_string(gzipped.size()) +
  21179. "\r\n"
  21180. "Connection: close\r\n\r\n" +
  21181. gzipped;
  21182. with_single_response(response, [&](Client &cli) {
  21183. cli.set_decompress(false);
  21184. auto handle = cli.open_stream("GET", "/");
  21185. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21186. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21187. EXPECT_EQ(gzipped, read_all(handle));
  21188. EXPECT_FALSE(handle.has_read_error());
  21189. });
  21190. with_single_response(response, [&](Client &cli) {
  21191. cli.set_decompress(false);
  21192. auto res = stream::Get(cli, "/", 7);
  21193. ASSERT_TRUE(res) << to_string(res.error());
  21194. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21195. EXPECT_EQ(gzipped, res.read_all());
  21196. EXPECT_FALSE(res.has_read_error());
  21197. });
  21198. }
  21199. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21200. // Neither Content-Length nor chunked: the body ends at the close
  21201. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21202. "Connection: close\r\n"
  21203. "\r\n"
  21204. "hello";
  21205. with_single_response(close_delimited, [](Client &cli) {
  21206. auto handle = cli.open_stream("GET", "/");
  21207. ASSERT_TRUE(handle.is_valid());
  21208. EXPECT_EQ("hello", read_all(handle));
  21209. EXPECT_FALSE(handle.has_read_error());
  21210. });
  21211. // A close before the end of the Content-Length is still an error
  21212. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21213. "Content-Length: 10\r\n"
  21214. "\r\n"
  21215. "hello";
  21216. with_single_response(short_content_length, [](Client &cli) {
  21217. auto handle = cli.open_stream("GET", "/");
  21218. ASSERT_TRUE(handle.is_valid());
  21219. read_all(handle);
  21220. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21221. });
  21222. // So is a close before the last chunk
  21223. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21224. "Transfer-Encoding: chunked\r\n"
  21225. "\r\n"
  21226. "5\r\nhello\r\n";
  21227. with_single_response(short_chunked, [](Client &cli) {
  21228. auto handle = cli.open_stream("GET", "/");
  21229. ASSERT_TRUE(handle.is_valid());
  21230. read_all(handle);
  21231. EXPECT_TRUE(handle.has_read_error());
  21232. });
  21233. }
  21234. #ifdef CPPHTTPLIB_SSL_ENABLED
  21235. // Serves `response` to one request, then closes with or without a close_notify
  21236. template <typename Fn>
  21237. static void with_single_tls_response(const std::string &response,
  21238. bool close_notify, Fn fn) {
  21239. #ifndef _WIN32
  21240. signal(SIGPIPE, SIG_IGN);
  21241. #endif
  21242. std::promise<int> port_promise;
  21243. auto port_future = port_promise.get_future();
  21244. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21245. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21246. default_socket_options(srv);
  21247. sockaddr_in addr{};
  21248. addr.sin_family = AF_INET;
  21249. addr.sin_port = htons(0);
  21250. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21251. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21252. ::listen(srv, 1) != 0) {
  21253. port_promise.set_value(-1);
  21254. detail::close_socket(srv);
  21255. return;
  21256. }
  21257. socklen_t addr_len = sizeof(addr);
  21258. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21259. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21260. auto cli = ::accept(srv, nullptr, nullptr);
  21261. if (cli != INVALID_SOCKET) {
  21262. auto ctx = tls::create_server_context();
  21263. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21264. nullptr);
  21265. auto session = tls::create_session(ctx, cli);
  21266. tls::TlsError err;
  21267. if (tls::accept_nonblocking(session, cli, 5, 0, &err, nullptr)) {
  21268. // The request head first, so that closing the socket sends a FIN
  21269. // rather than an RST for the unread bytes.
  21270. std::string req;
  21271. char buf[256];
  21272. while (req.find("\r\n\r\n") == std::string::npos) {
  21273. auto n = tls::read(session, buf, sizeof(buf), err);
  21274. if (n <= 0) { break; }
  21275. req.append(buf, static_cast<size_t>(n));
  21276. }
  21277. size_t sent = 0;
  21278. while (sent < response.size()) {
  21279. auto n = tls::write(session, response.data() + sent,
  21280. response.size() - sent, err);
  21281. if (n <= 0) { break; }
  21282. sent += static_cast<size_t>(n);
  21283. }
  21284. if (close_notify) { tls::shutdown(session, true); }
  21285. }
  21286. tls::free_session(session);
  21287. detail::close_socket(cli);
  21288. tls::free_context(ctx);
  21289. }
  21290. detail::close_socket(srv);
  21291. });
  21292. auto se = detail::scope_exit([&] { server_thread.join(); });
  21293. auto port = port_future.get();
  21294. ASSERT_GT(port, 0);
  21295. SSLClient cli("127.0.0.1", port);
  21296. cli.enable_server_certificate_verification(false);
  21297. fn(cli);
  21298. }
  21299. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21300. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21301. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21302. "Connection: close\r\n"
  21303. "\r\n"
  21304. "hello";
  21305. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21306. auto res = cli.Get("/");
  21307. ASSERT_TRUE(res) << to_string(res.error());
  21308. EXPECT_EQ("hello", res->body);
  21309. });
  21310. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21311. auto res = cli.Get("/");
  21312. ASSERT_FALSE(res);
  21313. EXPECT_EQ(Error::Read, res.error());
  21314. });
  21315. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21316. auto handle = cli.open_stream("GET", "/");
  21317. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21318. read_all(handle);
  21319. EXPECT_TRUE(handle.has_read_error());
  21320. });
  21321. // A framed body ends where its framing says, with or without the alert
  21322. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21323. "Content-Length: 5\r\n"
  21324. "Connection: close\r\n"
  21325. "\r\n"
  21326. "hello";
  21327. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21328. auto res = cli.Get("/");
  21329. ASSERT_TRUE(res) << to_string(res.error());
  21330. EXPECT_EQ("hello", res->body);
  21331. });
  21332. }
  21333. #endif
  21334. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21335. const char *responses[] = {
  21336. "HTTP/1.1 103 Early Hints\r\n"
  21337. "Link: </style.css>; rel=preload\r\n"
  21338. "\r\n"
  21339. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21340. "HTTP/1.1 100 Continue\r\n"
  21341. "X-Note: interim\r\n"
  21342. "\r\n"
  21343. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21344. };
  21345. for (auto response : responses) {
  21346. with_single_response(response, [](Client &cli) {
  21347. auto res = cli.Get("/");
  21348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21349. EXPECT_EQ(StatusCode::OK_200, res->status);
  21350. EXPECT_EQ("ok", res->body);
  21351. });
  21352. }
  21353. }
  21354. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21355. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21356. const std::string final_response =
  21357. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21358. std::string interims;
  21359. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21360. interims += interim;
  21361. }
  21362. with_single_response(interims + final_response, [](Client &cli) {
  21363. auto res = cli.Get("/");
  21364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21365. EXPECT_EQ("ok", res->body);
  21366. });
  21367. with_single_response(interims + interim + final_response, [](Client &cli) {
  21368. auto res = cli.Get("/");
  21369. ASSERT_FALSE(res);
  21370. EXPECT_EQ(Error::Read, res.error());
  21371. });
  21372. }
  21373. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21374. #ifndef _WIN32
  21375. signal(SIGPIPE, SIG_IGN);
  21376. #endif
  21377. // The server answers the head without asking for the body. Bytes it then
  21378. // reads on the connection would be taken for the body the request declared.
  21379. auto closed_by_client = false;
  21380. std::promise<int> port_promise;
  21381. auto server_thread = serve_single_response(
  21382. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21383. [&](socket_t sock) {
  21384. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21385. char buf[256];
  21386. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21387. });
  21388. Client cli("127.0.0.1", port_promise.get_future().get());
  21389. cli.set_keep_alive(true);
  21390. cli.set_read_timeout(1, 0);
  21391. // Long enough for the client to send Expect: 100-continue.
  21392. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21394. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21395. cli.Get("/second");
  21396. server_thread.join();
  21397. EXPECT_TRUE(closed_by_client);
  21398. }
  21399. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21400. // Long enough for the client to send Expect: 100-continue
  21401. with_single_response(
  21402. "HTTP/1.1 103 Early Hints\r\n"
  21403. "Link: </style.css>; rel=preload\r\n"
  21404. "\r\n"
  21405. "HTTP/1.1 401 Unauthorized\r\n"
  21406. "Content-Length: 0\r\n\r\n",
  21407. [](Client &cli) {
  21408. cli.set_read_timeout(2, 0);
  21409. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21411. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21412. });
  21413. }
  21414. #ifdef CPPHTTPLIB_SSL_ENABLED
  21415. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21416. #ifndef _WIN32
  21417. signal(SIGPIPE, SIG_IGN);
  21418. #endif
  21419. auto reused = false;
  21420. std::promise<int> port_promise;
  21421. auto server_thread = serve_single_response(
  21422. port_promise,
  21423. "HTTP/1.1 401 Unauthorized\r\n"
  21424. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21425. "Content-Length: 0\r\n\r\n",
  21426. [&](socket_t sock) {
  21427. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21428. char buf[256];
  21429. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21430. });
  21431. Client cli("127.0.0.1", port_promise.get_future().get());
  21432. cli.set_keep_alive(true);
  21433. cli.set_digest_auth("user", "pass");
  21434. cli.set_read_timeout(1, 0);
  21435. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21436. server_thread.join();
  21437. EXPECT_FALSE(reused);
  21438. }
  21439. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21440. // Any other answer to CONNECT would read as the origin's response.
  21441. struct {
  21442. const char *response;
  21443. bool passed_on;
  21444. } cases[] = {
  21445. {"HTTP/1.1 201 Created\r\n"
  21446. "Set-Cookie: session=from-proxy\r\n"
  21447. "Content-Length: 0\r\n\r\n",
  21448. false},
  21449. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21450. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21451. "Content-Length: 0\r\n\r\n",
  21452. true},
  21453. };
  21454. for (const auto &c : cases) {
  21455. std::promise<int> port_promise;
  21456. auto server_thread = serve_single_response(port_promise, c.response);
  21457. SSLClient cli("example.com", 443);
  21458. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21459. auto res = cli.Get("/");
  21460. server_thread.join();
  21461. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21462. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21463. if (res) {
  21464. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21465. }
  21466. }
  21467. }
  21468. #endif
  21469. // Records the client's error logger calls as "error METHOD path", or
  21470. // "error null" for a call without a request
  21471. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21472. return [&log](const Error &err, const Request *req) {
  21473. log.push_back(to_string(err) + " " +
  21474. (req ? req->method + " " + req->path : "null"));
  21475. };
  21476. }
  21477. // A failed request is reported once, with the request the caller made
  21478. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21479. Server svr;
  21480. svr.Get("/big", [](const Request &, Response &res) {
  21481. res.set_content(std::string(100000, 'b'), "text/plain");
  21482. });
  21483. auto port = svr.bind_to_any_port(HOST);
  21484. std::thread t([&]() { svr.listen_after_bind(); });
  21485. auto se = detail::scope_exit([&] {
  21486. svr.stop();
  21487. t.join();
  21488. });
  21489. svr.wait_until_ready();
  21490. Client cli(HOST, port);
  21491. std::vector<std::string> log;
  21492. cli.set_error_logger(record_errors(log));
  21493. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21494. cli.Get("/big", [](const char *, size_t) { return false; });
  21495. EXPECT_EQ(expected, log);
  21496. log.clear();
  21497. cli.Get("/big", [](size_t, size_t) { return false; });
  21498. EXPECT_EQ(expected, log);
  21499. }
  21500. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21501. // Fails while the body is read
  21502. auto broken = [](const Request &, Response &res) {
  21503. res.set_content_provider(10, "text/plain",
  21504. [](size_t, size_t, DataSink &) { return false; });
  21505. };
  21506. Server other;
  21507. other.Get("/broken", broken);
  21508. auto other_port = other.bind_to_any_port(HOST);
  21509. std::thread other_t([&]() { other.listen_after_bind(); });
  21510. auto other_se = detail::scope_exit([&] {
  21511. other.stop();
  21512. other_t.join();
  21513. });
  21514. other.wait_until_ready();
  21515. Server svr;
  21516. svr.Get("/broken", broken);
  21517. svr.Get("/same-origin",
  21518. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21519. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21520. res.set_redirect("http://" + std::string(HOST) + ":" +
  21521. std::to_string(other_port) + "/broken");
  21522. });
  21523. auto port = svr.bind_to_any_port(HOST);
  21524. std::thread t([&]() { svr.listen_after_bind(); });
  21525. auto se = detail::scope_exit([&] {
  21526. svr.stop();
  21527. t.join();
  21528. });
  21529. svr.wait_until_ready();
  21530. Client cli(HOST, port);
  21531. cli.set_follow_location(true);
  21532. std::vector<std::string> log;
  21533. cli.set_error_logger(record_errors(log));
  21534. for (auto path : {"/same-origin", "/cross-origin"}) {
  21535. log.clear();
  21536. auto res = cli.Get(path);
  21537. ASSERT_FALSE(res);
  21538. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21539. log);
  21540. }
  21541. }
  21542. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21543. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21544. std::vector<std::string> log;
  21545. cli.set_error_logger(record_errors(log));
  21546. auto handle = cli.open_stream("GET", "/x");
  21547. EXPECT_FALSE(handle.is_valid());
  21548. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21549. log);
  21550. });
  21551. }
  21552. #ifdef CPPHTTPLIB_SSL_ENABLED
  21553. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21554. // Not a TLS server, so the handshake fails. It waits for a request line in
  21555. // the handshake bytes, so a short read timeout lets it close quickly.
  21556. Server svr;
  21557. svr.set_read_timeout(0, 100000);
  21558. svr.Get("/x", [](const Request &, Response &res) {
  21559. res.set_content("x", "text/plain");
  21560. });
  21561. auto port = svr.bind_to_any_port(HOST);
  21562. std::thread t([&]() { svr.listen_after_bind(); });
  21563. auto se = detail::scope_exit([&] {
  21564. svr.stop();
  21565. t.join();
  21566. });
  21567. svr.wait_until_ready();
  21568. std::vector<std::string> log;
  21569. SSLClient cli(HOST, port);
  21570. cli.enable_server_certificate_verification(false);
  21571. cli.set_error_logger(record_errors(log));
  21572. auto res = cli.Get("/x");
  21573. ASSERT_FALSE(res);
  21574. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21575. log.clear();
  21576. auto handle = cli.open_stream("GET", "/x");
  21577. EXPECT_FALSE(handle.is_valid());
  21578. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21579. log.clear();
  21580. SSLClient no_ca(HOST, port);
  21581. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21582. no_ca.set_error_logger(record_errors(log));
  21583. res = no_ca.Get("/x");
  21584. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21585. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21586. }
  21587. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21588. #ifndef _WIN32
  21589. signal(SIGPIPE, SIG_IGN);
  21590. #endif
  21591. // Refused, answered with a challenge, or closed without an answer
  21592. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21593. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21594. "Content-Length: 0\r\n\r\n",
  21595. ""}) {
  21596. std::promise<int> port_promise;
  21597. auto server_thread = serve_single_response(port_promise, response);
  21598. SSLClient cli("example.com", 443);
  21599. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21600. std::vector<std::string> log;
  21601. cli.set_error_logger(record_errors(log));
  21602. auto res = cli.Get("/");
  21603. server_thread.join();
  21604. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21605. << response;
  21606. }
  21607. }
  21608. #endif
  21609. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21610. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21611. // the chunked coding and drop Content-Length, so a front-end that trusts
  21612. // Content-Length would disagree about where the body ends (response
  21613. // smuggling). The client must reject such a response.
  21614. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21615. for (const char *te : {"chunked", "gzip, chunked"}) {
  21616. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21617. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21618. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21619. "5\r\nhello\r\n0\r\n\r\n";
  21620. with_single_response(response, [&](Client &cli) {
  21621. auto res = cli.Get("/");
  21622. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21623. EXPECT_EQ(Error::Read, res.error()) << te;
  21624. });
  21625. with_single_response(response, [&](Client &cli) {
  21626. auto handle = cli.open_stream("GET", "/");
  21627. EXPECT_FALSE(handle.is_valid()) << te;
  21628. EXPECT_EQ(Error::Read, handle.error) << te;
  21629. });
  21630. }
  21631. }
  21632. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21633. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21634. // closing the connection (unlike a request, which must be rejected).
  21635. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21636. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21637. "Transfer-Encoding: chunked\r\n"
  21638. "Connection: close\r\n"
  21639. "\r\n"
  21640. "5\r\nhello\r\n0\r\n\r\n",
  21641. "HTTP/1.1 200 OK\r\n"
  21642. "Transfer-Encoding: gzip\r\n"
  21643. "Connection: close\r\n"
  21644. "\r\n"
  21645. "hello"}) {
  21646. with_single_response(response, [&](Client &cli) {
  21647. auto res = cli.Get("/");
  21648. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21649. EXPECT_EQ("hello", res->body);
  21650. });
  21651. with_single_response(response, [&](Client &cli) {
  21652. auto handle = cli.open_stream("GET", "/");
  21653. ASSERT_TRUE(handle.is_valid()) << response;
  21654. EXPECT_EQ("hello", read_all(handle));
  21655. });
  21656. }
  21657. }
  21658. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21659. // framing headers describe nothing to read and must not be rejected.
  21660. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21661. const std::string framing = "Content-Length: 5\r\n"
  21662. "Transfer-Encoding: chunked\r\n"
  21663. "Connection: close\r\n"
  21664. "\r\n";
  21665. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21666. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21667. });
  21668. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21669. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21670. });
  21671. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21672. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21673. with_single_response(response, [&](Client &cli) {
  21674. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21675. });
  21676. with_single_response(response, [&](Client &cli) {
  21677. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21678. });
  21679. }
  21680. }
  21681. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21682. // header section, so a stream opened on one has nothing to read, whatever
  21683. // framing or coding headers it carries.
  21684. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21685. struct Case {
  21686. const char *method;
  21687. const char *status;
  21688. };
  21689. // A reader of the declared body reports an early close when nothing
  21690. // follows, and hands back what does.
  21691. struct Framing {
  21692. const char *headers;
  21693. const char *after;
  21694. };
  21695. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21696. Case{"GET", "304 Not Modified"}}) {
  21697. for (const auto &f :
  21698. {Framing{"Content-Length: 5\r\n", ""},
  21699. Framing{"Content-Length: 5\r\n", "hello"},
  21700. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21701. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21702. // Not decoded, so a build without Brotli opens it too
  21703. Framing{"Content-Encoding: br\r\n", ""}}) {
  21704. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21705. "Connection: close\r\n"
  21706. "\r\n" +
  21707. f.after;
  21708. with_single_response(response, [&](Client &cli) {
  21709. auto handle = cli.open_stream(c.method, "/");
  21710. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21711. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21712. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21713. });
  21714. }
  21715. }
  21716. }
  21717. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21718. // response, is faulty framing, so the connection is not reused after it.
  21719. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21720. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21721. "Content-Length: 0\r\n"
  21722. "Transfer-Encoding: chunked\r\n"
  21723. "\r\n"
  21724. "5\r\nhello\r\n0\r\n\r\n",
  21725. "HTTP/1.0 200 Connection established\r\n"
  21726. "Connection: keep-alive\r\n"
  21727. "Transfer-Encoding: chunked\r\n"
  21728. "\r\n"
  21729. "5\r\nhello\r\n0\r\n\r\n"}) {
  21730. with_single_response(response, [&](Client &cli) {
  21731. cli.set_keep_alive(true);
  21732. auto res = cli.Get("/");
  21733. ASSERT_TRUE(res) << response;
  21734. EXPECT_EQ("hello", res->body);
  21735. EXPECT_FALSE(cli.is_socket_open()) << response;
  21736. });
  21737. }
  21738. }
  21739. // A payload max length of 0 means no limit, however the body is framed.
  21740. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21741. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21742. "Transfer-Encoding: chunked\r\n"
  21743. "\r\n"
  21744. "5\r\nhello\r\n0\r\n\r\n",
  21745. "HTTP/1.1 200 OK\r\n"
  21746. "Connection: close\r\n"
  21747. "\r\n"
  21748. "hello"}) {
  21749. with_single_response(response, [&](Client &cli) {
  21750. cli.set_payload_max_length(0);
  21751. auto res = cli.Get("/");
  21752. ASSERT_TRUE(res) << response;
  21753. EXPECT_EQ("hello", res->body) << response;
  21754. });
  21755. }
  21756. }
  21757. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21758. Server svr;
  21759. svr.set_payload_max_length(0);
  21760. svr.Post("/echo", [](const Request &req, Response &res) {
  21761. res.set_content(req.body, "text/plain");
  21762. });
  21763. auto port = svr.bind_to_any_port(HOST);
  21764. thread t = thread([&] { svr.listen_after_bind(); });
  21765. auto se = detail::scope_exit([&] {
  21766. svr.stop();
  21767. t.join();
  21768. ASSERT_FALSE(svr.is_running());
  21769. });
  21770. svr.wait_until_ready();
  21771. Client cli(HOST, port);
  21772. auto res = cli.Post(
  21773. "/echo",
  21774. [](size_t /*offset*/, DataSink &sink) {
  21775. sink.write("hello", 5);
  21776. sink.done();
  21777. return true;
  21778. },
  21779. "text/plain");
  21780. ASSERT_TRUE(res);
  21781. EXPECT_EQ(StatusCode::OK_200, res->status);
  21782. EXPECT_EQ("hello", res->body);
  21783. }
  21784. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21785. TEST_F(OpenStreamTest, Gzip) {
  21786. Client cli("127.0.0.1", port_);
  21787. auto handle = cli.open_stream("GET", "/compressible", {},
  21788. {{"Accept-Encoding", "gzip"}});
  21789. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21790. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21791. }
  21792. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21793. Client cli("127.0.0.1", port_);
  21794. auto handle =
  21795. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21796. {{"Accept-Encoding", "gzip"}});
  21797. ASSERT_TRUE(handle.is_valid());
  21798. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21799. EXPECT_EQ("123456789", read_all(handle));
  21800. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21801. }
  21802. #endif
  21803. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21804. TEST_F(OpenStreamTest, Brotli) {
  21805. Client cli("127.0.0.1", port_);
  21806. auto handle =
  21807. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21808. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21809. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21810. }
  21811. #endif
  21812. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21813. TEST_F(OpenStreamTest, Zstd) {
  21814. Client cli("127.0.0.1", port_);
  21815. auto handle = cli.open_stream("GET", "/compressible", {},
  21816. {{"Accept-Encoding", "zstd"}});
  21817. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21818. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21819. }
  21820. #endif
  21821. #ifdef CPPHTTPLIB_SSL_ENABLED
  21822. class SSLOpenStreamTest : public ::testing::Test {
  21823. protected:
  21824. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21825. void SetUp() override {
  21826. svr_.Get("/hello", [](const Request &, Response &res) {
  21827. res.set_content("Hello SSL World!", "text/plain");
  21828. });
  21829. svr_.Get("/chunked", [](const Request &, Response &res) {
  21830. res.set_chunked_content_provider("text/plain",
  21831. [](size_t offset, DataSink &sink) {
  21832. if (offset < 15) {
  21833. sink.write("chunk", 5);
  21834. return true;
  21835. }
  21836. sink.done();
  21837. return true;
  21838. });
  21839. });
  21840. svr_.Post("/echo", [](const Request &req, Response &res) {
  21841. res.set_content(req.body, req.get_header_value("Content-Type"));
  21842. });
  21843. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21844. std::string body = req.body;
  21845. res.set_chunked_content_provider(
  21846. "text/plain", [body](size_t offset, DataSink &sink) {
  21847. if (offset < body.size()) {
  21848. sink.write(body.data() + offset, body.size() - offset);
  21849. }
  21850. sink.done();
  21851. return true;
  21852. });
  21853. });
  21854. port_ = svr_.bind_to_any_port("127.0.0.1");
  21855. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21856. svr_.wait_until_ready();
  21857. }
  21858. void TearDown() override {
  21859. svr_.stop();
  21860. if (thread_.joinable()) thread_.join();
  21861. }
  21862. SSLServer svr_;
  21863. std::thread thread_;
  21864. int port_ = 0;
  21865. };
  21866. TEST_F(SSLOpenStreamTest, Basic) {
  21867. SSLClient cli("127.0.0.1", port_);
  21868. cli.enable_server_certificate_verification(false);
  21869. auto handle = cli.open_stream("GET", "/hello");
  21870. ASSERT_TRUE(handle.is_valid());
  21871. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21872. }
  21873. TEST_F(SSLOpenStreamTest, Chunked) {
  21874. SSLClient cli("127.0.0.1", port_);
  21875. cli.enable_server_certificate_verification(false);
  21876. auto handle = cli.open_stream("GET", "/chunked");
  21877. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21878. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21879. "Transfer-Encoding") == "chunked");
  21880. auto body = read_all(handle);
  21881. EXPECT_EQ("chunkchunkchunk", body);
  21882. }
  21883. TEST_F(SSLOpenStreamTest, Post) {
  21884. SSLClient cli("127.0.0.1", port_);
  21885. cli.enable_server_certificate_verification(false);
  21886. auto handle =
  21887. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21888. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21889. EXPECT_EQ(200, handle.response->status);
  21890. auto body = read_all(handle);
  21891. EXPECT_EQ("Hello SSL POST", body);
  21892. }
  21893. TEST_F(SSLOpenStreamTest, PostChunked) {
  21894. SSLClient cli("127.0.0.1", port_);
  21895. cli.enable_server_certificate_verification(false);
  21896. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21897. "Chunked SSL Data", "text/plain");
  21898. ASSERT_TRUE(handle.is_valid());
  21899. EXPECT_EQ(200, handle.response->status);
  21900. auto body = read_all(handle);
  21901. EXPECT_EQ("Chunked SSL Data", body);
  21902. }
  21903. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21904. // Content-Length is terminated by the server closing the connection. When the
  21905. // SSL peer sends a close_notify after the body, the client must treat it as a
  21906. // clean EOF and return a successful response rather than an error.
  21907. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21908. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21909. ASSERT_TRUE(svr.is_valid());
  21910. svr.set_keep_alive_max_count(1);
  21911. const std::string expected_body = "Hello from connection-close response!";
  21912. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21913. res.set_content_provider("text/plain",
  21914. [&](size_t offset, DataSink &sink) -> bool {
  21915. if (offset < expected_body.size()) {
  21916. sink.write(expected_body.data() + offset,
  21917. expected_body.size() - offset);
  21918. }
  21919. sink.done();
  21920. return true;
  21921. });
  21922. });
  21923. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21924. auto se = detail::scope_exit([&] {
  21925. svr.stop();
  21926. listen_thread.join();
  21927. ASSERT_FALSE(svr.is_running());
  21928. });
  21929. svr.wait_until_ready();
  21930. SSLClient cli(HOST, PORT);
  21931. cli.enable_server_certificate_verification(false);
  21932. auto res = cli.Get("/no-content-length");
  21933. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21934. EXPECT_EQ(StatusCode::OK_200, res->status);
  21935. EXPECT_EQ(expected_body, res->body);
  21936. }
  21937. // Without Content-Length, the full buffer size reaches tls::read().
  21938. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21939. if (sizeof(size_t) <= sizeof(int)) {
  21940. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21941. }
  21942. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21943. ASSERT_TRUE(svr.is_valid());
  21944. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21945. res.set_content_provider("text/plain",
  21946. [&](size_t offset, DataSink &sink) -> bool {
  21947. if (offset == 0) { sink.write("Hello", 5); }
  21948. sink.done();
  21949. return true;
  21950. });
  21951. });
  21952. auto port = svr.bind_to_any_port(HOST);
  21953. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21954. auto se = detail::scope_exit([&] {
  21955. svr.stop();
  21956. listen_thread.join();
  21957. });
  21958. svr.wait_until_ready();
  21959. SSLClient cli(HOST, port);
  21960. cli.enable_server_certificate_verification(false);
  21961. auto handle = cli.open_stream("GET", "/no-content-length");
  21962. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21963. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21964. std::unique_ptr<char[]> buf(new char[len]);
  21965. std::string body;
  21966. ssize_t n;
  21967. while ((n = handle.read(buf.get(), len)) > 0) {
  21968. body.append(buf.get(), static_cast<size_t>(n));
  21969. }
  21970. EXPECT_EQ(0, n);
  21971. EXPECT_EQ("Hello", body);
  21972. }
  21973. #endif // CPPHTTPLIB_SSL_ENABLED
  21974. //==============================================================================
  21975. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21976. // results for various scenarios.
  21977. //==============================================================================
  21978. TEST(ParityTest, GetVsOpenStream) {
  21979. Server svr;
  21980. const std::string path = "/parity";
  21981. const std::string content = "Parity test content: hello world";
  21982. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21983. res.set_content(content, "text/plain");
  21984. });
  21985. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21986. auto se = detail::scope_exit([&] {
  21987. svr.stop();
  21988. t.join();
  21989. ASSERT_FALSE(svr.is_running());
  21990. });
  21991. svr.wait_until_ready();
  21992. Client cli(HOST, PORT);
  21993. // Non-stream path
  21994. auto r1 = cli.Get(path);
  21995. ASSERT_TRUE(r1);
  21996. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21997. // Stream path
  21998. auto h = cli.open_stream("GET", path);
  21999. ASSERT_TRUE(h.is_valid());
  22000. EXPECT_EQ(r1->body, read_all(h));
  22001. }
  22002. // Helper to compress data with provided compressor type T
  22003. template <typename Compressor>
  22004. static std::string compress_payload_for_parity(const std::string &in) {
  22005. std::string out;
  22006. Compressor compressor;
  22007. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  22008. [&](const char *data, size_t n) {
  22009. out.append(data, n);
  22010. return true;
  22011. });
  22012. EXPECT_TRUE(ok);
  22013. return out;
  22014. }
  22015. // Helper function for compression parity tests
  22016. template <typename Compressor>
  22017. static void test_compression_parity(const std::string &original,
  22018. const std::string &path,
  22019. const std::string &encoding) {
  22020. const std::string compressed =
  22021. compress_payload_for_parity<Compressor>(original);
  22022. Server svr;
  22023. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22024. res.set_content(compressed, "application/octet-stream");
  22025. res.set_header("Content-Encoding", encoding);
  22026. });
  22027. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  22028. auto se = detail::scope_exit([&] {
  22029. svr.stop();
  22030. t.join();
  22031. ASSERT_FALSE(svr.is_running());
  22032. });
  22033. svr.wait_until_ready();
  22034. Client cli(HOST, PORT);
  22035. // Non-streaming
  22036. {
  22037. auto res = cli.Get(path);
  22038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22039. EXPECT_EQ(StatusCode::OK_200, res->status);
  22040. EXPECT_EQ(original, res->body);
  22041. }
  22042. // Streaming
  22043. {
  22044. auto h = cli.open_stream("GET", path);
  22045. ASSERT_TRUE(h.is_valid());
  22046. EXPECT_EQ(original, read_all(h));
  22047. }
  22048. }
  22049. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22050. TEST(ParityTest, Gzip) {
  22051. test_compression_parity<detail::gzip_compressor>(
  22052. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22053. }
  22054. #endif
  22055. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22056. TEST(ParityTest, Brotli) {
  22057. test_compression_parity<detail::brotli_compressor>(
  22058. "Hello, brotli parity test payload", "/parity-br", "br");
  22059. }
  22060. #endif
  22061. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22062. TEST(ParityTest, Zstd) {
  22063. test_compression_parity<detail::zstd_compressor>(
  22064. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22065. }
  22066. #endif
  22067. //==============================================================================
  22068. // New Stream API Tests
  22069. //==============================================================================
  22070. inline std::string read_body(httplib::stream::Result &result) {
  22071. std::string body;
  22072. while (result.next()) {
  22073. body.append(result.data(), result.size());
  22074. }
  22075. return body;
  22076. }
  22077. TEST(ClientConnectionTest, Basic) {
  22078. httplib::ClientConnection conn;
  22079. EXPECT_FALSE(conn.is_open());
  22080. conn.sock = 1;
  22081. EXPECT_TRUE(conn.is_open());
  22082. httplib::ClientConnection conn2(std::move(conn));
  22083. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22084. conn2.sock = INVALID_SOCKET;
  22085. }
  22086. // Unified test server for all stream::* tests
  22087. class StreamApiTest : public ::testing::Test {
  22088. protected:
  22089. void SetUp() override {
  22090. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22091. res.set_content("Hello World!", "text/plain");
  22092. });
  22093. svr_.Get("/echo-params",
  22094. [](const httplib::Request &req, httplib::Response &res) {
  22095. std::string r;
  22096. for (const auto &p : req.params) {
  22097. if (!r.empty()) r += "&";
  22098. r += p.first + "=" + p.second;
  22099. }
  22100. res.set_content(r, "text/plain");
  22101. });
  22102. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22103. res.set_content(req.body, req.get_header_value("Content-Type"));
  22104. });
  22105. svr_.Post("/echo-headers",
  22106. [](const httplib::Request &req, httplib::Response &res) {
  22107. std::string r;
  22108. for (const auto &h : req.headers)
  22109. r += h.first + ": " + h.second + "\n";
  22110. res.set_content(r, "text/plain");
  22111. });
  22112. svr_.Post("/echo-params",
  22113. [](const httplib::Request &req, httplib::Response &res) {
  22114. std::string r = "params:";
  22115. for (const auto &p : req.params)
  22116. r += p.first + "=" + p.second + ";";
  22117. res.set_content(r + " body:" + req.body, "text/plain");
  22118. });
  22119. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22120. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22121. });
  22122. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22123. res.set_content("PUT:" + req.body, "text/plain");
  22124. });
  22125. svr_.Patch("/echo",
  22126. [](const httplib::Request &req, httplib::Response &res) {
  22127. res.set_content("PATCH:" + req.body, "text/plain");
  22128. });
  22129. svr_.Delete(
  22130. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22131. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22132. "text/plain");
  22133. });
  22134. svr_.Get("/head-test",
  22135. [](const httplib::Request &, httplib::Response &res) {
  22136. res.set_content("body for HEAD", "text/plain");
  22137. });
  22138. svr_.Options("/options",
  22139. [](const httplib::Request &, httplib::Response &res) {
  22140. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22141. });
  22142. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22143. svr_.wait_until_ready();
  22144. }
  22145. void TearDown() override {
  22146. svr_.stop();
  22147. if (thread_.joinable()) thread_.join();
  22148. }
  22149. httplib::Server svr_;
  22150. std::thread thread_;
  22151. };
  22152. // stream::Get tests
  22153. TEST_F(StreamApiTest, GetBasic) {
  22154. httplib::Client cli(HOST, PORT);
  22155. auto result = httplib::stream::Get(cli, "/hello");
  22156. ASSERT_TRUE(result.is_valid());
  22157. EXPECT_EQ(200, result.status());
  22158. EXPECT_EQ("Hello World!", read_body(result));
  22159. }
  22160. TEST_F(StreamApiTest, GetWithParams) {
  22161. httplib::Client cli(HOST, PORT);
  22162. httplib::Params params{{"foo", "bar"}};
  22163. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22164. ASSERT_TRUE(result.is_valid());
  22165. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22166. }
  22167. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22168. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22169. httplib::Client cli(HOST, PORT);
  22170. cli.set_payload_max_length(0);
  22171. auto result = httplib::stream::Get(cli, "/hello");
  22172. ASSERT_TRUE(result.is_valid());
  22173. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22174. EXPECT_EQ("Hello World!", read_body(result));
  22175. }
  22176. #endif
  22177. TEST_F(StreamApiTest, GetConnectionError) {
  22178. httplib::Client cli(HOST, 9999);
  22179. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22180. }
  22181. TEST_F(StreamApiTest, Get404) {
  22182. httplib::Client cli(HOST, PORT);
  22183. auto result = httplib::stream::Get(cli, "/nonexistent");
  22184. EXPECT_TRUE(result.is_valid());
  22185. EXPECT_EQ(404, result.status());
  22186. }
  22187. // stream::Post tests
  22188. TEST_F(StreamApiTest, PostBasic) {
  22189. httplib::Client cli(HOST, PORT);
  22190. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22191. "application/json");
  22192. ASSERT_TRUE(result.is_valid());
  22193. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22194. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22195. }
  22196. TEST_F(StreamApiTest, PostWithHeaders) {
  22197. httplib::Client cli(HOST, PORT);
  22198. httplib::Headers headers{{"X-Custom", "value"}};
  22199. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22200. "text/plain");
  22201. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22202. }
  22203. TEST_F(StreamApiTest, PostWithParams) {
  22204. httplib::Client cli(HOST, PORT);
  22205. httplib::Params params{{"k", "v"}};
  22206. auto result =
  22207. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22208. auto body = read_body(result);
  22209. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22210. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22211. }
  22212. TEST_F(StreamApiTest, PostLarge) {
  22213. httplib::Client cli(HOST, PORT);
  22214. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22215. size_t total = 0;
  22216. while (result.next()) {
  22217. total += result.size();
  22218. }
  22219. EXPECT_EQ(100u * 1024u, total);
  22220. }
  22221. // stream::Put/Patch tests
  22222. TEST_F(StreamApiTest, PutAndPatch) {
  22223. httplib::Client cli(HOST, PORT);
  22224. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22225. EXPECT_EQ("PUT:test", read_body(put));
  22226. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22227. EXPECT_EQ("PATCH:test", read_body(patch));
  22228. }
  22229. // stream::Delete tests
  22230. TEST_F(StreamApiTest, Delete) {
  22231. httplib::Client cli(HOST, PORT);
  22232. auto del1 = httplib::stream::Delete(cli, "/resource");
  22233. EXPECT_EQ("Deleted", read_body(del1));
  22234. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22235. EXPECT_EQ("Deleted:data", read_body(del2));
  22236. }
  22237. // stream::Head/Options tests
  22238. TEST_F(StreamApiTest, HeadAndOptions) {
  22239. httplib::Client cli(HOST, PORT);
  22240. auto head = httplib::stream::Head(cli, "/head-test");
  22241. EXPECT_TRUE(head.is_valid());
  22242. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22243. auto opts = httplib::stream::Options(cli, "/options");
  22244. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22245. }
  22246. // SSL stream::* tests
  22247. #ifdef CPPHTTPLIB_SSL_ENABLED
  22248. class SSLStreamApiTest : public ::testing::Test {
  22249. protected:
  22250. void SetUp() override {
  22251. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22252. res.set_content("Hello SSL!", "text/plain");
  22253. });
  22254. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22255. res.set_content(req.body, "text/plain");
  22256. });
  22257. port_ = svr_.bind_to_any_port("127.0.0.1");
  22258. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22259. svr_.wait_until_ready();
  22260. }
  22261. void TearDown() override {
  22262. svr_.stop();
  22263. if (thread_.joinable()) thread_.join();
  22264. }
  22265. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22266. std::thread thread_;
  22267. int port_ = 0;
  22268. };
  22269. TEST_F(SSLStreamApiTest, GetAndPost) {
  22270. httplib::SSLClient cli("127.0.0.1", port_);
  22271. cli.enable_server_certificate_verification(false);
  22272. auto get = httplib::stream::Get(cli, "/hello");
  22273. EXPECT_EQ("Hello SSL!", read_body(get));
  22274. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22275. EXPECT_EQ("test", read_body(post));
  22276. }
  22277. #endif
  22278. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22279. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22280. // BodyReader
  22281. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22282. // Test that read timeout during streaming is detected
  22283. // Use a large content-length response where server delays mid-stream
  22284. Server svr;
  22285. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22286. // Send a large response with delay in the middle
  22287. res.set_content_provider(
  22288. 1000, // content_length
  22289. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22290. if (offset < 100) {
  22291. // Send first 100 bytes immediately
  22292. std::string data(100, 'A');
  22293. sink.write(data.c_str(), data.size());
  22294. return true;
  22295. }
  22296. // Then delay longer than client timeout
  22297. std::this_thread::sleep_for(std::chrono::seconds(3));
  22298. std::string data(900, 'B');
  22299. sink.write(data.c_str(), data.size());
  22300. return true;
  22301. });
  22302. });
  22303. auto port = 8091;
  22304. std::thread t([&]() { svr.listen("localhost", port); });
  22305. svr.wait_until_ready();
  22306. Client cli("localhost", port);
  22307. cli.set_read_timeout(1, 0); // 1 second timeout
  22308. auto handle = cli.open_stream("GET", "/slow-stream");
  22309. ASSERT_TRUE(handle.is_valid());
  22310. char buf[256];
  22311. ssize_t total = 0;
  22312. ssize_t n;
  22313. bool got_error = false;
  22314. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22315. total += n;
  22316. }
  22317. if (n < 0) {
  22318. got_error = true;
  22319. // Should be timeout or read error
  22320. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22321. handle.get_read_error() == Error::Read)
  22322. << "Actual error: " << to_string(handle.get_read_error());
  22323. }
  22324. // Either we got an error, or we got less data than expected
  22325. EXPECT_TRUE(got_error || total < 1000)
  22326. << "Expected timeout but got all " << total << " bytes";
  22327. svr.stop();
  22328. t.join();
  22329. }
  22330. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22331. // Test connection closed detection via BodyReader
  22332. Server svr;
  22333. std::atomic<bool> close_now{false};
  22334. svr.Get("/will-close", [&](const Request &, Response &res) {
  22335. res.set_content_provider(
  22336. 10000, // Large content_length that we won't fully send
  22337. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22338. if (offset < 100) {
  22339. std::string data(100, 'X');
  22340. sink.write(data.c_str(), data.size());
  22341. return true;
  22342. }
  22343. // Wait for signal then abort
  22344. while (!close_now) {
  22345. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22346. }
  22347. return false; // Abort - server will close connection
  22348. });
  22349. });
  22350. auto port = 8092;
  22351. std::thread t([&]() { svr.listen("localhost", port); });
  22352. svr.wait_until_ready();
  22353. Client cli("localhost", port);
  22354. auto handle = cli.open_stream("GET", "/will-close");
  22355. ASSERT_TRUE(handle.is_valid());
  22356. char buf[256];
  22357. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22358. EXPECT_GT(n, 0) << "First read should succeed";
  22359. // Signal server to close
  22360. close_now = true;
  22361. // Keep reading until error or EOF
  22362. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22363. // Keep reading
  22364. }
  22365. // Should get an error since content_length wasn't satisfied
  22366. if (n < 0) {
  22367. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22368. handle.get_read_error() == Error::Read)
  22369. << "Actual error: " << to_string(handle.get_read_error());
  22370. }
  22371. svr.stop();
  22372. t.join();
  22373. }
  22374. #ifdef CPPHTTPLIB_SSL_ENABLED
  22375. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22376. // Test that read timeout during SSL streaming is detected
  22377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22378. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22379. res.set_content_provider(
  22380. 1000, "text/plain",
  22381. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22382. if (offset < 100) {
  22383. std::string data(100, 'A');
  22384. sink.write(data.c_str(), data.size());
  22385. return true;
  22386. }
  22387. std::this_thread::sleep_for(std::chrono::seconds(3));
  22388. std::string data(900, 'B');
  22389. sink.write(data.c_str(), data.size());
  22390. return true;
  22391. });
  22392. });
  22393. auto port = 8093;
  22394. std::thread t([&]() { svr.listen("localhost", port); });
  22395. svr.wait_until_ready();
  22396. SSLClient cli("localhost", port);
  22397. cli.enable_server_certificate_verification(false);
  22398. cli.set_read_timeout(1, 0); // 1 second timeout
  22399. auto handle = cli.open_stream("GET", "/slow-stream");
  22400. ASSERT_TRUE(handle.is_valid());
  22401. char buf[256];
  22402. ssize_t total = 0;
  22403. ssize_t n;
  22404. bool got_error = false;
  22405. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22406. total += n;
  22407. }
  22408. if (n < 0) {
  22409. got_error = true;
  22410. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22411. handle.get_read_error() == Error::Read)
  22412. << "Actual error: " << to_string(handle.get_read_error());
  22413. }
  22414. EXPECT_TRUE(got_error || total < 1000)
  22415. << "Expected timeout but got all " << total << " bytes";
  22416. svr.stop();
  22417. t.join();
  22418. }
  22419. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22420. // Test SSL connection closed detection
  22421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22422. std::atomic<bool> close_now{false};
  22423. svr.Get("/will-close", [&](const Request &, Response &res) {
  22424. res.set_content_provider(
  22425. 10000, "text/plain",
  22426. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22427. if (offset < 100) {
  22428. std::string data(100, 'X');
  22429. sink.write(data.c_str(), data.size());
  22430. return true;
  22431. }
  22432. while (!close_now) {
  22433. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22434. }
  22435. return false;
  22436. });
  22437. });
  22438. auto port = 8094;
  22439. std::thread t([&]() { svr.listen("localhost", port); });
  22440. svr.wait_until_ready();
  22441. SSLClient cli("localhost", port);
  22442. cli.enable_server_certificate_verification(false);
  22443. auto handle = cli.open_stream("GET", "/will-close");
  22444. ASSERT_TRUE(handle.is_valid());
  22445. char buf[256];
  22446. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22447. EXPECT_GT(n, 0);
  22448. // Signal server to close
  22449. close_now = true;
  22450. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22451. // Keep reading
  22452. }
  22453. if (n < 0) {
  22454. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22455. handle.get_read_error() == Error::Read)
  22456. << "Actual error: " << to_string(handle.get_read_error());
  22457. }
  22458. svr.stop();
  22459. t.join();
  22460. }
  22461. #endif
  22462. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22463. using namespace httplib;
  22464. // Create a test file
  22465. const char *fname = "etag_testfile.txt";
  22466. const char *content = "etag-content";
  22467. {
  22468. std::ofstream ofs(fname);
  22469. ofs << content;
  22470. ASSERT_TRUE(ofs.good());
  22471. }
  22472. Server svr;
  22473. svr.set_mount_point("/static", ".");
  22474. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22475. svr.wait_until_ready();
  22476. Client cli(HOST, PORT);
  22477. // First request: should get 200 with ETag header
  22478. auto res1 = cli.Get("/static/etag_testfile.txt");
  22479. ASSERT_TRUE(res1);
  22480. ASSERT_EQ(200, res1->status);
  22481. ASSERT_TRUE(res1->has_header("ETag"));
  22482. std::string etag = res1->get_header_value("ETag");
  22483. EXPECT_FALSE(etag.empty());
  22484. // Verify ETag format: W/"hex-hex"
  22485. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22486. EXPECT_EQ('W', etag[0]);
  22487. EXPECT_EQ('/', etag[1]);
  22488. EXPECT_EQ('"', etag[2]);
  22489. EXPECT_EQ('"', etag.back());
  22490. // Exact match: expect 304 Not Modified
  22491. Headers h2 = {{"If-None-Match", etag}};
  22492. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22493. ASSERT_TRUE(res2);
  22494. EXPECT_EQ(304, res2->status);
  22495. // Wildcard match: expect 304 Not Modified
  22496. Headers h3 = {{"If-None-Match", "*"}};
  22497. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22498. ASSERT_TRUE(res3);
  22499. EXPECT_EQ(304, res3->status);
  22500. // Non-matching ETag: expect 200
  22501. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22502. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22503. ASSERT_TRUE(res4);
  22504. EXPECT_EQ(200, res4->status);
  22505. // Multiple ETags with one matching: expect 304
  22506. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22507. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22508. ASSERT_TRUE(res5);
  22509. EXPECT_EQ(304, res5->status);
  22510. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22511. // that equivalent to the single comma-separated list above, so the match on
  22512. // the second line must still be found.
  22513. Headers h6;
  22514. h6.emplace("If-None-Match", "W/\"other\"");
  22515. h6.emplace("If-None-Match", etag);
  22516. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22517. ASSERT_TRUE(res6);
  22518. EXPECT_EQ(304, res6->status);
  22519. svr.stop();
  22520. t.join();
  22521. std::remove(fname);
  22522. }
  22523. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22524. using namespace httplib;
  22525. Server svr;
  22526. svr.set_mount_point("/static", ".");
  22527. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22528. svr.wait_until_ready();
  22529. Client cli(HOST, PORT);
  22530. // Send If-None-Match: * to a non-existent file
  22531. Headers h = {{"If-None-Match", "*"}};
  22532. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22534. EXPECT_EQ(404, res->status);
  22535. svr.stop();
  22536. t.join();
  22537. }
  22538. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22539. using namespace httplib;
  22540. // Create a test file
  22541. const char *fname = "etag_boundary_testfile.txt";
  22542. const char *content = "boundary-test";
  22543. {
  22544. std::ofstream ofs(fname);
  22545. ofs << content;
  22546. ASSERT_TRUE(ofs.good());
  22547. }
  22548. Server svr;
  22549. svr.set_mount_point("/static", ".");
  22550. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22551. svr.wait_until_ready();
  22552. Client cli(HOST, PORT);
  22553. // Get the actual ETag
  22554. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22555. ASSERT_TRUE(res1);
  22556. ASSERT_EQ(200, res1->status);
  22557. ASSERT_TRUE(res1->has_header("ETag"));
  22558. std::string etag = res1->get_header_value("ETag");
  22559. // Test 1: Very long ETag value (longer than actual ETag)
  22560. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22561. Headers h1 = {{"If-None-Match", "W/"
  22562. "\"very-long-etag-value-that-is-much-longer-"
  22563. "than-the-actual-etag-value\""}};
  22564. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22565. ASSERT_TRUE(res2);
  22566. EXPECT_EQ(200, res2->status); // Should not match
  22567. // Test 2: Long string followed by wildcard
  22568. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22569. // string)
  22570. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22571. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22572. ASSERT_TRUE(res3);
  22573. EXPECT_EQ(304, res3->status); // Should match on "*"
  22574. // Test 3: Wildcard followed by long string
  22575. // Should match on "*" immediately and return 304
  22576. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22577. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22578. ASSERT_TRUE(res4);
  22579. EXPECT_EQ(304, res4->status); // Should match on "*"
  22580. // Test 4: Multiple long non-matching values
  22581. // Should NOT match and return 200 (test that all comparisons are safe)
  22582. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22583. "W/\"second-long-non-matching-value\", "
  22584. "W/\"third-long-non-matching-value\""}};
  22585. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22586. ASSERT_TRUE(res5);
  22587. EXPECT_EQ(200, res5->status); // Should not match
  22588. // Test 5: Single character that is not "*" (edge case)
  22589. Headers h5 = {{"If-None-Match", "X"}};
  22590. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22591. ASSERT_TRUE(res6);
  22592. EXPECT_EQ(200, res6->status); // Should not match
  22593. svr.stop();
  22594. t.join();
  22595. std::remove(fname);
  22596. }
  22597. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22598. using namespace httplib;
  22599. // Create a test file
  22600. const char *fname = "ims_testfile.txt";
  22601. const char *content = "if-modified-since-test";
  22602. {
  22603. std::ofstream ofs(fname);
  22604. ofs << content;
  22605. ASSERT_TRUE(ofs.good());
  22606. }
  22607. Server svr;
  22608. svr.set_mount_point("/static", ".");
  22609. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22610. svr.wait_until_ready();
  22611. Client cli(HOST, PORT);
  22612. // First request: should get 200 with Last-Modified header
  22613. auto res1 = cli.Get("/static/ims_testfile.txt");
  22614. ASSERT_TRUE(res1);
  22615. ASSERT_EQ(200, res1->status);
  22616. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22617. std::string last_modified = res1->get_header_value("Last-Modified");
  22618. EXPECT_FALSE(last_modified.empty());
  22619. // If-Modified-Since with same time: expect 304
  22620. Headers h2 = {{"If-Modified-Since", last_modified}};
  22621. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22622. ASSERT_TRUE(res2);
  22623. EXPECT_EQ(304, res2->status);
  22624. // If-Modified-Since with future time: expect 304
  22625. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22626. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22627. ASSERT_TRUE(res3);
  22628. EXPECT_EQ(304, res3->status);
  22629. // If-Modified-Since with past time: expect 200
  22630. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22631. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22632. ASSERT_TRUE(res4);
  22633. EXPECT_EQ(200, res4->status);
  22634. // If-None-Match takes precedence over If-Modified-Since
  22635. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22636. ASSERT_TRUE(res1->has_header("ETag"));
  22637. std::string etag = res1->get_header_value("ETag");
  22638. Headers h5 = {{"If-None-Match", etag},
  22639. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22640. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22641. ASSERT_TRUE(res5);
  22642. EXPECT_EQ(304, res5->status);
  22643. svr.stop();
  22644. t.join();
  22645. std::remove(fname);
  22646. }
  22647. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22648. using namespace httplib;
  22649. Server svr;
  22650. // Endpoint that returns compressible content
  22651. svr.Get("/compressible", [](const Request &, Response &res) {
  22652. // Return a large enough body to trigger compression
  22653. std::string body(1000, 'a');
  22654. res.set_content(body, "text/plain");
  22655. });
  22656. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22657. svr.wait_until_ready();
  22658. Client cli(HOST, PORT);
  22659. // Request with gzip support: should get Vary header when compressed
  22660. cli.set_compress(true);
  22661. auto res1 = cli.Get("/compressible");
  22662. ASSERT_TRUE(res1);
  22663. EXPECT_EQ(200, res1->status);
  22664. // If Content-Encoding is set, Vary should also be set
  22665. if (res1->has_header("Content-Encoding")) {
  22666. EXPECT_TRUE(res1->has_header("Vary"));
  22667. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22668. }
  22669. // Request without Accept-Encoding header: should not have compression
  22670. Headers h_no_compress;
  22671. auto res2 = cli.Get("/compressible", h_no_compress);
  22672. ASSERT_TRUE(res2);
  22673. EXPECT_EQ(200, res2->status);
  22674. // Verify Vary header is present when compression is applied
  22675. // (the exact behavior depends on server configuration)
  22676. svr.stop();
  22677. t.join();
  22678. }
  22679. TEST(ETagTest, IfRangeWithETag) {
  22680. using namespace httplib;
  22681. // Create a test file with known content
  22682. const char *fname = "if_range_testfile.txt";
  22683. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22684. {
  22685. std::ofstream ofs(fname);
  22686. ofs << content;
  22687. ASSERT_TRUE(ofs.good());
  22688. }
  22689. Server svr;
  22690. svr.set_mount_point("/static", ".");
  22691. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22692. svr.wait_until_ready();
  22693. Client cli(HOST, PORT);
  22694. // First request: get ETag
  22695. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22696. ASSERT_TRUE(res1);
  22697. ASSERT_EQ(200, res1->status);
  22698. ASSERT_TRUE(res1->has_header("ETag"));
  22699. std::string etag = res1->get_header_value("ETag");
  22700. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22701. // Since our server generates weak ETags (W/"..."), If-Range with our
  22702. // ETag should NOT result in partial content - it should return full content.
  22703. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22704. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22705. ASSERT_TRUE(res2);
  22706. // Weak ETag in If-Range -> full content (200), not partial (206)
  22707. EXPECT_EQ(200, res2->status);
  22708. EXPECT_EQ(content, res2->body);
  22709. EXPECT_FALSE(res2->has_header("Content-Range"));
  22710. // Range request with non-matching If-Range (ETag): should get 200 (full
  22711. // content)
  22712. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22713. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22714. ASSERT_TRUE(res3);
  22715. EXPECT_EQ(200, res3->status);
  22716. EXPECT_EQ(content, res3->body);
  22717. EXPECT_FALSE(res3->has_header("Content-Range"));
  22718. // Range request with strong ETag (hypothetical - our server doesn't generate
  22719. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22720. // should return full content)
  22721. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22722. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22723. ASSERT_TRUE(res4);
  22724. EXPECT_EQ(200, res4->status);
  22725. EXPECT_EQ(content, res4->body);
  22726. EXPECT_FALSE(res4->has_header("Content-Range"));
  22727. svr.stop();
  22728. t.join();
  22729. std::remove(fname);
  22730. }
  22731. TEST(ETagTest, IfRangeWithDate) {
  22732. using namespace httplib;
  22733. // Create a test file
  22734. const char *fname = "if_range_date_testfile.txt";
  22735. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22736. {
  22737. std::ofstream ofs(fname);
  22738. ofs << content;
  22739. ASSERT_TRUE(ofs.good());
  22740. }
  22741. Server svr;
  22742. svr.set_mount_point("/static", ".");
  22743. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22744. svr.wait_until_ready();
  22745. Client cli(HOST, PORT);
  22746. // First request: get Last-Modified
  22747. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22748. ASSERT_TRUE(res1);
  22749. ASSERT_EQ(200, res1->status);
  22750. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22751. std::string last_modified = res1->get_header_value("Last-Modified");
  22752. // Range request with matching If-Range (date): should get 206
  22753. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22754. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22755. ASSERT_TRUE(res2);
  22756. EXPECT_EQ(206, res2->status);
  22757. EXPECT_EQ("FGHIJ", res2->body);
  22758. // Range request with old If-Range date: should get 200 (full content)
  22759. Headers h3 = {{"Range", "bytes=5-9"},
  22760. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22761. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22762. ASSERT_TRUE(res3);
  22763. EXPECT_EQ(200, res3->status);
  22764. EXPECT_EQ(content, res3->body);
  22765. // Range request with future If-Range date: should get 206
  22766. Headers h4 = {{"Range", "bytes=0-4"},
  22767. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22768. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22769. ASSERT_TRUE(res4);
  22770. EXPECT_EQ(206, res4->status);
  22771. EXPECT_EQ("ABCDE", res4->body);
  22772. svr.stop();
  22773. t.join();
  22774. std::remove(fname);
  22775. }
  22776. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22777. using namespace httplib;
  22778. const char *fname = "etag_malformed.txt";
  22779. const char *content = "malformed-etag";
  22780. {
  22781. std::ofstream ofs(fname);
  22782. ofs << content;
  22783. ASSERT_TRUE(ofs.good());
  22784. }
  22785. Server svr;
  22786. svr.set_mount_point("/static", ".");
  22787. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22788. svr.wait_until_ready();
  22789. Client cli(HOST, PORT);
  22790. // baseline: should get 200 and an ETag
  22791. auto res1 = cli.Get("/static/etag_malformed.txt");
  22792. ASSERT_TRUE(res1);
  22793. ASSERT_EQ(200, res1->status);
  22794. ASSERT_TRUE(res1->has_header("ETag"));
  22795. // Malformed ETag value (missing quotes) should be treated as non-matching
  22796. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22797. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22798. ASSERT_TRUE(res_bad);
  22799. EXPECT_EQ(200, res_bad->status);
  22800. // Whitespace-only header value should be considered invalid / non-matching
  22801. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22802. "Host: localhost\r\n"
  22803. "If-None-Match: \r\n"
  22804. "Connection: close\r\n"
  22805. "\r\n";
  22806. std::string out;
  22807. ASSERT_TRUE(send_request(5, raw_req, &out));
  22808. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22809. svr.stop();
  22810. t.join();
  22811. std::remove(fname);
  22812. }
  22813. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22814. using namespace httplib;
  22815. const char *fname = "ims_invalid_format.txt";
  22816. const char *content = "ims-bad-format";
  22817. {
  22818. std::ofstream ofs(fname);
  22819. ofs << content;
  22820. ASSERT_TRUE(ofs.good());
  22821. }
  22822. Server svr;
  22823. svr.set_mount_point("/static", ".");
  22824. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22825. svr.wait_until_ready();
  22826. Client cli(HOST, PORT);
  22827. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22828. ASSERT_TRUE(res1);
  22829. ASSERT_EQ(200, res1->status);
  22830. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22831. // If-Modified-Since with invalid format should not result in 304
  22832. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22833. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22834. ASSERT_TRUE(res_bad);
  22835. EXPECT_EQ(200, res_bad->status);
  22836. // If-Range with invalid date format should be treated as mismatch -> full
  22837. // content (200)
  22838. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22839. {"If-Range", "invalid-date"}};
  22840. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22841. ASSERT_TRUE(res_ifrange);
  22842. EXPECT_EQ(200, res_ifrange->status);
  22843. svr.stop();
  22844. t.join();
  22845. std::remove(fname);
  22846. }
  22847. TEST(ETagTest, IfRangeWithMalformedETag) {
  22848. using namespace httplib;
  22849. const char *fname = "ifrange_malformed.txt";
  22850. const std::string content = "0123456789";
  22851. {
  22852. std::ofstream ofs(fname);
  22853. ofs << content;
  22854. ASSERT_TRUE(ofs.good());
  22855. }
  22856. Server svr;
  22857. svr.set_mount_point("/static", ".");
  22858. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22859. svr.wait_until_ready();
  22860. Client cli(HOST, PORT);
  22861. // First request: get ETag
  22862. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22863. ASSERT_TRUE(res1);
  22864. ASSERT_EQ(200, res1->status);
  22865. ASSERT_TRUE(res1->has_header("ETag"));
  22866. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22867. // full content (200)
  22868. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22869. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22870. ASSERT_TRUE(res2);
  22871. EXPECT_EQ(200, res2->status);
  22872. EXPECT_EQ(content, res2->body);
  22873. svr.stop();
  22874. t.join();
  22875. std::remove(fname);
  22876. }
  22877. TEST(ETagTest, ExtremeLargeDateValues) {
  22878. using namespace httplib;
  22879. const char *fname = "ims_extreme_date.txt";
  22880. const char *content = "ims-extreme-date";
  22881. {
  22882. std::ofstream ofs(fname);
  22883. ofs << content;
  22884. ASSERT_TRUE(ofs.good());
  22885. }
  22886. Server svr;
  22887. svr.set_mount_point("/static", ".");
  22888. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22889. svr.wait_until_ready();
  22890. Client cli(HOST, PORT);
  22891. auto res1 = cli.Get(std::string("/static/") + fname);
  22892. ASSERT_TRUE(res1);
  22893. ASSERT_EQ(200, res1->status);
  22894. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22895. // Extremely large year that may overflow date parsing routines.
  22896. Headers h_large_date = {
  22897. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22898. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22899. ASSERT_TRUE(res_bad);
  22900. // Expect server to treat this as invalid/mismatch and return full content
  22901. EXPECT_EQ(200, res_bad->status);
  22902. // If-Range with extremely large date should be treated as mismatch -> full
  22903. // content (200)
  22904. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22905. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22906. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22907. ASSERT_TRUE(res_ifrange);
  22908. EXPECT_EQ(200, res_ifrange->status);
  22909. svr.stop();
  22910. t.join();
  22911. std::remove(fname);
  22912. }
  22913. TEST(ETagTest, NegativeFileModificationTime) {
  22914. using namespace httplib;
  22915. const char *fname = "ims_negative_mtime.txt";
  22916. const std::string content = "negative-mtime";
  22917. {
  22918. std::ofstream ofs(fname);
  22919. ofs << content;
  22920. ASSERT_TRUE(ofs.good());
  22921. }
  22922. // Try to set file mtime to a negative value. This may fail on some
  22923. // platforms/filesystems; if it fails, the test will still verify server
  22924. // behaves safely by performing a regular conditional request.
  22925. #if defined(__APPLE__) || defined(__linux__)
  22926. bool set_negative = false;
  22927. do {
  22928. struct timeval times[2];
  22929. // access time: now
  22930. times[0].tv_sec = time(nullptr);
  22931. times[0].tv_usec = 0;
  22932. // modification time: negative (e.g., -1)
  22933. times[1].tv_sec = -1;
  22934. times[1].tv_usec = 0;
  22935. if (utimes(fname, times) == 0) { set_negative = true; }
  22936. } while (0);
  22937. #else
  22938. bool set_negative = false;
  22939. #endif
  22940. Server svr;
  22941. svr.set_mount_point("/static", ".");
  22942. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22943. svr.wait_until_ready();
  22944. Client cli(HOST, PORT);
  22945. auto res1 = cli.Get(std::string("/static/") + fname);
  22946. ASSERT_TRUE(res1);
  22947. ASSERT_EQ(200, res1->status);
  22948. bool has_last_modified = res1->has_header("Last-Modified");
  22949. std::string last_modified;
  22950. if (has_last_modified) {
  22951. last_modified = res1->get_header_value("Last-Modified");
  22952. }
  22953. if (set_negative) {
  22954. // If we successfully set a negative mtime, ensure server returns a
  22955. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22956. // with an old date and ensure server handles it without crash.
  22957. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22958. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22959. ASSERT_TRUE(res2);
  22960. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22961. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22962. } else {
  22963. // Could not set negative mtime on this platform; fall back to verifying
  22964. // that normal invalid/malformed dates are treated safely (non-304).
  22965. Headers h_bad_date = {
  22966. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22967. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22968. ASSERT_TRUE(res_bad);
  22969. EXPECT_EQ(200, res_bad->status);
  22970. }
  22971. svr.stop();
  22972. t.join();
  22973. std::remove(fname);
  22974. }
  22975. //==============================================================================
  22976. // Integration Tests with Server
  22977. //==============================================================================
  22978. class SSEIntegrationTest : public ::testing::Test {
  22979. protected:
  22980. void SetUp() override {
  22981. stop_server_.store(false);
  22982. events_.clear();
  22983. server_ = httplib::detail::make_unique<Server>();
  22984. setup_server();
  22985. start_server();
  22986. }
  22987. void TearDown() override {
  22988. stop_server_.store(true);
  22989. event_cv_.notify_all();
  22990. server_->stop();
  22991. if (server_thread_.joinable()) { server_thread_.join(); }
  22992. }
  22993. void setup_server() {
  22994. // Simple SSE endpoint
  22995. server_->Get("/events", [this](const Request &req, Response &res) {
  22996. auto last_id = req.get_header_value("Last-Event-ID");
  22997. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22998. res.set_chunked_content_provider(
  22999. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  23000. std::unique_lock<std::mutex> lock(event_mutex_);
  23001. if (event_cv_.wait_for(
  23002. lock, std::chrono::milliseconds(200), [this] {
  23003. return !events_.empty() || stop_server_.load();
  23004. })) {
  23005. if (stop_server_.load()) { return false; }
  23006. if (!events_.empty()) {
  23007. std::string event = events_.front();
  23008. events_.erase(events_.begin());
  23009. sink.write(event.data(), event.size());
  23010. return true;
  23011. }
  23012. }
  23013. return !stop_server_.load();
  23014. });
  23015. });
  23016. // Endpoint that returns error
  23017. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  23018. res.status = 500;
  23019. res.set_content("Internal Server Error", "text/plain");
  23020. });
  23021. // Endpoint for custom event types
  23022. server_->Get("/custom-events", [](const Request &, Response &res) {
  23023. res.set_chunked_content_provider(
  23024. "text/event-stream", [](size_t offset, DataSink &sink) {
  23025. if (offset == 0) {
  23026. std::string event = "event: update\ndata: updated\n\n"
  23027. "event: delete\ndata: deleted\n\n";
  23028. sink.write(event.data(), event.size());
  23029. }
  23030. return false; // End stream after sending
  23031. });
  23032. });
  23033. }
  23034. void start_server() {
  23035. port_ = server_->bind_to_any_port(HOST);
  23036. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23037. // Wait for server to start
  23038. while (!server_->is_running()) {
  23039. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23040. }
  23041. }
  23042. int get_port() const { return port_; }
  23043. void send_event(const std::string &event) {
  23044. std::lock_guard<std::mutex> lock(event_mutex_);
  23045. events_.push_back(event);
  23046. event_cv_.notify_all();
  23047. }
  23048. std::unique_ptr<Server> server_;
  23049. std::thread server_thread_;
  23050. std::mutex event_mutex_;
  23051. std::condition_variable event_cv_;
  23052. std::vector<std::string> events_;
  23053. std::atomic<bool> stop_server_{false};
  23054. std::string last_received_event_id_;
  23055. int port_ = 0;
  23056. };
  23057. //==============================================================================
  23058. // SSE Parser Tests
  23059. //==============================================================================
  23060. struct SSEParseResult {
  23061. std::vector<sse::SSEMessage> events;
  23062. std::vector<std::string> ids;
  23063. std::vector<int> retries;
  23064. bool ok = true;
  23065. std::string trace; // Every handler call in order
  23066. };
  23067. static SSEParseResult
  23068. sse_parse(const std::vector<std::string> &chunks,
  23069. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23070. SSEParseResult r;
  23071. detail::SSEParser parser(
  23072. [&](const sse::SSEMessage &msg) {
  23073. r.events.push_back(msg);
  23074. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23075. },
  23076. [&](const std::string &id) {
  23077. r.ids.push_back(id);
  23078. r.trace += "id[" + id + "]";
  23079. },
  23080. [&](int retry_ms) {
  23081. r.retries.push_back(retry_ms);
  23082. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23083. },
  23084. max_event_length);
  23085. for (const auto &chunk : chunks) {
  23086. if (!parser.parse(chunk.data(), chunk.size())) {
  23087. r.ok = false;
  23088. break;
  23089. }
  23090. }
  23091. return r;
  23092. }
  23093. static SSEParseResult sse_parse(const std::string &stream) {
  23094. return sse_parse(std::vector<std::string>{stream});
  23095. }
  23096. TEST(SSEParserTest, SingleLineData) {
  23097. auto r = sse_parse("data: hello\n\n");
  23098. ASSERT_EQ(r.events.size(), 1u);
  23099. EXPECT_EQ(r.events[0].data, "hello");
  23100. EXPECT_EQ(r.events[0].event, "message");
  23101. }
  23102. TEST(SSEParserTest, MultiLineData) {
  23103. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23104. ASSERT_EQ(r.events.size(), 1u);
  23105. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23106. }
  23107. TEST(SSEParserTest, CustomEventType) {
  23108. auto r = sse_parse("event: update\ndata: payload\n\n");
  23109. ASSERT_EQ(r.events.size(), 1u);
  23110. EXPECT_EQ(r.events[0].event, "update");
  23111. EXPECT_EQ(r.events[0].data, "payload");
  23112. }
  23113. TEST(SSEParserTest, EventIdHandling) {
  23114. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23115. ASSERT_EQ(r.events.size(), 1u);
  23116. EXPECT_EQ(r.events[0].id, "12345");
  23117. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23118. }
  23119. TEST(SSEParserTest, EmptyEventId) {
  23120. auto r = sse_parse("id:\ndata: test\n\n");
  23121. ASSERT_EQ(r.events.size(), 1u);
  23122. EXPECT_EQ(r.events[0].id, "");
  23123. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23124. }
  23125. TEST(SSEParserTest, CommentsIgnored) {
  23126. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23127. ASSERT_EQ(r.events.size(), 1u);
  23128. EXPECT_EQ(r.events[0].data, "hello");
  23129. EXPECT_EQ(r.events[0].event, "message");
  23130. }
  23131. TEST(SSEParserTest, ColonInValue) {
  23132. auto r = sse_parse("data: hello:world:test\n\n");
  23133. ASSERT_EQ(r.events.size(), 1u);
  23134. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23135. }
  23136. TEST(SSEParserTest, FieldNameOnly) {
  23137. // A line without a colon is a field name with an empty value
  23138. auto r = sse_parse("data\n\n");
  23139. ASSERT_EQ(r.events.size(), 1u);
  23140. EXPECT_EQ(r.events[0].data, "");
  23141. }
  23142. TEST(SSEParserTest, TrailingCarriageReturn) {
  23143. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23144. ASSERT_EQ(r.events.size(), 1u);
  23145. EXPECT_EQ(r.events[0].event, "update");
  23146. EXPECT_EQ(r.events[0].data, "hello");
  23147. }
  23148. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23149. auto r = sse_parse("data\r\n\r\n");
  23150. ASSERT_EQ(r.events.size(), 1u);
  23151. EXPECT_EQ(r.events[0].data, "");
  23152. }
  23153. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23154. auto r = sse_parse("event: update\rdata: hello\r\r");
  23155. ASSERT_EQ(r.events.size(), 1u);
  23156. EXPECT_EQ(r.events[0].event, "update");
  23157. EXPECT_EQ(r.events[0].data, "hello");
  23158. }
  23159. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23160. // Chunk boundaries fall inside every \r\n and right before the first one
  23161. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23162. "\ndata: hello\r", "\n\r", "\n"});
  23163. ASSERT_EQ(r.events.size(), 1u);
  23164. EXPECT_EQ(r.events[0].event, "update");
  23165. EXPECT_EQ(r.events[0].data, "hello");
  23166. }
  23167. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23168. // Only a BOM at the start of the stream is ignored
  23169. auto r = sse_parse("\xEF\xBB\xBF"
  23170. "data: first\n\n"
  23171. "\xEF\xBB\xBF"
  23172. "data: second\n\n");
  23173. ASSERT_EQ(r.events.size(), 1u);
  23174. EXPECT_EQ(r.events[0].data, "first");
  23175. }
  23176. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23177. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23178. ASSERT_EQ(r.events.size(), 1u);
  23179. EXPECT_EQ(r.events[0].data, "hello");
  23180. EXPECT_EQ(r.events[0].event, "message");
  23181. }
  23182. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23183. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23184. ASSERT_EQ(r.events.size(), 2u);
  23185. EXPECT_EQ(r.events[0].data, "hello");
  23186. EXPECT_EQ(r.events[1].data, "hello");
  23187. }
  23188. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23189. // An event without data is not dispatched, and its type must not leak
  23190. // into the next event
  23191. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23192. ASSERT_EQ(r.events.size(), 1u);
  23193. EXPECT_EQ(r.events[0].event, "message");
  23194. EXPECT_EQ(r.events[0].data, "hello");
  23195. }
  23196. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23197. // Also when the empty field replaces an earlier type
  23198. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23199. ASSERT_EQ(r.events.size(), 2u);
  23200. EXPECT_EQ(r.events[0].event, "message");
  23201. EXPECT_EQ(r.events[1].event, "message");
  23202. }
  23203. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23204. auto r = sse_parse("id: 42\n\n");
  23205. EXPECT_TRUE(r.events.empty());
  23206. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23207. }
  23208. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23209. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23210. ASSERT_EQ(r.events.size(), 2u);
  23211. EXPECT_EQ(r.events[0].id, "1");
  23212. EXPECT_EQ(r.events[1].id, "");
  23213. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23214. }
  23215. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23216. // Ids that cannot be carried in a Last-Event-ID header
  23217. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23218. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23219. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23220. }
  23221. TEST(SSEParserTest, RetryDigitsOnly) {
  23222. auto r = sse_parse("retry: 1000\n");
  23223. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23224. // A value that is not all ASCII digits, or does not fit, is ignored
  23225. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23226. EXPECT_TRUE(r.retries.empty());
  23227. }
  23228. TEST(SSEParserTest, CompleteEventParsing) {
  23229. auto r = sse_parse("event: notification\nid: evt-42\n"
  23230. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23231. ASSERT_EQ(r.events.size(), 1u);
  23232. EXPECT_EQ(r.events[0].event, "notification");
  23233. EXPECT_EQ(r.events[0].id, "evt-42");
  23234. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23235. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23236. }
  23237. TEST(SSEParserTest, IncompleteEventNotReported) {
  23238. // An event still waiting for its blank line when the stream ends is
  23239. // discarded per the SSE spec
  23240. auto r = sse_parse("id: 1\ndata: x\n");
  23241. EXPECT_TRUE(r.events.empty());
  23242. EXPECT_TRUE(r.ids.empty());
  23243. }
  23244. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23245. const std::vector<std::string> streams = {
  23246. "\xEF\xBB\xBF"
  23247. "data: bom\r\n\r\n",
  23248. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23249. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23250. };
  23251. for (const auto &stream : streams) {
  23252. auto expected = sse_parse(stream).trace;
  23253. ASSERT_FALSE(expected.empty());
  23254. for (size_t i = 0; i <= stream.size(); i++) {
  23255. auto r = sse_parse(
  23256. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23257. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23258. }
  23259. std::vector<std::string> bytes;
  23260. for (auto c : stream) {
  23261. bytes.emplace_back(1, c);
  23262. }
  23263. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23264. }
  23265. }
  23266. TEST(SSEParserTest, MaxEventLength) {
  23267. // A line still waiting for its end
  23268. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23269. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23270. // Data accumulated over the lines of one event
  23271. EXPECT_TRUE(
  23272. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23273. EXPECT_FALSE(
  23274. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23275. // 0 means no limit
  23276. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23277. // Events completed in the same chunk are still reported
  23278. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23279. EXPECT_FALSE(r.ok);
  23280. ASSERT_EQ(r.events.size(), 1u);
  23281. EXPECT_EQ(r.events[0].data, "a");
  23282. }
  23283. TEST(SSEMessageTest, Clear) {
  23284. sse::SSEMessage msg;
  23285. msg.event = "custom";
  23286. msg.data = "some data";
  23287. msg.id = "123";
  23288. msg.clear();
  23289. EXPECT_EQ(msg.event, "message");
  23290. EXPECT_EQ(msg.data, "");
  23291. EXPECT_EQ(msg.id, "");
  23292. }
  23293. //==============================================================================
  23294. // SSE Integration Tests
  23295. //==============================================================================
  23296. // Test: Successful connection and on_open callback
  23297. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23298. // Add a simple endpoint that sends one event and closes
  23299. server_->Get("/simple-event", [](const Request &, Response &res) {
  23300. res.set_chunked_content_provider(
  23301. "text/event-stream", [](size_t offset, DataSink &sink) {
  23302. if (offset == 0) {
  23303. std::string event = "data: hello\n\n";
  23304. sink.write(event.data(), event.size());
  23305. }
  23306. return false; // Close stream after sending
  23307. });
  23308. });
  23309. Client client("localhost", get_port());
  23310. sse::SSEClient sse(client, "/simple-event");
  23311. std::atomic<bool> open_called{false};
  23312. std::atomic<bool> message_received{false};
  23313. sse.on_open([&open_called]() { open_called.store(true); });
  23314. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23315. if (msg.data == "hello") { message_received.store(true); }
  23316. });
  23317. sse.set_reconnect_interval(100);
  23318. sse.set_max_reconnect_attempts(1);
  23319. // Start async
  23320. sse.start_async();
  23321. // Wait for message to be processed
  23322. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23323. sse.stop();
  23324. EXPECT_TRUE(open_called.load());
  23325. EXPECT_TRUE(message_received.load());
  23326. }
  23327. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23328. // A data line that never ends.
  23329. server_->Get("/endless-line", [](const Request &, Response &res) {
  23330. res.set_chunked_content_provider(
  23331. "text/event-stream", [](size_t offset, DataSink &sink) {
  23332. if (offset == 0) { sink.write("data: ", 6); }
  23333. std::string chunk(64 * 1024, 'A');
  23334. return sink.write(chunk.data(), chunk.size());
  23335. });
  23336. });
  23337. Client client("localhost", get_port());
  23338. sse::SSEClient sse(client, "/endless-line");
  23339. std::atomic<bool> too_long{false};
  23340. sse.on_error([&](Error err) {
  23341. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23342. });
  23343. sse.set_max_reconnect_attempts(1);
  23344. sse.start_async();
  23345. for (int i = 0; i < 500 && !too_long; i++) {
  23346. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23347. }
  23348. sse.stop();
  23349. EXPECT_TRUE(too_long);
  23350. }
  23351. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23352. // Far more in all than the client's payload limit below.
  23353. server_->Get("/many-events", [](const Request &, Response &res) {
  23354. res.set_chunked_content_provider(
  23355. "text/event-stream", [](size_t offset, DataSink &sink) {
  23356. if (offset == 0) {
  23357. std::string events;
  23358. for (int i = 0; i < 1000; i++) {
  23359. events += "data: message\n\n";
  23360. }
  23361. sink.write(events.data(), events.size());
  23362. }
  23363. return false;
  23364. });
  23365. });
  23366. Client client("localhost", get_port());
  23367. client.set_payload_max_length(1024);
  23368. sse::SSEClient sse(client, "/many-events");
  23369. std::atomic<int> messages{0};
  23370. std::atomic<bool> too_large{false};
  23371. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23372. sse.on_error([&](Error err) {
  23373. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23374. });
  23375. sse.set_max_reconnect_attempts(1);
  23376. sse.start_async();
  23377. for (int i = 0; i < 500 && messages < 1000; i++) {
  23378. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23379. }
  23380. sse.stop();
  23381. EXPECT_GE(messages.load(), 1000);
  23382. EXPECT_FALSE(too_large);
  23383. }
  23384. // Test: on_message callback
  23385. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23386. // Endpoint that sends multiple events then closes
  23387. server_->Get("/multi-event", [](const Request &, Response &res) {
  23388. res.set_chunked_content_provider(
  23389. "text/event-stream", [](size_t offset, DataSink &sink) {
  23390. if (offset == 0) {
  23391. std::string events = "data: message1\n\ndata: message2\n\n";
  23392. sink.write(events.data(), events.size());
  23393. }
  23394. return false;
  23395. });
  23396. });
  23397. Client client("localhost", get_port());
  23398. sse::SSEClient sse(client, "/multi-event");
  23399. std::vector<std::string> received_messages;
  23400. std::mutex messages_mutex;
  23401. sse.on_message([&](const sse::SSEMessage &msg) {
  23402. std::lock_guard<std::mutex> lock(messages_mutex);
  23403. received_messages.push_back(msg.data);
  23404. });
  23405. sse.set_reconnect_interval(100);
  23406. sse.set_max_reconnect_attempts(1);
  23407. sse.start_async();
  23408. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23409. sse.stop();
  23410. std::lock_guard<std::mutex> lock(messages_mutex);
  23411. EXPECT_GE(received_messages.size(), 2u);
  23412. if (received_messages.size() >= 2) {
  23413. EXPECT_EQ(received_messages[0], "message1");
  23414. EXPECT_EQ(received_messages[1], "message2");
  23415. }
  23416. }
  23417. // Test: on_event for specific types
  23418. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23419. Client client("localhost", get_port());
  23420. sse::SSEClient sse(client, "/custom-events");
  23421. std::atomic<bool> update_received{false};
  23422. std::atomic<bool> delete_received{false};
  23423. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23424. if (msg.data == "updated") { update_received.store(true); }
  23425. });
  23426. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23427. if (msg.data == "deleted") { delete_received.store(true); }
  23428. });
  23429. sse.set_max_reconnect_attempts(1);
  23430. sse.start_async();
  23431. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23432. sse.stop();
  23433. EXPECT_TRUE(update_received.load());
  23434. EXPECT_TRUE(delete_received.load());
  23435. }
  23436. // Test: on_error callback on connection failure
  23437. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23438. // Connect to a non-existent port
  23439. Client client("localhost", 59999);
  23440. sse::SSEClient sse(client, "/events");
  23441. std::atomic<bool> error_called{false};
  23442. Error received_error = Error::Success;
  23443. sse.on_error([&](Error err) {
  23444. error_called.store(true);
  23445. received_error = err;
  23446. });
  23447. sse.set_reconnect_interval(50);
  23448. sse.set_max_reconnect_attempts(1);
  23449. sse.start_async();
  23450. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23451. sse.stop();
  23452. EXPECT_TRUE(error_called.load());
  23453. EXPECT_NE(received_error, Error::Success);
  23454. }
  23455. // Test: Last-Event-ID header sent on reconnect
  23456. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23457. // Endpoint that sends event with ID
  23458. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23459. res.set_chunked_content_provider(
  23460. "text/event-stream", [](size_t offset, DataSink &sink) {
  23461. if (offset == 0) {
  23462. std::string event = "id: evt-123\ndata: test\n\n";
  23463. sink.write(event.data(), event.size());
  23464. }
  23465. return false;
  23466. });
  23467. });
  23468. Client client("localhost", get_port());
  23469. sse::SSEClient sse(client, "/event-with-id");
  23470. std::atomic<bool> id_received{false};
  23471. sse.on_message([&](const sse::SSEMessage &msg) {
  23472. if (!msg.id.empty()) { id_received.store(true); }
  23473. });
  23474. sse.set_reconnect_interval(100);
  23475. sse.set_max_reconnect_attempts(1);
  23476. sse.start_async();
  23477. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23478. sse.stop();
  23479. EXPECT_TRUE(id_received.load());
  23480. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23481. }
  23482. // Test: last_event_id() read from another thread while start_async() runs
  23483. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23484. // Ids of every length up to 200, so the stored id keeps changing size
  23485. server_->Get("/many-ids", [](const Request &, Response &res) {
  23486. res.set_chunked_content_provider(
  23487. "text/event-stream", [](size_t offset, DataSink &sink) {
  23488. if (offset == 0) {
  23489. std::string events;
  23490. for (size_t i = 0; i < 2000; i++) {
  23491. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23492. events += "data: x\n\n";
  23493. }
  23494. events += "id: end\ndata: x\n\n";
  23495. sink.write(events.data(), events.size());
  23496. }
  23497. return false;
  23498. });
  23499. });
  23500. Client client("localhost", get_port());
  23501. sse::SSEClient sse(client, "/many-ids");
  23502. // Wait out the rest of the test rather than replay the stream
  23503. sse.set_reconnect_interval(10000);
  23504. sse.set_max_reconnect_attempts(1);
  23505. sse.start_async();
  23506. auto well_formed = true;
  23507. std::string id;
  23508. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23509. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23510. id = sse.last_event_id();
  23511. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23512. well_formed = false;
  23513. }
  23514. }
  23515. sse.stop();
  23516. EXPECT_TRUE(well_formed);
  23517. EXPECT_EQ(sse.last_event_id(), "end");
  23518. }
  23519. // Test: Manual stop
  23520. TEST_F(SSEIntegrationTest, ManualStop) {
  23521. // Endpoint that sends one event and stays open briefly. The server outlives
  23522. // this test body, so the provider uses the fixture's flag, not a local.
  23523. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23524. res.set_chunked_content_provider(
  23525. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23526. if (offset == 0) {
  23527. std::string event = "data: connected\n\n";
  23528. sink.write(event.data(), event.size());
  23529. }
  23530. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23531. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23532. }
  23533. return false;
  23534. });
  23535. });
  23536. Client client("localhost", get_port());
  23537. sse::SSEClient sse(client, "/stay-open");
  23538. std::atomic<bool> connected{false};
  23539. sse.on_open([&connected]() { connected.store(true); });
  23540. sse.set_reconnect_interval(100);
  23541. sse.set_max_reconnect_attempts(1);
  23542. sse.start_async();
  23543. // Wait for connection to establish
  23544. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23545. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23546. }
  23547. EXPECT_TRUE(connected.load());
  23548. EXPECT_TRUE(sse.is_connected());
  23549. // Signal handler to stop
  23550. stop_server_.store(true);
  23551. // Stop SSE client
  23552. sse.stop();
  23553. EXPECT_FALSE(sse.is_connected());
  23554. }
  23555. // Sends one event, then nothing until stop is set
  23556. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23557. return [&stop](const Request &, Response &res) {
  23558. res.set_chunked_content_provider(
  23559. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23560. if (offset == 0) {
  23561. std::string event = "data: hello\n\n";
  23562. sink.write(event.data(), event.size());
  23563. }
  23564. while (!stop.load()) {
  23565. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23566. }
  23567. return false;
  23568. });
  23569. };
  23570. }
  23571. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23572. static void check_stop_interrupts_blocked_read(Client &client) {
  23573. client.set_read_timeout(30, 0);
  23574. for (auto by_destructor : {false, true}) {
  23575. std::atomic<bool> received{false};
  23576. std::chrono::steady_clock::time_point start;
  23577. {
  23578. sse::SSEClient sse(client, "/idle-stream");
  23579. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23580. sse.start_async();
  23581. for (int i = 0; i < 500 && !received.load(); ++i) {
  23582. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23583. }
  23584. ASSERT_TRUE(received.load());
  23585. // Let the client block in the next read
  23586. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23587. start = std::chrono::steady_clock::now();
  23588. if (!by_destructor) { sse.stop(); }
  23589. }
  23590. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23591. std::chrono::seconds(2));
  23592. }
  23593. }
  23594. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23595. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23596. Client client("localhost", get_port());
  23597. check_stop_interrupts_blocked_read(client);
  23598. }
  23599. #ifdef CPPHTTPLIB_SSL_ENABLED
  23600. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23602. std::atomic<bool> done{false};
  23603. svr.Get("/idle-stream", idle_event_stream(done));
  23604. auto port = svr.bind_to_any_port(HOST);
  23605. std::thread t([&] { svr.listen_after_bind(); });
  23606. auto se = detail::scope_exit([&] {
  23607. done.store(true);
  23608. svr.stop();
  23609. t.join();
  23610. });
  23611. svr.wait_until_ready();
  23612. Client client("https://localhost:" + std::to_string(port));
  23613. client.enable_server_certificate_verification(false);
  23614. check_stop_interrupts_blocked_read(client);
  23615. }
  23616. #endif
  23617. // Test: SSEClient with custom headers
  23618. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23619. // Setup a server endpoint that checks for custom header
  23620. std::atomic<bool> header_received{false};
  23621. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23622. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23623. header_received.store(true);
  23624. }
  23625. res.set_chunked_content_provider("text/event-stream",
  23626. [](size_t, DataSink &) { return false; });
  23627. });
  23628. Client client("localhost", get_port());
  23629. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23630. sse::SSEClient sse(client, "/header-check", headers);
  23631. sse.set_max_reconnect_attempts(1);
  23632. sse.start_async();
  23633. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23634. sse.stop();
  23635. EXPECT_TRUE(header_received.load());
  23636. }
  23637. // Test: Reconnect interval configuration
  23638. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23639. Client client("localhost", get_port());
  23640. sse::SSEClient sse(client, "/events");
  23641. auto &result = sse.set_reconnect_interval(500);
  23642. // Builder pattern should return reference to self
  23643. EXPECT_EQ(&result, &sse);
  23644. }
  23645. // Test: Max reconnect attempts
  23646. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23647. // Connect to non-existent port to force reconnects
  23648. Client client("localhost", 59998);
  23649. sse::SSEClient sse(client, "/events");
  23650. std::atomic<int> error_count{0};
  23651. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23652. sse.set_reconnect_interval(50);
  23653. sse.set_max_reconnect_attempts(2);
  23654. auto start = std::chrono::steady_clock::now();
  23655. sse.start(); // Blocking call
  23656. auto end = std::chrono::steady_clock::now();
  23657. // Should have stopped after 2 failed attempts
  23658. EXPECT_GE(error_count.load(), 2);
  23659. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23660. auto duration =
  23661. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23662. #ifdef _WIN32
  23663. // Windows is much slower for socket connection failures
  23664. EXPECT_LT(duration.count(), 7000);
  23665. #else
  23666. EXPECT_LT(duration.count(), 1000);
  23667. #endif
  23668. }
  23669. // Test: Multi-line data in integration
  23670. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23671. // Endpoint with multi-line data
  23672. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23673. res.set_chunked_content_provider(
  23674. "text/event-stream", [](size_t offset, DataSink &sink) {
  23675. if (offset == 0) {
  23676. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23677. sink.write(event.data(), event.size());
  23678. }
  23679. return false;
  23680. });
  23681. });
  23682. Client client("localhost", get_port());
  23683. sse::SSEClient sse(client, "/multiline-data");
  23684. std::string received_data;
  23685. std::mutex data_mutex;
  23686. sse.on_message([&](const sse::SSEMessage &msg) {
  23687. std::lock_guard<std::mutex> lock(data_mutex);
  23688. received_data = msg.data;
  23689. });
  23690. sse.set_reconnect_interval(100);
  23691. sse.set_max_reconnect_attempts(1);
  23692. sse.start_async();
  23693. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23694. sse.stop();
  23695. std::lock_guard<std::mutex> lock(data_mutex);
  23696. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23697. }
  23698. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23699. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23700. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23701. DataSink &sink) {
  23702. if (offset == 0) {
  23703. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23704. sink.write(events.data(), events.size());
  23705. }
  23706. return false;
  23707. });
  23708. });
  23709. Client client("localhost", get_port());
  23710. sse::SSEClient sse(client, "/empty-data-lines");
  23711. std::mutex mutex;
  23712. std::condition_variable cv;
  23713. std::vector<std::string> received;
  23714. sse.on_message([&](const sse::SSEMessage &msg) {
  23715. std::lock_guard<std::mutex> lock(mutex);
  23716. received.push_back(msg.data);
  23717. cv.notify_all();
  23718. });
  23719. sse.set_max_reconnect_attempts(1);
  23720. sse.start_async();
  23721. {
  23722. std::unique_lock<std::mutex> lock(mutex);
  23723. cv.wait_for(lock, std::chrono::seconds(2),
  23724. [&] { return received.size() >= 3; });
  23725. }
  23726. sse.stop();
  23727. ASSERT_GE(received.size(), 3u);
  23728. EXPECT_EQ(received[0], "");
  23729. EXPECT_EQ(received[1], "\nhello");
  23730. EXPECT_EQ(received[2], "");
  23731. }
  23732. // Test: Auto-reconnect after server disconnection
  23733. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23734. std::atomic<int> connection_count{0};
  23735. std::atomic<int> message_count{0};
  23736. // Endpoint that sends one event and closes, forcing reconnect
  23737. server_->Get("/reconnect-test",
  23738. [&connection_count](const Request &, Response &res) {
  23739. connection_count.fetch_add(1);
  23740. res.set_chunked_content_provider(
  23741. "text/event-stream", [](size_t offset, DataSink &sink) {
  23742. if (offset == 0) {
  23743. std::string event = "data: hello\n\n";
  23744. sink.write(event.data(), event.size());
  23745. }
  23746. return false; // Close connection after sending
  23747. });
  23748. });
  23749. Client client("localhost", get_port());
  23750. sse::SSEClient sse(client, "/reconnect-test");
  23751. sse.on_message([&message_count](const sse::SSEMessage &) {
  23752. message_count.fetch_add(1);
  23753. });
  23754. sse.set_reconnect_interval(100);
  23755. sse.set_max_reconnect_attempts(3);
  23756. sse.start_async();
  23757. // Wait long enough for multiple reconnects
  23758. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23759. sse.stop();
  23760. // Should have connected multiple times (initial + reconnects)
  23761. EXPECT_GE(connection_count.load(), 2);
  23762. // Should have received messages from multiple connections
  23763. EXPECT_GE(message_count.load(), 2);
  23764. }
  23765. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23766. std::atomic<int> connection_count{0};
  23767. // Neither Content-Length nor chunked: the close ends the stream
  23768. server_->Get("/close-delimited",
  23769. [&connection_count](const Request &, Response &res) {
  23770. connection_count.fetch_add(1);
  23771. res.set_content_provider(
  23772. "text/event-stream", [](size_t offset, DataSink &sink) {
  23773. if (offset == 0) {
  23774. std::string event = "data: hello\n\n";
  23775. sink.write(event.data(), event.size());
  23776. } else {
  23777. sink.done();
  23778. }
  23779. return true;
  23780. });
  23781. });
  23782. Client client("localhost", get_port());
  23783. sse::SSEClient sse(client, "/close-delimited");
  23784. std::atomic<int> error_count{0};
  23785. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23786. sse.set_reconnect_interval(100);
  23787. sse.start_async();
  23788. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23789. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23790. }
  23791. sse.stop();
  23792. // Reconnects as after any end of the stream, but reports no error
  23793. EXPECT_GE(connection_count.load(), 2);
  23794. EXPECT_EQ(0, error_count.load());
  23795. }
  23796. // Test: A retry field of all ASCII digits sets the reconnection time
  23797. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23798. std::mutex mutex;
  23799. std::condition_variable cv;
  23800. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23801. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23802. {
  23803. std::lock_guard<std::mutex> lock(mutex);
  23804. connected_at.push_back(std::chrono::steady_clock::now());
  23805. cv.notify_all();
  23806. }
  23807. res.set_chunked_content_provider(
  23808. "text/event-stream", [](size_t offset, DataSink &sink) {
  23809. if (offset == 0) {
  23810. std::string event = "retry: 0\ndata: hello\n\n";
  23811. sink.write(event.data(), event.size());
  23812. }
  23813. return false;
  23814. });
  23815. });
  23816. Client client("localhost", get_port());
  23817. sse::SSEClient sse(client, "/zero-retry");
  23818. sse.set_reconnect_interval(10000);
  23819. sse.start_async();
  23820. {
  23821. std::unique_lock<std::mutex> lock(mutex);
  23822. cv.wait_for(lock, std::chrono::seconds(5),
  23823. [&] { return connected_at.size() >= 2; });
  23824. }
  23825. sse.stop();
  23826. // The server-supplied interval is applied, but never below 100ms, so
  23827. // "retry: 0" does not cause a busy reconnect loop
  23828. std::lock_guard<std::mutex> lock(mutex);
  23829. ASSERT_GE(connected_at.size(), 2u);
  23830. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23831. connected_at[1] - connected_at[0])
  23832. .count();
  23833. EXPECT_GE(interval_ms, 100);
  23834. }
  23835. // Test: Last-Event-ID sent on reconnect
  23836. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23837. std::atomic<int> connection_count{0};
  23838. std::vector<std::string> received_last_event_ids;
  23839. std::mutex id_mutex;
  23840. // Endpoint that checks Last-Event-ID header and sends event with ID
  23841. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23842. int conn = connection_count.fetch_add(1);
  23843. // Capture the Last-Event-ID header from each connection
  23844. {
  23845. std::lock_guard<std::mutex> lock(id_mutex);
  23846. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23847. }
  23848. res.set_chunked_content_provider(
  23849. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23850. if (offset == 0) {
  23851. std::string event =
  23852. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23853. sink.write(event.data(), event.size());
  23854. }
  23855. return false;
  23856. });
  23857. });
  23858. Client client("localhost", get_port());
  23859. sse::SSEClient sse(client, "/reconnect-with-id");
  23860. sse.set_reconnect_interval(100);
  23861. sse.set_max_reconnect_attempts(3);
  23862. sse.start_async();
  23863. // Wait for at least 2 connections
  23864. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23865. sse.stop();
  23866. // Verify behavior
  23867. std::lock_guard<std::mutex> lock(id_mutex);
  23868. EXPECT_GE(received_last_event_ids.size(), 2u);
  23869. // First connection should have no Last-Event-ID
  23870. if (!received_last_event_ids.empty()) {
  23871. EXPECT_EQ(received_last_event_ids[0], "");
  23872. }
  23873. // Second connection should have Last-Event-ID from first connection
  23874. if (received_last_event_ids.size() >= 2) {
  23875. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23876. }
  23877. }
  23878. // Test: set_headers updates headers used on reconnect
  23879. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23880. std::vector<std::string> received_tokens;
  23881. std::mutex token_mutex;
  23882. // Endpoint that captures Authorization header
  23883. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23884. {
  23885. std::lock_guard<std::mutex> lock(token_mutex);
  23886. received_tokens.push_back(req.get_header_value("Authorization"));
  23887. }
  23888. res.set_chunked_content_provider(
  23889. "text/event-stream", [](size_t offset, DataSink &sink) {
  23890. if (offset == 0) {
  23891. std::string event = "data: hello\n\n";
  23892. sink.write(event.data(), event.size());
  23893. }
  23894. return false; // Close connection to trigger reconnect
  23895. });
  23896. });
  23897. Client client("localhost", get_port());
  23898. Headers headers = {{"Authorization", "Bearer old-token"}};
  23899. sse::SSEClient sse(client, "/auth-check", headers);
  23900. // Update headers on each successful connection
  23901. sse.on_open(
  23902. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23903. sse.set_reconnect_interval(100);
  23904. sse.set_max_reconnect_attempts(3);
  23905. sse.start_async();
  23906. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23907. sse.stop();
  23908. std::lock_guard<std::mutex> lock(token_mutex);
  23909. ASSERT_GE(received_tokens.size(), 2u);
  23910. // First connection uses original header
  23911. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23912. // Second connection uses updated header from set_headers
  23913. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23914. }
  23915. // Test: 401 allows reconnection (so on_error can refresh headers)
  23916. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23917. std::atomic<int> connection_count{0};
  23918. // Endpoint: returns 401 on first attempt, 200 on second
  23919. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23920. int conn = connection_count.fetch_add(1);
  23921. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23922. res.status = StatusCode::Unauthorized_401;
  23923. res.set_content("Unauthorized", "text/plain");
  23924. return;
  23925. }
  23926. res.set_chunked_content_provider(
  23927. "text/event-stream", [](size_t offset, DataSink &sink) {
  23928. if (offset == 0) {
  23929. std::string event = "data: authenticated\n\n";
  23930. sink.write(event.data(), event.size());
  23931. }
  23932. return false;
  23933. });
  23934. });
  23935. Client client("localhost", get_port());
  23936. Headers headers = {{"Authorization", "Bearer expired"}};
  23937. sse::SSEClient sse(client, "/auth-retry", headers);
  23938. std::atomic<bool> message_received{false};
  23939. // Refresh token on error
  23940. sse.on_error(
  23941. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23942. sse.on_message([&](const sse::SSEMessage &msg) {
  23943. if (msg.data == "authenticated") { message_received.store(true); }
  23944. });
  23945. sse.set_reconnect_interval(100);
  23946. sse.set_max_reconnect_attempts(3);
  23947. sse.start_async();
  23948. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23949. sse.stop();
  23950. // Should have reconnected after 401 and succeeded with new token
  23951. EXPECT_GE(connection_count.load(), 2);
  23952. EXPECT_TRUE(message_received.load());
  23953. }
  23954. TEST(Issue2318Test, EmptyHostString) {
  23955. {
  23956. httplib::Client cli_empty("", PORT);
  23957. auto res = cli_empty.Get("/");
  23958. ASSERT_FALSE(res);
  23959. EXPECT_EQ(httplib::Error::Connection, res.error());
  23960. }
  23961. {
  23962. httplib::Client cli(" ", PORT);
  23963. auto res = cli.Get("/");
  23964. ASSERT_FALSE(res);
  23965. EXPECT_EQ(httplib::Error::Connection, res.error());
  23966. }
  23967. }
  23968. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23969. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23970. Server svr;
  23971. // Set a small payload limit (1KB)
  23972. svr.set_payload_max_length(1024);
  23973. svr.Post("/test", [&](const Request &req, Response &res) {
  23974. res.set_content("Body size: " + std::to_string(req.body.size()),
  23975. "text/plain");
  23976. });
  23977. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23978. auto se = detail::scope_exit([&] {
  23979. svr.stop();
  23980. listen_thread.join();
  23981. });
  23982. svr.wait_until_ready();
  23983. // Create data that compresses well but exceeds limit when decompressed
  23984. // 8KB of repeated null bytes compresses to a very small size
  23985. std::string original_data(8 * 1024, '\0');
  23986. // Compress the data using gzip
  23987. std::string compressed_data;
  23988. detail::gzip_compressor compressor;
  23989. compressor.compress(original_data.data(), original_data.size(), true,
  23990. [&](const char *data, size_t size) {
  23991. compressed_data.append(data, size);
  23992. return true;
  23993. });
  23994. // Verify compression worked (compressed should be much smaller)
  23995. ASSERT_LT(compressed_data.size(), original_data.size());
  23996. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23997. // Send compressed data with Content-Encoding: gzip
  23998. Client cli(HOST, PORT);
  23999. Headers headers = {{"Content-Encoding", "gzip"}};
  24000. auto res =
  24001. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  24002. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  24003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24004. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  24005. }
  24006. #endif
  24007. // ============================================================================
  24008. // OpenSSL-Specific Tests
  24009. // ============================================================================
  24010. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24011. X509 *readCertificate(const std::string &strFileName) {
  24012. std::ifstream inStream(strFileName);
  24013. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  24014. std::istreambuf_iterator<char>());
  24015. if (strCertPEM.empty()) return (nullptr);
  24016. BIO *pbCert = BIO_new(BIO_s_mem());
  24017. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  24018. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  24019. BIO_free(pbCert);
  24020. return (pCert);
  24021. }
  24022. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  24023. std::ifstream inStream(strFileName);
  24024. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  24025. std::istreambuf_iterator<char>());
  24026. if (strPrivateKeyPEM.empty()) return (nullptr);
  24027. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  24028. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  24029. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  24030. BIO_free(pbPrivKey);
  24031. return (pPrivateKey);
  24032. }
  24033. TEST(BindServerTest, UpdateCerts) {
  24034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24035. int port = svr.bind_to_any_port("0.0.0.0");
  24036. ASSERT_TRUE(svr.is_valid());
  24037. ASSERT_TRUE(port > 0);
  24038. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24039. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24040. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24041. ASSERT_TRUE(cert != nullptr);
  24042. ASSERT_TRUE(ca_cert != nullptr);
  24043. ASSERT_TRUE(key != nullptr);
  24044. X509_STORE *cert_store = X509_STORE_new();
  24045. X509_STORE_add_cert(cert_store, ca_cert);
  24046. // svr.update_certs(cert, key, cert_store); // deprecated
  24047. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24048. CLIENT_CA_CERT_FILE);
  24049. ASSERT_TRUE(svr.is_valid());
  24050. svr.stop();
  24051. X509_STORE_free(cert_store);
  24052. X509_free(cert);
  24053. X509_free(ca_cert);
  24054. EVP_PKEY_free(key);
  24055. }
  24056. // Test that update_certs() updates client CA list correctly
  24057. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24058. // Start with file-based constructor
  24059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24060. ASSERT_TRUE(svr.is_valid());
  24061. // Initially no client CA list should be set
  24062. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24063. ASSERT_TRUE(ssl_ctx != nullptr);
  24064. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24065. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24066. // Now update with client CA (PEM string)
  24067. std::string cert_pem, key_pem, ca_pem;
  24068. read_file(SERVER_CERT_FILE, cert_pem);
  24069. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24070. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24071. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24072. ASSERT_TRUE(svr.is_valid());
  24073. // Now client CA list should be set
  24074. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24075. ASSERT_TRUE(ca_list_after != nullptr);
  24076. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24077. }
  24078. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24079. // Test that the file-path SSLServer constructor properly sets the client CA
  24080. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24082. ASSERT_TRUE(svr.is_valid());
  24083. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24084. ASSERT_TRUE(ssl_ctx != nullptr);
  24085. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24086. ASSERT_TRUE(ca_list != nullptr);
  24087. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24088. }
  24089. #endif
  24090. // ============================================================================
  24091. // MbedTLS-Specific Tests
  24092. // ============================================================================
  24093. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24094. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24095. using namespace httplib::tls;
  24096. // Track if callback was invoked
  24097. bool callback_invoked = false;
  24098. // The callback receives void* ctx which is actually MbedTlsContext*
  24099. // We can access the mbedtls_ssl_config via the context
  24100. auto setup_callback = [&callback_invoked](void *ctx) {
  24101. callback_invoked = true;
  24102. // Cast to MbedTlsContext* to access the ssl config
  24103. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24104. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24105. // Use static variables to hold certificate data (simplified for test)
  24106. static mbedtls_x509_crt own_cert;
  24107. static mbedtls_pk_context own_key;
  24108. static mbedtls_x509_crt ca_chain;
  24109. static bool initialized = false;
  24110. if (!initialized) {
  24111. mbedtls_x509_crt_init(&own_cert);
  24112. mbedtls_pk_init(&own_key);
  24113. mbedtls_x509_crt_init(&ca_chain);
  24114. // Load server certificate
  24115. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24116. return false;
  24117. }
  24118. // Load server private key.
  24119. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24120. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24121. #if MBEDTLS_VERSION_MAJOR == 3
  24122. ,
  24123. mbedtls_ctr_drbg_random, nullptr
  24124. #endif
  24125. ) != 0) {
  24126. return false;
  24127. }
  24128. // Load CA chain for client verification
  24129. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24130. return false;
  24131. }
  24132. initialized = true;
  24133. }
  24134. // Configure the SSL config
  24135. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24136. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24137. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24138. // Set minimum TLS version using mbedTLS native API
  24139. #if MBEDTLS_VERSION_MAJOR >= 3
  24140. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24141. #else
  24142. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24143. MBEDTLS_SSL_MINOR_VERSION_3);
  24144. #endif
  24145. return true;
  24146. };
  24147. SSLServer svr(setup_callback);
  24148. ASSERT_TRUE(svr.is_valid());
  24149. ASSERT_TRUE(callback_invoked);
  24150. svr.Get("/test", [&](const Request &req, Response &res) {
  24151. res.set_content("test", "text/plain");
  24152. auto cert = req.peer_cert();
  24153. ASSERT_TRUE(static_cast<bool>(cert));
  24154. auto common_name = cert.subject_cn();
  24155. EXPECT_EQ("Common Name", common_name);
  24156. });
  24157. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24158. auto se = detail::scope_exit([&] {
  24159. svr.stop();
  24160. t.join();
  24161. ASSERT_FALSE(svr.is_running());
  24162. });
  24163. svr.wait_until_ready();
  24164. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24165. cli.enable_server_certificate_verification(false);
  24166. cli.set_connection_timeout(30);
  24167. auto res = cli.Get("/test");
  24168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24169. ASSERT_EQ(StatusCode::OK_200, res->status);
  24170. }
  24171. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24172. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24173. // keep-alive SSL session, which reads through that config in
  24174. // mbedtls_ssl_close_notify.
  24175. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24176. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24177. ASSERT_TRUE(svr.is_valid());
  24178. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24179. res.set_content("test", "text/plain");
  24180. });
  24181. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24182. auto se = detail::scope_exit([&] {
  24183. svr.stop();
  24184. t.join();
  24185. ASSERT_FALSE(svr.is_running());
  24186. });
  24187. svr.wait_until_ready();
  24188. {
  24189. SSLClient cli(HOST, PORT);
  24190. cli.enable_server_certificate_verification(false);
  24191. cli.set_keep_alive(true);
  24192. auto res = cli.Get("/test");
  24193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24194. ASSERT_EQ(StatusCode::OK_200, res->status);
  24195. // cli is destructed here with the keep-alive SSL session still open.
  24196. }
  24197. }
  24198. #endif
  24199. // WebSocket Tests
  24200. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24201. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24202. // defining the meaning of these bits has been negotiated.
  24203. auto make_frame = [](uint8_t first_byte) {
  24204. std::string frame;
  24205. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24206. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24207. frame += "Hello";
  24208. return frame;
  24209. };
  24210. // RSV1 set (0x40)
  24211. {
  24212. detail::BufferStream strm;
  24213. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24214. ws::Opcode opcode;
  24215. std::string payload;
  24216. bool fin;
  24217. EXPECT_EQ(
  24218. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24219. ws::impl::FrameRead::ProtocolError);
  24220. }
  24221. // RSV2 set (0x20)
  24222. {
  24223. detail::BufferStream strm;
  24224. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24225. ws::Opcode opcode;
  24226. std::string payload;
  24227. bool fin;
  24228. EXPECT_EQ(
  24229. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24230. ws::impl::FrameRead::ProtocolError);
  24231. }
  24232. // RSV3 set (0x10)
  24233. {
  24234. detail::BufferStream strm;
  24235. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24236. ws::Opcode opcode;
  24237. std::string payload;
  24238. bool fin;
  24239. EXPECT_EQ(
  24240. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24241. ws::impl::FrameRead::ProtocolError);
  24242. }
  24243. // No RSV bits set - should succeed
  24244. {
  24245. detail::BufferStream strm;
  24246. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24247. ws::Opcode opcode;
  24248. std::string payload;
  24249. bool fin;
  24250. EXPECT_EQ(
  24251. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24252. ws::impl::FrameRead::Ok);
  24253. EXPECT_EQ(ws::Opcode::Text, opcode);
  24254. EXPECT_EQ("Hello", payload);
  24255. EXPECT_TRUE(fin);
  24256. }
  24257. }
  24258. TEST(WebSocketTest, ControlFrameValidation) {
  24259. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24260. // payload length <= 125.
  24261. // Ping with FIN=0 - must be rejected
  24262. {
  24263. detail::BufferStream strm;
  24264. std::string frame;
  24265. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24266. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24267. strm.write(frame.data(), frame.size());
  24268. ws::Opcode opcode;
  24269. std::string payload;
  24270. bool fin;
  24271. EXPECT_EQ(
  24272. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24273. ws::impl::FrameRead::ProtocolError);
  24274. }
  24275. // Close with FIN=0 - must be rejected
  24276. {
  24277. detail::BufferStream strm;
  24278. std::string frame;
  24279. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24280. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24281. strm.write(frame.data(), frame.size());
  24282. ws::Opcode opcode;
  24283. std::string payload;
  24284. bool fin;
  24285. EXPECT_EQ(
  24286. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24287. ws::impl::FrameRead::ProtocolError);
  24288. }
  24289. // Ping with payload_len=126 (extended length) - must be rejected
  24290. {
  24291. detail::BufferStream strm;
  24292. std::string frame;
  24293. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24294. frame += static_cast<char>(126); // payload_len=126 (>125)
  24295. frame += static_cast<char>(0x00); // extended length high byte
  24296. frame += static_cast<char>(126); // extended length low byte
  24297. frame += std::string(126, 'x');
  24298. strm.write(frame.data(), frame.size());
  24299. ws::Opcode opcode;
  24300. std::string payload;
  24301. bool fin;
  24302. EXPECT_EQ(
  24303. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24304. ws::impl::FrameRead::ProtocolError);
  24305. }
  24306. // Ping with FIN=1 and payload_len=125 - should succeed
  24307. {
  24308. detail::BufferStream strm;
  24309. std::string frame;
  24310. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24311. frame += static_cast<char>(125); // payload_len=125
  24312. frame += std::string(125, 'x');
  24313. strm.write(frame.data(), frame.size());
  24314. ws::Opcode opcode;
  24315. std::string payload;
  24316. bool fin;
  24317. EXPECT_EQ(
  24318. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24319. ws::impl::FrameRead::Ok);
  24320. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24321. EXPECT_EQ(125u, payload.size());
  24322. EXPECT_TRUE(fin);
  24323. }
  24324. }
  24325. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24326. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24327. // length MUST be 0.
  24328. // MSB set - must be rejected
  24329. {
  24330. detail::BufferStream strm;
  24331. std::string frame;
  24332. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24333. frame += static_cast<char>(127); // 64-bit extended length
  24334. frame += static_cast<char>(0x80); // MSB set (invalid)
  24335. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24336. strm.write(frame.data(), frame.size());
  24337. ws::Opcode opcode;
  24338. std::string payload;
  24339. bool fin;
  24340. EXPECT_EQ(
  24341. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24342. ws::impl::FrameRead::ProtocolError);
  24343. }
  24344. // MSB clear - should pass length parsing (will be rejected by max_len,
  24345. // but that's a different check; use a small length to verify)
  24346. {
  24347. detail::BufferStream strm;
  24348. std::string frame;
  24349. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24350. frame += static_cast<char>(127); // 64-bit extended length
  24351. frame += std::string(7, '\0'); // high bytes = 0
  24352. frame += static_cast<char>(0x03); // length = 3
  24353. frame += "abc";
  24354. strm.write(frame.data(), frame.size());
  24355. ws::Opcode opcode;
  24356. std::string payload;
  24357. bool fin;
  24358. EXPECT_EQ(
  24359. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24360. ws::impl::FrameRead::Ok);
  24361. EXPECT_EQ(ws::Opcode::Text, opcode);
  24362. EXPECT_EQ("abc", payload);
  24363. }
  24364. }
  24365. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24366. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24367. // Valid UTF-8
  24368. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24369. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24370. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24371. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24372. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24373. // Invalid UTF-8
  24374. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24375. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24376. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24377. EXPECT_FALSE(
  24378. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24379. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24380. }
  24381. TEST(WebSocketTest, ConnectAndDisconnect) {
  24382. Server svr;
  24383. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24384. std::string msg;
  24385. while (ws.read(msg)) {}
  24386. });
  24387. auto port = svr.bind_to_any_port(HOST);
  24388. std::thread t([&]() { svr.listen_after_bind(); });
  24389. svr.wait_until_ready();
  24390. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24391. auto res = client.connect();
  24392. ASSERT_TRUE(res);
  24393. EXPECT_EQ(Error::Success, res.error());
  24394. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24395. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24396. EXPECT_TRUE(client.is_open());
  24397. client.close();
  24398. EXPECT_FALSE(client.is_open());
  24399. svr.stop();
  24400. t.join();
  24401. }
  24402. TEST(WebSocketTest, ValidURL) {
  24403. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24404. EXPECT_TRUE(ws1.is_valid());
  24405. ws::WebSocketClient ws2("ws://example.com/path");
  24406. EXPECT_TRUE(ws2.is_valid());
  24407. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24408. EXPECT_TRUE(ws3.is_valid());
  24409. #ifdef CPPHTTPLIB_SSL_ENABLED
  24410. ws::WebSocketClient wss1("wss://example.com/path");
  24411. EXPECT_TRUE(wss1.is_valid());
  24412. ws::WebSocketClient wss2("wss://example.com:443/path");
  24413. EXPECT_TRUE(wss2.is_valid());
  24414. #endif
  24415. }
  24416. TEST(WebSocketTest, InvalidURL) {
  24417. // No scheme
  24418. ws::WebSocketClient ws1("localhost:8080/path");
  24419. EXPECT_FALSE(ws1.is_valid());
  24420. // No path
  24421. ws::WebSocketClient ws2("ws://localhost:8080");
  24422. EXPECT_FALSE(ws2.is_valid());
  24423. // Empty string
  24424. ws::WebSocketClient ws3("");
  24425. EXPECT_FALSE(ws3.is_valid());
  24426. // Missing host
  24427. ws::WebSocketClient ws4("ws://:8080/path");
  24428. EXPECT_FALSE(ws4.is_valid());
  24429. // Port number overflow — should not crash
  24430. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24431. EXPECT_FALSE(ws5.is_valid());
  24432. // Port out of range
  24433. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24434. EXPECT_FALSE(ws6.is_valid());
  24435. }
  24436. TEST(WebSocketTest, UnsupportedScheme) {
  24437. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24438. ws::WebSocketClient ws1("http://localhost:8080/path");
  24439. EXPECT_FALSE(ws1.is_valid());
  24440. ws::WebSocketClient ws2("https://localhost:8080/path");
  24441. EXPECT_FALSE(ws2.is_valid());
  24442. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24443. EXPECT_FALSE(ws3.is_valid());
  24444. #else
  24445. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24446. std::invalid_argument);
  24447. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24448. std::invalid_argument);
  24449. #endif
  24450. }
  24451. TEST(WebSocketTest, ConnectWhenInvalid) {
  24452. ws::WebSocketClient ws("not a valid url");
  24453. EXPECT_FALSE(ws.is_valid());
  24454. auto res = ws.connect();
  24455. EXPECT_FALSE(res);
  24456. EXPECT_EQ(Error::Connection, res.error());
  24457. EXPECT_EQ(-1, res.status());
  24458. }
  24459. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24460. // Grab a port that is free, then close it again so nothing listens there
  24461. Server svr;
  24462. auto port = svr.bind_to_any_port(HOST);
  24463. svr.stop();
  24464. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24465. auto res = client.connect();
  24466. ASSERT_FALSE(res);
  24467. EXPECT_EQ(Error::Connection, res.error());
  24468. EXPECT_EQ(-1, res.status());
  24469. }
  24470. TEST(WebSocketTest, DefaultPort) {
  24471. ws::WebSocketClient ws1("ws://example.com/path");
  24472. EXPECT_TRUE(ws1.is_valid());
  24473. // ws:// defaults to port 80 (verified by successful parse)
  24474. #ifdef CPPHTTPLIB_SSL_ENABLED
  24475. ws::WebSocketClient ws2("wss://example.com/path");
  24476. EXPECT_TRUE(ws2.is_valid());
  24477. // wss:// defaults to port 443 (verified by successful parse)
  24478. #endif
  24479. }
  24480. TEST(WebSocketTest, IPv6LiteralAddress) {
  24481. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24482. EXPECT_TRUE(ws1.is_valid());
  24483. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24484. EXPECT_TRUE(ws2.is_valid());
  24485. }
  24486. TEST(WebSocketTest, ComplexPath) {
  24487. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24488. EXPECT_TRUE(ws1.is_valid());
  24489. ws::WebSocketClient ws2("ws://localhost:8080/");
  24490. EXPECT_TRUE(ws2.is_valid());
  24491. }
  24492. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24493. Server svr;
  24494. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24495. std::string msg;
  24496. while (ws.read(msg)) {}
  24497. });
  24498. auto port = svr.bind_to_any_port(HOST);
  24499. std::thread t([&]() { svr.listen_after_bind(); });
  24500. svr.wait_until_ready();
  24501. auto another_host = "example.com";
  24502. auto wrong_ip = "192.0.2.1";
  24503. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24504. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24505. ASSERT_TRUE(client.connect());
  24506. EXPECT_TRUE(client.is_open());
  24507. client.close();
  24508. svr.stop();
  24509. t.join();
  24510. }
  24511. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24512. Server svr;
  24513. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24514. std::string msg;
  24515. while (ws.read(msg)) {}
  24516. });
  24517. auto port = svr.bind_to_any_port(HOST);
  24518. std::thread t([&]() { svr.listen_after_bind(); });
  24519. svr.wait_until_ready();
  24520. auto wrong_ip = "192.0.2.1";
  24521. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24522. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24523. client.set_connection_timeout(1);
  24524. client.set_read_timeout(1);
  24525. client.set_write_timeout(1);
  24526. EXPECT_FALSE(client.connect());
  24527. EXPECT_FALSE(client.is_open());
  24528. svr.stop();
  24529. t.join();
  24530. }
  24531. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24532. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24533. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24534. // (RFC 6761) is only a map key and the Host header value.
  24535. auto host = "target.invalid";
  24536. Server svr;
  24537. std::string received_host;
  24538. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24539. received_host = req.get_header_value("Host");
  24540. std::string msg;
  24541. while (ws.read(msg)) {}
  24542. });
  24543. auto port = svr.bind_to_any_port(HOST);
  24544. std::thread t([&]() { svr.listen_after_bind(); });
  24545. // ASSERT_* below returns from the test body, which would leave t joinable
  24546. // and make ~thread call std::terminate.
  24547. auto se = detail::scope_exit([&] {
  24548. svr.stop();
  24549. if (t.joinable()) { t.join(); }
  24550. });
  24551. svr.wait_until_ready();
  24552. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24553. std::to_string(port) + "/ws");
  24554. client.set_direct_hostname_addr_map({{host, HOST}});
  24555. ASSERT_TRUE(client.connect());
  24556. EXPECT_TRUE(client.is_open());
  24557. client.close();
  24558. svr.stop();
  24559. t.join();
  24560. // The mapping only redirects the connection; the identity stays host_.
  24561. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24562. }
  24563. class WebSocketIntegrationTest : public ::testing::Test {
  24564. protected:
  24565. void SetUp() override {
  24566. server_ = httplib::detail::make_unique<Server>();
  24567. setup_server();
  24568. start_server();
  24569. }
  24570. void TearDown() override {
  24571. server_->stop();
  24572. if (server_thread_.joinable()) { server_thread_.join(); }
  24573. }
  24574. void setup_server() {
  24575. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24576. std::string msg;
  24577. ws::ReadResult ret;
  24578. while ((ret = ws.read(msg))) {
  24579. if (ret == ws::Binary) {
  24580. ws.send(msg.data(), msg.size());
  24581. } else {
  24582. ws.send(msg);
  24583. }
  24584. }
  24585. });
  24586. server_->WebSocket("/ws-echo-string",
  24587. [](const Request &, ws::WebSocket &ws) {
  24588. std::string msg;
  24589. while (ws.read(msg)) {
  24590. ws.send("echo: " + msg);
  24591. }
  24592. });
  24593. server_->WebSocket(
  24594. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24595. // Echo back request metadata
  24596. ws.send("path:" + req.path);
  24597. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24598. std::string msg;
  24599. while (ws.read(msg)) {}
  24600. });
  24601. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24602. std::string msg;
  24603. ws.read(msg); // wait for a message
  24604. ws.close();
  24605. });
  24606. server_->WebSocket("/ws-close-status",
  24607. [](const Request &, ws::WebSocket &ws) {
  24608. std::string msg;
  24609. ws.read(msg); // wait for a message
  24610. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24611. });
  24612. server_->WebSocket(
  24613. "/ws-subprotocol",
  24614. [](const Request &, ws::WebSocket &ws) {
  24615. std::string msg;
  24616. while (ws.read(msg)) {
  24617. ws.send(msg);
  24618. }
  24619. },
  24620. [](const std::vector<std::string> &protocols) -> std::string {
  24621. for (const auto &p : protocols) {
  24622. if (p == "graphql-ws") { return p; }
  24623. }
  24624. return "";
  24625. });
  24626. server_->WebSocket(
  24627. "/ws-subprotocol-unoffered",
  24628. [](const Request &, ws::WebSocket &ws) {
  24629. std::string msg;
  24630. while (ws.read(msg)) {
  24631. ws.send(msg);
  24632. }
  24633. },
  24634. [](const std::vector<std::string> &) -> std::string {
  24635. return "admin";
  24636. });
  24637. }
  24638. void start_server() {
  24639. port_ = server_->bind_to_any_port(HOST);
  24640. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24641. server_->wait_until_ready();
  24642. }
  24643. std::unique_ptr<Server> server_;
  24644. std::thread server_thread_;
  24645. int port_ = 0;
  24646. };
  24647. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24648. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24649. "/ws-echo");
  24650. ASSERT_TRUE(client.connect());
  24651. ASSERT_TRUE(client.is_open());
  24652. ASSERT_TRUE(client.send("Hello WebSocket"));
  24653. std::string msg;
  24654. EXPECT_EQ(ws::Text, client.read(msg));
  24655. EXPECT_EQ("Hello WebSocket", msg);
  24656. client.close();
  24657. }
  24658. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24660. "/ws-echo");
  24661. ASSERT_TRUE(client.connect());
  24662. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24663. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24664. std::string msg;
  24665. EXPECT_EQ(ws::Binary, client.read(msg));
  24666. EXPECT_EQ(binary_data, msg);
  24667. client.close();
  24668. }
  24669. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24670. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24671. "/ws-echo");
  24672. ASSERT_TRUE(client.connect());
  24673. for (int i = 0; i < 10; i++) {
  24674. auto text = "message " + std::to_string(i);
  24675. ASSERT_TRUE(client.send(text));
  24676. std::string msg;
  24677. ASSERT_TRUE(client.read(msg));
  24678. EXPECT_EQ(text, msg);
  24679. }
  24680. client.close();
  24681. }
  24682. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24683. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24684. "/ws-close");
  24685. ASSERT_TRUE(client.connect());
  24686. // Send a message to trigger the server to close
  24687. ASSERT_TRUE(client.send("trigger close"));
  24688. // The server will close, so read should return false
  24689. std::string msg;
  24690. EXPECT_FALSE(client.read(msg));
  24691. EXPECT_FALSE(client.is_open());
  24692. }
  24693. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24694. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24695. "/ws-echo");
  24696. ASSERT_TRUE(client.connect());
  24697. // 128KB message
  24698. std::string large_data(128 * 1024, 'X');
  24699. ASSERT_TRUE(client.send(large_data));
  24700. std::string msg;
  24701. ASSERT_TRUE(client.read(msg));
  24702. EXPECT_EQ(large_data, msg);
  24703. client.close();
  24704. }
  24705. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24707. "/ws-echo");
  24708. ASSERT_TRUE(client.connect());
  24709. const int num_threads = 4;
  24710. std::vector<std::thread> threads;
  24711. std::atomic<int> send_count{0};
  24712. for (int t = 0; t < num_threads; t++) {
  24713. threads.emplace_back([&client, &send_count, t]() {
  24714. for (int i = 0; i < 5; i++) {
  24715. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24716. if (client.send(text)) { send_count++; }
  24717. }
  24718. });
  24719. }
  24720. for (auto &th : threads) {
  24721. th.join();
  24722. }
  24723. int received = 0;
  24724. std::string msg;
  24725. while (received < send_count.load()) {
  24726. if (!client.read(msg)) { break; }
  24727. received++;
  24728. }
  24729. EXPECT_EQ(send_count.load(), received);
  24730. client.close();
  24731. }
  24732. TEST_F(WebSocketIntegrationTest, ReadString) {
  24733. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24734. "/ws-echo-string");
  24735. ASSERT_TRUE(client.connect());
  24736. ASSERT_TRUE(client.send("hello"));
  24737. std::string msg;
  24738. ASSERT_TRUE(client.read(msg));
  24739. EXPECT_EQ("echo: hello", msg);
  24740. ASSERT_TRUE(client.send("world"));
  24741. ASSERT_TRUE(client.read(msg));
  24742. EXPECT_EQ("echo: world", msg);
  24743. client.close();
  24744. }
  24745. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24746. Headers headers = {{"X-Test-Header", "test-value"}};
  24747. ws::WebSocketClient client(
  24748. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24749. ASSERT_TRUE(client.connect());
  24750. std::string msg;
  24751. ASSERT_TRUE(client.read(msg));
  24752. EXPECT_EQ("path:/ws-request-info", msg);
  24753. ASSERT_TRUE(client.read(msg));
  24754. EXPECT_EQ("header:test-value", msg);
  24755. client.close();
  24756. }
  24757. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24758. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24759. "/ws-echo");
  24760. client.set_read_timeout(1, 0); // 1 second
  24761. ASSERT_TRUE(client.connect());
  24762. // Don't send anything — server echo handler waits for a message, so read()
  24763. // should time out. The connection survives it: nothing was consumed.
  24764. std::string msg;
  24765. EXPECT_EQ(client.read(msg), ws::Timeout);
  24766. EXPECT_TRUE(client.is_open());
  24767. // And it is still usable afterwards.
  24768. EXPECT_TRUE(client.send("after timeout"));
  24769. EXPECT_EQ(client.read(msg), ws::Text);
  24770. EXPECT_EQ(msg, "after timeout");
  24771. }
  24772. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24773. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24774. "/ws-echo");
  24775. client.set_read_timeout(1, 0);
  24776. ASSERT_TRUE(client.connect());
  24777. ASSERT_TRUE(client.send("first"));
  24778. std::string msg;
  24779. ASSERT_EQ(client.read(msg), ws::Text);
  24780. ASSERT_EQ(msg, "first");
  24781. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24782. // not be used with a read timeout: it would reprocess the previous message.
  24783. EXPECT_EQ(client.read(msg), ws::Timeout);
  24784. EXPECT_EQ(msg, "first");
  24785. }
  24786. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24787. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24788. "/ws-echo");
  24789. ASSERT_TRUE(client.connect());
  24790. // Setting it once the connection is open reaches the live stream, not just
  24791. // the seed for the next connect().
  24792. client.set_read_timeout(1, 0);
  24793. std::string msg;
  24794. EXPECT_EQ(client.read(msg), ws::Timeout);
  24795. EXPECT_TRUE(client.is_open());
  24796. }
  24797. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24798. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24799. "/ws-echo");
  24800. client.set_read_timeout(5, 0);
  24801. ASSERT_TRUE(client.connect());
  24802. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24803. // The server should reject it and close the connection.
  24804. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24805. client.send(oversized);
  24806. // The server's read() should have failed due to payload limit,
  24807. // so our read() should return false (connection closed).
  24808. std::string msg;
  24809. EXPECT_FALSE(client.read(msg));
  24810. }
  24811. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24812. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24813. "/ws-echo");
  24814. client.set_read_timeout(10, 0);
  24815. ASSERT_TRUE(client.connect());
  24816. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24817. // This should succeed.
  24818. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24819. ASSERT_TRUE(client.send(at_limit));
  24820. std::string msg;
  24821. ASSERT_TRUE(client.read(msg));
  24822. EXPECT_EQ(at_limit.size(), msg.size());
  24823. client.close();
  24824. }
  24825. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24826. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24827. "/nonexistent");
  24828. auto res = client.connect();
  24829. EXPECT_FALSE(res);
  24830. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24831. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24832. EXPECT_FALSE(client.is_open());
  24833. }
  24834. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24835. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24836. "/ws-echo");
  24837. ASSERT_TRUE(client.connect());
  24838. ASSERT_TRUE(client.send(""));
  24839. std::string msg;
  24840. EXPECT_EQ(ws::Text, client.read(msg));
  24841. EXPECT_EQ("", msg);
  24842. client.close();
  24843. }
  24844. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24845. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24846. "/ws-echo");
  24847. // First connection
  24848. ASSERT_TRUE(client.connect());
  24849. ASSERT_TRUE(client.send("first"));
  24850. std::string msg;
  24851. ASSERT_TRUE(client.read(msg));
  24852. EXPECT_EQ("first", msg);
  24853. client.close();
  24854. EXPECT_FALSE(client.is_open());
  24855. // Reconnect using the same client object
  24856. ASSERT_TRUE(client.connect());
  24857. ASSERT_TRUE(client.is_open());
  24858. ASSERT_TRUE(client.send("second"));
  24859. ASSERT_TRUE(client.read(msg));
  24860. EXPECT_EQ("second", msg);
  24861. client.close();
  24862. }
  24863. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24864. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24865. "/ws-close-status");
  24866. ASSERT_TRUE(client.connect());
  24867. // Trigger the server to close with GoingAway status
  24868. ASSERT_TRUE(client.send("trigger"));
  24869. // read() should return false after receiving the close frame
  24870. std::string msg;
  24871. EXPECT_FALSE(client.read(msg));
  24872. EXPECT_FALSE(client.is_open());
  24873. }
  24874. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24875. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24876. "/ws-echo");
  24877. ASSERT_TRUE(client.connect());
  24878. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24879. EXPECT_FALSE(client.is_open());
  24880. }
  24881. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24882. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24883. ws::WebSocketClient client(
  24884. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24885. ASSERT_TRUE(client.connect());
  24886. // Server should have selected graphql-ws
  24887. EXPECT_EQ("graphql-ws", client.subprotocol());
  24888. client.close();
  24889. }
  24890. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24891. Headers headers;
  24892. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24893. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24894. ws::WebSocketClient client(
  24895. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24896. ASSERT_TRUE(client.connect());
  24897. // The offer on the second field line counts too, so graphql-ws is selected
  24898. EXPECT_EQ("graphql-ws", client.subprotocol());
  24899. client.close();
  24900. }
  24901. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24902. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24903. ws::WebSocketClient client(
  24904. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24905. ASSERT_TRUE(client.connect());
  24906. // Server should not have selected any subprotocol
  24907. EXPECT_TRUE(client.subprotocol().empty());
  24908. client.close();
  24909. }
  24910. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24911. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24912. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24913. "/ws-subprotocol-unoffered",
  24914. headers);
  24915. ASSERT_TRUE(client.connect());
  24916. EXPECT_TRUE(client.subprotocol().empty());
  24917. client.close();
  24918. }
  24919. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24920. // Connect without requesting any subprotocol
  24921. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24922. "/ws-subprotocol");
  24923. ASSERT_TRUE(client.connect());
  24924. EXPECT_TRUE(client.subprotocol().empty());
  24925. client.close();
  24926. }
  24927. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24928. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24929. "/ws-echo");
  24930. client.set_tcp_nodelay(true);
  24931. client.set_connection_timeout(3, 0);
  24932. bool socket_options_called = false;
  24933. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24934. ASSERT_TRUE(client.connect());
  24935. ASSERT_TRUE(client.is_open());
  24936. EXPECT_TRUE(socket_options_called);
  24937. ASSERT_TRUE(client.send("hello"));
  24938. std::string msg;
  24939. auto result = client.read(msg);
  24940. EXPECT_EQ(result, ws::ReadResult::Text);
  24941. EXPECT_EQ(msg, "hello");
  24942. client.close();
  24943. }
  24944. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24945. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24946. "/ws-echo");
  24947. client.set_connection_timeout(std::chrono::seconds(3));
  24948. client.set_write_timeout(std::chrono::seconds(3));
  24949. // A sub-second remainder exercises the seconds/microseconds split.
  24950. client.set_read_timeout(std::chrono::milliseconds(1500));
  24951. ASSERT_TRUE(client.connect());
  24952. auto start = std::chrono::steady_clock::now();
  24953. std::string msg;
  24954. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24955. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24956. std::chrono::steady_clock::now() - start)
  24957. .count();
  24958. // Above 1s so that dropping the microseconds half of the split fails here.
  24959. // Ignoring the setter altogether would not reach this line at all: a client
  24960. // waits forever by default.
  24961. EXPECT_GE(elapsed, 1400);
  24962. EXPECT_LT(elapsed, 30000);
  24963. }
  24964. #ifndef _WIN32
  24965. // A send() that times out after part of the data went out returns the count
  24966. // written so far. Every byte of the frame must still be sent, or the peer reads
  24967. // the next frame's header and payload as the rest of this one.
  24968. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24969. signal(SIGPIPE, SIG_IGN);
  24970. const std::string large(4 * 1024 * 1024, 'A');
  24971. std::atomic<bool> large_sent{false};
  24972. std::atomic<bool> small_sent{false};
  24973. Server svr;
  24974. svr.set_write_timeout(0, 500000);
  24975. svr.set_socket_options([](socket_t sock) {
  24976. int size = 8192;
  24977. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24978. reinterpret_cast<const char *>(&size), sizeof(size));
  24979. });
  24980. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24981. large_sent = ws.send(large.data(), large.size());
  24982. small_sent = ws.send("after");
  24983. std::string msg;
  24984. while (ws.read(msg)) {}
  24985. });
  24986. auto port = svr.bind_to_any_port(HOST);
  24987. std::thread t([&]() { svr.listen_after_bind(); });
  24988. auto se = detail::scope_exit([&] {
  24989. svr.stop();
  24990. t.join();
  24991. });
  24992. svr.wait_until_ready();
  24993. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24994. std::to_string(port) + "/ws");
  24995. client.set_read_timeout(5);
  24996. client.set_socket_options([](socket_t sock) {
  24997. int size = 8192;
  24998. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24999. reinterpret_cast<const char *>(&size), sizeof(size));
  25000. });
  25001. ASSERT_TRUE(client.connect());
  25002. // Outlast the server's write timeout, then drain.
  25003. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  25004. std::string msg;
  25005. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  25006. EXPECT_TRUE(msg == large);
  25007. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  25008. EXPECT_EQ("after", msg);
  25009. EXPECT_TRUE(large_sent);
  25010. EXPECT_TRUE(small_sent);
  25011. client.close();
  25012. }
  25013. // A send() that fails partway leaves a frame on the wire whose header announces
  25014. // more than was sent. Nothing may follow it, or the peer reads the next frames
  25015. // as the rest of it and a later payload's bytes as a frame of their own.
  25016. TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
  25017. signal(SIGPIPE, SIG_IGN);
  25018. const std::string large(4 * 1024 * 1024, 'A');
  25019. std::atomic<bool> large_sent{true};
  25020. std::atomic<bool> open_after_failure{true};
  25021. std::atomic<bool> handler_done{false};
  25022. Server svr;
  25023. svr.set_write_timeout(0, 200000);
  25024. svr.set_socket_options([](socket_t sock) {
  25025. int size = 8192;
  25026. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25027. reinterpret_cast<const char *>(&size), sizeof(size));
  25028. });
  25029. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25030. large_sent = ws.send(large.data(), large.size());
  25031. open_after_failure = ws.is_open();
  25032. handler_done = true;
  25033. });
  25034. auto port = svr.bind_to_any_port(HOST);
  25035. std::thread t([&]() { svr.listen_after_bind(); });
  25036. auto se = detail::scope_exit([&] {
  25037. svr.stop();
  25038. t.join();
  25039. });
  25040. svr.wait_until_ready();
  25041. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25042. std::to_string(port) + "/ws");
  25043. client.set_socket_options([](socket_t sock) {
  25044. int size = 8192;
  25045. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25046. reinterpret_cast<const char *>(&size), sizeof(size));
  25047. });
  25048. ASSERT_TRUE(client.connect());
  25049. // Read nothing, so the server's write times out partway through the frame.
  25050. for (int i = 0; i < 100 && !handler_done; i++) {
  25051. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25052. }
  25053. ASSERT_TRUE(handler_done);
  25054. ASSERT_FALSE(large_sent);
  25055. EXPECT_FALSE(open_after_failure);
  25056. client.close();
  25057. }
  25058. #endif
  25059. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  25060. Server svr;
  25061. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25062. if (!req.has_header("Authorization")) {
  25063. res.status = StatusCode::Unauthorized_401;
  25064. res.set_content("Unauthorized", "text/plain");
  25065. return Server::HandlerResponse::Handled;
  25066. }
  25067. return Server::HandlerResponse::Unhandled;
  25068. });
  25069. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25070. std::string msg;
  25071. while (ws.read(msg)) {
  25072. ws.send(msg);
  25073. }
  25074. });
  25075. auto port = svr.bind_to_any_port("localhost");
  25076. std::thread t([&]() { svr.listen_after_bind(); });
  25077. svr.wait_until_ready();
  25078. // Without Authorization header - should be rejected before upgrade
  25079. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  25080. EXPECT_FALSE(client1.connect());
  25081. // The rejection is framed like any other HTTP response
  25082. {
  25083. Client cli("localhost", port);
  25084. Headers headers = {{"Upgrade", "websocket"},
  25085. {"Connection", "Upgrade"},
  25086. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25087. {"Sec-WebSocket-Version", "13"}};
  25088. auto res = cli.Get("/ws", headers);
  25089. ASSERT_TRUE(res);
  25090. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25091. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25092. EXPECT_EQ("Unauthorized", res->body);
  25093. }
  25094. // With Authorization header - should succeed
  25095. Headers headers = {{"Authorization", "Bearer token123"}};
  25096. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25097. headers);
  25098. ASSERT_TRUE(client2.connect());
  25099. ASSERT_TRUE(client2.send("hello"));
  25100. std::string msg;
  25101. ASSERT_TRUE(client2.read(msg));
  25102. EXPECT_EQ("hello", msg);
  25103. client2.close();
  25104. svr.stop();
  25105. t.join();
  25106. }
  25107. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25108. Server svr;
  25109. std::atomic<int> pre_routing_calls{0};
  25110. std::atomic<int> pre_request_calls{0};
  25111. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25112. pre_routing_calls++;
  25113. if (req.path == "/handled") {
  25114. res.set_content("handled", "text/plain");
  25115. return Server::HandlerResponse::Handled;
  25116. }
  25117. return Server::HandlerResponse::Unhandled;
  25118. });
  25119. svr.set_pre_request_handler([&](const Request &, Response &) {
  25120. pre_request_calls++;
  25121. return Server::HandlerResponse::Unhandled;
  25122. });
  25123. svr.Get("/http", [](const Request &, Response &res) {
  25124. res.set_content("http", "text/plain");
  25125. });
  25126. svr.WebSocket("/ws",
  25127. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25128. auto port = svr.bind_to_any_port("localhost");
  25129. std::thread t([&]() { svr.listen_after_bind(); });
  25130. auto se = detail::scope_exit([&] {
  25131. svr.stop();
  25132. t.join();
  25133. });
  25134. svr.wait_until_ready();
  25135. Headers upgrade = {{"Upgrade", "websocket"},
  25136. {"Connection", "Upgrade"},
  25137. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25138. {"Sec-WebSocket-Version", "13"}};
  25139. auto get = [&](const char *path) {
  25140. pre_routing_calls = 0;
  25141. return Client("localhost", port).Get(path, upgrade);
  25142. };
  25143. // No WebSocket route, but an HTTP one
  25144. auto res = get("/http");
  25145. ASSERT_TRUE(res);
  25146. EXPECT_EQ(StatusCode::OK_200, res->status);
  25147. EXPECT_EQ("http", res->body);
  25148. EXPECT_EQ(1, pre_routing_calls);
  25149. EXPECT_EQ(1, pre_request_calls);
  25150. // No route at all
  25151. res = get("/none");
  25152. ASSERT_TRUE(res);
  25153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25154. EXPECT_EQ(1, pre_routing_calls);
  25155. // Answered by the pre-routing handler
  25156. res = get("/handled");
  25157. ASSERT_TRUE(res);
  25158. EXPECT_EQ(StatusCode::OK_200, res->status);
  25159. EXPECT_EQ("handled", res->body);
  25160. EXPECT_EQ(1, pre_routing_calls);
  25161. // A WebSocket route
  25162. pre_routing_calls = 0;
  25163. pre_request_calls = 0;
  25164. {
  25165. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25166. "/ws");
  25167. ASSERT_TRUE(client.connect());
  25168. std::string msg;
  25169. ASSERT_TRUE(client.read(msg));
  25170. EXPECT_EQ("ws", msg);
  25171. client.close();
  25172. }
  25173. EXPECT_EQ(1, pre_routing_calls);
  25174. EXPECT_EQ(1, pre_request_calls);
  25175. }
  25176. // An upgrade request answered by a hook leaves its body unread, so that body
  25177. // must not be served as the next request on the connection.
  25178. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25179. Server svr;
  25180. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25181. if (req.path == "/pre-routing") {
  25182. res.set_content("pre-routing", "text/plain");
  25183. return Server::HandlerResponse::Handled;
  25184. }
  25185. return Server::HandlerResponse::Unhandled;
  25186. });
  25187. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25188. if (req.matched_route == "/pre-request") {
  25189. res.set_content("pre-request", "text/plain");
  25190. return Server::HandlerResponse::Handled;
  25191. }
  25192. return Server::HandlerResponse::Unhandled;
  25193. });
  25194. svr.Get("/smuggled", [](const Request &, Response &res) {
  25195. res.set_content("smuggled", "text/plain");
  25196. });
  25197. svr.WebSocket("/pre-request",
  25198. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25199. auto port = svr.bind_to_any_port(HOST);
  25200. std::thread t([&]() { svr.listen_after_bind(); });
  25201. auto se = detail::scope_exit([&] {
  25202. svr.stop();
  25203. t.join();
  25204. });
  25205. svr.wait_until_ready();
  25206. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25207. for (auto path : {"/pre-routing", "/pre-request"}) {
  25208. std::string req = std::string("GET ") + path +
  25209. " HTTP/1.1\r\n"
  25210. "Host: localhost\r\n"
  25211. "Upgrade: websocket\r\n"
  25212. "Connection: Upgrade\r\n"
  25213. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25214. "Sec-WebSocket-Version: 13\r\n"
  25215. "Content-Length: " +
  25216. std::to_string(body.size()) + "\r\n\r\n" + body;
  25217. std::string res;
  25218. ASSERT_TRUE(send_request(5, req, &res, port));
  25219. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25220. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25221. // Only one response, and the body was not served as a request
  25222. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25223. }
  25224. }
  25225. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25226. Server svr;
  25227. std::atomic<int> pre_request_calls{0};
  25228. std::atomic<bool> route_matched{false};
  25229. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25230. pre_request_calls++;
  25231. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25232. if (req.get_header_value("Authorization") != "Bearer token123") {
  25233. res.status = StatusCode::Unauthorized_401;
  25234. res.set_content("Unauthorized", "text/plain");
  25235. return Server::HandlerResponse::Handled;
  25236. }
  25237. return Server::HandlerResponse::Unhandled;
  25238. });
  25239. std::atomic<bool> handler_called{false};
  25240. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25241. handler_called = true;
  25242. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25243. });
  25244. auto port = svr.bind_to_any_port("localhost");
  25245. std::thread t([&]() { svr.listen_after_bind(); });
  25246. svr.wait_until_ready();
  25247. // Without Authorization header - should be rejected before upgrade
  25248. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25249. "/ws/1");
  25250. EXPECT_FALSE(client1.connect());
  25251. EXPECT_FALSE(handler_called);
  25252. EXPECT_EQ(1, pre_request_calls);
  25253. EXPECT_TRUE(route_matched);
  25254. // The rejection is an ordinary HTTP response, not a protocol switch
  25255. {
  25256. Client cli("localhost", port);
  25257. Headers headers = {{"Upgrade", "websocket"},
  25258. {"Connection", "Upgrade"},
  25259. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25260. {"Sec-WebSocket-Version", "13"}};
  25261. auto res = cli.Get("/ws/1", headers);
  25262. ASSERT_TRUE(res);
  25263. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25264. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25265. EXPECT_EQ("Unauthorized", res->body);
  25266. }
  25267. EXPECT_FALSE(handler_called);
  25268. // With Authorization header - should succeed
  25269. Headers headers = {{"Authorization", "Bearer token123"}};
  25270. ws::WebSocketClient client2(
  25271. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25272. ASSERT_TRUE(client2.connect());
  25273. std::string msg;
  25274. ASSERT_TRUE(client2.read(msg));
  25275. EXPECT_EQ("/ws/:id 2", msg);
  25276. EXPECT_TRUE(handler_called);
  25277. client2.close();
  25278. svr.stop();
  25279. t.join();
  25280. }
  25281. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25282. static Headers websocket_upgrade_headers() {
  25283. return {{"Upgrade", "websocket"},
  25284. {"Connection", "Upgrade"},
  25285. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25286. {"Sec-WebSocket-Version", "13"},
  25287. {"Sec-WebSocket-Protocol", "chat"}};
  25288. }
  25289. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25290. Server svr;
  25291. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25292. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25293. return Server::HandlerResponse::Unhandled;
  25294. });
  25295. svr.set_pre_request_handler([](const Request &req, Response &) {
  25296. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25297. return Server::HandlerResponse::Unhandled;
  25298. });
  25299. svr.set_exception_handler(
  25300. [](const Request &, Response &res, std::exception_ptr ep) {
  25301. try {
  25302. std::rethrow_exception(ep);
  25303. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25304. });
  25305. auto handler = [](const Request &, ws::WebSocket &) {};
  25306. svr.WebSocket("/pre-routing", handler);
  25307. svr.WebSocket("/pre-request", handler);
  25308. svr.WebSocket("/sub-protocol", handler,
  25309. [](const std::vector<std::string> &) -> std::string {
  25310. throw std::runtime_error("/sub-protocol");
  25311. });
  25312. auto port = svr.bind_to_any_port(HOST);
  25313. ASSERT_GT(port, 0);
  25314. thread t = thread([&] { svr.listen_after_bind(); });
  25315. auto se = detail::scope_exit([&] {
  25316. svr.stop();
  25317. t.join();
  25318. ASSERT_FALSE(svr.is_running());
  25319. });
  25320. svr.wait_until_ready();
  25321. Client cli(HOST, port);
  25322. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25323. auto res = cli.Get(path, websocket_upgrade_headers());
  25324. if (!res) {
  25325. ADD_FAILURE() << path << ": " << to_string(res.error());
  25326. continue;
  25327. }
  25328. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25329. EXPECT_EQ(path, res->body);
  25330. }
  25331. }
  25332. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25333. Server svr;
  25334. svr.set_pre_routing_handler(
  25335. [](const Request &, Response &) -> Server::HandlerResponse {
  25336. throw std::runtime_error("pre-routing");
  25337. });
  25338. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25339. auto port = svr.bind_to_any_port(HOST);
  25340. ASSERT_GT(port, 0);
  25341. thread t = thread([&] { svr.listen_after_bind(); });
  25342. auto se = detail::scope_exit([&] {
  25343. svr.stop();
  25344. t.join();
  25345. ASSERT_FALSE(svr.is_running());
  25346. });
  25347. svr.wait_until_ready();
  25348. Client cli(HOST, port);
  25349. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25350. ASSERT_TRUE(res) << to_string(res.error());
  25351. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25352. }
  25353. #endif
  25354. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25355. Server svr;
  25356. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25357. // A read timeout is how a handler gets control back. Without it, a handler
  25358. // parked in read() can never write on the connection it is reading.
  25359. ws.set_read_timeout(std::chrono::milliseconds(100));
  25360. std::string msg;
  25361. while (ws.is_open()) {
  25362. auto r = ws.read(msg);
  25363. if (r == httplib::ws::Timeout) {
  25364. ws.send("tick");
  25365. continue;
  25366. }
  25367. if (r == httplib::ws::Fail) { break; }
  25368. ws.send(msg);
  25369. }
  25370. });
  25371. auto port = svr.bind_to_any_port("localhost");
  25372. std::thread t([&]() { svr.listen_after_bind(); });
  25373. svr.wait_until_ready();
  25374. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25375. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25376. ASSERT_TRUE(client.connect());
  25377. // The client sends nothing, so anything it receives came out of the
  25378. // handler's timeout path.
  25379. std::string msg;
  25380. ASSERT_EQ(client.read(msg), ws::Text);
  25381. EXPECT_EQ("tick", msg);
  25382. client.close();
  25383. svr.stop();
  25384. t.join();
  25385. }
  25386. // Stream::read may return fewer bytes than asked for. This is that contract at
  25387. // its worst -- one byte per call -- which is what a frame header straddling a
  25388. // read buffer's boundary looks like to the frame parser.
  25389. class WsByteAtATimeStream : public Stream {
  25390. public:
  25391. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25392. bool is_readable() const override { return true; }
  25393. bool wait_readable() const override { return true; }
  25394. bool wait_writable() const override { return true; }
  25395. ssize_t read(char *ptr, size_t size) override {
  25396. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25397. *ptr = data_[pos_++];
  25398. return 1;
  25399. }
  25400. ssize_t write(const char *, size_t size) override {
  25401. return static_cast<ssize_t>(size);
  25402. }
  25403. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25404. ip = "127.0.0.1";
  25405. port = 0;
  25406. }
  25407. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25408. ip = "127.0.0.1";
  25409. port = 0;
  25410. }
  25411. socket_t socket() const override { return INVALID_SOCKET; }
  25412. time_t duration() const override { return 0; }
  25413. private:
  25414. std::string data_;
  25415. size_t pos_ = 0;
  25416. };
  25417. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25418. // The payload uses the 16-bit extended length, so the header, the length
  25419. // and the mask key are all multi-byte fields here. Each used to be read
  25420. // with a single read() call, which fails as soon as one is split. The
  25421. // payload is also a little over one read chunk, so it is read in two.
  25422. std::string body;
  25423. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25424. body += static_cast<char>(i % 251);
  25425. }
  25426. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25427. std::string frame;
  25428. frame += static_cast<char>(0x81); // FIN + Text
  25429. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25430. frame += static_cast<char>(body.size() >> 8);
  25431. frame += static_cast<char>(body.size() & 0xff);
  25432. for (size_t i = 0; i < 4; i++) {
  25433. frame += static_cast<char>(mask[i]);
  25434. }
  25435. for (size_t i = 0; i < body.size(); i++) {
  25436. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25437. }
  25438. WsByteAtATimeStream strm(frame);
  25439. ws::Opcode opcode;
  25440. std::string payload;
  25441. bool fin = false;
  25442. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25443. /*expect_masked=*/true, body.size()),
  25444. ws::impl::FrameRead::Ok);
  25445. EXPECT_TRUE(fin);
  25446. EXPECT_EQ(opcode, ws::Opcode::Text);
  25447. EXPECT_EQ(payload, body);
  25448. }
  25449. // Keeps what is written, counting the writes, and reads it back.
  25450. class WsWriteCountingStream : public Stream {
  25451. public:
  25452. bool is_readable() const override { return true; }
  25453. bool wait_readable() const override { return true; }
  25454. bool wait_writable() const override { return true; }
  25455. ssize_t read(char *ptr, size_t size) override {
  25456. auto n = (std::min)(size, data_.size() - pos_);
  25457. if (n == 0) { return 0; }
  25458. memcpy(ptr, data_.data() + pos_, n);
  25459. pos_ += n;
  25460. return static_cast<ssize_t>(n);
  25461. }
  25462. ssize_t write(const char *ptr, size_t size) override {
  25463. writes++;
  25464. data_.append(ptr, size);
  25465. return static_cast<ssize_t>(size);
  25466. }
  25467. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25468. ip = "127.0.0.1";
  25469. port = 0;
  25470. }
  25471. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25472. ip = "127.0.0.1";
  25473. port = 0;
  25474. }
  25475. socket_t socket() const override { return INVALID_SOCKET; }
  25476. time_t duration() const override { return 0; }
  25477. int writes = 0;
  25478. private:
  25479. std::string data_;
  25480. size_t pos_ = 0;
  25481. };
  25482. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25483. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25484. // masked and not, reads back as written; a payload over one chunk follows
  25485. // its first in more writes.
  25486. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25487. for (auto mask : {false, true}) {
  25488. std::string body(len, '\0');
  25489. for (size_t i = 0; i < len; i++) {
  25490. body[i] = static_cast<char>(i % 251);
  25491. }
  25492. WsWriteCountingStream strm;
  25493. ASSERT_TRUE(detail::write_websocket_frame(
  25494. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25495. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25496. ws::Opcode opcode;
  25497. std::string payload;
  25498. bool fin = false;
  25499. ASSERT_EQ(
  25500. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25501. ws::impl::FrameRead::Ok)
  25502. << len << " " << mask;
  25503. EXPECT_TRUE(fin);
  25504. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25505. EXPECT_EQ(body, payload) << len << " " << mask;
  25506. }
  25507. }
  25508. }
  25509. // Hands out its pieces one read at a time, timing out between each two.
  25510. class WsTimeoutBetweenPiecesStream : public Stream {
  25511. public:
  25512. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25513. : pieces_(std::move(pieces)) {}
  25514. bool is_readable() const override { return true; }
  25515. bool wait_readable() const override { return true; }
  25516. bool wait_writable() const override { return true; }
  25517. ssize_t read(char *ptr, size_t size) override {
  25518. if (time_out_) {
  25519. time_out_ = false;
  25520. error_ = Error::Timeout;
  25521. return -1;
  25522. }
  25523. if (i_ >= pieces_.size()) {
  25524. error_ = Error::ConnectionClosed;
  25525. return 0;
  25526. }
  25527. auto &piece = pieces_[i_];
  25528. auto n = (std::min)(size, piece.size() - at_);
  25529. memcpy(ptr, piece.data() + at_, n);
  25530. at_ += n;
  25531. if (at_ == piece.size()) {
  25532. i_++;
  25533. at_ = 0;
  25534. time_out_ = true;
  25535. }
  25536. return static_cast<ssize_t>(n);
  25537. }
  25538. ssize_t write(const char *, size_t size) override {
  25539. return static_cast<ssize_t>(size);
  25540. }
  25541. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25542. ip = "127.0.0.1";
  25543. port = 0;
  25544. }
  25545. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25546. ip = "127.0.0.1";
  25547. port = 0;
  25548. }
  25549. socket_t socket() const override { return INVALID_SOCKET; }
  25550. time_t duration() const override { return 0; }
  25551. private:
  25552. std::vector<std::string> pieces_;
  25553. size_t i_ = 0;
  25554. size_t at_ = 0;
  25555. bool time_out_ = false;
  25556. };
  25557. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25558. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25559. std::string frame = "\x81\x85";
  25560. frame.append(4, '\0');
  25561. frame += "Hello";
  25562. // The header's first byte, then its second with half the mask key, then
  25563. // the rest
  25564. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25565. frame.substr(4)};
  25566. WsTimeoutBetweenPiecesStream strm(pieces);
  25567. ws::impl::FrameReader reader;
  25568. ws::Opcode opcode;
  25569. std::string payload;
  25570. bool fin = false;
  25571. for (int i = 0; i < 2; i++) {
  25572. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25573. reader.read(strm, opcode, payload, fin, true, 0));
  25574. EXPECT_TRUE(reader.begun());
  25575. }
  25576. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25577. reader.read(strm, opcode, payload, fin, true, 0));
  25578. EXPECT_FALSE(reader.begun());
  25579. EXPECT_TRUE(fin);
  25580. EXPECT_EQ(ws::Opcode::Text, opcode);
  25581. EXPECT_EQ("Hello", payload);
  25582. // Read in one go, the frame cannot be gone on with after a timeout
  25583. WsTimeoutBetweenPiecesStream again(pieces);
  25584. EXPECT_EQ(
  25585. ws::impl::FrameRead::Fail,
  25586. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25587. }
  25588. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25589. std::string body(2000, 'x');
  25590. std::string frame;
  25591. frame += static_cast<char>(0x82); // FIN + Binary
  25592. frame += static_cast<char>(126); // 16-bit length follows
  25593. frame += static_cast<char>(body.size() >> 8);
  25594. frame += static_cast<char>(body.size() & 0xff);
  25595. frame += body;
  25596. detail::BufferStream strm;
  25597. strm.write(frame.data(), frame.size());
  25598. ws::Opcode opcode;
  25599. std::string payload;
  25600. bool fin;
  25601. EXPECT_EQ(
  25602. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25603. ws::impl::FrameRead::Ok);
  25604. EXPECT_EQ(body, payload);
  25605. }
  25606. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25607. // The header announces the largest payload allowed, and only 3 bytes of it
  25608. // ever arrive.
  25609. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25610. std::string frame;
  25611. frame += static_cast<char>(0x82); // FIN + Binary
  25612. frame += static_cast<char>(127); // 64-bit length follows
  25613. for (int shift = 56; shift >= 0; shift -= 8) {
  25614. frame += static_cast<char>((len >> shift) & 0xff);
  25615. }
  25616. frame += "abc";
  25617. detail::BufferStream strm;
  25618. strm.write(frame.data(), frame.size());
  25619. ws::Opcode opcode;
  25620. std::string payload;
  25621. bool fin;
  25622. EXPECT_EQ(
  25623. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25624. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25625. ws::impl::FrameRead::Fail);
  25626. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25627. }
  25628. TEST(WebSocketTest, QueryStringInHandshake) {
  25629. Server svr;
  25630. std::mutex mtx;
  25631. std::string received_target;
  25632. std::string received_token;
  25633. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25634. {
  25635. std::lock_guard<std::mutex> lock(mtx);
  25636. received_target = req.target;
  25637. if (req.has_param("token")) {
  25638. received_token = req.get_param_value("token");
  25639. }
  25640. }
  25641. std::string msg;
  25642. while (ws.read(msg)) {
  25643. ws.send(msg);
  25644. }
  25645. });
  25646. auto port = svr.bind_to_any_port("localhost");
  25647. std::thread t([&]() { svr.listen_after_bind(); });
  25648. svr.wait_until_ready();
  25649. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25650. "/ws?token=ABC&session=123");
  25651. ASSERT_TRUE(client.connect());
  25652. // Round-trip ensures the handler has run and captured the request.
  25653. ASSERT_TRUE(client.send("hello"));
  25654. std::string msg;
  25655. ASSERT_TRUE(client.read(msg));
  25656. EXPECT_EQ("hello", msg);
  25657. client.close();
  25658. {
  25659. std::lock_guard<std::mutex> lock(mtx);
  25660. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25661. EXPECT_EQ("ABC", received_token);
  25662. }
  25663. svr.stop();
  25664. t.join();
  25665. }
  25666. // Run a handshake against a throwaway server and hand the request the server
  25667. // received back to the caller, so tests can assert on the headers the client
  25668. // actually put on the wire.
  25669. static void capture_websocket_handshake_request(
  25670. const Headers &client_headers,
  25671. std::function<void(const Request &, int port)> verify) {
  25672. Server svr;
  25673. std::mutex mtx;
  25674. Request received;
  25675. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25676. {
  25677. std::lock_guard<std::mutex> lock(mtx);
  25678. received = req;
  25679. }
  25680. std::string msg;
  25681. while (ws.read(msg)) {
  25682. ws.send(msg);
  25683. }
  25684. });
  25685. auto port = svr.bind_to_any_port("localhost");
  25686. std::thread t([&]() { svr.listen_after_bind(); });
  25687. auto se = detail::scope_exit([&] {
  25688. svr.stop();
  25689. t.join();
  25690. });
  25691. svr.wait_until_ready();
  25692. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25693. client_headers);
  25694. ASSERT_TRUE(client.connect());
  25695. ASSERT_TRUE(client.send("hello"));
  25696. std::string msg;
  25697. ASSERT_TRUE(client.read(msg));
  25698. client.close();
  25699. {
  25700. std::lock_guard<std::mutex> lock(mtx);
  25701. verify(received, port);
  25702. }
  25703. }
  25704. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25705. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25706. // Non-default port must be present in the Host header. Default ports
  25707. // (80/443) are omitted; that logic is covered by
  25708. // MakeHostAndPortStringTest.
  25709. EXPECT_EQ("localhost:" + std::to_string(port),
  25710. req.get_header_value("Host"));
  25711. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25712. req.get_header_value("User-Agent"));
  25713. EXPECT_FALSE(req.has_header("Accept"));
  25714. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25715. EXPECT_FALSE(req.has_header("Content-Length"));
  25716. });
  25717. }
  25718. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25719. capture_websocket_handshake_request(
  25720. {{"Host", "example.com"},
  25721. {"User-Agent", "custom-agent"},
  25722. {"X-Custom", "value"}},
  25723. [](const Request &req, int) {
  25724. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25725. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25726. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25727. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25728. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25729. });
  25730. }
  25731. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25732. capture_websocket_handshake_request(
  25733. {{"Upgrade", "bogus"},
  25734. {"Connection", "close"},
  25735. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25736. {"Sec-WebSocket-Version", "8"}},
  25737. [](const Request &req, int) {
  25738. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25739. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25740. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25741. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25742. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25743. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25744. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25745. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25746. req.get_header_value("Sec-WebSocket-Key"));
  25747. });
  25748. }
  25749. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25750. // A header the client refuses to send must abort the handshake before any
  25751. // part of it reaches the wire; a lone request line would otherwise sit in
  25752. // the peer's buffer as a truncated request.
  25753. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25754. ASSERT_NE(INVALID_SOCKET, srv);
  25755. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25756. sockaddr_in addr{};
  25757. addr.sin_family = AF_INET;
  25758. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25759. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25760. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25761. ASSERT_EQ(0, ::listen(srv, 1));
  25762. sockaddr_in bound{};
  25763. socklen_t bound_len = sizeof(bound);
  25764. ASSERT_EQ(
  25765. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25766. auto port = ntohs(bound.sin_port);
  25767. ssize_t received = -1;
  25768. std::thread t([&] {
  25769. // Bound every blocking call so a regression fails the test with a bad
  25770. // value instead of hanging the suite.
  25771. fd_set rfds;
  25772. FD_ZERO(&rfds);
  25773. FD_SET(srv, &rfds);
  25774. timeval tv{5, 0};
  25775. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25776. 0) {
  25777. return;
  25778. }
  25779. sockaddr_in cli_addr{};
  25780. socklen_t cli_len = sizeof(cli_addr);
  25781. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25782. if (cli == INVALID_SOCKET) { return; }
  25783. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25784. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25785. char buf[4096];
  25786. received = ::recv(cli, buf, sizeof(buf), 0);
  25787. });
  25788. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25789. // connect() has already shut the socket down by the time it returns false,
  25790. // so the peer sees EOF without waiting for the client to be destroyed.
  25791. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25792. {{"X-Bad", "a\r\nInjected: 1"}});
  25793. EXPECT_FALSE(client.connect());
  25794. t.join();
  25795. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25796. EXPECT_EQ(0, received);
  25797. }
  25798. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25799. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25800. // contains "upgrade" as a substring is a different token and must not
  25801. // start a WebSocket handshake.
  25802. auto make_request = [](const std::vector<std::string> &connection_values) {
  25803. Request req;
  25804. req.method = "GET";
  25805. req.headers.emplace("Upgrade", "websocket");
  25806. for (const auto &value : connection_values) {
  25807. req.headers.emplace("Connection", value);
  25808. }
  25809. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25810. req.headers.emplace("Sec-WebSocket-Version", "13");
  25811. return req;
  25812. };
  25813. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25814. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25815. EXPECT_TRUE(
  25816. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25817. EXPECT_TRUE(
  25818. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25819. EXPECT_TRUE(
  25820. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25821. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25822. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25823. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25824. EXPECT_FALSE(
  25825. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25826. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25827. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25828. }
  25829. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25830. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25831. // asks recipients to match each protocol-name case-insensitively, and RFC
  25832. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25833. // client naming websocket alongside another protocol, or on a second field
  25834. // line, is offering websocket; a value that merely contains "websocket" as a
  25835. // substring is a different protocol name and is not.
  25836. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25837. Request req;
  25838. req.method = "GET";
  25839. for (const auto &value : upgrade_values) {
  25840. req.headers.emplace("Upgrade", value);
  25841. }
  25842. req.headers.emplace("Connection", "Upgrade");
  25843. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25844. req.headers.emplace("Sec-WebSocket-Version", "13");
  25845. return req;
  25846. };
  25847. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25848. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25849. EXPECT_TRUE(
  25850. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25851. EXPECT_TRUE(
  25852. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25853. EXPECT_TRUE(
  25854. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25855. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25856. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25857. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25858. EXPECT_FALSE(
  25859. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25860. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25861. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25862. }
  25863. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25864. Server svr;
  25865. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25866. auto port = svr.bind_to_any_port("localhost");
  25867. std::thread t([&]() { svr.listen_after_bind(); });
  25868. auto se = detail::scope_exit([&] {
  25869. svr.stop();
  25870. t.join();
  25871. });
  25872. svr.wait_until_ready();
  25873. Headers headers = {{"Upgrade", "websocket"},
  25874. {"Connection", "notupgrade"},
  25875. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25876. {"Sec-WebSocket-Version", "13"}};
  25877. Client cli("localhost", port);
  25878. auto res = cli.Get("/ws", headers);
  25879. // The route exists only as a WebSocket route, so a request that fails the
  25880. // handshake check falls through to ordinary routing.
  25881. ASSERT_TRUE(res);
  25882. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25883. }
  25884. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25885. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25886. // Connection value is the only thing left for the client to reject.
  25887. Server svr;
  25888. svr.Get("/ws", [](const Request &req, Response &res) {
  25889. res.status = StatusCode::SwitchingProtocol_101;
  25890. res.set_header("Upgrade", "websocket");
  25891. res.set_header("Connection", "notupgrade");
  25892. res.set_header("Sec-WebSocket-Accept",
  25893. detail::websocket_accept_key(
  25894. req.get_header_value("Sec-WebSocket-Key")));
  25895. });
  25896. auto port = svr.bind_to_any_port("localhost");
  25897. std::thread t([&]() { svr.listen_after_bind(); });
  25898. auto se = detail::scope_exit([&] {
  25899. svr.stop();
  25900. t.join();
  25901. });
  25902. svr.wait_until_ready();
  25903. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25904. auto res = client.connect();
  25905. EXPECT_FALSE(res);
  25906. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25907. EXPECT_FALSE(client.is_open());
  25908. }
  25909. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25910. Server svr;
  25911. svr.Get("/ws", [](const Request &req, Response &res) {
  25912. res.status = StatusCode::SwitchingProtocol_101;
  25913. res.set_header("Upgrade", "websocket");
  25914. res.set_header("Connection", "Upgrade");
  25915. res.set_header("Sec-WebSocket-Accept",
  25916. detail::websocket_accept_key(
  25917. req.get_header_value("Sec-WebSocket-Key")));
  25918. res.set_header("Sec-WebSocket-Protocol", "admin");
  25919. });
  25920. auto port = svr.bind_to_any_port("localhost");
  25921. std::thread t([&]() { svr.listen_after_bind(); });
  25922. auto se = detail::scope_exit([&] {
  25923. svr.stop();
  25924. t.join();
  25925. });
  25926. svr.wait_until_ready();
  25927. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25928. // Server selects a subprotocol the client never offered
  25929. {
  25930. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25931. ws::WebSocketClient client(url, headers);
  25932. auto res = client.connect();
  25933. EXPECT_FALSE(res);
  25934. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25935. EXPECT_FALSE(client.is_open());
  25936. EXPECT_TRUE(client.subprotocol().empty());
  25937. }
  25938. // Client offered none but the server named one anyway
  25939. {
  25940. ws::WebSocketClient client(url);
  25941. auto res = client.connect();
  25942. EXPECT_FALSE(res);
  25943. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25944. EXPECT_FALSE(client.is_open());
  25945. EXPECT_TRUE(client.subprotocol().empty());
  25946. }
  25947. }
  25948. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25949. // The socket path doubles as the URL host, so it must not contain '/'.
  25950. const char *shard = getenv("GTEST_SHARD_INDEX");
  25951. const std::string sock_path =
  25952. shard ? std::string("httplib-ws-") + shard + ".sock"
  25953. : std::string("httplib-ws.sock");
  25954. std::remove(sock_path.c_str());
  25955. Server svr;
  25956. std::mutex mtx;
  25957. std::string received_host;
  25958. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25959. {
  25960. std::lock_guard<std::mutex> lock(mtx);
  25961. received_host = req.get_header_value("Host");
  25962. }
  25963. std::string msg;
  25964. while (ws.read(msg)) {
  25965. ws.send(msg);
  25966. }
  25967. });
  25968. svr.set_address_family(AF_UNIX);
  25969. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25970. auto se = detail::scope_exit([&] {
  25971. svr.stop();
  25972. t.join();
  25973. std::remove(sock_path.c_str());
  25974. });
  25975. svr.wait_until_ready();
  25976. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25977. client.set_address_family(AF_UNIX);
  25978. ASSERT_TRUE(client.connect());
  25979. ASSERT_TRUE(client.send("hello"));
  25980. std::string msg;
  25981. ASSERT_TRUE(client.read(msg));
  25982. client.close();
  25983. {
  25984. std::lock_guard<std::mutex> lock(mtx);
  25985. // There is no host:port for a Unix socket, so the same "localhost"
  25986. // placeholder the HTTP client uses is expected.
  25987. EXPECT_EQ("localhost", received_host);
  25988. }
  25989. }
  25990. // Two threads must never parse WebSocket frames from the same stream.
  25991. // close() used to read the peer's Close reply with its own frame read, so it
  25992. // raced a reader thread that was in the middle of a payload: the payload loop
  25993. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25994. // so bytes taken by close() were replaced with bytes from further along the
  25995. // stream. The message kept its length and silently changed content.
  25996. //
  25997. // The raw peer below sends a frame header plus part of the payload, waits for
  25998. // the handler to call close(), and only then sends the rest. Whichever thread
  25999. // would win the race for those bytes, the message must arrive intact, because
  26000. // close() must not touch the stream while read() owns it.
  26001. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  26002. #ifndef _WIN32
  26003. signal(SIGPIPE, SIG_IGN);
  26004. #endif
  26005. const size_t payload_len = 120; // fits the 7-bit length field
  26006. const size_t prefix_len = 8;
  26007. const int attempts = 8;
  26008. std::string expected(payload_len, '\0');
  26009. for (size_t i = 0; i < payload_len; i++) {
  26010. expected[i] = static_cast<char>('a' + i % 26);
  26011. }
  26012. std::atomic<bool> peer_stalled{false};
  26013. std::atomic<bool> handler_done{false};
  26014. std::mutex received_mutex;
  26015. std::vector<std::string> received;
  26016. // Bound every wait, so a regression fails the test instead of hanging the
  26017. // suite.
  26018. auto wait_for = [](const std::atomic<bool> &flag) {
  26019. for (int i = 0; i < 500 && !flag; i++) {
  26020. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26021. }
  26022. };
  26023. Server svr;
  26024. svr.set_websocket_ping_interval(0);
  26025. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26026. std::thread reader([&]() {
  26027. std::string msg;
  26028. while (ws.read(msg)) {
  26029. std::lock_guard<std::mutex> guard(received_mutex);
  26030. received.push_back(msg);
  26031. }
  26032. });
  26033. // Wait until the peer stalls mid-payload, so the reader thread is parked
  26034. // inside a frame when close() runs.
  26035. wait_for(peer_stalled);
  26036. ws.close();
  26037. reader.join();
  26038. handler_done = true;
  26039. });
  26040. auto port = svr.bind_to_any_port("127.0.0.1");
  26041. std::thread t([&]() { svr.listen_after_bind(); });
  26042. auto se = detail::scope_exit([&] {
  26043. svr.stop();
  26044. t.join();
  26045. });
  26046. svr.wait_until_ready();
  26047. auto send_bytes = [](socket_t s, const std::string &data) {
  26048. #ifdef _WIN32
  26049. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  26050. #else
  26051. auto n = ::send(s, data.data(), data.size(), 0);
  26052. #endif
  26053. return n == static_cast<decltype(n)>(data.size());
  26054. };
  26055. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  26056. // Every length used here fits the 7-bit length field.
  26057. auto masked_header = [](uint8_t first_byte, size_t len) {
  26058. std::string h;
  26059. h += static_cast<char>(first_byte);
  26060. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  26061. h.append(4, '\0'); // mask key
  26062. return h;
  26063. };
  26064. for (int attempt = 0; attempt < attempts; attempt++) {
  26065. peer_stalled = false;
  26066. handler_done = false;
  26067. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26068. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  26069. auto se_sock = detail::scope_exit([&] {
  26070. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  26071. });
  26072. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26073. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  26074. sockaddr_in addr{};
  26075. addr.sin_family = AF_INET;
  26076. addr.sin_port = htons(static_cast<uint16_t>(port));
  26077. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26078. ASSERT_EQ(
  26079. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  26080. << "attempt " << attempt;
  26081. ASSERT_TRUE(send_bytes(sock,
  26082. "GET /ws HTTP/1.1\r\n"
  26083. "Host: 127.0.0.1\r\n"
  26084. "Upgrade: websocket\r\n"
  26085. "Connection: Upgrade\r\n"
  26086. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26087. "Sec-WebSocket-Version: 13\r\n"
  26088. "\r\n"))
  26089. << "attempt " << attempt;
  26090. std::string response;
  26091. while (response.find("\r\n\r\n") == std::string::npos) {
  26092. char buf[512];
  26093. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26094. if (n <= 0) { break; }
  26095. response.append(buf, static_cast<size_t>(n));
  26096. }
  26097. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26098. << "attempt " << attempt;
  26099. // Send the header of a Binary message but only the first prefix_len bytes
  26100. // of its payload, leaving the reader thread stalled inside the payload.
  26101. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26102. expected.substr(0, prefix_len)))
  26103. << "attempt " << attempt;
  26104. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26105. peer_stalled = true;
  26106. // Let close() send its Close frame and park in its own read before the
  26107. // rest of the payload arrives, so both threads are waiting for it.
  26108. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26109. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26110. close_frame += static_cast<char>(0x03); // status 1000
  26111. close_frame += static_cast<char>(0xE8);
  26112. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26113. << "attempt " << attempt;
  26114. // Closing the peer releases the reader thread even on the buggy path,
  26115. // where it waits for bytes another thread already consumed.
  26116. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26117. detail::close_socket(sock);
  26118. sock = INVALID_SOCKET;
  26119. wait_for(handler_done);
  26120. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26121. }
  26122. std::lock_guard<std::mutex> guard(received_mutex);
  26123. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26124. << "a message in flight when close() ran was dropped";
  26125. for (size_t i = 0; i < received.size(); i++) {
  26126. EXPECT_EQ(expected, received[i]) << "message " << i;
  26127. }
  26128. }
  26129. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26130. // returning the socket, or INVALID_SOCKET.
  26131. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26132. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26133. if (sock == INVALID_SOCKET) { return sock; }
  26134. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26135. sockaddr_in addr{};
  26136. addr.sin_family = AF_INET;
  26137. addr.sin_port = htons(static_cast<uint16_t>(port));
  26138. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26139. std::string req = "GET " + path +
  26140. " HTTP/1.1\r\n"
  26141. "Host: 127.0.0.1\r\n"
  26142. "Upgrade: websocket\r\n"
  26143. "Connection: Upgrade\r\n"
  26144. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26145. "Sec-WebSocket-Version: 13\r\n"
  26146. "\r\n";
  26147. std::string res;
  26148. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26149. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26150. static_cast<ssize_t>(req.size())) {
  26151. char c;
  26152. while (res.find("\r\n\r\n") == std::string::npos &&
  26153. ::recv(sock, &c, 1, 0) == 1) {
  26154. res += c;
  26155. }
  26156. }
  26157. if (res.find(" 101 ") == std::string::npos) {
  26158. detail::close_socket(sock);
  26159. return INVALID_SOCKET;
  26160. }
  26161. return sock;
  26162. }
  26163. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26164. // The payload must fit the 7-bit length field.
  26165. static std::string masked_frame(uint8_t first_byte,
  26166. const std::string &payload) {
  26167. std::string f;
  26168. f += static_cast<char>(first_byte);
  26169. f += static_cast<char>(0x80 | payload.size());
  26170. f.append(4, '\0');
  26171. return f + payload;
  26172. }
  26173. // Sends frames on a new raw connection to /ws and returns the first n bytes the
  26174. // server sends back, or what came before it closed.
  26175. static std::string raw_websocket_reply(int port, const std::string &frames,
  26176. size_t n) {
  26177. auto sock = connect_raw_websocket(port, "/ws");
  26178. if (sock == INVALID_SOCKET) { return std::string(); }
  26179. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26180. std::string reply;
  26181. char buf[256];
  26182. while (reply.size() < n) {
  26183. auto got = ::recv(sock, buf, sizeof(buf), 0);
  26184. if (got <= 0) { break; }
  26185. reply.append(buf, static_cast<size_t>(got));
  26186. }
  26187. detail::close_socket(sock);
  26188. return reply;
  26189. }
  26190. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26191. std::atomic<bool> done{false};
  26192. std::string received;
  26193. Server svr;
  26194. svr.set_websocket_ping_interval(0);
  26195. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26196. std::string msg;
  26197. if (ws.read(msg) == ws::Binary) { received = msg; }
  26198. done = true;
  26199. });
  26200. auto port = svr.bind_to_any_port("127.0.0.1");
  26201. std::thread t([&]() { svr.listen_after_bind(); });
  26202. auto se = detail::scope_exit([&] {
  26203. svr.stop();
  26204. t.join();
  26205. });
  26206. svr.wait_until_ready();
  26207. auto sock = connect_raw_websocket(port, "/ws");
  26208. ASSERT_NE(INVALID_SOCKET, sock);
  26209. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26210. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26211. masked_frame(0x89, "p") + // FIN + Ping
  26212. masked_frame(0x80, "lo"); // FIN + Continuation
  26213. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26214. for (int i = 0; i < 500 && !done; i++) {
  26215. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26216. }
  26217. ASSERT_TRUE(done);
  26218. EXPECT_EQ("Hello", received);
  26219. // The Ping between the fragments is answered with a Pong.
  26220. char pong[3];
  26221. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26222. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26223. }
  26224. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26225. #ifndef _WIN32
  26226. signal(SIGPIPE, SIG_IGN);
  26227. #endif
  26228. std::atomic<bool> read_ended{false};
  26229. std::atomic<bool> sending{true};
  26230. Server svr;
  26231. svr.set_websocket_ping_interval(0);
  26232. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26233. std::thread reader([&]() {
  26234. std::string msg;
  26235. while (ws.read(msg)) {}
  26236. read_ended = true;
  26237. });
  26238. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26239. ws.close();
  26240. reader.join();
  26241. });
  26242. auto port = svr.bind_to_any_port("127.0.0.1");
  26243. std::thread t([&]() { svr.listen_after_bind(); });
  26244. auto se = detail::scope_exit([&] {
  26245. svr.stop();
  26246. t.join();
  26247. });
  26248. svr.wait_until_ready();
  26249. auto sock = connect_raw_websocket(port, "/ws");
  26250. ASSERT_NE(INVALID_SOCKET, sock);
  26251. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26252. // A Text message whose empty continuation frames never end
  26253. std::thread sender([&]() {
  26254. auto data = masked_frame(0x01, "");
  26255. while (sending) {
  26256. data += masked_frame(0x00, "");
  26257. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26258. return;
  26259. }
  26260. data.clear();
  26261. }
  26262. });
  26263. for (int i = 0; i < 300 && !read_ended; i++) {
  26264. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26265. }
  26266. sending = false;
  26267. sender.join();
  26268. EXPECT_TRUE(read_ended);
  26269. }
  26270. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26271. Server svr;
  26272. svr.set_websocket_ping_interval(-1);
  26273. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26274. std::string msg;
  26275. while (ws.read(msg)) {}
  26276. });
  26277. auto port = svr.bind_to_any_port("127.0.0.1");
  26278. std::thread t([&]() { svr.listen_after_bind(); });
  26279. auto se = detail::scope_exit([&] {
  26280. svr.stop();
  26281. t.join();
  26282. });
  26283. svr.wait_until_ready();
  26284. auto sock = connect_raw_websocket(port, "/ws");
  26285. ASSERT_NE(INVALID_SOCKET, sock);
  26286. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26287. // Nothing comes while the client stays quiet.
  26288. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26289. char c;
  26290. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26291. }
  26292. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26293. // and that has to end a read() already waiting on the peer, on every platform.
  26294. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26295. // The peer sends no pings, and its handler never calls read(), which is
  26296. // where pongs are written.
  26297. std::mutex mutex;
  26298. std::condition_variable cv;
  26299. auto release = false;
  26300. svr.set_websocket_ping_interval(0);
  26301. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26302. std::unique_lock<std::mutex> lock(mutex);
  26303. cv.wait(lock, [&] { return release; });
  26304. });
  26305. auto port = svr.bind_to_any_port(HOST);
  26306. std::thread t([&]() { svr.listen_after_bind(); });
  26307. auto se = detail::scope_exit([&] {
  26308. {
  26309. std::lock_guard<std::mutex> lock(mutex);
  26310. release = true;
  26311. }
  26312. cv.notify_all();
  26313. svr.stop();
  26314. t.join();
  26315. });
  26316. svr.wait_until_ready();
  26317. ws::WebSocketClient client(std::string(scheme) +
  26318. "://localhost:" + std::to_string(port) + "/ws");
  26319. #ifdef CPPHTTPLIB_SSL_ENABLED
  26320. client.enable_server_certificate_verification(false);
  26321. #endif
  26322. // A ping a second, given up on after two go unanswered: about 3s
  26323. client.set_websocket_ping_interval(1);
  26324. client.set_websocket_max_missed_pongs(2);
  26325. // Well past that, so that a read the timeout ends instead stands out
  26326. client.set_read_timeout(10);
  26327. ASSERT_TRUE(client.connect());
  26328. auto start = std::chrono::steady_clock::now();
  26329. std::string msg;
  26330. EXPECT_EQ(ws::Fail, client.read(msg));
  26331. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26332. std::chrono::steady_clock::now() - start)
  26333. .count(),
  26334. 6000);
  26335. EXPECT_FALSE(client.is_open());
  26336. }
  26337. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26338. Server svr;
  26339. check_pong_timeout_ends_read(svr, "ws");
  26340. }
  26341. #ifdef CPPHTTPLIB_SSL_ENABLED
  26342. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26344. ASSERT_TRUE(svr.is_valid());
  26345. check_pong_timeout_ends_read(svr, "wss");
  26346. }
  26347. #endif
  26348. // listen() returns only after every handler has, so Server::stop() has to end
  26349. // a WebSocket handler's read() waiting on a client that stays connected and
  26350. // quiet, whether or not the handler bounded its reads, and the client's
  26351. // connection ends with it.
  26352. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26353. bool bounded) {
  26354. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26355. if (bounded) { ws.set_read_timeout(0, 50000); }
  26356. std::string msg;
  26357. while (ws.read(msg) != ws::Fail) {}
  26358. });
  26359. auto port = svr.bind_to_any_port(HOST);
  26360. std::thread t([&]() { svr.listen_after_bind(); });
  26361. auto se = detail::scope_exit([&] {
  26362. if (t.joinable()) {
  26363. svr.stop();
  26364. t.join();
  26365. }
  26366. });
  26367. svr.wait_until_ready();
  26368. ws::WebSocketClient client(std::string(scheme) +
  26369. "://localhost:" + std::to_string(port) + "/ws");
  26370. #ifdef CPPHTTPLIB_SSL_ENABLED
  26371. client.enable_server_certificate_verification(false);
  26372. #endif
  26373. client.set_read_timeout(2);
  26374. ASSERT_TRUE(client.connect());
  26375. auto stopped = std::async(std::launch::async, [&] {
  26376. svr.stop();
  26377. t.join();
  26378. });
  26379. std::string msg;
  26380. EXPECT_EQ(ws::Fail, client.read(msg));
  26381. EXPECT_FALSE(client.is_open());
  26382. auto in_time =
  26383. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26384. // A handler the stop did not reach ends when the client leaves
  26385. if (!in_time) { client.close(); }
  26386. stopped.wait();
  26387. EXPECT_TRUE(in_time);
  26388. }
  26389. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26390. Server svr;
  26391. check_stop_ends_websocket_read(svr, "ws", false);
  26392. }
  26393. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26394. Server svr;
  26395. check_stop_ends_websocket_read(svr, "ws", true);
  26396. }
  26397. #ifdef CPPHTTPLIB_SSL_ENABLED
  26398. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26399. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26400. ASSERT_TRUE(svr.is_valid());
  26401. check_stop_ends_websocket_read(svr, "wss", false);
  26402. }
  26403. #endif
  26404. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26405. // dropped connection, whether the handler waits for a message or for the rest
  26406. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26407. // time out inside the message as well, and the stop ends them too.
  26408. static void check_stop_closes_with_going_away(const std::string &sent,
  26409. bool bounded = false) {
  26410. Server svr;
  26411. svr.set_websocket_ping_interval(0);
  26412. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26413. if (bounded) { ws.set_read_timeout(0, 10000); }
  26414. std::string msg;
  26415. while (ws.read(msg) != ws::Fail) {}
  26416. });
  26417. auto port = svr.bind_to_any_port("127.0.0.1");
  26418. std::thread t([&]() { svr.listen_after_bind(); });
  26419. auto se = detail::scope_exit([&] {
  26420. svr.stop();
  26421. t.join();
  26422. });
  26423. svr.wait_until_ready();
  26424. // Closed before the join above, which a handler the stop did not reach
  26425. // would otherwise hold up.
  26426. auto sock = connect_raw_websocket(port, "/ws");
  26427. ASSERT_NE(INVALID_SOCKET, sock);
  26428. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26429. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26430. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26431. // Let the handler take what was sent and wait for more
  26432. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26433. svr.stop();
  26434. // FIN + Close, its length, then the code: unmasked, from a server
  26435. std::string head;
  26436. char c;
  26437. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26438. head += c;
  26439. }
  26440. const std::string reason = "server stopping";
  26441. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26442. "\x03\xe9",
  26443. head);
  26444. }
  26445. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26446. check_stop_closes_with_going_away("");
  26447. }
  26448. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26449. // A Text frame without FIN: the first fragment of a message
  26450. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26451. }
  26452. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26453. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26454. /*bounded=*/true);
  26455. }
  26456. // A handler that bounds its reads gets control back within its timeout even
  26457. // while a message arrives in pieces, and the message whole once the last has
  26458. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26459. // sent a while after the one before, much longer than the handler's timeout.
  26460. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26461. const std::string &expected) {
  26462. std::atomic<bool> done{false};
  26463. std::string received;
  26464. std::chrono::steady_clock::duration longest{};
  26465. Server svr;
  26466. svr.set_websocket_ping_interval(0);
  26467. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26468. ws.set_read_timeout(0, 10000);
  26469. std::string msg;
  26470. ws::ReadResult r;
  26471. do {
  26472. auto began = std::chrono::steady_clock::now();
  26473. r = ws.read(msg);
  26474. longest = (std::max)(longest, std::chrono::steady_clock::now() - began);
  26475. } while (r == ws::Timeout);
  26476. if (r == ws::Text) { received = msg; }
  26477. done = true;
  26478. });
  26479. auto port = svr.bind_to_any_port("127.0.0.1");
  26480. std::thread t([&]() { svr.listen_after_bind(); });
  26481. auto se = detail::scope_exit([&] {
  26482. svr.stop();
  26483. t.join();
  26484. });
  26485. svr.wait_until_ready();
  26486. auto sock = connect_raw_websocket(port, "/ws");
  26487. ASSERT_NE(INVALID_SOCKET, sock);
  26488. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26489. for (const auto &piece : pieces) {
  26490. ASSERT_EQ(static_cast<ssize_t>(piece.size()),
  26491. detail::send_socket(sock, piece.data(), piece.size(), 0));
  26492. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26493. }
  26494. for (int i = 0; i < 500 && !done; i++) {
  26495. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26496. }
  26497. ASSERT_TRUE(done);
  26498. EXPECT_EQ(expected, received);
  26499. // Far under the 200 ms between the pieces, however loaded the machine
  26500. EXPECT_LT(longest, std::chrono::milliseconds(150));
  26501. }
  26502. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26503. // The header's first byte, then its second with half the mask key, then
  26504. // the rest: what a frame written in several writes may look like when
  26505. // Nagle's algorithm holds the later ones back for an ACK.
  26506. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26507. check_bounded_read_resumes(
  26508. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26509. }
  26510. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26511. check_bounded_read_resumes(
  26512. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26513. }
  26514. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26515. Server svr;
  26516. svr.set_websocket_ping_interval(0);
  26517. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26518. std::string msg;
  26519. while (ws.read(msg)) {}
  26520. });
  26521. auto port = svr.bind_to_any_port("127.0.0.1");
  26522. std::thread t([&]() { svr.listen_after_bind(); });
  26523. auto se = detail::scope_exit([&] {
  26524. svr.stop();
  26525. t.join();
  26526. });
  26527. svr.wait_until_ready();
  26528. // Each Close payload and the reply it should get: an echo when valid, 1002
  26529. // otherwise.
  26530. std::vector<std::pair<std::string, std::string>> cases = {
  26531. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26532. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26533. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26534. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26535. };
  26536. // Also between the fragments of a message.
  26537. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26538. for (const auto &c : cases) {
  26539. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26540. c.second,
  26541. raw_websocket_reply(port, prefix + masked_frame(0x88, c.first),
  26542. 2 + c.second.size()));
  26543. }
  26544. }
  26545. }
  26546. TEST(WebSocketTest, FailsABadFrameWithACloseStatus) {
  26547. Server svr;
  26548. svr.set_websocket_ping_interval(0);
  26549. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26550. std::string msg;
  26551. while (ws.read(msg)) {}
  26552. });
  26553. auto port = svr.bind_to_any_port("127.0.0.1");
  26554. std::thread t([&]() { svr.listen_after_bind(); });
  26555. auto se = detail::scope_exit([&] {
  26556. svr.stop();
  26557. t.join();
  26558. });
  26559. svr.wait_until_ready();
  26560. // A header that announces one byte over the limit, and none of its payload
  26561. std::string too_big = "\x82\xff";
  26562. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1;
  26563. for (int shift = 56; shift >= 0; shift -= 8) {
  26564. too_big += static_cast<char>((len >> shift) & 0xff);
  26565. }
  26566. too_big.append(4, '\0');
  26567. const std::string protocol_error("\x03\xea"); // 1002
  26568. const std::string too_big_error("\x03\xf1"); // 1009
  26569. // What the client sends and the status the server closes with
  26570. std::vector<std::pair<std::string, std::string>> cases = {
  26571. {masked_frame(0xc1, "a"), protocol_error}, // RSV1
  26572. {std::string("\x81\x01") + "a", protocol_error}, // not masked
  26573. {masked_frame(0x09, ""), protocol_error}, // fragmented Ping
  26574. {masked_frame(0x83, ""), protocol_error}, // reserved opcode
  26575. {masked_frame(0x8b, ""), protocol_error}, // reserved control opcode
  26576. {masked_frame(0x80, "a"), protocol_error}, // continuation, no start
  26577. {masked_frame(0x01, "a") + masked_frame(0x81, "b"),
  26578. protocol_error}, // a new message inside a fragmented one
  26579. {std::string("\x81\xff\x80", 3) + std::string(11, '\0'),
  26580. protocol_error}, // 64-bit length with its top bit set
  26581. {too_big, too_big_error},
  26582. };
  26583. for (const auto &c : cases) {
  26584. EXPECT_EQ(std::string("\x88\x02") + c.second,
  26585. raw_websocket_reply(port, c.first, 4));
  26586. }
  26587. }
  26588. TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
  26589. SilentListener listener;
  26590. ASSERT_NE(INVALID_SOCKET, listener.sock);
  26591. // A peer that completes the handshake, then sends a masked frame, which a
  26592. // server must never do, and keeps what the client sends back.
  26593. std::string reply;
  26594. std::thread peer([&]() {
  26595. auto sock = listener.accept();
  26596. if (sock == INVALID_SOCKET) { return; }
  26597. std::string req;
  26598. char c;
  26599. while (req.find("\r\n\r\n") == std::string::npos &&
  26600. ::recv(sock, &c, 1, 0) == 1) {
  26601. req += c;
  26602. }
  26603. const std::string field = "Sec-WebSocket-Key: ";
  26604. auto pos = req.find(field);
  26605. if (pos != std::string::npos) {
  26606. pos += field.size();
  26607. auto key = req.substr(pos, req.find("\r\n", pos) - pos);
  26608. auto res = "HTTP/1.1 101 Switching Protocols\r\n"
  26609. "Upgrade: websocket\r\n"
  26610. "Connection: Upgrade\r\n"
  26611. "Sec-WebSocket-Accept: " +
  26612. detail::websocket_accept_key(key) + "\r\n\r\n" +
  26613. masked_frame(0x81, "a");
  26614. detail::send_socket(sock, res.data(), res.size(), 0);
  26615. // FIN + Close, masked with a length of 2, the mask key, the code
  26616. char buf[256];
  26617. while (reply.size() < 8) {
  26618. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26619. if (n <= 0) { break; }
  26620. reply.append(buf, static_cast<size_t>(n));
  26621. }
  26622. }
  26623. detail::close_socket(sock);
  26624. });
  26625. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(listener.port) +
  26626. "/ws");
  26627. auto connected = static_cast<bool>(client.connect());
  26628. std::string msg;
  26629. auto r = connected ? client.read(msg) : ws::Fail;
  26630. peer.join();
  26631. ASSERT_TRUE(connected);
  26632. EXPECT_EQ(ws::Fail, r);
  26633. detail::BufferStream strm;
  26634. strm.write(reply.data(), reply.size());
  26635. ws::Opcode opcode;
  26636. std::string payload;
  26637. bool fin;
  26638. ASSERT_EQ(
  26639. ws::impl::FrameRead::Ok,
  26640. ws::impl::read_websocket_frame(strm, opcode, payload, fin, true, 125));
  26641. EXPECT_EQ(ws::Opcode::Close, opcode);
  26642. EXPECT_EQ(std::string("\x03\xea"), payload);
  26643. }
  26644. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26645. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26646. protected:
  26647. void SetUp() override {
  26648. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26649. SERVER_PRIVATE_KEY_FILE);
  26650. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26651. std::string msg;
  26652. ws::ReadResult ret;
  26653. while ((ret = ws.read(msg))) {
  26654. if (ret == ws::Binary) {
  26655. ws.send(msg.data(), msg.size());
  26656. } else {
  26657. ws.send(msg);
  26658. }
  26659. }
  26660. });
  26661. port_ = server_->bind_to_any_port(HOST);
  26662. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26663. server_->wait_until_ready();
  26664. }
  26665. void TearDown() override {
  26666. server_->stop();
  26667. if (server_thread_.joinable()) { server_thread_.join(); }
  26668. }
  26669. std::unique_ptr<SSLServer> server_;
  26670. std::thread server_thread_;
  26671. int port_ = 0;
  26672. };
  26673. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26674. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26675. {
  26676. ws::WebSocketClient client(url);
  26677. client.enable_server_certificate_verification(false);
  26678. auto calls = 0;
  26679. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26680. calls++;
  26681. return false;
  26682. });
  26683. EXPECT_FALSE(client.connect());
  26684. EXPECT_GT(calls, 0);
  26685. }
  26686. {
  26687. ws::WebSocketClient client(url);
  26688. client.enable_server_certificate_verification(false);
  26689. client.set_session_verifier([](tls::session_t) {
  26690. return SSLVerifierResponse::CertificateRejected;
  26691. });
  26692. EXPECT_FALSE(client.connect());
  26693. }
  26694. {
  26695. ws::WebSocketClient client(url);
  26696. client.enable_server_certificate_verification(false);
  26697. client.set_session_verifier([](tls::session_t) {
  26698. return SSLVerifierResponse::CertificateAccepted;
  26699. });
  26700. EXPECT_TRUE(client.connect());
  26701. }
  26702. }
  26703. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26704. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26705. "/ws-echo");
  26706. client.enable_server_certificate_verification(false);
  26707. ASSERT_TRUE(client.connect());
  26708. ASSERT_TRUE(client.is_open());
  26709. ASSERT_TRUE(client.send("Hello WSS"));
  26710. std::string msg;
  26711. EXPECT_EQ(ws::Text, client.read(msg));
  26712. EXPECT_EQ("Hello WSS", msg);
  26713. client.close();
  26714. }
  26715. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26716. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26717. "/ws-echo");
  26718. client.enable_server_certificate_verification(false);
  26719. EXPECT_TRUE(client.connect());
  26720. }
  26721. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26722. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26723. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26724. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26725. // client (without calling close() first) is the only path that runs
  26726. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26727. // bug exactly.
  26728. //
  26729. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26730. // when linked against an instrumented libssl; run under Valgrind to catch it
  26731. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26732. // suite (the freed session otherwise stalls on the close handshake) — this test
  26733. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26734. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26735. {
  26736. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26737. "/ws-echo");
  26738. client.enable_server_certificate_verification(false);
  26739. client.set_read_timeout(2, 0);
  26740. client.set_write_timeout(2, 0);
  26741. ASSERT_TRUE(client.connect());
  26742. ASSERT_TRUE(client.is_open());
  26743. ASSERT_TRUE(client.send("still open"));
  26744. // Intentionally do NOT call client.close(): leaving scope runs
  26745. // shutdown_and_close() with the WebSocket still open, which must send the
  26746. // close frame while the TLS session is still alive.
  26747. }
  26748. }
  26749. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26750. // shutdown_and_close() at the start of connect(), reproducing the same
  26751. // use-after-free within the test body rather than at scope exit. The second
  26752. // connect must succeed and echo, proving the close handshake ran over a live
  26753. // session. See the note above about memory-tool requirements.
  26754. TEST_F(WebSocketSSLIntegrationTest,
  26755. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26756. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26757. "/ws-echo");
  26758. client.enable_server_certificate_verification(false);
  26759. client.set_read_timeout(2, 0);
  26760. client.set_write_timeout(2, 0);
  26761. ASSERT_TRUE(client.connect());
  26762. ASSERT_TRUE(client.is_open());
  26763. ASSERT_TRUE(client.send("still open"));
  26764. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26765. // the still-open connection, which must not touch a freed TLS session.
  26766. ASSERT_TRUE(client.connect());
  26767. ASSERT_TRUE(client.is_open());
  26768. ASSERT_TRUE(client.send("after reconnect"));
  26769. std::string msg;
  26770. EXPECT_EQ(ws::Text, client.read(msg));
  26771. EXPECT_EQ("after reconnect", msg);
  26772. client.close();
  26773. }
  26774. #endif
  26775. #ifdef CPPHTTPLIB_SSL_ENABLED
  26776. class WebSocketSSLCATest : public ::testing::Test {
  26777. protected:
  26778. void SetUp() override {
  26779. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26780. SERVER_PRIVATE_KEY_FILE);
  26781. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26782. std::string msg;
  26783. while (ws.read(msg)) {
  26784. ws.send(msg);
  26785. }
  26786. });
  26787. port_ = server_->bind_to_any_port("127.0.0.1");
  26788. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26789. server_->wait_until_ready();
  26790. }
  26791. void TearDown() override {
  26792. server_->stop();
  26793. if (server_thread_.joinable()) { server_thread_.join(); }
  26794. }
  26795. std::string url() const {
  26796. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26797. }
  26798. std::unique_ptr<SSLServer> server_;
  26799. std::thread server_thread_;
  26800. int port_ = 0;
  26801. };
  26802. // A custom CA loaded as PEM verifies the server with full certificate
  26803. // verification enabled
  26804. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26805. ws::WebSocketClient client(url());
  26806. std::string cert;
  26807. read_file(SERVER_CERT2_FILE, cert);
  26808. client.load_ca_cert_store(cert.c_str(), cert.size());
  26809. ASSERT_TRUE(client.connect());
  26810. ASSERT_TRUE(client.send("hello"));
  26811. std::string msg;
  26812. EXPECT_EQ(ws::Text, client.read(msg));
  26813. EXPECT_EQ("hello", msg);
  26814. client.close();
  26815. }
  26816. // A custom CA that does not cover the server must fail verification (the
  26817. // custom CA is exclusive; system certs are not loaded alongside it)
  26818. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26819. ws::WebSocketClient client(url());
  26820. std::string cert;
  26821. read_file(CLIENT_CA_CERT_FILE, cert);
  26822. client.load_ca_cert_store(cert.c_str(), cert.size());
  26823. auto res = client.connect();
  26824. ASSERT_FALSE(res);
  26825. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26826. EXPECT_EQ(-1, res.status());
  26827. EXPECT_NE(0u, res.ssl_backend_error());
  26828. }
  26829. // The same CA as a file path rather than PEM in memory
  26830. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26831. ws::WebSocketClient client(url());
  26832. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26833. ASSERT_TRUE(client.connect());
  26834. ASSERT_TRUE(client.send("hello"));
  26835. std::string msg;
  26836. EXPECT_EQ(ws::Text, client.read(msg));
  26837. EXPECT_EQ("hello", msg);
  26838. client.close();
  26839. }
  26840. // ...and a CA file that does not cover the server still fails, so it is the
  26841. // path above that decides the outcome
  26842. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26843. ws::WebSocketClient client(url());
  26844. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26845. ASSERT_FALSE(client.connect());
  26846. }
  26847. // Regression test: reconnecting with a native custom CA store used to reuse
  26848. // a store handle the previous TLS context had already freed (use-after-free
  26849. // under the OpenSSL backend). The context now lives as long as the client.
  26850. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26851. ws::WebSocketClient client(url());
  26852. std::string cert;
  26853. read_file(SERVER_CERT2_FILE, cert);
  26854. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26855. ASSERT_TRUE(client.connect());
  26856. client.close();
  26857. ASSERT_TRUE(client.connect());
  26858. ASSERT_TRUE(client.send("again"));
  26859. std::string msg;
  26860. EXPECT_EQ(ws::Text, client.read(msg));
  26861. EXPECT_EQ("again", msg);
  26862. client.close();
  26863. }
  26864. // Regression test: a certificate with a trusted chain but no identity match
  26865. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26866. // verification entirely for IP hosts, so this connection succeeded there.
  26867. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26868. // chain verification while the identity check must still fail.
  26869. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26870. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26871. ASSERT_TRUE(svr.is_valid());
  26872. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26873. std::string msg;
  26874. while (ws.read(msg)) {
  26875. ws.send(msg);
  26876. }
  26877. });
  26878. auto port = svr.bind_to_any_port("127.0.0.1");
  26879. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26880. auto se = detail::scope_exit([&] {
  26881. svr.stop();
  26882. t.join();
  26883. });
  26884. svr.wait_until_ready();
  26885. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26886. "/echo");
  26887. std::string cert;
  26888. read_file(SERVER_CERT_FILE, cert);
  26889. client.load_ca_cert_store(cert.c_str(), cert.size());
  26890. ASSERT_FALSE(client.connect());
  26891. }
  26892. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26893. // SNI, so nothing binds the host name to the TLS session. These bind the
  26894. // server to "localhost" instead, the only shape that exercises the SNI and
  26895. // hostname-verification path with certificate verification left enabled.
  26896. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26897. protected:
  26898. void Start(const char *cert_file) {
  26899. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26900. SERVER_PRIVATE_KEY_FILE);
  26901. ASSERT_TRUE(server_->is_valid());
  26902. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26903. std::string msg;
  26904. while (ws.read(msg)) {
  26905. ws.send(msg);
  26906. }
  26907. });
  26908. port_ = server_->bind_to_any_port("localhost");
  26909. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26910. server_->wait_until_ready();
  26911. }
  26912. void TearDown() override {
  26913. if (server_) { server_->stop(); }
  26914. if (server_thread_.joinable()) { server_thread_.join(); }
  26915. }
  26916. std::string url() const {
  26917. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26918. }
  26919. std::unique_ptr<SSLServer> server_;
  26920. std::thread server_thread_;
  26921. int port_ = 0;
  26922. };
  26923. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26924. // out and the connection is usable
  26925. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26926. Start(SERVER_CERT2_FILE);
  26927. ws::WebSocketClient client(url());
  26928. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26929. ASSERT_TRUE(client.connect());
  26930. ASSERT_TRUE(client.send("hello"));
  26931. std::string msg;
  26932. EXPECT_EQ(ws::Text, client.read(msg));
  26933. EXPECT_EQ("hello", msg);
  26934. client.close();
  26935. }
  26936. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26937. // while the identity check must still reject "localhost"
  26938. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26939. Start(SERVER_CERT_FILE);
  26940. ws::WebSocketClient client(url());
  26941. client.set_ca_cert_path(SERVER_CERT_FILE);
  26942. auto res = client.connect();
  26943. ASSERT_FALSE(res);
  26944. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26945. EXPECT_EQ(-1, res.status());
  26946. }
  26947. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26948. // disabled: the chain is still checked, only the identity check is skipped
  26949. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26950. Start(SERVER_CERT_FILE);
  26951. ws::WebSocketClient client(url());
  26952. client.set_ca_cert_path(SERVER_CERT_FILE);
  26953. client.enable_server_hostname_verification(false);
  26954. ASSERT_TRUE(client.connect());
  26955. ASSERT_TRUE(client.send("hello"));
  26956. std::string msg;
  26957. EXPECT_EQ(ws::Text, client.read(msg));
  26958. EXPECT_EQ("hello", msg);
  26959. client.close();
  26960. }
  26961. // A CA that did not sign the server certificate fails the chain, even though
  26962. // the name would match
  26963. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26964. Start(SERVER_CERT2_FILE);
  26965. ws::WebSocketClient client(url());
  26966. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26967. ASSERT_FALSE(client.connect());
  26968. }
  26969. // With verification disabled, neither the chain nor the name is checked
  26970. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26971. Start(SERVER_CERT_FILE);
  26972. ws::WebSocketClient client(url());
  26973. client.enable_server_certificate_verification(false);
  26974. ASSERT_TRUE(client.connect());
  26975. ASSERT_TRUE(client.send("hello"));
  26976. std::string msg;
  26977. EXPECT_EQ(ws::Text, client.read(msg));
  26978. EXPECT_EQ("hello", msg);
  26979. client.close();
  26980. }
  26981. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26982. protected:
  26983. void SetUp() override {
  26984. server_ = httplib::detail::make_unique<SSLServer>(
  26985. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26986. ASSERT_TRUE(server_->is_valid());
  26987. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26988. std::string msg;
  26989. while (ws.read(msg)) {
  26990. ws.send(msg);
  26991. }
  26992. });
  26993. port_ = server_->bind_to_any_port("localhost");
  26994. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26995. server_->wait_until_ready();
  26996. }
  26997. void TearDown() override {
  26998. server_->stop();
  26999. if (server_thread_.joinable()) { server_thread_.join(); }
  27000. }
  27001. std::string url() const {
  27002. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  27003. }
  27004. void ConnectWithClientCert(const std::string &client_cert_file,
  27005. const std::string &client_private_key_file,
  27006. const char *private_key_password) {
  27007. std::string cert_pem, key_pem;
  27008. read_file(client_cert_file, cert_pem);
  27009. read_file(client_private_key_file, key_pem);
  27010. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  27011. key_pem.c_str(), key_pem.size(),
  27012. private_key_password};
  27013. ConnectWithPem(pem);
  27014. }
  27015. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  27016. ws::WebSocketClient client(url(), pem);
  27017. ASSERT_TRUE(client.is_valid());
  27018. client.enable_server_certificate_verification(false);
  27019. ASSERT_TRUE(client.connect());
  27020. ASSERT_TRUE(client.send("hello"));
  27021. std::string msg;
  27022. EXPECT_EQ(ws::Text, client.read(msg));
  27023. EXPECT_EQ("hello", msg);
  27024. client.close();
  27025. }
  27026. std::unique_ptr<SSLServer> server_;
  27027. std::thread server_thread_;
  27028. int port_ = 0;
  27029. };
  27030. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  27031. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  27032. }
  27033. // Control for the tests above: the fixture's server really does require a
  27034. // client certificate, so it is the PEM the constructor installed that decides
  27035. // the outcome.
  27036. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  27037. ws::WebSocketClient client(url());
  27038. ASSERT_TRUE(client.is_valid());
  27039. client.enable_server_certificate_verification(false);
  27040. EXPECT_FALSE(client.connect());
  27041. }
  27042. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  27043. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  27044. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  27045. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  27046. }
  27047. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  27048. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  27049. std::string cert_pem, key_pem;
  27050. read_file(CLIENT_CERT_FILE, cert_pem);
  27051. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  27052. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  27053. std::vector<char> key(key_pem.begin(), key_pem.end());
  27054. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  27055. key.size(), nullptr};
  27056. ConnectWithPem(pem);
  27057. }
  27058. #endif
  27059. #if !defined(_WIN32)
  27060. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  27061. auto secret_dir = std::string("./symlink_test_secret");
  27062. auto served_dir = std::string("./symlink_test_served");
  27063. auto secret_file = secret_dir + "/secret.txt";
  27064. auto symlink_path = served_dir + "/escape";
  27065. // Setup: create directories and files
  27066. mkdir(secret_dir.c_str(), 0755);
  27067. mkdir(served_dir.c_str(), 0755);
  27068. {
  27069. std::ofstream ofs(secret_file);
  27070. ofs << "SECRET_DATA";
  27071. }
  27072. // Create symlink using absolute path so it resolves correctly
  27073. #ifdef PATH_MAX
  27074. char abs_secret[PATH_MAX];
  27075. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  27076. #else
  27077. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  27078. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  27079. ASSERT_NE(nullptr, abs_secret);
  27080. #endif
  27081. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  27082. auto se = detail::scope_exit([&] {
  27083. unlink(symlink_path.c_str());
  27084. unlink(secret_file.c_str());
  27085. rmdir(served_dir.c_str());
  27086. rmdir(secret_dir.c_str());
  27087. });
  27088. Server svr;
  27089. svr.set_mount_point("/", served_dir);
  27090. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27091. auto se2 = detail::scope_exit([&] {
  27092. svr.stop();
  27093. listen_thread.join();
  27094. });
  27095. svr.wait_until_ready();
  27096. Client cli("localhost", PORT);
  27097. // Symlink pointing outside base dir should be blocked
  27098. auto res = cli.Get("/escape/secret.txt");
  27099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27100. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27101. }
  27102. #else
  27103. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  27104. auto secret_dir = std::string("junction_test_secret");
  27105. auto served_dir = std::string("junction_test_served");
  27106. auto secret_file = secret_dir + "\\secret.txt";
  27107. auto junction_path = served_dir + "\\escape";
  27108. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  27109. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  27110. {
  27111. std::ofstream ofs(secret_file);
  27112. ofs << "SECRET_DATA";
  27113. }
  27114. // A junction needs no privilege to create, unlike a symlink
  27115. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  27116. ASSERT_EQ(0, std::system(cmd.c_str()));
  27117. auto se = detail::scope_exit([&] {
  27118. ::RemoveDirectoryA(junction_path.c_str());
  27119. std::remove(secret_file.c_str());
  27120. ::RemoveDirectoryA(served_dir.c_str());
  27121. ::RemoveDirectoryA(secret_dir.c_str());
  27122. });
  27123. Server svr;
  27124. svr.set_mount_point("/", served_dir);
  27125. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27126. auto se2 = detail::scope_exit([&] {
  27127. svr.stop();
  27128. listen_thread.join();
  27129. });
  27130. svr.wait_until_ready();
  27131. Client cli("localhost", PORT);
  27132. // Junction pointing outside base dir should be blocked
  27133. auto res = cli.Get("/escape/secret.txt");
  27134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27135. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27136. }
  27137. #endif
  27138. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  27139. // "GET /smuggled" request), reads the first response, and only then sends the
  27140. // embedded request as the body. Returns how many times /smuggled ran.
  27141. //
  27142. // The body is sent AFTER receiving the first response (as in the original
  27143. // PoC) so that the stream_line_reader cannot buffer it together with the
  27144. // headers of the first request.
  27145. static int count_smuggled_requests(const std::string &outer_head,
  27146. std::string &first_response) {
  27147. Server svr;
  27148. svr.set_mount_point("/", "./www");
  27149. std::atomic<int> smuggled_count(0);
  27150. svr.Get("/smuggled", [&](const Request &, Response &res) {
  27151. smuggled_count++;
  27152. res.set_content("oops", "text/plain");
  27153. });
  27154. svr.Post("/post", [&](const Request &req, Response &res) {
  27155. res.set_content(req.body, "text/plain");
  27156. });
  27157. auto port = svr.bind_to_any_port("localhost");
  27158. thread t = thread([&] { svr.listen_after_bind(); });
  27159. auto se = detail::scope_exit([&] {
  27160. svr.stop();
  27161. t.join();
  27162. });
  27163. svr.wait_until_ready();
  27164. auto error = Error::Success;
  27165. auto sock = detail::create_client_socket(
  27166. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  27167. /*connection_timeout_sec=*/2, 0,
  27168. /*read_timeout_sec=*/2, 0,
  27169. /*write_timeout_sec=*/2, 0, std::string(), error);
  27170. EXPECT_NE(INVALID_SOCKET, sock);
  27171. if (sock == INVALID_SOCKET) { return -1; }
  27172. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27173. // The "smuggled" request will be sent as the body of the outer request
  27174. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  27175. "Host: localhost\r\n"
  27176. "Connection: close\r\n"
  27177. "\r\n";
  27178. auto head = outer_head;
  27179. auto len = std::to_string(smuggled.size());
  27180. for (auto pos = head.find("{len}"); pos != std::string::npos;
  27181. pos = head.find("{len}", pos + len.size())) {
  27182. head.replace(pos, 5, len);
  27183. }
  27184. // Step 1: Send only the outer request headers (no body yet)
  27185. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  27186. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  27187. // Step 2: Read the first response
  27188. char buf[4096];
  27189. for (;;) {
  27190. auto n = recv(sock, buf, sizeof(buf), 0);
  27191. if (n <= 0) break;
  27192. first_response.append(buf, static_cast<size_t>(n));
  27193. // Stop once we have a complete response (headers + body)
  27194. auto hdr_end = first_response.find("\r\n\r\n");
  27195. if (hdr_end != std::string::npos) {
  27196. // Check for Content-Length to know when the body is complete
  27197. auto cl_pos = first_response.find("Content-Length:");
  27198. if (cl_pos != std::string::npos) {
  27199. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27200. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27201. auto cl = std::stoul(
  27202. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27203. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27204. } else {
  27205. break; // No Content-Length, assume headers-only response
  27206. }
  27207. }
  27208. }
  27209. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27210. // vulnerable server the keep-alive loop reads this as a second request. The
  27211. // server may already have closed the connection, so the result is ignored.
  27212. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27213. // Half-close so that a server which drained the body sees EOF and closes,
  27214. // instead of the read below waiting for the read timeout.
  27215. #ifdef _WIN32
  27216. ::shutdown(sock, SD_SEND);
  27217. #else
  27218. ::shutdown(sock, SHUT_WR);
  27219. #endif
  27220. // Step 4: Read until the server closes the connection
  27221. for (;;) {
  27222. auto n = recv(sock, buf, sizeof(buf), 0);
  27223. if (n <= 0) break;
  27224. }
  27225. return smuggled_count.load();
  27226. }
  27227. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27228. // A GET request with Content-Length to a static file handler must have its
  27229. // body drained before the keep-alive connection is reused. Otherwise the
  27230. // unread body bytes are interpreted as the next HTTP request.
  27231. std::string first_response;
  27232. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27233. "Host: localhost\r\n"
  27234. "Content-Length: {len}\r\n"
  27235. "\r\n",
  27236. first_response));
  27237. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27238. }
  27239. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27240. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27241. // be answered with 400 and the connection closed. Treating it as "no body"
  27242. // leaves the body to be parsed as the next request.
  27243. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27244. const char *targets[] = {
  27245. "GET /file", // handler that never reads the body
  27246. "GET /not-found", // no handler matches (404)
  27247. "POST /post", // handler that reads the body
  27248. };
  27249. for (auto target : targets) {
  27250. for (auto value : values) {
  27251. std::string first_response;
  27252. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27253. " HTTP/1.1\r\n"
  27254. "Host: localhost\r\n"
  27255. "Content-Length: " +
  27256. value + "\r\n\r\n",
  27257. first_response))
  27258. << target << " with Content-Length: " << value;
  27259. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27260. << target << " with Content-Length: " << value;
  27261. }
  27262. }
  27263. }
  27264. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27265. // A 400 for an unparseable request line leaves the rest of the message
  27266. // unread, so the connection must be closed rather than reused.
  27267. std::string first_response;
  27268. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27269. "Host: localhost\r\n"
  27270. "Content-Length: {len}\r\n"
  27271. "\r\n",
  27272. first_response));
  27273. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27274. }
  27275. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27276. // Same as above for a header block that fails to parse.
  27277. std::string first_response;
  27278. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27279. "Host: localhost\r\n"
  27280. "Bad Header\r\n"
  27281. "Content-Length: {len}\r\n"
  27282. "\r\n",
  27283. first_response));
  27284. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27285. }
  27286. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27287. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27288. // server must not read another request on that connection, even when the
  27289. // request had no body to drain.
  27290. std::string first_response;
  27291. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27292. "Host: localhost\r\n"
  27293. "\r\n",
  27294. first_response));
  27295. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27296. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27297. }
  27298. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27299. // A content reader that stops early leaves the stream inside the body.
  27300. // Draining the whole Content-Length from there, or reading the body again,
  27301. // reads into the next request, and whatever follows is parsed as a request
  27302. // of its own.
  27303. Server svr;
  27304. std::atomic<int> smuggled_count(0);
  27305. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27306. svr.Post("/upload", [](const Request &req, Response &res,
  27307. const ContentReader &content_reader) {
  27308. // Stop at the last chunk, so the whole body has been read however it
  27309. // arrives.
  27310. auto length = req.get_header_value_u64("Content-Length");
  27311. size_t total = 0;
  27312. auto consumed = content_reader([&](const char *, size_t n) {
  27313. total += n;
  27314. return total < length;
  27315. });
  27316. EXPECT_FALSE(consumed);
  27317. if (req.has_param("retry")) {
  27318. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27319. }
  27320. // Replace the 400 the aborted read set, which would close the connection.
  27321. res.set_redirect("/done");
  27322. });
  27323. auto port = svr.bind_to_any_port(HOST);
  27324. thread t = thread([&] { svr.listen_after_bind(); });
  27325. auto se = detail::scope_exit([&] {
  27326. svr.stop();
  27327. t.join();
  27328. });
  27329. svr.wait_until_ready();
  27330. // A front end sees the second request as a POST whose body is the GET. The
  27331. // first body is as long as the POST's headers, so draining it again reads
  27332. // exactly those and leaves the GET to be parsed next.
  27333. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27334. "Host: localhost\r\n"
  27335. "\r\n";
  27336. std::string second_head = "POST /post HTTP/1.1\r\n"
  27337. "Host: localhost\r\n"
  27338. "Content-Length: " +
  27339. std::to_string(inner.size()) +
  27340. "\r\n"
  27341. "\r\n";
  27342. for (auto target : {"/upload", "/upload?retry"}) {
  27343. smuggled_count = 0;
  27344. std::string request = "POST " + std::string(target) +
  27345. " HTTP/1.1\r\n"
  27346. "Host: localhost\r\n"
  27347. "Content-Length: " +
  27348. std::to_string(second_head.size()) +
  27349. "\r\n"
  27350. "\r\n" +
  27351. std::string(second_head.size(), 'A') + second_head +
  27352. inner;
  27353. std::string response;
  27354. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27355. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27356. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27357. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27358. EXPECT_EQ(0, smuggled_count.load()) << target;
  27359. }
  27360. }
  27361. // An error response closes the connection anyway, so the body is left unread
  27362. // with a redirect, such as one to a login page.
  27363. static void serve_redirects(Server &svr,
  27364. const std::function<void(int)> &client) {
  27365. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27366. res.set_redirect("/login");
  27367. return Server::HandlerResponse::Handled;
  27368. });
  27369. auto port = svr.bind_to_any_port(HOST);
  27370. ASSERT_GT(port, 0);
  27371. thread t = thread([&] { svr.listen_after_bind(); });
  27372. auto se = detail::scope_exit([&] {
  27373. svr.stop();
  27374. t.join();
  27375. ASSERT_FALSE(svr.is_running());
  27376. });
  27377. svr.wait_until_ready();
  27378. client(port);
  27379. }
  27380. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27381. Server svr;
  27382. serve_redirects(svr, [](int port) {
  27383. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27384. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27385. std::to_string(body.size()) + "\r\n\r\n" + body +
  27386. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27387. std::string resp;
  27388. ASSERT_TRUE(send_request(1, req, &resp, port));
  27389. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27390. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27391. });
  27392. }
  27393. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27394. Server svr;
  27395. svr.set_read_timeout(0, 200000);
  27396. serve_redirects(svr, [](int port) {
  27397. // A byte every 100 ms keeps each read within the read timeout, but not the
  27398. // body as a whole, so the server closes and the bytes sent after that fail.
  27399. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27400. "Content-Length: 10\r\n\r\n"};
  27401. parts.resize(11, "x");
  27402. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27403. });
  27404. }
  27405. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27406. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27407. // must be rejected with 400 Bad Request.
  27408. Server svr;
  27409. svr.Post("/test", [&](const Request &, Response &res) {
  27410. res.set_content("ok", "text/plain");
  27411. });
  27412. thread t = thread([&] { svr.listen(HOST, PORT); });
  27413. auto se = detail::scope_exit([&] {
  27414. svr.stop();
  27415. t.join();
  27416. ASSERT_FALSE(svr.is_running());
  27417. });
  27418. svr.wait_until_ready();
  27419. // Exact "chunked"
  27420. {
  27421. auto req = "POST /test HTTP/1.1\r\n"
  27422. "Host: localhost\r\n"
  27423. "Content-Length: 5\r\n"
  27424. "Transfer-Encoding: chunked\r\n"
  27425. "Connection: close\r\n"
  27426. "\r\n"
  27427. "hello";
  27428. std::string response;
  27429. ASSERT_TRUE(send_request(1, req, &response));
  27430. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27431. response.substr(0, response.find("\r\n")));
  27432. }
  27433. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27434. {
  27435. auto req = "POST /test HTTP/1.1\r\n"
  27436. "Host: localhost\r\n"
  27437. "Content-Length: 5\r\n"
  27438. "Transfer-Encoding: gzip, chunked\r\n"
  27439. "Connection: close\r\n"
  27440. "\r\n"
  27441. "hello";
  27442. std::string response;
  27443. ASSERT_TRUE(send_request(1, req, &response));
  27444. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27445. response.substr(0, response.find("\r\n")));
  27446. }
  27447. }
  27448. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27449. Server svr;
  27450. svr.Post("/test", [&](const Request &, Response &res) {
  27451. res.set_content("ok", "text/plain");
  27452. });
  27453. thread t = thread([&] { svr.listen(HOST, PORT); });
  27454. auto se = detail::scope_exit([&] {
  27455. svr.stop();
  27456. t.join();
  27457. ASSERT_FALSE(svr.is_running());
  27458. });
  27459. svr.wait_until_ready();
  27460. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27461. // length cannot be determined, so the server must answer 400 and close
  27462. // rather than treat the request as bodyless and leave the body in the
  27463. // socket for the next request to pick up.
  27464. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27465. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27466. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27467. std::string response;
  27468. ASSERT_TRUE(send_request(1, req, &response));
  27469. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27470. response.substr(0, response.find("\r\n")))
  27471. << transfer_encoding;
  27472. }
  27473. // RFC 9110 5.3: the codings may also be split across several
  27474. // Transfer-Encoding lines, which combine in the order they were received.
  27475. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27476. // just like the single-line "chunked, gzip" above.
  27477. {
  27478. auto req = "POST /test HTTP/1.1\r\n"
  27479. "Host: localhost\r\n"
  27480. "Transfer-Encoding: chunked\r\n"
  27481. "Transfer-Encoding: gzip\r\n"
  27482. "\r\n"
  27483. "0\r\n\r\n";
  27484. std::string response;
  27485. ASSERT_TRUE(send_request(1, req, &response));
  27486. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27487. response.substr(0, response.find("\r\n")));
  27488. }
  27489. }
  27490. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27491. Server svr;
  27492. svr.Post("/test", [&](const Request &, Response &res) {
  27493. res.set_content("ok", "text/plain");
  27494. });
  27495. auto port = svr.bind_to_any_port(HOST);
  27496. ASSERT_GT(port, 0);
  27497. thread t = thread([&] { svr.listen_after_bind(); });
  27498. auto se = detail::scope_exit([&] {
  27499. svr.stop();
  27500. t.join();
  27501. ASSERT_FALSE(svr.is_running());
  27502. });
  27503. svr.wait_until_ready();
  27504. for (auto transfer_encoding :
  27505. {"Transfer-Encoding: gzip, chunked\r\n",
  27506. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27507. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27508. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27509. transfer_encoding + "\r\n0\r\n\r\n";
  27510. std::string response;
  27511. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27512. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27513. response.substr(0, response.find("\r\n")))
  27514. << transfer_encoding;
  27515. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27516. << transfer_encoding;
  27517. }
  27518. }
  27519. // Regression for issue #2450: a DELETE without Content-Length on a
  27520. // keep-alive connection must not let the post-response drain consume the
  27521. // next request's bytes.
  27522. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27523. Server svr;
  27524. std::atomic<int> delete_count(0);
  27525. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27526. delete_count++;
  27527. res.status = StatusCode::NoContent_204;
  27528. });
  27529. auto port = svr.bind_to_any_port(HOST);
  27530. thread t = thread([&] { svr.listen_after_bind(); });
  27531. auto se = detail::scope_exit([&] {
  27532. svr.stop();
  27533. t.join();
  27534. });
  27535. svr.wait_until_ready();
  27536. auto error = Error::Success;
  27537. auto sock = detail::create_client_socket(
  27538. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27539. /*connection_timeout_sec=*/2, 0,
  27540. /*read_timeout_sec=*/2, 0,
  27541. /*write_timeout_sec=*/2, 0, std::string(), error);
  27542. ASSERT_NE(INVALID_SOCKET, sock);
  27543. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27544. auto send_request_and_read_response = [&](const std::string &req,
  27545. std::string &out) -> bool {
  27546. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27547. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27548. char buf[4096];
  27549. for (;;) {
  27550. auto n = recv(sock, buf, sizeof(buf), 0);
  27551. if (n <= 0) { return !out.empty(); }
  27552. out.append(buf, static_cast<size_t>(n));
  27553. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27554. }
  27555. };
  27556. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27557. "Host: localhost\r\n"
  27558. "\r\n";
  27559. std::string resp1;
  27560. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27561. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27562. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27563. "Host: localhost\r\n"
  27564. "Connection: close\r\n"
  27565. "\r\n";
  27566. std::string resp2;
  27567. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27568. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27569. EXPECT_EQ(2, delete_count.load());
  27570. }
  27571. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27572. Server svr;
  27573. svr.Post("/ingest", [&](const Request &, Response &res,
  27574. const ContentReader &content_reader) {
  27575. auto consumed = content_reader([](const char *, size_t) { return false; });
  27576. EXPECT_FALSE(consumed);
  27577. res.status = StatusCode::Conflict_409;
  27578. res.set_header("Connection", "close");
  27579. });
  27580. auto port = svr.bind_to_any_port(HOST);
  27581. thread t = thread([&] { svr.listen_after_bind(); });
  27582. auto se = detail::scope_exit([&] {
  27583. svr.stop();
  27584. t.join();
  27585. });
  27586. svr.wait_until_ready();
  27587. auto error = Error::Success;
  27588. auto sock = detail::create_client_socket(
  27589. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27590. /*connection_timeout_sec=*/2, 0,
  27591. /*read_timeout_sec=*/1, 0,
  27592. /*write_timeout_sec=*/2, 0, std::string(), error);
  27593. ASSERT_NE(INVALID_SOCKET, sock);
  27594. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27595. std::string request = "POST /ingest HTTP/1.1\r\n"
  27596. "Host: localhost\r\n"
  27597. "Transfer-Encoding: chunked\r\n"
  27598. "\r\n"
  27599. "4\r\n"
  27600. "data\r\n";
  27601. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27602. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27603. std::string response;
  27604. ssize_t received = 0;
  27605. do {
  27606. char buf[4096];
  27607. received = recv(sock, buf, sizeof(buf), 0);
  27608. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27609. } while (received > 0);
  27610. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27611. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27612. EXPECT_EQ(0, received);
  27613. }
  27614. namespace no_proxy_test {
  27615. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27616. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27617. // calling listen().
  27618. class ScopedServer {
  27619. public:
  27620. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27621. ~ScopedServer() {
  27622. svr_.stop();
  27623. if (th_.joinable()) { th_.join(); }
  27624. }
  27625. Server &svr() { return svr_; }
  27626. int port() const { return port_; }
  27627. void listen() {
  27628. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27629. svr_.wait_until_ready();
  27630. }
  27631. private:
  27632. Server svr_;
  27633. std::thread th_;
  27634. int port_ = 0;
  27635. };
  27636. class ProxyAndTargetServers {
  27637. public:
  27638. ProxyAndTargetServers() {
  27639. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27640. proxy_hits_++;
  27641. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27642. res.set_content("via-proxy", "text/plain");
  27643. });
  27644. target_.Get(".*", [this](const Request &req, Response &res) {
  27645. target_hits_++;
  27646. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27647. res.set_content("direct", "text/plain");
  27648. });
  27649. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27650. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27651. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27652. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27653. proxy_mock_.wait_until_ready();
  27654. target_.wait_until_ready();
  27655. }
  27656. ~ProxyAndTargetServers() {
  27657. proxy_mock_.stop();
  27658. target_.stop();
  27659. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27660. if (target_thread_.joinable()) { target_thread_.join(); }
  27661. }
  27662. Server &proxy_mock() { return proxy_mock_; }
  27663. Server &target() { return target_; }
  27664. int proxy_port() const { return proxy_port_; }
  27665. int target_port() const { return target_port_; }
  27666. int proxy_hits() const { return proxy_hits_.load(); }
  27667. int target_hits() const { return target_hits_.load(); }
  27668. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27669. void reset_counters() {
  27670. proxy_hits_ = 0;
  27671. target_hits_ = 0;
  27672. last_had_proxy_authz_ = false;
  27673. }
  27674. private:
  27675. Server proxy_mock_;
  27676. Server target_;
  27677. std::thread proxy_thread_;
  27678. std::thread target_thread_;
  27679. int proxy_port_ = 0;
  27680. int target_port_ = 0;
  27681. std::atomic<int> proxy_hits_{0};
  27682. std::atomic<int> target_hits_{0};
  27683. std::atomic<bool> last_had_proxy_authz_{false};
  27684. };
  27685. inline std::unique_ptr<Client> make_client(const std::string &host,
  27686. ProxyAndTargetServers &s) {
  27687. auto cli = detail::make_unique<Client>(host, s.target_port());
  27688. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27689. cli->set_proxy("127.0.0.1", s.proxy_port());
  27690. return cli;
  27691. }
  27692. } // namespace no_proxy_test
  27693. using no_proxy_test::make_client;
  27694. using no_proxy_test::ProxyAndTargetServers;
  27695. // A stream request carries the credentials a buffered request does
  27696. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27697. no_proxy_test::ScopedServer origin;
  27698. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27699. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27700. });
  27701. origin.listen();
  27702. Client cli("127.0.0.1", origin.port());
  27703. cli.set_basic_auth("user", "pass");
  27704. auto handle = cli.open_stream("GET", "/x");
  27705. ASSERT_TRUE(handle.is_valid());
  27706. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27707. Client bearer("127.0.0.1", origin.port());
  27708. bearer.set_bearer_token_auth("tok");
  27709. auto handle2 = bearer.open_stream("GET", "/x");
  27710. ASSERT_TRUE(handle2.is_valid());
  27711. EXPECT_EQ("Bearer tok", read_all(handle2));
  27712. }
  27713. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27714. // takes its own credentials, as for a buffered request
  27715. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27716. std::string target, authz, proxy_authz;
  27717. no_proxy_test::ScopedServer proxy;
  27718. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27719. target = req.target;
  27720. authz = req.get_header_value("Authorization");
  27721. proxy_authz = req.get_header_value("Proxy-Authorization");
  27722. res.set_content("ok", "text/plain");
  27723. });
  27724. proxy.listen();
  27725. Client cli("origin.example", 8080);
  27726. cli.set_proxy("127.0.0.1", proxy.port());
  27727. cli.set_proxy_basic_auth("puser", "ppass");
  27728. cli.set_basic_auth("user", "pass");
  27729. auto handle = cli.open_stream("GET", "/x");
  27730. ASSERT_TRUE(handle.is_valid());
  27731. EXPECT_EQ("ok", read_all(handle));
  27732. EXPECT_EQ("http://origin.example:8080/x", target);
  27733. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27734. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27735. }
  27736. // In absolute-form the path follows the authority, so a path that does not
  27737. // begin with '/' would make the proxy connect to another host
  27738. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27739. std::vector<std::string> targets;
  27740. no_proxy_test::ScopedServer proxy;
  27741. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27742. targets.push_back(req.target);
  27743. res.set_content("ok", "text/plain");
  27744. });
  27745. proxy.listen();
  27746. Client cli("origin.example", 8080);
  27747. cli.set_proxy("127.0.0.1", proxy.port());
  27748. cli.set_basic_auth("user", "pass");
  27749. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27750. auto res = cli.Get(path);
  27751. EXPECT_FALSE(res) << path;
  27752. auto handle = cli.open_stream("GET", path);
  27753. EXPECT_FALSE(handle.is_valid()) << path;
  27754. }
  27755. EXPECT_TRUE(targets.empty());
  27756. auto res = cli.Get("/x");
  27757. ASSERT_TRUE(res);
  27758. ASSERT_EQ(1u, targets.size());
  27759. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27760. }
  27761. TEST(NoProxyTest, ExactHostnameBypasses) {
  27762. ProxyAndTargetServers s;
  27763. auto cli = make_client("example.com", s);
  27764. cli->set_no_proxy({"example.com"});
  27765. auto res = cli->Get("/");
  27766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27767. EXPECT_EQ(0, s.proxy_hits());
  27768. EXPECT_EQ(1, s.target_hits());
  27769. }
  27770. TEST(NoProxyTest, SubdomainBypasses) {
  27771. ProxyAndTargetServers s;
  27772. auto cli = make_client("foo.example.com", s);
  27773. cli->set_no_proxy({"example.com"});
  27774. auto res = cli->Get("/");
  27775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27776. EXPECT_EQ(0, s.proxy_hits());
  27777. EXPECT_EQ(1, s.target_hits());
  27778. }
  27779. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27780. // Regression guard: "evilexample.com" must not be considered a subdomain
  27781. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27782. // check would let traffic bypass the proxy and leak credentials direct
  27783. // to the attacker host.
  27784. ProxyAndTargetServers s;
  27785. auto cli = make_client("evilexample.com", s);
  27786. cli->set_no_proxy({"example.com"});
  27787. auto res = cli->Get("/");
  27788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27789. EXPECT_GE(s.proxy_hits(), 1);
  27790. EXPECT_EQ(0, s.target_hits());
  27791. }
  27792. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27793. ProxyAndTargetServers s;
  27794. auto cli = make_client("example.com.evil.com", s);
  27795. cli->set_no_proxy({"example.com"});
  27796. auto res = cli->Get("/");
  27797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27798. EXPECT_GE(s.proxy_hits(), 1);
  27799. EXPECT_EQ(0, s.target_hits());
  27800. }
  27801. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27802. ProxyAndTargetServers s;
  27803. auto cli = make_client("example.com", s);
  27804. cli->set_no_proxy({".example.com"});
  27805. auto res = cli->Get("/");
  27806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27807. EXPECT_EQ(0, s.proxy_hits());
  27808. EXPECT_EQ(1, s.target_hits());
  27809. }
  27810. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27811. ProxyAndTargetServers s;
  27812. auto cli = make_client("Example.COM", s);
  27813. cli->set_no_proxy({"EXAMPLE.com"});
  27814. auto res = cli->Get("/");
  27815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27816. EXPECT_EQ(0, s.proxy_hits());
  27817. EXPECT_EQ(1, s.target_hits());
  27818. }
  27819. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27820. ProxyAndTargetServers s;
  27821. auto cli = make_client("example.com.", s);
  27822. cli->set_no_proxy({"example.com"});
  27823. auto res = cli->Get("/");
  27824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27825. EXPECT_EQ(0, s.proxy_hits());
  27826. EXPECT_EQ(1, s.target_hits());
  27827. }
  27828. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27829. // Trailing dots must be normalized on BOTH sides — host and entry.
  27830. // An implementation that only strips the host-side trailing dot would
  27831. // fail to match host "example.com" against entry "example.com." because
  27832. // a literal substring search would compare 11 chars against 12.
  27833. ProxyAndTargetServers s;
  27834. auto cli = make_client("example.com", s);
  27835. cli->set_no_proxy({"example.com."});
  27836. auto res = cli->Get("/");
  27837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27838. EXPECT_EQ(0, s.proxy_hits());
  27839. EXPECT_EQ(1, s.target_hits());
  27840. }
  27841. TEST(NoProxyTest, WildcardBypassesEverything) {
  27842. ProxyAndTargetServers s;
  27843. auto cli = make_client("anything.invalid.test", s);
  27844. cli->set_no_proxy({"*"});
  27845. auto res = cli->Get("/");
  27846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27847. EXPECT_EQ(0, s.proxy_hits());
  27848. EXPECT_EQ(1, s.target_hits());
  27849. }
  27850. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27851. ProxyAndTargetServers s;
  27852. Client cli("127.0.0.1", s.target_port());
  27853. cli.set_proxy("127.0.0.1", s.proxy_port());
  27854. cli.set_no_proxy({"127.0.0.1"});
  27855. auto res = cli.Get("/");
  27856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27857. EXPECT_EQ(0, s.proxy_hits());
  27858. EXPECT_EQ(1, s.target_hits());
  27859. }
  27860. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27861. ProxyAndTargetServers s;
  27862. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27863. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27864. cli.set_proxy("127.0.0.1", s.proxy_port());
  27865. cli.set_no_proxy({"::1"});
  27866. auto res = cli.Get("/");
  27867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27868. EXPECT_EQ(0, s.proxy_hits());
  27869. EXPECT_EQ(1, s.target_hits());
  27870. }
  27871. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27872. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27873. // must still be recognized as IPv6 for CIDR matching. Implementations
  27874. // that detect IPv6 only when the host begins with '[' would parse the
  27875. // host as a hostname and miss the match.
  27876. ProxyAndTargetServers s;
  27877. Client cli("fe80::1", s.target_port());
  27878. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27879. cli.set_proxy("127.0.0.1", s.proxy_port());
  27880. cli.set_no_proxy({"fe80::/10"});
  27881. auto res = cli.Get("/");
  27882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27883. EXPECT_EQ(0, s.proxy_hits());
  27884. EXPECT_EQ(1, s.target_hits());
  27885. }
  27886. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  27887. ProxyAndTargetServers s;
  27888. Client cli("::1", s.target_port());
  27889. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27890. cli.set_proxy("127.0.0.1", s.proxy_port());
  27891. cli.set_no_proxy({"[::1]"});
  27892. auto res = cli.Get("/");
  27893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27894. EXPECT_EQ(0, s.proxy_hits());
  27895. EXPECT_EQ(1, s.target_hits());
  27896. }
  27897. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27898. ProxyAndTargetServers s;
  27899. Client cli("fe80::1", s.target_port());
  27900. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27901. cli.set_proxy("127.0.0.1", s.proxy_port());
  27902. cli.set_no_proxy({"[fe80::]/10"});
  27903. auto res = cli.Get("/");
  27904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27905. EXPECT_EQ(0, s.proxy_hits());
  27906. EXPECT_EQ(1, s.target_hits());
  27907. }
  27908. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27909. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27910. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27911. // tricks via address-family conversion.
  27912. ProxyAndTargetServers s;
  27913. Client cli("::ffff:127.0.0.1", s.target_port());
  27914. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27915. cli.set_proxy("127.0.0.1", s.proxy_port());
  27916. cli.set_no_proxy({"127.0.0.1"});
  27917. auto res = cli.Get("/");
  27918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27919. EXPECT_GE(s.proxy_hits(), 1);
  27920. EXPECT_EQ(0, s.target_hits());
  27921. }
  27922. TEST(NoProxyTest, IPv4CidrMatch) {
  27923. ProxyAndTargetServers s;
  27924. Client cli("127.0.0.1", s.target_port());
  27925. cli.set_proxy("127.0.0.1", s.proxy_port());
  27926. cli.set_no_proxy({"127.0.0.0/8"});
  27927. auto res = cli.Get("/");
  27928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27929. EXPECT_EQ(0, s.proxy_hits());
  27930. EXPECT_EQ(1, s.target_hits());
  27931. }
  27932. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27933. ProxyAndTargetServers s;
  27934. Client cli("127.0.0.1", s.target_port());
  27935. cli.set_proxy("127.0.0.1", s.proxy_port());
  27936. cli.set_no_proxy({"10.0.0.0/8"});
  27937. auto res = cli.Get("/");
  27938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27939. EXPECT_GE(s.proxy_hits(), 1);
  27940. EXPECT_EQ(0, s.target_hits());
  27941. }
  27942. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27943. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27944. // IPv4 target matches.
  27945. ProxyAndTargetServers s;
  27946. Client cli("127.0.0.1", s.target_port());
  27947. cli.set_proxy("127.0.0.1", s.proxy_port());
  27948. cli.set_no_proxy({"0.0.0.0/0"});
  27949. auto res = cli.Get("/");
  27950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27951. EXPECT_EQ(0, s.proxy_hits());
  27952. EXPECT_EQ(1, s.target_hits());
  27953. }
  27954. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  27955. ProxyAndTargetServers s;
  27956. Client cli("127.0.0.1", s.target_port());
  27957. cli.set_proxy("127.0.0.1", s.proxy_port());
  27958. cli.set_no_proxy({"127.0.0.1"});
  27959. auto res = cli.Get("/");
  27960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27961. EXPECT_EQ(0, s.proxy_hits());
  27962. EXPECT_EQ(1, s.target_hits());
  27963. }
  27964. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27965. ProxyAndTargetServers s;
  27966. Client cli("127.0.0.1", s.target_port());
  27967. cli.set_proxy("127.0.0.1", s.proxy_port());
  27968. cli.set_no_proxy({"127.0.0.0/33"});
  27969. auto res = cli.Get("/");
  27970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27971. EXPECT_GE(s.proxy_hits(), 1);
  27972. EXPECT_EQ(0, s.target_hits());
  27973. }
  27974. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27975. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27976. ProxyAndTargetServers s;
  27977. Client cli("127.0.0.1", s.target_port());
  27978. cli.set_proxy("127.0.0.1", s.proxy_port());
  27979. cli.set_no_proxy({"127.0.0.1/"});
  27980. auto res = cli.Get("/");
  27981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27982. EXPECT_GE(s.proxy_hits(), 1);
  27983. EXPECT_EQ(0, s.target_hits());
  27984. }
  27985. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  27986. ProxyAndTargetServers s;
  27987. auto cli = make_client("internal.corp", s);
  27988. cli->set_proxy_basic_auth("u", "p");
  27989. cli->set_no_proxy({"internal.corp"});
  27990. auto res = cli->Get("/");
  27991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27992. EXPECT_EQ(1, s.target_hits());
  27993. EXPECT_EQ(0, s.proxy_hits());
  27994. EXPECT_FALSE(s.last_had_proxy_authz())
  27995. << "Proxy-Authorization must not be sent direct to the target";
  27996. }
  27997. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27998. ProxyAndTargetServers s;
  27999. auto cli = make_client("public.example", s);
  28000. cli->set_proxy_basic_auth("u", "p");
  28001. cli->set_no_proxy({"internal.corp"}); // does not match
  28002. auto res = cli->Get("/");
  28003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28004. EXPECT_GE(s.proxy_hits(), 1);
  28005. EXPECT_TRUE(s.last_had_proxy_authz());
  28006. }
  28007. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  28008. std::atomic<int> hits{0};
  28009. std::atomic<int> hits_with_authz{0};
  28010. no_proxy_test::ScopedServer proxy_mock;
  28011. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28012. hits++;
  28013. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  28014. if (req.target.find("/redir") != std::string::npos) {
  28015. res.set_redirect("http://other.example/landed");
  28016. } else {
  28017. res.set_content("via-proxy", "text/plain");
  28018. }
  28019. });
  28020. proxy_mock.listen();
  28021. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  28022. hits = 0;
  28023. hits_with_authz = 0;
  28024. Client cli("public.example", 80);
  28025. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28026. cli.set_proxy_basic_auth(c.first, c.second);
  28027. cli.set_follow_location(true);
  28028. // The redirect to another host goes through the proxy as well
  28029. auto res = cli.Get("/redir");
  28030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28031. EXPECT_EQ(2, hits.load());
  28032. EXPECT_EQ(2, hits_with_authz.load());
  28033. }
  28034. }
  28035. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  28036. ProxyAndTargetServers s;
  28037. auto cli = make_client("anything.test", s);
  28038. auto res = cli->Get("/");
  28039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28040. EXPECT_GE(s.proxy_hits(), 1);
  28041. EXPECT_EQ(0, s.target_hits());
  28042. }
  28043. TEST(NoProxyTest, PortSpecificEntryRejected) {
  28044. ProxyAndTargetServers s;
  28045. auto cli = make_client("example.com", s);
  28046. cli->set_no_proxy({"example.com:8080"});
  28047. auto res = cli->Get("/");
  28048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28049. EXPECT_GE(s.proxy_hits(), 1);
  28050. EXPECT_EQ(0, s.target_hits());
  28051. }
  28052. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  28053. ProxyAndTargetServers s;
  28054. auto cli = make_client("anything.test", s);
  28055. cli->set_no_proxy({"", " ", "\t"});
  28056. auto res = cli->Get("/");
  28057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28058. EXPECT_GE(s.proxy_hits(), 1);
  28059. EXPECT_EQ(0, s.target_hits());
  28060. }
  28061. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  28062. // An entry with leading/trailing whitespace must still match — env-style
  28063. // values are commonly pasted with stray spaces and an implementation
  28064. // that feeds the raw token directly to inet_pton would fail to match
  28065. // valid CIDRs because of the spaces.
  28066. ProxyAndTargetServers s;
  28067. Client cli("127.0.0.1", s.target_port());
  28068. cli.set_proxy("127.0.0.1", s.proxy_port());
  28069. cli.set_no_proxy({" 127.0.0.0/8 "});
  28070. auto res = cli.Get("/");
  28071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28072. EXPECT_EQ(0, s.proxy_hits());
  28073. EXPECT_EQ(1, s.target_hits());
  28074. }
  28075. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  28076. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  28077. // go direct and must NOT carry Proxy-Authorization.
  28078. std::atomic<int> proxy_hits{0};
  28079. std::atomic<int> target_hits{0};
  28080. std::atomic<bool> target_saw_authz{false};
  28081. no_proxy_test::ScopedServer proxy_mock, target;
  28082. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28083. proxy_hits++;
  28084. res.status = 302;
  28085. res.set_header("Location", "http://127.0.0.1:" +
  28086. std::to_string(target.port()) + "/landed");
  28087. });
  28088. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28089. target_hits++;
  28090. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  28091. res.set_content("direct", "text/plain");
  28092. });
  28093. proxy_mock.listen();
  28094. target.listen();
  28095. Client cli("public.example", target.port());
  28096. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28097. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28098. cli.set_proxy_basic_auth("u", "p");
  28099. cli.set_no_proxy({"127.0.0.1"});
  28100. cli.set_follow_location(true);
  28101. auto res = cli.Get("/redir");
  28102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28103. EXPECT_GE(proxy_hits.load(), 1);
  28104. EXPECT_GE(target_hits.load(), 1);
  28105. EXPECT_FALSE(target_saw_authz.load());
  28106. }
  28107. #ifdef CPPHTTPLIB_SSL_ENABLED
  28108. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  28109. // Direct origin replying 407 must not trigger the digest retry; otherwise
  28110. // proxy creds would be sent to the (possibly hostile) origin.
  28111. std::atomic<int> target_hits{0};
  28112. std::atomic<bool> target_saw_proxy_authz{false};
  28113. no_proxy_test::ScopedServer target;
  28114. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28115. target_hits++;
  28116. if (req.has_header("Proxy-Authorization")) {
  28117. target_saw_proxy_authz = true;
  28118. }
  28119. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28120. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  28121. "nonce=\"abc\", algorithm=MD5");
  28122. });
  28123. target.listen();
  28124. // The proxy address is set to the target's port: the bypass MUST kick in;
  28125. // if it doesn't, the test still routes "via proxy" to the same server and
  28126. // the Proxy-Authorization assertion below catches the leak.
  28127. Client cli("evil.example", target.port());
  28128. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  28129. cli.set_proxy("127.0.0.1", target.port());
  28130. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28131. cli.set_no_proxy({"evil.example"});
  28132. auto res = cli.Get("/x");
  28133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28134. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28135. EXPECT_EQ(1, target_hits.load());
  28136. EXPECT_FALSE(target_saw_proxy_authz.load());
  28137. }
  28138. #endif
  28139. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  28140. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  28141. std::atomic<int> proxy_hits{0};
  28142. std::atomic<int> bypass_hits{0};
  28143. std::atomic<bool> proxy_saw_c_url{false};
  28144. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  28145. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28146. proxy_hits++;
  28147. if (req.path.find("/start") != std::string::npos) {
  28148. res.status = 302;
  28149. res.set_header("Location", "http://127.0.0.1:" +
  28150. std::to_string(bypass_server.port()) +
  28151. "/middle");
  28152. return;
  28153. }
  28154. if (req.path.find("/end") != std::string::npos) {
  28155. proxy_saw_c_url = true;
  28156. res.set_content("c-via-proxy", "text/plain");
  28157. return;
  28158. }
  28159. res.set_content("unexpected", "text/plain");
  28160. });
  28161. // public.example's "advertised" port is arbitrary (the request never lands
  28162. // there — it goes through the proxy), but use a dynamic value to stay
  28163. // friendly with sharded parallel runs.
  28164. int public_port = bypass_server.port();
  28165. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  28166. bypass_hits++;
  28167. res.status = 302;
  28168. res.set_header("Location", "http://public.example:" +
  28169. std::to_string(public_port) + "/end");
  28170. });
  28171. proxy_mock.listen();
  28172. bypass_server.listen();
  28173. Client cli("public.example", public_port);
  28174. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28175. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28176. cli.set_no_proxy({"127.0.0.1"});
  28177. cli.set_follow_location(true);
  28178. auto res = cli.Get("/start");
  28179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28180. EXPECT_EQ(StatusCode::OK_200, res->status);
  28181. EXPECT_EQ("c-via-proxy", res->body);
  28182. EXPECT_GE(proxy_hits.load(), 2);
  28183. EXPECT_GE(bypass_hits.load(), 1);
  28184. EXPECT_TRUE(proxy_saw_c_url.load());
  28185. }
  28186. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  28187. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28188. // request reconnects to the correct endpoint.
  28189. std::atomic<int> proxy_hits{0};
  28190. std::atomic<int> target_hits{0};
  28191. no_proxy_test::ScopedServer proxy_mock, target;
  28192. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28193. proxy_hits++;
  28194. res.set_content("via-proxy", "text/plain");
  28195. });
  28196. target.svr().Get(".*", [&](const Request &, Response &res) {
  28197. target_hits++;
  28198. res.set_content("direct", "text/plain");
  28199. });
  28200. proxy_mock.listen();
  28201. target.listen();
  28202. Client cli("public.example", target.port());
  28203. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28204. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28205. cli.set_keep_alive(true);
  28206. auto res1 = cli.Get("/a");
  28207. ASSERT_TRUE(res1);
  28208. EXPECT_EQ("via-proxy", res1->body);
  28209. EXPECT_EQ(1, proxy_hits.load());
  28210. EXPECT_EQ(0, target_hits.load());
  28211. cli.set_no_proxy({"public.example"});
  28212. auto res2 = cli.Get("/b");
  28213. ASSERT_TRUE(res2);
  28214. EXPECT_EQ("direct", res2->body);
  28215. EXPECT_EQ(1, proxy_hits.load());
  28216. EXPECT_EQ(1, target_hits.load());
  28217. }
  28218. // Forward declarations (see the base64_encode note).
  28219. namespace httplib {
  28220. namespace detail {
  28221. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28222. int shutdown_socket(socket_t sock) noexcept;
  28223. } // namespace detail
  28224. } // namespace httplib
  28225. namespace proxy_tunnel_test {
  28226. const char *const kTunnelEstablished =
  28227. "HTTP/1.1 200 Connection established\r\n\r\n";
  28228. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28229. using ConnectReply = std::function<std::string(const std::string &head)>;
  28230. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28231. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28232. class ScopedConnectProxy {
  28233. public:
  28234. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28235. : forward_port_(forward_port), reply_(std::move(reply)) {
  28236. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28237. if (listen_sock_ == INVALID_SOCKET) { return; }
  28238. auto a = loopback(0);
  28239. auto addr = reinterpret_cast<sockaddr *>(&a);
  28240. socklen_t alen = sizeof(a);
  28241. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28242. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28243. ::listen(listen_sock_, 4) != 0) {
  28244. return;
  28245. }
  28246. port_ = ntohs(a.sin_port);
  28247. th_ = std::thread([this] { run(); });
  28248. }
  28249. ~ScopedConnectProxy() {
  28250. if (th_.joinable()) {
  28251. stop_ = true;
  28252. auto wake = connect_to(port_);
  28253. th_.join();
  28254. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28255. }
  28256. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28257. }
  28258. int port() const { return port_; }
  28259. int connect_hits() const { return connect_hits_.load(); }
  28260. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28261. std::string connect_request() const {
  28262. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28263. return connect_request_;
  28264. }
  28265. private:
  28266. static sockaddr_in loopback(int port) {
  28267. sockaddr_in a{};
  28268. a.sin_family = AF_INET;
  28269. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28270. a.sin_port = htons(static_cast<unsigned short>(port));
  28271. return a;
  28272. }
  28273. static socket_t connect_to(int port) {
  28274. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28275. if (sock == INVALID_SOCKET) { return sock; }
  28276. auto a = loopback(port);
  28277. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28278. detail::close_socket(sock);
  28279. return INVALID_SOCKET;
  28280. }
  28281. return sock;
  28282. }
  28283. static bool send_all(socket_t sock, const char *data, size_t size) {
  28284. while (size > 0) {
  28285. auto n = detail::send_socket(sock, data, size, 0);
  28286. if (n <= 0) { return false; }
  28287. data += n;
  28288. size -= static_cast<size_t>(n);
  28289. }
  28290. return true;
  28291. }
  28292. void run() {
  28293. for (;;) {
  28294. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28295. if (stop_) {
  28296. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28297. return;
  28298. }
  28299. if (client == INVALID_SOCKET) { continue; }
  28300. serve(client);
  28301. detail::close_socket(client);
  28302. }
  28303. }
  28304. void serve(socket_t client) {
  28305. std::string head;
  28306. char buf[2048];
  28307. while (head.find("\r\n\r\n") == std::string::npos) {
  28308. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28309. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28310. if (n <= 0) { return; }
  28311. head.append(buf, static_cast<size_t>(n));
  28312. }
  28313. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28314. connect_hits_++;
  28315. {
  28316. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28317. connect_request_ = head;
  28318. }
  28319. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28320. if (!send_all(client, res.data(), res.size()) ||
  28321. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28322. return;
  28323. }
  28324. auto origin = connect_to(forward_port_);
  28325. if (origin == INVALID_SOCKET) { return; }
  28326. // When either side stops, shut both down so the other pump returns too.
  28327. auto pump = [&](socket_t from, socket_t to) {
  28328. char b[8192];
  28329. for (;;) {
  28330. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28331. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28332. }
  28333. detail::shutdown_socket(client);
  28334. detail::shutdown_socket(origin);
  28335. };
  28336. std::thread up([&] { pump(client, origin); });
  28337. pump(origin, client);
  28338. up.join();
  28339. detail::close_socket(origin);
  28340. }
  28341. int forward_port_;
  28342. ConnectReply reply_;
  28343. socket_t listen_sock_ = INVALID_SOCKET;
  28344. int port_ = 0;
  28345. std::thread th_;
  28346. std::atomic<bool> stop_{false};
  28347. std::atomic<int> connect_hits_{0};
  28348. mutable std::mutex connect_request_mutex_;
  28349. std::string connect_request_;
  28350. };
  28351. } // namespace proxy_tunnel_test
  28352. #ifdef CPPHTTPLIB_SSL_ENABLED
  28353. namespace proxy_tunnel_test {
  28354. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28355. class ScopedSSLServer {
  28356. public:
  28357. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28358. port_ = svr_.bind_to_any_port("127.0.0.1");
  28359. }
  28360. ~ScopedSSLServer() {
  28361. svr_.stop();
  28362. if (th_.joinable()) { th_.join(); }
  28363. }
  28364. SSLServer &svr() { return svr_; }
  28365. int port() const { return port_; }
  28366. void listen() {
  28367. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28368. svr_.wait_until_ready();
  28369. }
  28370. private:
  28371. SSLServer svr_;
  28372. std::thread th_;
  28373. int port_ = 0;
  28374. };
  28375. // Sends one request through the CONNECT proxy to the TLS origin with a
  28376. // credential configured for each hop, and checks that each credential reaches
  28377. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28378. // origin's (every header in origin_headers) on the tunnelled request.
  28379. void CredentialsStayWithTheirHop(
  28380. const std::function<void(SSLClient &)> &set_credentials,
  28381. const std::string &scheme,
  28382. const std::vector<std::string> &origin_headers = {"Authorization"},
  28383. bool stream = false) {
  28384. std::atomic<int> origin_hits{0};
  28385. std::atomic<bool> origin_saw_proxy_authz{false};
  28386. std::atomic<bool> origin_saw_headers{false};
  28387. ScopedSSLServer origin;
  28388. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28389. origin_hits++;
  28390. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28391. origin_saw_headers =
  28392. std::all_of(origin_headers.begin(), origin_headers.end(),
  28393. [&](const std::string &h) { return req.has_header(h); });
  28394. res.set_content("ok", "text/plain");
  28395. });
  28396. origin.listen();
  28397. ScopedConnectProxy proxy(origin.port());
  28398. ASSERT_NE(0, proxy.port());
  28399. // Pinned to 127.0.0.1 for the same reason as the test below.
  28400. SSLClient cli("127.0.0.1", origin.port());
  28401. cli.enable_server_certificate_verification(false);
  28402. cli.set_proxy("127.0.0.1", proxy.port());
  28403. set_credentials(cli);
  28404. if (stream) {
  28405. auto handle = cli.open_stream("GET", "/x");
  28406. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28407. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28408. } else {
  28409. auto res = cli.Get("/x");
  28410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28411. EXPECT_EQ(StatusCode::OK_200, res->status);
  28412. }
  28413. EXPECT_EQ(1, origin_hits.load());
  28414. EXPECT_EQ(1, proxy.connect_hits());
  28415. EXPECT_TRUE(origin_saw_headers.load());
  28416. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28417. << "Proxy-Authorization must not be sent inside the tunnel";
  28418. auto connect_req = proxy.connect_request();
  28419. EXPECT_NE(std::string::npos,
  28420. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28421. for (const auto &h : origin_headers) {
  28422. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28423. << h << " must not be sent to the proxy on CONNECT";
  28424. }
  28425. }
  28426. } // namespace proxy_tunnel_test
  28427. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28428. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28429. [](SSLClient &cli) {
  28430. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28431. cli.set_basic_auth("origin-user", "origin-pass");
  28432. },
  28433. "Basic");
  28434. }
  28435. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28436. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28437. [](SSLClient &cli) {
  28438. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28439. cli.set_basic_auth("origin-user", "origin-pass");
  28440. },
  28441. "Basic", {"Authorization"}, true);
  28442. }
  28443. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28444. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28445. [](SSLClient &cli) {
  28446. cli.set_proxy_bearer_token_auth("proxy-token");
  28447. cli.set_bearer_token_auth("origin-token");
  28448. },
  28449. "Bearer");
  28450. }
  28451. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28452. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28453. [](SSLClient &cli) {
  28454. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28455. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28456. {"Cookie", "sid=origin-session"},
  28457. {"X-Api-Key", "origin-key"}});
  28458. },
  28459. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28460. }
  28461. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28462. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28463. // retry; otherwise proxy creds would be sent to the origin.
  28464. std::atomic<int> origin_hits{0};
  28465. std::atomic<bool> origin_saw_proxy_authz{false};
  28466. proxy_tunnel_test::ScopedSSLServer origin;
  28467. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28468. origin_hits++;
  28469. if (req.has_header("Proxy-Authorization")) {
  28470. origin_saw_proxy_authz = true;
  28471. }
  28472. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28473. res.set_header("Proxy-Authenticate",
  28474. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28475. "algorithm=MD5");
  28476. });
  28477. origin.listen();
  28478. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28479. ASSERT_NE(0, proxy.port());
  28480. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28481. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28482. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28483. // and answer with its own status, making this test flaky.
  28484. SSLClient cli("127.0.0.1", origin.port());
  28485. cli.enable_server_certificate_verification(false);
  28486. cli.set_proxy("127.0.0.1", proxy.port());
  28487. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28488. auto res = cli.Get("/x");
  28489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28490. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28491. EXPECT_EQ(1, origin_hits.load());
  28492. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28493. EXPECT_EQ(1, proxy.connect_hits());
  28494. }
  28495. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28496. std::string origin_sni;
  28497. std::string origin_host;
  28498. proxy_tunnel_test::ScopedSSLServer origin;
  28499. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28500. origin_sni = req.sni();
  28501. origin_host = req.get_header_value("Host");
  28502. res.set_content("ok", "text/plain");
  28503. });
  28504. origin.listen();
  28505. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28506. ASSERT_NE(0, proxy.port());
  28507. SSLClient cli("origin.example", origin.port());
  28508. cli.enable_server_certificate_verification(false);
  28509. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28510. cli.set_proxy("127.0.0.1", proxy.port());
  28511. auto res = cli.Get("/x");
  28512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28513. EXPECT_EQ(StatusCode::OK_200, res->status);
  28514. auto port = std::to_string(origin.port());
  28515. auto target = "127.0.0.1:" + port;
  28516. auto connect_req = proxy.connect_request();
  28517. EXPECT_EQ(1, proxy.connect_hits());
  28518. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28519. EXPECT_NE(std::string::npos,
  28520. connect_req.find("\r\nHost: " + target + "\r\n"));
  28521. EXPECT_EQ("origin.example", origin_sni);
  28522. EXPECT_EQ("origin.example:" + port, origin_host);
  28523. }
  28524. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28525. proxy_tunnel_test::ScopedSSLServer origin;
  28526. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28527. res.set_content("ok", "text/plain");
  28528. });
  28529. origin.listen();
  28530. proxy_tunnel_test::ScopedConnectProxy proxy(
  28531. origin.port(), [](const std::string &head) -> std::string {
  28532. if (head.find(
  28533. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28534. std::string::npos) {
  28535. return proxy_tunnel_test::kTunnelEstablished;
  28536. }
  28537. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28538. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28539. "nonce=\"abc\", algorithm=MD5\r\n"
  28540. "Content-Length: 0\r\n\r\n";
  28541. });
  28542. ASSERT_NE(0, proxy.port());
  28543. SSLClient cli("origin.example", origin.port());
  28544. cli.enable_server_certificate_verification(false);
  28545. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28546. cli.set_proxy("127.0.0.1", proxy.port());
  28547. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28548. auto res = cli.Get("/x");
  28549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28550. EXPECT_EQ(StatusCode::OK_200, res->status);
  28551. // The retried CONNECT is the one the proxy saw last.
  28552. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28553. auto connect_req = proxy.connect_request();
  28554. EXPECT_EQ(2, proxy.connect_hits());
  28555. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28556. EXPECT_NE(std::string::npos,
  28557. connect_req.find("\r\nHost: " + target + "\r\n"));
  28558. }
  28559. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28560. proxy_tunnel_test::ScopedSSLServer origin;
  28561. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28562. res.set_content("ok", "text/plain");
  28563. });
  28564. origin.listen();
  28565. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28566. ASSERT_NE(0, proxy.port());
  28567. SSLClient cli("origin.example", origin.port());
  28568. cli.enable_server_certificate_verification(false);
  28569. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28570. cli.set_proxy("127.0.0.1", proxy.port());
  28571. auto res = cli.Get("/x");
  28572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28573. EXPECT_EQ(StatusCode::OK_200, res->status);
  28574. auto target = "origin.example:" + std::to_string(origin.port());
  28575. auto connect_req = proxy.connect_request();
  28576. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28577. EXPECT_NE(std::string::npos,
  28578. connect_req.find("\r\nHost: " + target + "\r\n"));
  28579. }
  28580. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28581. proxy_tunnel_test::ScopedSSLServer origin;
  28582. auto port = std::to_string(origin.port());
  28583. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28584. res.set_redirect("https://next.example:" + port + "/y");
  28585. });
  28586. origin.svr().Get("/y", [](const Request &, Response &res) {
  28587. res.set_content("ok", "text/plain");
  28588. });
  28589. origin.listen();
  28590. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28591. ASSERT_NE(0, proxy.port());
  28592. SSLClient cli("origin.example", origin.port());
  28593. cli.enable_server_certificate_verification(false);
  28594. cli.set_tunnel_hostname_addr_map(
  28595. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28596. cli.set_proxy("127.0.0.1", proxy.port());
  28597. cli.set_follow_location(true);
  28598. auto res = cli.Get("/x");
  28599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28600. EXPECT_EQ("ok", res->body);
  28601. // The last CONNECT is the redirect client's.
  28602. ASSERT_EQ(2, proxy.connect_hits());
  28603. auto target = "127.0.0.1:" + port;
  28604. auto connect_req = proxy.connect_request();
  28605. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28606. EXPECT_NE(std::string::npos,
  28607. connect_req.find("\r\nHost: " + target + "\r\n"));
  28608. }
  28609. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28610. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28611. std::atomic<int> origin_hits{0};
  28612. proxy_tunnel_test::ScopedSSLServer origin;
  28613. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28614. origin_hits++;
  28615. res.set_content("ok", "text/plain");
  28616. });
  28617. origin.listen();
  28618. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28619. ASSERT_NE(0, proxy.port());
  28620. SSLClient cli("127.0.0.1", origin.port());
  28621. cli.enable_server_certificate_verification(false);
  28622. cli.set_proxy("127.0.0.1", proxy.port());
  28623. cli.set_keep_alive(true);
  28624. cli.set_session_verifier(
  28625. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28626. auto res = cli.Get("/x");
  28627. EXPECT_FALSE(res);
  28628. ASSERT_FALSE(cli.is_socket_open());
  28629. res = cli.Get("/x");
  28630. EXPECT_FALSE(res);
  28631. EXPECT_EQ(2, proxy.connect_hits());
  28632. auto handle = cli.open_stream("GET", "/x");
  28633. EXPECT_FALSE(handle.is_valid());
  28634. EXPECT_EQ(3, proxy.connect_hits());
  28635. EXPECT_EQ(0, origin_hits.load());
  28636. }
  28637. #endif
  28638. namespace proxy_tunnel_test {
  28639. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28640. // anything else gets a 407 with `challenge`.
  28641. ConnectReply require_proxy_auth(const std::string &expected,
  28642. const std::string &challenge) {
  28643. return [=](const std::string &head) -> std::string {
  28644. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28645. std::string::npos) {
  28646. return kTunnelEstablished;
  28647. }
  28648. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28649. "Proxy-Authenticate: " +
  28650. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28651. };
  28652. }
  28653. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28654. // request, then echoes.
  28655. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28656. ws.send(
  28657. "authorization:" + req.get_header_value("Authorization") +
  28658. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28659. std::string msg;
  28660. while (ws.read(msg)) {
  28661. ws.send(msg);
  28662. }
  28663. }
  28664. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28665. class ScopedWebSocketOrigin {
  28666. public:
  28667. ScopedWebSocketOrigin() {
  28668. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28669. server_.listen();
  28670. }
  28671. int port() const { return server_.port(); }
  28672. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28673. std::string url() const {
  28674. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28675. }
  28676. private:
  28677. no_proxy_test::ScopedServer server_;
  28678. };
  28679. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28680. // passed as a constructor header, and checks that each reaches only its hop.
  28681. void WebSocketCredentialsStayWithTheirHop(
  28682. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28683. const std::string &proxy_authz, const std::string &origin_authz) {
  28684. ScopedWebSocketOrigin origin;
  28685. ScopedConnectProxy proxy(
  28686. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28687. ASSERT_NE(0, proxy.port());
  28688. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28689. client.set_proxy("127.0.0.1", proxy.port());
  28690. set_proxy_credentials(client);
  28691. auto res = client.connect();
  28692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28693. std::string msg;
  28694. ASSERT_TRUE(client.read(msg));
  28695. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28696. client.close();
  28697. EXPECT_EQ(1, proxy.connect_hits());
  28698. EXPECT_EQ(std::string::npos,
  28699. proxy.connect_request().find("\r\nAuthorization: "))
  28700. << "origin credentials must not be sent to the proxy";
  28701. }
  28702. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28703. void WebSocketSetterCredentialsStayWithTheirHop(
  28704. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28705. const std::string &proxy_authz, const std::string &origin_authz) {
  28706. ScopedWebSocketOrigin origin;
  28707. ScopedConnectProxy proxy(
  28708. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28709. ASSERT_NE(0, proxy.port());
  28710. ws::WebSocketClient client(origin.url());
  28711. client.set_proxy("127.0.0.1", proxy.port());
  28712. set_credentials(client);
  28713. auto res = client.connect();
  28714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28715. std::string msg;
  28716. ASSERT_TRUE(client.read(msg));
  28717. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28718. client.close();
  28719. EXPECT_EQ(1, proxy.connect_hits());
  28720. EXPECT_EQ(std::string::npos,
  28721. proxy.connect_request().find("\r\nAuthorization: "))
  28722. << "origin credentials must not be sent to the proxy";
  28723. }
  28724. } // namespace proxy_tunnel_test
  28725. namespace {
  28726. // Connects `client` and returns the Authorization header its upgrade
  28727. // request carried, or "<failed>" when the connection could not be opened.
  28728. std::string websocket_authorization(ws::WebSocketClient &client) {
  28729. if (!client.connect()) { return "<failed>"; }
  28730. std::string msg;
  28731. if (!client.read(msg)) { return "<failed>"; }
  28732. client.close();
  28733. auto prefix = std::string("authorization:");
  28734. auto end = msg.find("|proxy-authorization:");
  28735. return msg.substr(prefix.size(), end - prefix.size());
  28736. }
  28737. } // namespace
  28738. TEST(WebSocketClientAuthTest, BasicAuth) {
  28739. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28740. ws::WebSocketClient client(origin.url());
  28741. client.set_basic_auth("user", "pass");
  28742. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28743. websocket_authorization(client));
  28744. }
  28745. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28746. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28747. ws::WebSocketClient client(origin.url());
  28748. client.set_basic_auth("user", "");
  28749. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28750. websocket_authorization(client));
  28751. }
  28752. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28753. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28754. ws::WebSocketClient client(origin.url());
  28755. client.set_bearer_token_auth("token123");
  28756. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28757. }
  28758. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28759. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28760. ws::WebSocketClient client(origin.url());
  28761. client.set_bearer_token_auth("token123");
  28762. client.set_basic_auth("user", "pass");
  28763. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28764. websocket_authorization(client));
  28765. }
  28766. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28767. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28768. ws::WebSocketClient client(origin.url(),
  28769. {{"Authorization", "Bearer from-header"}});
  28770. client.set_bearer_token_auth("from-setter");
  28771. client.set_basic_auth("user", "pass");
  28772. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28773. }
  28774. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28775. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28776. ws::WebSocketClient client(origin.url());
  28777. EXPECT_EQ("", websocket_authorization(client));
  28778. client.set_bearer_token_auth("first");
  28779. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28780. client.set_bearer_token_auth("second");
  28781. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28782. client.set_bearer_token_auth("");
  28783. EXPECT_EQ("", websocket_authorization(client));
  28784. }
  28785. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28786. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28787. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28788. ASSERT_NE(0, proxy.port());
  28789. ws::WebSocketClient client(origin.url());
  28790. client.set_proxy("127.0.0.1", proxy.port());
  28791. auto res = client.connect();
  28792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28793. std::string msg;
  28794. ASSERT_TRUE(client.read(msg));
  28795. ASSERT_TRUE(client.send("hello"));
  28796. ASSERT_TRUE(client.read(msg));
  28797. EXPECT_EQ("hello", msg);
  28798. client.close();
  28799. EXPECT_EQ(1, proxy.connect_hits());
  28800. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28801. auto connect_req = proxy.connect_request();
  28802. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28803. EXPECT_NE(std::string::npos,
  28804. connect_req.find("\r\nHost: " + target + "\r\n"));
  28805. }
  28806. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28807. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28808. [](ws::WebSocketClient &cli) {
  28809. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28810. },
  28811. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28812. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28813. }
  28814. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28815. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28816. [](ws::WebSocketClient &cli) {
  28817. cli.set_proxy_bearer_token_auth("proxy-token");
  28818. },
  28819. "Bearer proxy-token", "Bearer origin-token");
  28820. }
  28821. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28822. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28823. [](ws::WebSocketClient &cli) {
  28824. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28825. cli.set_basic_auth("origin-user", "origin-pass");
  28826. },
  28827. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28828. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28829. }
  28830. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28831. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28832. [](ws::WebSocketClient &cli) {
  28833. cli.set_proxy_bearer_token_auth("proxy-token");
  28834. cli.set_bearer_token_auth("origin-token");
  28835. },
  28836. "Bearer proxy-token", "Bearer origin-token");
  28837. }
  28838. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28839. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28840. proxy_tunnel_test::ScopedConnectProxy proxy(
  28841. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28842. "Basic " + detail::base64_encode("proxy-user:"),
  28843. "Basic realm=\"proxy\""));
  28844. ASSERT_NE(0, proxy.port());
  28845. ws::WebSocketClient client(origin.url());
  28846. client.set_proxy("127.0.0.1", proxy.port());
  28847. client.set_proxy_basic_auth("proxy-user", "");
  28848. auto res = client.connect();
  28849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28850. client.close();
  28851. EXPECT_EQ(1, proxy.connect_hits());
  28852. }
  28853. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28854. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28855. proxy_tunnel_test::ScopedConnectProxy proxy(
  28856. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28857. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28858. ASSERT_NE(0, proxy.port());
  28859. ws::WebSocketClient client(origin.url());
  28860. client.set_proxy("127.0.0.1", proxy.port());
  28861. auto res = client.connect();
  28862. EXPECT_FALSE(res);
  28863. EXPECT_EQ(Error::ProxyConnection, res.error());
  28864. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28865. EXPECT_EQ("Basic realm=\"proxy\"",
  28866. res.get_header_value("Proxy-Authenticate"));
  28867. EXPECT_FALSE(client.is_open());
  28868. }
  28869. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28870. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28871. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28872. ASSERT_NE(0, proxy.port());
  28873. ws::WebSocketClient client(origin.url());
  28874. client.set_proxy("127.0.0.1", proxy.port());
  28875. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28876. client.set_no_proxy({"127.0.0.1"});
  28877. auto res = client.connect();
  28878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28879. std::string msg;
  28880. ASSERT_TRUE(client.read(msg));
  28881. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28882. << "proxy credentials must not reach a bypassed origin";
  28883. client.close();
  28884. EXPECT_EQ(0, proxy.connect_hits());
  28885. }
  28886. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28887. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28888. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28889. ASSERT_NE(0, proxy.port());
  28890. ws::WebSocketClient client(origin.url());
  28891. client.set_proxy("127.0.0.1", proxy.port());
  28892. ASSERT_TRUE(client.connect());
  28893. ASSERT_TRUE(client.connect());
  28894. client.close();
  28895. EXPECT_EQ(2, proxy.connect_hits());
  28896. }
  28897. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28898. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28899. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28900. ASSERT_NE(0, proxy.port());
  28901. auto port = std::to_string(origin.port());
  28902. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28903. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28904. client.set_proxy("127.0.0.1", proxy.port());
  28905. auto res = client.connect();
  28906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28907. std::string msg;
  28908. ASSERT_TRUE(client.read(msg));
  28909. client.close();
  28910. EXPECT_EQ(1, proxy.connect_hits());
  28911. auto target = "127.0.0.1:" + port;
  28912. auto connect_req = proxy.connect_request();
  28913. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28914. EXPECT_NE(std::string::npos,
  28915. connect_req.find("\r\nHost: " + target + "\r\n"));
  28916. }
  28917. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28918. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28919. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28920. ASSERT_NE(0, proxy.port());
  28921. auto port = std::to_string(origin.port());
  28922. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28923. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28924. client.set_proxy("127.0.0.1", proxy.port());
  28925. auto res = client.connect();
  28926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28927. client.close();
  28928. auto target = "origin.example:" + port;
  28929. auto connect_req = proxy.connect_request();
  28930. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28931. EXPECT_NE(std::string::npos,
  28932. connect_req.find("\r\nHost: " + target + "\r\n"));
  28933. }
  28934. #ifdef CPPHTTPLIB_SSL_ENABLED
  28935. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28936. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28937. proxy_tunnel_test::ScopedConnectProxy proxy(
  28938. origin.port(), [](const std::string &head) -> std::string {
  28939. if (head.find(
  28940. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28941. std::string::npos) {
  28942. return proxy_tunnel_test::kTunnelEstablished;
  28943. }
  28944. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28945. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28946. "nonce=\"abc\", algorithm=MD5\r\n"
  28947. "Content-Length: 0\r\n\r\n";
  28948. });
  28949. ASSERT_NE(0, proxy.port());
  28950. ws::WebSocketClient client(origin.url());
  28951. client.set_proxy("127.0.0.1", proxy.port());
  28952. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28953. auto res = client.connect();
  28954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28955. std::string msg;
  28956. ASSERT_TRUE(client.read(msg));
  28957. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28958. client.close();
  28959. EXPECT_EQ(2, proxy.connect_hits());
  28960. }
  28961. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28962. proxy_tunnel_test::ScopedSSLServer origin;
  28963. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28964. origin.listen();
  28965. proxy_tunnel_test::ScopedConnectProxy proxy(
  28966. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28967. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28968. ASSERT_NE(0, proxy.port());
  28969. ws::WebSocketClient client(
  28970. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28971. client.enable_server_certificate_verification(false);
  28972. client.set_proxy("127.0.0.1", proxy.port());
  28973. client.set_proxy_bearer_token_auth("proxy-token");
  28974. auto res = client.connect();
  28975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28976. std::string msg;
  28977. ASSERT_TRUE(client.read(msg));
  28978. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28979. << "Proxy-Authorization must not be sent inside the tunnel";
  28980. client.close();
  28981. EXPECT_EQ(1, proxy.connect_hits());
  28982. }
  28983. #endif
  28984. // ---------------------------------------------------------------------------
  28985. // Poller
  28986. // ---------------------------------------------------------------------------
  28987. namespace poller_test {
  28988. struct PollerBackend {
  28989. const char *name;
  28990. std::unique_ptr<detail::Poller> (*create)();
  28991. };
  28992. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  28993. *os << backend.name;
  28994. }
  28995. // Every backend runs the same contract tests. A new one is added here only.
  28996. std::vector<PollerBackend> poller_backends() {
  28997. return {
  28998. {"poll", &detail::PollPoller::create},
  28999. #ifdef __linux__
  29000. {"epoll", &detail::EpollPoller::create},
  29001. #endif
  29002. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  29003. {"kqueue", &detail::KqueuePoller::create},
  29004. #endif
  29005. };
  29006. }
  29007. // A descriptor whose readability the test controls.
  29008. struct TestSocketPair {
  29009. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  29010. TestSocketPair() { detail::create_socket_pair(fd); }
  29011. ~TestSocketPair() {
  29012. for (auto s : fd) {
  29013. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  29014. }
  29015. }
  29016. bool ok() const { return fd[0] != INVALID_SOCKET; }
  29017. socket_t reader() const { return fd[0]; }
  29018. void make_readable() {
  29019. const char c = 1;
  29020. detail::send_socket(fd[1], &c, 1, 0);
  29021. }
  29022. void close_writer() {
  29023. detail::close_socket(fd[1]);
  29024. fd[1] = INVALID_SOCKET;
  29025. }
  29026. };
  29027. using Tokens = std::vector<detail::Poller::Token>;
  29028. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  29029. protected:
  29030. void SetUp() override {
  29031. poller_ = GetParam().create();
  29032. ASSERT_TRUE(poller_ != nullptr);
  29033. }
  29034. Tokens wait_for(int timeout_ms) {
  29035. Tokens ready;
  29036. poller_->wait(timeout_ms, ready);
  29037. std::sort(ready.begin(), ready.end());
  29038. return ready;
  29039. }
  29040. std::unique_ptr<detail::Poller> poller_;
  29041. };
  29042. } // namespace poller_test
  29043. using poller_test::PollerTest;
  29044. using poller_test::TestSocketPair;
  29045. using poller_test::Tokens;
  29046. INSTANTIATE_TEST_SUITE_P(
  29047. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  29048. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  29049. return std::string(p.param.name);
  29050. });
  29051. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  29052. TestSocketPair sp;
  29053. ASSERT_TRUE(sp.ok());
  29054. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  29055. EXPECT_EQ(Tokens{}, wait_for(0));
  29056. sp.make_readable();
  29057. EXPECT_EQ(Tokens{7}, wait_for(1000));
  29058. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  29059. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  29060. EXPECT_EQ(Tokens{8}, wait_for(1000));
  29061. }
  29062. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  29063. TestSocketPair sp;
  29064. ASSERT_TRUE(sp.ok());
  29065. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29066. poller_->disarm(sp.reader());
  29067. poller_->disarm(sp.reader()); // disarming twice is harmless
  29068. sp.make_readable();
  29069. EXPECT_EQ(Tokens{}, wait_for(0));
  29070. }
  29071. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  29072. TestSocketPair sp;
  29073. ASSERT_TRUE(sp.ok());
  29074. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29075. auto start = std::chrono::steady_clock::now();
  29076. EXPECT_EQ(Tokens{}, wait_for(30));
  29077. auto elapsed = std::chrono::steady_clock::now() - start;
  29078. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  29079. EXPECT_LT(elapsed, std::chrono::seconds(1));
  29080. }
  29081. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  29082. std::vector<std::unique_ptr<TestSocketPair>> sps;
  29083. for (detail::Poller::Token i = 0; i < 8; i++) {
  29084. sps.emplace_back(new TestSocketPair());
  29085. ASSERT_TRUE(sps.back()->ok());
  29086. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  29087. }
  29088. sps[0]->make_readable();
  29089. sps[3]->make_readable();
  29090. sps[7]->make_readable();
  29091. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  29092. // The others are still armed, the delivered ones are not.
  29093. sps[1]->make_readable();
  29094. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29095. EXPECT_EQ(Tokens{}, wait_for(0));
  29096. }
  29097. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  29098. TestSocketPair s0, s1, s2;
  29099. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  29100. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  29101. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  29102. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  29103. // A delivery may move another entry inside the poller.
  29104. s0.make_readable();
  29105. EXPECT_EQ(Tokens{0}, wait_for(1000));
  29106. // The entries left must still be found by descriptor.
  29107. poller_->disarm(s2.reader());
  29108. s1.make_readable();
  29109. s2.make_readable();
  29110. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29111. }
  29112. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  29113. TestSocketPair sp;
  29114. ASSERT_TRUE(sp.ok());
  29115. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  29116. sp.close_writer();
  29117. EXPECT_EQ(Tokens{5}, wait_for(1000));
  29118. char c;
  29119. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  29120. }
  29121. TEST_P(PollerTest, WakeEndsABlockedWait) {
  29122. std::thread waker([&] {
  29123. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  29124. poller_->wake();
  29125. });
  29126. Tokens ready;
  29127. auto start = std::chrono::steady_clock::now();
  29128. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  29129. waker.join();
  29130. EXPECT_TRUE(ready.empty());
  29131. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  29132. }
  29133. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  29134. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  29135. Tokens ready;
  29136. EXPECT_TRUE(poller_->wait(1000, ready));
  29137. }
  29138. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  29139. for (int i = 0; i < 1000; i++) {
  29140. poller_->wake();
  29141. }
  29142. Tokens ready;
  29143. EXPECT_TRUE(poller_->wait(0, ready));
  29144. EXPECT_FALSE(poller_->wait(0, ready));
  29145. poller_->wake();
  29146. EXPECT_TRUE(poller_->wait(0, ready));
  29147. }
  29148. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  29149. // Two threads publish changes and wake() after each, as a reactor's workers
  29150. // do. Every change must be seen without a wait() timing out. A lost wake()
  29151. // needs an unlucky interleaving, hence the rounds.
  29152. for (int round = 0; round < 5; round++) {
  29153. SCOPED_TRACE(round);
  29154. const int per_thread = 20000;
  29155. std::atomic<int> posted{0};
  29156. auto post = [&] {
  29157. for (int i = 0; i < per_thread; i++) {
  29158. posted++;
  29159. poller_->wake();
  29160. }
  29161. };
  29162. std::thread t1(post), t2(post);
  29163. auto lost = false;
  29164. Tokens ready;
  29165. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  29166. if (!poller_->wait(1000, ready)) {
  29167. lost = true;
  29168. break;
  29169. }
  29170. }
  29171. t1.join();
  29172. t2.join();
  29173. ASSERT_FALSE(lost);
  29174. }
  29175. }
  29176. TEST(PollerFactoryTest, MakePollerWorks) {
  29177. auto poller = detail::make_poller();
  29178. ASSERT_TRUE(poller != nullptr);
  29179. poller->wake();
  29180. std::vector<detail::Poller::Token> ready;
  29181. EXPECT_TRUE(poller->wait(1000, ready));
  29182. }
  29183. // ---------------------------------------------------------------------------
  29184. // Keep-alive parking
  29185. // ---------------------------------------------------------------------------
  29186. namespace parking_test {
  29187. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29188. // runs once the port is bound and listening, before the server accepts.
  29189. struct RunningServer {
  29190. explicit RunningServer(
  29191. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29192. : svr_(svr) {
  29193. port = svr_.bind_to_any_port("127.0.0.1");
  29194. if (before_listen) { before_listen(port); }
  29195. thread = std::thread([this] { svr_.listen_after_bind(); });
  29196. svr_.wait_until_ready();
  29197. }
  29198. ~RunningServer() {
  29199. svr_.stop();
  29200. if (thread.joinable()) { thread.join(); }
  29201. }
  29202. Server &svr_;
  29203. int port = 0;
  29204. std::thread thread;
  29205. };
  29206. struct Sockets {
  29207. std::vector<socket_t> socks;
  29208. ~Sockets() {
  29209. for (auto s : socks) {
  29210. detail::close_socket(s);
  29211. }
  29212. }
  29213. socket_t connect(int port) {
  29214. auto error = Error::Success;
  29215. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29216. false, false, nullptr, 2, 0, 2, 0, 2,
  29217. 0, std::string(), error);
  29218. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29219. return s;
  29220. }
  29221. };
  29222. std::chrono::steady_clock::time_point in_ms(int ms) {
  29223. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29224. }
  29225. bool readable_by(socket_t sock,
  29226. std::chrono::steady_clock::time_point deadline) {
  29227. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29228. deadline - std::chrono::steady_clock::now())
  29229. .count();
  29230. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29231. }
  29232. bool send_get(socket_t sock, const std::string &path = "/") {
  29233. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29234. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29235. static_cast<ssize_t>(req.size());
  29236. }
  29237. // Reads one response whose body is "ok".
  29238. bool receives_ok(socket_t sock, int timeout_ms) {
  29239. auto deadline = in_ms(timeout_ms);
  29240. std::string buf;
  29241. while (readable_by(sock, deadline)) {
  29242. char tmp[1024];
  29243. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29244. if (n <= 0) { return false; }
  29245. buf.append(tmp, static_cast<size_t>(n));
  29246. auto end = buf.find("\r\n\r\n");
  29247. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29248. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29249. buf.compare(end + 4, 2, "ok") == 0;
  29250. }
  29251. }
  29252. return false;
  29253. }
  29254. bool get_ok(socket_t sock, int timeout_ms) {
  29255. return send_get(sock) && receives_ok(sock, timeout_ms);
  29256. }
  29257. // Whether the server closes `sock` by `deadline`.
  29258. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29259. char c;
  29260. return readable_by(sock, deadline) &&
  29261. detail::read_socket(sock, &c, 1, 0) <= 0;
  29262. }
  29263. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29264. auto deadline = in_ms(timeout_ms);
  29265. while (!cond()) {
  29266. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29267. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29268. }
  29269. return true;
  29270. }
  29271. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29272. svr.new_task_queue = std::move(new_task_queue);
  29273. svr.set_keep_alive_parking(true);
  29274. svr.Get("/", [](const Request &, Response &res) {
  29275. res.set_content("ok", "text/plain");
  29276. });
  29277. }
  29278. std::function<TaskQueue *(void)> threads(size_t n) {
  29279. return [n] { return new ThreadPool(n); };
  29280. }
  29281. // Counts what the event loop managed to queue, so that a test can wait for it.
  29282. class CountingTaskQueue final : public TaskQueue {
  29283. public:
  29284. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29285. std::atomic<int> &full)
  29286. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29287. bool enqueue(std::function<void()> fn) override {
  29288. auto queued = pool_.enqueue([this, fn]() {
  29289. fn();
  29290. // Holds the worker back from taking the next job.
  29291. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29292. });
  29293. (queued ? ok_ : full_)++;
  29294. return queued;
  29295. }
  29296. void shutdown() override { pool_.shutdown(); }
  29297. std::atomic<int> pause_after_ms{0};
  29298. private:
  29299. ThreadPool pool_;
  29300. std::atomic<int> &ok_;
  29301. std::atomic<int> &full_;
  29302. };
  29303. // Holds handlers until it opens, or for 3 seconds at most.
  29304. class Gate {
  29305. public:
  29306. void wait() {
  29307. std::unique_lock<std::mutex> lock(m_);
  29308. entered_++;
  29309. cv_.notify_all();
  29310. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29311. }
  29312. void open() {
  29313. std::lock_guard<std::mutex> guard(m_);
  29314. open_ = true;
  29315. cv_.notify_all();
  29316. }
  29317. int entered() {
  29318. std::lock_guard<std::mutex> guard(m_);
  29319. return entered_;
  29320. }
  29321. private:
  29322. std::mutex m_;
  29323. std::condition_variable cv_;
  29324. bool open_ = false;
  29325. int entered_ = 0;
  29326. };
  29327. } // namespace parking_test
  29328. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29329. using namespace parking_test;
  29330. Server svr;
  29331. serve_ok(svr, threads(1));
  29332. RunningServer running(svr);
  29333. Sockets socks;
  29334. // One kept-alive connection that has been served, and many that have not
  29335. // sent anything yet. None of them may keep the only worker.
  29336. auto served = socks.connect(running.port);
  29337. ASSERT_TRUE(get_ok(served, 2000));
  29338. for (int i = 0; i < 49; i++) {
  29339. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29340. }
  29341. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29342. EXPECT_TRUE(get_ok(served, 1000));
  29343. }
  29344. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29345. using namespace parking_test;
  29346. Server svr;
  29347. serve_ok(svr, threads(1));
  29348. svr.set_keep_alive_timeout(1);
  29349. RunningServer running(svr);
  29350. Sockets socks;
  29351. for (int i = 0; i < 3; i++) {
  29352. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29353. }
  29354. // One worker waiting on each in turn would take about 3 seconds.
  29355. auto deadline = in_ms(2000);
  29356. for (auto s : socks.socks) {
  29357. EXPECT_TRUE(sees_eof(s, deadline));
  29358. }
  29359. }
  29360. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29361. using namespace parking_test;
  29362. std::atomic<int> queued{0}, full{0};
  29363. Server svr;
  29364. // One worker and room for one queued task.
  29365. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29366. Gate gate;
  29367. svr.Get("/block", [&](const Request &, Response &res) {
  29368. gate.wait();
  29369. res.set_content("ok", "text/plain");
  29370. });
  29371. RunningServer running(svr);
  29372. // Before the server stops, so that a failed run does not wait for the
  29373. // handler's timeout.
  29374. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29375. Sockets socks;
  29376. auto a = socks.connect(running.port);
  29377. ASSERT_TRUE(get_ok(a, 2000));
  29378. // B keeps the only worker busy.
  29379. auto b = socks.connect(running.port);
  29380. ASSERT_TRUE(send_get(b, "/block"));
  29381. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29382. // A new connection C fills the queue.
  29383. auto c = socks.connect(running.port);
  29384. ASSERT_TRUE(send_get(c));
  29385. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29386. // A's next request finds the queue full, but A has been served before, so it
  29387. // waits instead of being cut off.
  29388. ASSERT_TRUE(send_get(a));
  29389. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29390. gate.open();
  29391. EXPECT_TRUE(receives_ok(b, 2000));
  29392. EXPECT_TRUE(receives_ok(c, 2000));
  29393. EXPECT_TRUE(receives_ok(a, 2000));
  29394. }
  29395. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29396. using namespace parking_test;
  29397. std::atomic<int> queued{0}, full{0};
  29398. CountingTaskQueue *queue = nullptr;
  29399. Server svr;
  29400. // Two workers and room for one queued task.
  29401. serve_ok(svr,
  29402. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29403. Gate first, second;
  29404. svr.Get("/first", [&](const Request &, Response &res) {
  29405. first.wait();
  29406. res.set_content("ok", "text/plain");
  29407. });
  29408. svr.Get("/second", [&](const Request &, Response &res) {
  29409. second.wait();
  29410. res.set_content("ok", "text/plain");
  29411. });
  29412. RunningServer running(svr);
  29413. auto open_gates = detail::scope_exit([&] {
  29414. first.open();
  29415. second.open();
  29416. });
  29417. Sockets socks;
  29418. auto a = socks.connect(running.port);
  29419. ASSERT_TRUE(get_ok(a, 2000));
  29420. // B and D take both workers, and C fills the queue. One at a time: the
  29421. // queue has room for one job only until a worker takes it.
  29422. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29423. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29424. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29425. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29426. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29427. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29428. // A's next request waits in the backlog.
  29429. ASSERT_TRUE(send_get(a));
  29430. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29431. // B's worker finishes, then takes C off the queue only later, which makes
  29432. // room for A.
  29433. queue->pause_after_ms = 200;
  29434. first.open();
  29435. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29436. queue->pause_after_ms = 0;
  29437. second.open();
  29438. EXPECT_TRUE(receives_ok(a, 2000));
  29439. }
  29440. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29441. using namespace parking_test;
  29442. Server svr;
  29443. serve_ok(svr, threads(1));
  29444. svr.set_keep_alive_timeout(0);
  29445. // The request is on the socket before the server accepts the connection,
  29446. // so it does not race the 10 ms floor. Without the floor the connection is
  29447. // closed unread.
  29448. Sockets socks;
  29449. auto sock = INVALID_SOCKET;
  29450. RunningServer running(svr, [&](int port) {
  29451. sock = socks.connect(port);
  29452. send_get(sock);
  29453. });
  29454. EXPECT_TRUE(receives_ok(sock, 1000));
  29455. }
  29456. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29457. using namespace parking_test;
  29458. for (int round = 0; round < 5; round++) {
  29459. SCOPED_TRACE(round);
  29460. Server svr;
  29461. serve_ok(svr, threads(2));
  29462. RunningServer running(svr);
  29463. Sockets socks;
  29464. for (int i = 0; i < 20; i++) {
  29465. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29466. }
  29467. auto start = std::chrono::steady_clock::now();
  29468. svr.stop();
  29469. running.thread.join();
  29470. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29471. std::chrono::milliseconds(500));
  29472. auto deadline = in_ms(1000);
  29473. for (auto s : socks.socks) {
  29474. EXPECT_TRUE(sees_eof(s, deadline));
  29475. }
  29476. }
  29477. }
  29478. #ifdef CPPHTTPLIB_SSL_ENABLED
  29479. namespace parking_test {
  29480. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29481. // that has opened a connection ahead of time. Freeing the session sends no
  29482. // close_notify, so the connection stays quiet.
  29483. bool handshake_only(socket_t sock) {
  29484. auto ctx = tls::create_client_context();
  29485. tls::set_verify_client(ctx, false);
  29486. auto session = tls::create_session(ctx, sock);
  29487. auto se = detail::scope_exit([&] {
  29488. tls::free_session(session);
  29489. tls::free_context(ctx);
  29490. });
  29491. tls::TlsError err;
  29492. return session &&
  29493. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29494. }
  29495. Client tls_client(int port) {
  29496. Client cli("https://127.0.0.1:" + std::to_string(port));
  29497. cli.enable_server_certificate_verification(false);
  29498. cli.set_keep_alive(true);
  29499. cli.set_connection_timeout(1);
  29500. cli.set_read_timeout(1);
  29501. return cli;
  29502. }
  29503. bool tls_get_ok(Client &cli) {
  29504. auto res = cli.Get("/");
  29505. return res && res->body == "ok";
  29506. }
  29507. } // namespace parking_test
  29508. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29509. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29510. struct {
  29511. unsigned long version;
  29512. bool safe;
  29513. } cases[] = {
  29514. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29515. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29516. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29517. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29518. };
  29519. for (const auto &c : cases) {
  29520. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29521. << std::hex << c.version;
  29522. }
  29523. }
  29524. #endif
  29525. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29526. using namespace parking_test;
  29527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29528. ASSERT_TRUE(svr.is_valid());
  29529. serve_ok(svr, threads(1));
  29530. svr.set_read_timeout(1); // so that a failing run does not take long
  29531. RunningServer running(svr);
  29532. Sockets socks;
  29533. // One served connection, some that have not started their handshake, and
  29534. // one that has finished it and gone quiet. None may keep the only worker.
  29535. auto served = tls_client(running.port);
  29536. ASSERT_TRUE(tls_get_ok(served));
  29537. for (int i = 0; i < 10; i++) {
  29538. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29539. }
  29540. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29541. auto other = tls_client(running.port);
  29542. EXPECT_TRUE(tls_get_ok(other));
  29543. EXPECT_TRUE(tls_get_ok(served));
  29544. }
  29545. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29546. using namespace parking_test;
  29547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29548. ASSERT_TRUE(svr.is_valid());
  29549. serve_ok(svr, threads(1));
  29550. RunningServer running(svr);
  29551. Sockets socks;
  29552. auto plain = socks.connect(running.port);
  29553. ASSERT_TRUE(send_get(plain));
  29554. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29555. EXPECT_NE(0, svr.ssl_last_error());
  29556. }
  29557. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29558. using namespace parking_test;
  29559. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29560. ASSERT_TRUE(svr.is_valid());
  29561. serve_ok(svr, threads(2));
  29562. RunningServer running(svr);
  29563. std::vector<Client> clients;
  29564. for (int i = 0; i < 5; i++) {
  29565. clients.push_back(tls_client(running.port));
  29566. ASSERT_TRUE(tls_get_ok(clients.back()));
  29567. }
  29568. auto start = std::chrono::steady_clock::now();
  29569. svr.stop();
  29570. running.thread.join();
  29571. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29572. std::chrono::milliseconds(500));
  29573. }
  29574. #endif