test.cc 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690
  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. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  84. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  85. void shutdown(session_t session, bool graceful);
  86. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  87. namespace impl {
  88. SecTrustSettingsResult
  89. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  90. } // namespace impl
  91. #endif
  92. } // namespace tls
  93. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  94. namespace detail {
  95. bool ssl_free_buffers_is_safe(unsigned long version);
  96. } // namespace detail
  97. #endif
  98. } // namespace httplib
  99. #endif
  100. using namespace std;
  101. using namespace httplib;
  102. const char *HOST = "localhost";
  103. static int get_base_port() {
  104. const char *shard = getenv("GTEST_SHARD_INDEX");
  105. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  106. }
  107. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  108. // New standalone tests MUST use svr.bind_to_any_port() instead.
  109. const int PORT = get_base_port();
  110. const string LONG_QUERY_VALUE = string(25000, '@');
  111. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  112. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  113. const string TOO_LONG_QUERY_URL =
  114. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  115. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  116. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  117. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  118. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  119. return file.name == key;
  120. });
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return *it;
  123. #else
  124. if (it != items.end()) { return *it; }
  125. throw std::runtime_error("invalid multipart form data name error");
  126. #endif
  127. }
  128. static void read_file(const std::string &path, std::string &out) {
  129. std::ifstream fs(path, std::ios_base::binary);
  130. if (!fs) {
  131. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  132. return;
  133. #else
  134. throw std::runtime_error("File not found: " + path);
  135. #endif
  136. }
  137. fs.seekg(0, std::ios_base::end);
  138. auto size = fs.tellg();
  139. fs.seekg(0);
  140. out.resize(static_cast<size_t>(size));
  141. fs.read(&out[0], static_cast<std::streamsize>(size));
  142. }
  143. // httpbingo.org intermittently answers with gateway errors unrelated to the
  144. // client under test.
  145. static bool is_gateway_error(const Result &res) {
  146. return res && (res->status == StatusCode::BadGateway_502 ||
  147. res->status == StatusCode::ServiceUnavailable_503 ||
  148. res->status == StatusCode::GatewayTimeout_504);
  149. }
  150. template <typename F> static Result retry_gateway_errors(F &&send) {
  151. auto res = send();
  152. for (auto wait : {1, 2}) {
  153. if (!is_gateway_error(res)) { break; }
  154. std::this_thread::sleep_for(std::chrono::seconds(wait));
  155. res = send();
  156. }
  157. return res;
  158. }
  159. #define SKIP_ON_GATEWAY_ERROR(res) \
  160. do { \
  161. if (is_gateway_error(res)) { \
  162. GTEST_SKIP() << "gateway error " << (res)->status; \
  163. } \
  164. } while (0)
  165. class UnixSocketTest : public ::testing::Test {
  166. protected:
  167. void TearDown() override { std::remove(pathname_.c_str()); }
  168. void client_GET(const std::string &addr) {
  169. httplib::Client cli{addr};
  170. cli.set_address_family(AF_UNIX);
  171. ASSERT_TRUE(cli.is_valid());
  172. const auto &result = cli.Get(pattern_);
  173. ASSERT_TRUE(result) << "error: " << result.error();
  174. const auto &resp = result.value();
  175. EXPECT_EQ(resp.status, StatusCode::OK_200);
  176. EXPECT_EQ(resp.body, content_);
  177. }
  178. static std::string make_sock_path() {
  179. const char *shard = getenv("GTEST_SHARD_INDEX");
  180. return shard ? std::string("./httplib-server-") + shard + ".sock"
  181. : "./httplib-server.sock";
  182. }
  183. const std::string pathname_{make_sock_path()};
  184. const std::string pattern_{"/hi"};
  185. const std::string content_{"Hello World!"};
  186. };
  187. TEST_F(UnixSocketTest, pathname) {
  188. httplib::Server svr;
  189. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  190. res.set_content(content_, "text/plain");
  191. });
  192. std::thread t{[&] {
  193. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  194. }};
  195. auto se = detail::scope_exit([&] {
  196. svr.stop();
  197. t.join();
  198. ASSERT_FALSE(svr.is_running());
  199. });
  200. svr.wait_until_ready();
  201. ASSERT_TRUE(svr.is_running());
  202. client_GET(pathname_);
  203. // ".//x.sock", which is not taken for a URL
  204. client_GET("./" + pathname_.substr(1));
  205. }
  206. #if defined(__linux__) || \
  207. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  208. TEST_F(UnixSocketTest, PeerPid) {
  209. httplib::Server svr;
  210. std::string remote_port_val;
  211. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  212. res.set_content(content_, "text/plain");
  213. remote_port_val = std::to_string(req.remote_port);
  214. });
  215. std::thread t{[&] {
  216. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  217. }};
  218. auto se = detail::scope_exit([&] {
  219. svr.stop();
  220. t.join();
  221. ASSERT_FALSE(svr.is_running());
  222. });
  223. svr.wait_until_ready();
  224. ASSERT_TRUE(svr.is_running());
  225. client_GET(pathname_);
  226. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  227. }
  228. #endif
  229. #ifdef __linux__
  230. TEST_F(UnixSocketTest, abstract) {
  231. constexpr char svr_path[]{"\x00httplib-server.sock"};
  232. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  233. httplib::Server svr;
  234. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  235. res.set_content(content_, "text/plain");
  236. });
  237. std::thread t{[&] {
  238. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  239. }};
  240. auto se = detail::scope_exit([&] {
  241. svr.stop();
  242. t.join();
  243. ASSERT_FALSE(svr.is_running());
  244. });
  245. svr.wait_until_ready();
  246. ASSERT_TRUE(svr.is_running());
  247. client_GET(abstract_addr);
  248. }
  249. #endif
  250. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  251. httplib::Server svr;
  252. std::string received_host_header;
  253. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  254. // Capture the Host header sent by the client
  255. auto host_iter = req.headers.find("Host");
  256. if (host_iter != req.headers.end()) {
  257. received_host_header = host_iter->second;
  258. }
  259. res.set_content(content_, "text/plain");
  260. });
  261. std::thread t{[&] {
  262. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  263. }};
  264. auto se = detail::scope_exit([&] {
  265. svr.stop();
  266. t.join();
  267. ASSERT_FALSE(svr.is_running());
  268. });
  269. svr.wait_until_ready();
  270. ASSERT_TRUE(svr.is_running());
  271. // Test that Host header is automatically set to "localhost" for Unix socket
  272. // connections
  273. httplib::Client cli{pathname_};
  274. cli.set_address_family(AF_UNIX);
  275. ASSERT_TRUE(cli.is_valid());
  276. const auto &result = cli.Get(pattern_);
  277. ASSERT_TRUE(result) << "error: " << result.error();
  278. const auto &resp = result.value();
  279. EXPECT_EQ(resp.status, StatusCode::OK_200);
  280. EXPECT_EQ(resp.body, content_);
  281. // Verify that Host header was automatically set to "localhost"
  282. EXPECT_EQ(received_host_header, "localhost");
  283. }
  284. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  285. // Another socket in the working directory, which a Location can name as
  286. // its host
  287. const auto other_path = "other-" + pathname_.substr(2);
  288. httplib::Server svr;
  289. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  290. // An absolute Location naming the Host this client sends
  291. res.set_redirect("http://localhost" + pattern_);
  292. });
  293. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  294. res.set_redirect("http://" + other_path + pattern_);
  295. });
  296. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  297. res.set_redirect("http://mapped.test" + pattern_);
  298. });
  299. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  300. res.set_header("X-Auth", req.get_header_value("Authorization"));
  301. res.set_content(content_, "text/plain");
  302. });
  303. httplib::Server other;
  304. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  305. res.set_content("other", "text/plain");
  306. });
  307. std::thread t{[&] {
  308. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  309. }};
  310. std::thread t2{[&] {
  311. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  312. }};
  313. auto se = detail::scope_exit([&] {
  314. svr.stop();
  315. other.stop();
  316. t.join();
  317. t2.join();
  318. std::remove(other_path.c_str());
  319. });
  320. svr.wait_until_ready();
  321. other.wait_until_ready();
  322. httplib::Client cli{pathname_};
  323. cli.set_address_family(AF_UNIX);
  324. cli.set_follow_location(true);
  325. cli.set_bearer_token_auth("token");
  326. // Another host: the same socket, without the credentials
  327. auto res = cli.Get("/cross");
  328. ASSERT_TRUE(res) << "error: " << res.error();
  329. EXPECT_EQ(StatusCode::OK_200, res->status);
  330. EXPECT_EQ(content_, res->body);
  331. EXPECT_EQ("", res->get_header_value("X-Auth"));
  332. // localhost is this client's own host
  333. res = cli.Get("/redirect");
  334. ASSERT_TRUE(res) << "error: " << res.error();
  335. EXPECT_EQ(StatusCode::OK_200, res->status);
  336. EXPECT_EQ(content_, res->body);
  337. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  338. // A host the caller mapped to a socket goes there
  339. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  340. res = cli.Get("/mapped");
  341. ASSERT_TRUE(res) << "error: " << res.error();
  342. EXPECT_EQ(StatusCode::OK_200, res->status);
  343. EXPECT_EQ("other", res->body);
  344. }
  345. #ifndef _WIN32
  346. TEST(SocketStream, wait_writable_UNIX) {
  347. int fds[2];
  348. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  349. const auto asSocketStream = [&](socket_t fd,
  350. std::function<bool(Stream &)> func) {
  351. return detail::process_client_socket(
  352. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  353. };
  354. asSocketStream(fds[0], [&](Stream &s0) {
  355. EXPECT_EQ(s0.socket(), fds[0]);
  356. EXPECT_TRUE(s0.wait_writable());
  357. EXPECT_TRUE(s0.is_peer_alive());
  358. EXPECT_EQ(0, close(fds[1]));
  359. EXPECT_FALSE(s0.is_peer_alive());
  360. return true;
  361. });
  362. EXPECT_EQ(0, close(fds[0]));
  363. }
  364. TEST(SocketStream, wait_writable_INET) {
  365. sockaddr_in addr;
  366. memset(&addr, 0, sizeof(addr));
  367. addr.sin_family = AF_INET;
  368. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  369. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  370. int disconnected_svr_sock = -1;
  371. std::thread svr{[&] {
  372. const int s = socket(AF_INET, SOCK_STREAM, 0);
  373. ASSERT_LE(0, s);
  374. // PORT + 1 is shared with the SSL redirect tests and with
  375. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  376. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  377. // because that happens on a worker thread the ASSERT does not stop the
  378. // test: it runs on and fails at the disconnected_svr_sock check instead.
  379. default_socket_options(s);
  380. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  381. ASSERT_EQ(0, listen(s, 1));
  382. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  383. ASSERT_EQ(0, close(s));
  384. }};
  385. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  386. std::thread cli{[&] {
  387. const int s = socket(AF_INET, SOCK_STREAM, 0);
  388. ASSERT_LE(0, s);
  389. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  390. ASSERT_EQ(0, close(s));
  391. }};
  392. cli.join();
  393. svr.join();
  394. ASSERT_NE(disconnected_svr_sock, -1);
  395. const auto asSocketStream = [&](socket_t fd,
  396. std::function<bool(Stream &)> func) {
  397. return detail::process_client_socket(
  398. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  399. };
  400. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  401. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  402. // wait_writable() returns true because select_write() only checks if the
  403. // send buffer has space. Peer disconnection is detected later by send().
  404. EXPECT_TRUE(ss.wait_writable());
  405. return true;
  406. });
  407. ASSERT_EQ(0, close(disconnected_svr_sock));
  408. }
  409. #endif // #ifndef _WIN32
  410. TEST(SetSocketOptTest, TcpNoDelay) {
  411. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  412. ASSERT_NE(sock, INVALID_SOCKET);
  413. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  414. int val = 0;
  415. socklen_t len = sizeof(val);
  416. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  417. reinterpret_cast<char *>(&val), &len));
  418. EXPECT_NE(val, 0);
  419. detail::close_socket(sock);
  420. }
  421. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  422. // accept() reports failures through WSAGetLastError() on Windows and through
  423. // errno everywhere else. Asking the wrong one is what made the accept loop
  424. // treat every recoverable failure as fatal on Windows.
  425. struct Classification {
  426. bool resource;
  427. bool transient;
  428. };
  429. auto classify = [](int err) {
  430. #ifdef _WIN32
  431. WSASetLastError(err);
  432. #else
  433. errno = err;
  434. #endif
  435. // Read both before asserting: an assertion may clobber the error slot.
  436. Classification c;
  437. c.resource = detail::is_accept_resource_error();
  438. c.transient = detail::is_accept_transient_error();
  439. return c;
  440. };
  441. #ifdef _WIN32
  442. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  443. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  444. WSAECONNRESET, WSAECONNABORTED};
  445. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  446. #else
  447. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  448. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  449. ECONNABORTED};
  450. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  451. #endif
  452. for (auto err : resource_errors) {
  453. const auto c = classify(err);
  454. EXPECT_TRUE(c.resource) << "error " << err;
  455. EXPECT_FALSE(c.transient) << "error " << err;
  456. }
  457. for (auto err : transient_errors) {
  458. const auto c = classify(err);
  459. EXPECT_TRUE(c.transient) << "error " << err;
  460. EXPECT_FALSE(c.resource) << "error " << err;
  461. }
  462. for (auto err : fatal_errors) {
  463. const auto c = classify(err);
  464. EXPECT_FALSE(c.resource) << "error " << err;
  465. EXPECT_FALSE(c.transient) << "error " << err;
  466. }
  467. #ifdef _WIN32
  468. WSASetLastError(0);
  469. #else
  470. errno = 0;
  471. #endif
  472. }
  473. TEST(ClientTest, MoveConstructible) {
  474. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  475. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  476. }
  477. TEST(ClientTest, MoveAssignable) {
  478. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  479. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  480. }
  481. #ifdef _WIN32
  482. TEST(StartupTest, WSAStartup) {
  483. WSADATA wsaData;
  484. int ret = WSAStartup(0x0002, &wsaData);
  485. ASSERT_EQ(0, ret);
  486. }
  487. #endif
  488. TEST(DecodePathTest, PercentCharacter) {
  489. EXPECT_EQ(
  490. decode_path_component(
  491. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  492. U8("descrip=Gastos áéíóúñÑ 6"));
  493. }
  494. TEST(DecodePathTest, PercentCharacterNUL) {
  495. string expected;
  496. expected.push_back('x');
  497. expected.push_back('\0');
  498. expected.push_back('x');
  499. EXPECT_EQ(decode_path_component("x%00x"), expected);
  500. }
  501. TEST(DecodePathTest, UnicodeEncoding) {
  502. // %u0041 = 'A' (1-byte UTF-8)
  503. EXPECT_EQ("A", decode_path_component("%u0041"));
  504. // %u00E9 = 'é' (2-byte UTF-8)
  505. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  506. // %u3042 = 'あ' (3-byte UTF-8)
  507. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  508. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  509. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  510. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  511. // neighbours)
  512. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  513. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  514. }
  515. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  516. // A sign or whitespace inside the two-character escape window must not be
  517. // accepted as a valid percent-encoding; the sequence is passed through
  518. // literally, matching decode_uri_component / decode_path_component.
  519. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  520. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  521. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  522. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  523. // Well-formed escapes still decode.
  524. EXPECT_EQ("-", decode_query_component("%2D", false));
  525. EXPECT_EQ("A", decode_query_component("%41", false));
  526. }
  527. TEST(SanitizeFilenameTest, VariousPatterns) {
  528. // Path traversal
  529. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  530. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  531. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  532. // Normal and edge cases
  533. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  534. EXPECT_EQ("filename.txt",
  535. httplib::sanitize_filename("/path/to/filename.txt"));
  536. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  537. EXPECT_EQ("", httplib::sanitize_filename(".."));
  538. EXPECT_EQ("", httplib::sanitize_filename(""));
  539. // Null bytes stripped
  540. EXPECT_EQ("safe.txt",
  541. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  542. // Whitespace-only rejected
  543. EXPECT_EQ("", httplib::sanitize_filename(" "));
  544. }
  545. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  546. // before it is dropped; anywhere else it is an ordinary file name character.
  547. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  548. #ifdef _WIN32
  549. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  550. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  551. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  552. #else
  553. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  554. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  555. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  556. #endif
  557. }
  558. // Forward declaration (see the base64_encode note below): split builds move the
  559. // definition into httplib.cc, so re-declaring it here lets the test link.
  560. namespace httplib {
  561. namespace detail {
  562. bool is_chunked_transfer_encoding(const Headers &headers);
  563. } // namespace detail
  564. } // namespace httplib
  565. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  566. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  567. auto make = [](std::initializer_list<const char *> lines) {
  568. Headers h;
  569. for (auto te : lines) {
  570. if (te) { h.emplace("Transfer-Encoding", te); }
  571. }
  572. return h;
  573. };
  574. // Sole coding, matched case-insensitively.
  575. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  576. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  577. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  578. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  579. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  580. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  581. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  582. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  583. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  584. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  585. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  586. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  587. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  588. // were received, into one list. Headers preserves that order, so the answer
  589. // is decided by the last coding of the last line and the order the lines
  590. // arrived in is significant.
  591. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  592. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  593. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  594. // The split can fall anywhere in the list.
  595. EXPECT_TRUE(
  596. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  597. EXPECT_FALSE(
  598. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  599. // A trailing line naming no coding leaves the list ending in nothing, so it
  600. // must not inherit the chunked from the line before it.
  601. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  602. }
  603. // Forward declarations (see the base64_encode note below).
  604. namespace httplib {
  605. namespace detail {
  606. bool parse_status_line(const char *line, std::string &version, int &status,
  607. std::string &reason);
  608. std::string file_extension(const std::string &path);
  609. std::string
  610. find_content_type(const std::string &path,
  611. const std::map<std::string, std::string> &user_data,
  612. const std::string &default_content_type);
  613. bool can_compress_content_type(const std::string &content_type);
  614. bool is_prohibited_header_name(const std::string &name);
  615. bool is_valid_path(const std::string &path);
  616. #ifdef CPPHTTPLIB_SSL_ENABLED
  617. bool match_hostname(const std::string &pattern, const std::string &hostname);
  618. #endif
  619. } // namespace detail
  620. } // namespace httplib
  621. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  622. struct {
  623. const char *line;
  624. const char *version;
  625. int status;
  626. const char *reason;
  627. } cases[] = {
  628. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  629. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  630. // The reason phrase may be empty, or left out along with its space.
  631. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  632. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  633. };
  634. for (const auto &c : cases) {
  635. std::string version;
  636. int status = 0;
  637. std::string reason = "unset";
  638. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  639. << c.line;
  640. EXPECT_EQ(c.version, version);
  641. EXPECT_EQ(c.status, status);
  642. EXPECT_EQ(c.reason, reason);
  643. }
  644. }
  645. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  646. const char *lines[] = {
  647. "HTTP/2 200 OK\r\n",
  648. "HTTP/1.2 200 OK\r\n",
  649. "HTTP/1.1 20 OK\r\n",
  650. "HTTP/1.1 2000 OK\r\n",
  651. "HTTP/1.1 2x0 OK\r\n",
  652. "HTTP/1.1 200 OK\r\n",
  653. "HTTP/1.1 200OK\r\n",
  654. "HTTP/1.1 200 O\rK\r\n",
  655. "HTTP/1.1 200 OK",
  656. "HTTP/1.1 200 OK\r\nX",
  657. "",
  658. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  659. "HTTP/1.1 200 OK\n",
  660. #endif
  661. };
  662. for (auto line : lines) {
  663. std::string version;
  664. int status = 0;
  665. std::string reason;
  666. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  667. << line;
  668. }
  669. }
  670. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  671. // Long enough to overflow the stack when matched with std::regex.
  672. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  673. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  674. std::string version;
  675. int status = 0;
  676. std::string reason;
  677. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  678. EXPECT_EQ(200, status);
  679. EXPECT_EQ(long_reason, reason);
  680. }
  681. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  682. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  683. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  684. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  685. EXPECT_EQ("", detail::file_extension("noext"));
  686. EXPECT_EQ("", detail::file_extension("a."));
  687. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  688. EXPECT_EQ("", detail::file_extension("a.b-c"));
  689. // Long enough to overflow the stack when matched with std::regex.
  690. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  691. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  692. }
  693. #ifdef CPPHTTPLIB_SSL_ENABLED
  694. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  695. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  696. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  697. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  698. // A wildcard needs two labels after it, in the leftmost label only
  699. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  700. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  701. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  702. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  703. EXPECT_FALSE(
  704. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  705. // No name may have an empty label
  706. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  707. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  708. }
  709. #endif
  710. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  711. detail::case_ignore::hash hash;
  712. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  713. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  714. // Long enough to overflow the stack if hashed one call per character.
  715. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  716. }
  717. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  718. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  719. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  720. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  721. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  722. // Same 26-bit hash as html, svg and js.
  723. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  724. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  725. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  726. }
  727. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  728. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  729. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  730. }
  731. }
  732. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  733. // name anywhere else.
  734. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  735. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  736. #ifdef _WIN32
  737. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  738. #else
  739. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  740. #endif
  741. }
  742. }
  743. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  744. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  745. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  746. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  747. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  748. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  749. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  750. // Same 26-bit hash as application/json.
  751. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  752. }
  753. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  754. Request req;
  755. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  756. EXPECT_TRUE(req.is_multipart_form_data());
  757. std::string boundary;
  758. EXPECT_TRUE(detail::parse_multipart_boundary(
  759. req.get_header_value("Content-Type"), boundary));
  760. EXPECT_EQ("x", boundary);
  761. }
  762. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  763. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  764. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  765. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  766. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  767. // Same 26-bit hash as REMOTE_ADDR.
  768. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  769. }
  770. // Forward declaration: in split builds split.py strips `inline` and moves the
  771. // definition into httplib.cc, so detail::base64_encode is not visible from the
  772. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  773. // in both header-only and split builds.
  774. namespace httplib {
  775. namespace detail {
  776. std::string base64_encode(const std::string &in);
  777. } // namespace detail
  778. } // namespace httplib
  779. TEST(Base64EncodeTest, KnownAnswers) {
  780. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  781. // where the accumulator's top bit is already set before the next shift.
  782. EXPECT_EQ("", detail::base64_encode(""));
  783. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  784. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  785. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  786. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  787. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  788. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  789. // High bytes keep the top bit set across several rounds.
  790. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  791. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  792. }
  793. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  794. string unescapedCharacters = "-_.!~*'()";
  795. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  796. }
  797. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  798. string reservedCharacters = ";,/?:@&=+$";
  799. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  800. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  801. }
  802. TEST(ClientQueryOrder, PreserveOrder) {
  803. // This test reproduces Issue #2259: client may reorder query parameters
  804. // when sending a GET request. The expected behavior is that the client
  805. // preserves the original query string order when the caller supplied it
  806. // as part of the path.
  807. Server svr;
  808. svr.Get("/", [&](const Request &req, Response &res) {
  809. // Echo back the raw target so the test can assert ordering
  810. res.set_content(req.target, "text/plain");
  811. });
  812. std::thread t{[&] { svr.listen(HOST, PORT); }};
  813. auto se = detail::scope_exit([&] {
  814. svr.stop();
  815. t.join();
  816. ASSERT_FALSE(svr.is_running());
  817. });
  818. svr.wait_until_ready();
  819. Client cli(HOST, PORT);
  820. ASSERT_TRUE(cli.is_valid());
  821. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  822. auto res = cli.Get(original);
  823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  824. // Expect the echoed target to exactly match the original path (order
  825. // preserved)
  826. EXPECT_EQ(res->body, original);
  827. }
  828. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  829. string chineseCharacters = U8("中国語");
  830. string russianCharacters = U8("дом");
  831. string brazilianCharacters = U8("óculos");
  832. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  833. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  834. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  835. "%D0%B4%D0%BE%D0%BC");
  836. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  837. }
  838. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  839. string unescapedCharacters = "-_.!~*'()";
  840. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  841. }
  842. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  843. string reservedCharacters = ";,/?:@&=+$";
  844. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  845. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  846. }
  847. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  848. string chineseCharacters = U8("中国語");
  849. string russianCharacters = U8("дом");
  850. string brazilianCharacters = U8("óculos");
  851. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  852. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  853. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  854. "%D0%B4%D0%BE%D0%BC");
  855. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  856. }
  857. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  858. // Issue #2082 use case: encoding path component with ampersand
  859. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  860. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  861. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  862. }
  863. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  864. string unescapedCharacters = "-_.!~*'()";
  865. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  866. }
  867. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  868. string reservedCharacters = ";,/?:@&=+$#";
  869. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  870. }
  871. TEST(EncodeUriTest, TestUTF8Characters) {
  872. string chineseCharacters = U8("中国語");
  873. string russianCharacters = U8("дом");
  874. string brazilianCharacters = U8("óculos");
  875. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  876. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  877. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  878. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  879. }
  880. TEST(EncodeUriTest, TestCompleteUri) {
  881. string uri =
  882. "https://example.com/path/to/resource?query=value&param=test#fragment";
  883. EXPECT_EQ(
  884. httplib::encode_uri(uri),
  885. "https://example.com/path/to/resource?query=value&param=test#fragment");
  886. }
  887. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  888. string uri =
  889. "https://example.com/path with spaces/file name.html?q=hello world";
  890. EXPECT_EQ(httplib::encode_uri(uri),
  891. "https://example.com/path%20with%20spaces/"
  892. "file%20name.html?q=hello%20world");
  893. }
  894. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  895. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  896. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  897. }
  898. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  899. string unescapedCharacters = "-_.!~*'()";
  900. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  901. }
  902. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  903. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  904. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  905. string encodedBrazilian = "%C3%B3culos";
  906. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  907. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  908. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  909. }
  910. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  911. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  912. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  913. "Piri Tommy Villiers - on & on");
  914. }
  915. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  916. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  917. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  918. }
  919. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  920. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  921. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  922. }
  923. TEST(DecodeUriTest, TestUTF8Characters) {
  924. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  925. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  926. string encodedBrazilian = "%C3%B3culos";
  927. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  928. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  929. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  930. }
  931. TEST(DecodeUriTest, TestCompleteUri) {
  932. string encodedUri = "https://example.com/path%20with%20spaces/"
  933. "file%20name.html?q=hello%20world";
  934. EXPECT_EQ(
  935. httplib::decode_uri(encodedUri),
  936. "https://example.com/path with spaces/file name.html?q=hello world");
  937. }
  938. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  939. string original =
  940. "https://example.com/path with spaces/file name.html?q=hello world";
  941. string encoded = httplib::encode_uri(original);
  942. string decoded = httplib::decode_uri(encoded);
  943. EXPECT_EQ(decoded, original);
  944. }
  945. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  946. // decode_uri is the inverse of encode_uri: an escaped reserved character
  947. // stays encoded so it is not promoted into a real delimiter, while
  948. // non-reserved escapes still decode (like JS decodeURI).
  949. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  950. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  951. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  952. "%3F%3A%40%26%3D%2B%24%2C%3B");
  953. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  954. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  955. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  956. "http://example.com/a%2Fb");
  957. // decode_uri_component still decodes the reserved character.
  958. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  959. }
  960. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  961. string original = "Piri Tommy Villiers - on & on";
  962. string encoded = httplib::encode_uri_component(original);
  963. string decoded = httplib::decode_uri_component(encoded);
  964. EXPECT_EQ(decoded, original);
  965. }
  966. TEST(TrimTests, TrimStringTests) {
  967. EXPECT_EQ("abc", detail::trim_copy("abc"));
  968. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  969. EXPECT_TRUE(detail::trim_copy("").empty());
  970. }
  971. TEST(AsciiTest, LocaleIndependentClassification) {
  972. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  973. // which consult the global C locale: std::isalnum(0xC5) can return true
  974. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  975. // helpers must classify every byte by the ASCII grammar alone.
  976. for (int i = 0; i < 256; i++) {
  977. auto c = static_cast<char>(i);
  978. auto is_digit = i >= '0' && i <= '9';
  979. auto is_upper = i >= 'A' && i <= 'Z';
  980. auto is_lower = i >= 'a' && i <= 'z';
  981. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  982. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  983. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  984. << "byte " << i;
  985. }
  986. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  987. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  988. // Non-ASCII bytes must be percent-encoded, never passed through as
  989. // alphanumeric.
  990. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  991. }
  992. TEST(FromCharsTest, Double) {
  993. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  994. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  995. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  996. auto parse = [](const std::string &s, double &v) {
  997. return detail::from_chars(s.data(), s.data() + s.size(), v);
  998. };
  999. double v = -1.0;
  1000. // Representative quality values.
  1001. EXPECT_EQ(parse("0", v).ec, std::errc{});
  1002. EXPECT_DOUBLE_EQ(v, 0.0);
  1003. EXPECT_EQ(parse("1", v).ec, std::errc{});
  1004. EXPECT_DOUBLE_EQ(v, 1.0);
  1005. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  1006. EXPECT_DOUBLE_EQ(v, 0.8);
  1007. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  1008. EXPECT_DOUBLE_EQ(v, 0.001);
  1009. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  1010. EXPECT_DOUBLE_EQ(v, 1.0);
  1011. // A missing integer or fractional part is tolerated.
  1012. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  1013. EXPECT_DOUBLE_EQ(v, 0.5);
  1014. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  1015. EXPECT_DOUBLE_EQ(v, 5.0);
  1016. // Values outside [0, 1] still parse; the caller range-checks them.
  1017. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  1018. EXPECT_DOUBLE_EQ(v, 123.456);
  1019. // Stops at the first byte that is not part of the number and reports where.
  1020. std::string trailing = "0.9, text/html";
  1021. auto r = parse(trailing, v);
  1022. EXPECT_EQ(r.ec, std::errc{});
  1023. EXPECT_DOUBLE_EQ(v, 0.9);
  1024. EXPECT_EQ(*r.ptr, ',');
  1025. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1026. // outright, and an 'e'/'E' simply ends the number.
  1027. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1028. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1029. std::string exp_input = "1.5e3";
  1030. r = parse(exp_input, v);
  1031. EXPECT_EQ(r.ec, std::errc{});
  1032. EXPECT_DOUBLE_EQ(v, 1.5);
  1033. EXPECT_EQ(*r.ptr, 'e');
  1034. // Invalid inputs.
  1035. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1036. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1037. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1038. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1039. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1040. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1041. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1042. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1043. std::errc{});
  1044. EXPECT_DOUBLE_EQ(v, 0.0);
  1045. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1046. std::errc{});
  1047. EXPECT_GE(v, 0.0);
  1048. EXPECT_LE(v, 1.0);
  1049. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1050. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1051. }
  1052. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1053. // Simple case without quality values
  1054. std::vector<std::string> result1;
  1055. EXPECT_TRUE(detail::parse_accept_header(
  1056. "text/html,application/json,text/plain", result1));
  1057. EXPECT_EQ(result1.size(), 3U);
  1058. EXPECT_EQ(result1[0], "text/html");
  1059. EXPECT_EQ(result1[1], "application/json");
  1060. EXPECT_EQ(result1[2], "text/plain");
  1061. // With quality values
  1062. std::vector<std::string> result2;
  1063. EXPECT_TRUE(detail::parse_accept_header(
  1064. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1065. EXPECT_EQ(result2.size(), 3U);
  1066. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1067. EXPECT_EQ(result2[1], "text/html");
  1068. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1069. }
  1070. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1071. // Mixed with and without quality values
  1072. std::vector<std::string> result;
  1073. EXPECT_TRUE(detail::parse_accept_header(
  1074. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1075. EXPECT_EQ(result.size(), 3U);
  1076. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1077. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1078. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1079. }
  1080. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1081. // Empty header
  1082. std::vector<std::string> empty_result;
  1083. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1084. EXPECT_TRUE(empty_result.empty());
  1085. // Single type
  1086. std::vector<std::string> single_result;
  1087. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1088. EXPECT_EQ(single_result.size(), 1U);
  1089. EXPECT_EQ(single_result[0], "application/json");
  1090. // Wildcard types
  1091. std::vector<std::string> wildcard_result;
  1092. EXPECT_TRUE(detail::parse_accept_header(
  1093. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1094. EXPECT_EQ(wildcard_result.size(), 3U);
  1095. EXPECT_EQ(wildcard_result[0], "application/json");
  1096. EXPECT_EQ(wildcard_result[1], "text/*");
  1097. EXPECT_EQ(wildcard_result[2], "*/*");
  1098. }
  1099. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1100. // Common browser Accept header
  1101. std::vector<std::string> browser_result;
  1102. EXPECT_TRUE(
  1103. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1104. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1105. browser_result));
  1106. EXPECT_EQ(browser_result.size(), 6U);
  1107. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1108. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1109. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1110. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1111. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1112. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1113. // API client header
  1114. std::vector<std::string> api_result;
  1115. EXPECT_TRUE(detail::parse_accept_header(
  1116. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1117. api_result));
  1118. EXPECT_EQ(api_result.size(), 3U);
  1119. EXPECT_EQ(api_result[0], "application/json");
  1120. EXPECT_EQ(api_result[1], "application/xml");
  1121. EXPECT_EQ(api_result[2], "text/plain");
  1122. }
  1123. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1124. // Quality value with 3 decimal places
  1125. std::vector<std::string> decimal_result;
  1126. EXPECT_TRUE(detail::parse_accept_header(
  1127. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1128. EXPECT_EQ(decimal_result.size(), 2U);
  1129. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1130. EXPECT_EQ(decimal_result[1], "text/html");
  1131. // Zero quality (should still be included but with lowest priority)
  1132. std::vector<std::string> zero_q_result;
  1133. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1134. zero_q_result));
  1135. EXPECT_EQ(zero_q_result.size(), 2U);
  1136. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1137. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1138. // No spaces around commas
  1139. std::vector<std::string> no_space_result;
  1140. EXPECT_TRUE(detail::parse_accept_header(
  1141. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1142. no_space_result));
  1143. EXPECT_EQ(no_space_result.size(), 3U);
  1144. EXPECT_EQ(no_space_result[0], "text/html");
  1145. EXPECT_EQ(no_space_result[1], "application/json");
  1146. EXPECT_EQ(no_space_result[2], "text/plain");
  1147. }
  1148. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1149. // Quality values always use '.' as the decimal separator, so parsing must
  1150. // not depend on the process locale. An embedding application may have
  1151. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1152. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1153. std::string saved = cur ? cur : "C";
  1154. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1155. "fr_FR.UTF-8"};
  1156. bool switched = false;
  1157. for (const auto loc : comma_locales) {
  1158. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1159. std::localeconv()->decimal_point[0] == ',') {
  1160. switched = true;
  1161. break;
  1162. }
  1163. }
  1164. if (!switched) {
  1165. std::setlocale(LC_NUMERIC, saved.c_str());
  1166. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1167. }
  1168. // The higher-weighted type appears later in the list, so a correct parse
  1169. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1170. // sensitive parse reads both weights as 0 and leaves the original order.
  1171. std::vector<std::string> result;
  1172. EXPECT_TRUE(detail::parse_accept_header(
  1173. "application/json;q=0.1,text/html;q=0.9", result));
  1174. ASSERT_EQ(result.size(), 2U);
  1175. EXPECT_EQ(result[0], "text/html");
  1176. EXPECT_EQ(result[1], "application/json");
  1177. std::setlocale(LC_NUMERIC, saved.c_str());
  1178. }
  1179. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1180. std::vector<std::string> result;
  1181. // Invalid quality value (> 1.0)
  1182. EXPECT_FALSE(
  1183. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1184. // Invalid quality value (< 0.0)
  1185. EXPECT_FALSE(
  1186. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1187. // Invalid quality value (not a number)
  1188. EXPECT_FALSE(detail::parse_accept_header(
  1189. "text/html;q=invalid,application/json", result));
  1190. // A valid numeric prefix does not make the entire quality value valid.
  1191. EXPECT_FALSE(detail::parse_accept_header(
  1192. "text/html;q=0.5junk,application/json", result));
  1193. // Empty quality value
  1194. EXPECT_FALSE(
  1195. detail::parse_accept_header("text/html;q=,application/json", result));
  1196. // Invalid media type format (no slash and not wildcard)
  1197. EXPECT_FALSE(
  1198. detail::parse_accept_header("invalidtype,application/json", result));
  1199. // Valid cases should still work
  1200. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1201. EXPECT_EQ(result.size(), 1U);
  1202. EXPECT_EQ(result[0], "*/*");
  1203. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1204. EXPECT_EQ(result.size(), 1U);
  1205. EXPECT_EQ(result[0], "*");
  1206. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1207. EXPECT_EQ(result.size(), 1U);
  1208. EXPECT_EQ(result[0], "text/*");
  1209. }
  1210. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1211. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1212. // and must not be answered with 400 Bad Request.
  1213. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1214. struct {
  1215. const char *value;
  1216. std::vector<std::string> expected;
  1217. } cases[] = {
  1218. {",application/json", {"application/json"}},
  1219. {"text/html,", {"text/html"}},
  1220. {"text/html,,*/*", {"text/html", "*/*"}},
  1221. // An empty element may be spelled with whitespace in it
  1222. {"text/html, , application/json", {"text/html", "application/json"}},
  1223. // Nothing but empty elements is an empty list, which means the same
  1224. // thing as no Accept header at all
  1225. {",,,", {}},
  1226. // Quality values still apply across ignored empty elements
  1227. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1228. };
  1229. for (const auto &c : cases) {
  1230. std::vector<std::string> result;
  1231. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1232. << "value: " << c.value;
  1233. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1234. }
  1235. // An invalid entry is still rejected when empty elements surround it
  1236. std::vector<std::string> result;
  1237. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1238. }
  1239. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1240. // or ';' inside one does not end the list element or the parameter. Section
  1241. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1242. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1243. struct {
  1244. const char *value;
  1245. std::vector<std::string> expected;
  1246. } cases[] = {
  1247. {"text/html;profile=\"a,b\",application/json",
  1248. {"text/html", "application/json"}},
  1249. // A "q=" inside a quoted value is not the weight
  1250. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1251. {"text/html", "application/json"}},
  1252. // The weight after a quoted value still applies
  1253. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1254. {"application/json", "text/html"}},
  1255. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1256. {"application/json", "text/html"}},
  1257. {"text/html;profile=\"a\\\"b\",application/json",
  1258. {"text/html", "application/json"}},
  1259. // An escaped backslash does not escape the '"' after it
  1260. {"text/html;profile=\"a\\\\\",application/json",
  1261. {"text/html", "application/json"}},
  1262. };
  1263. for (const auto &c : cases) {
  1264. std::vector<std::string> result;
  1265. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1266. << "value: " << c.value;
  1267. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1268. }
  1269. }
  1270. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1271. Server svr;
  1272. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1273. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1274. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1275. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1276. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1277. res.set_content("ok", "text/plain");
  1278. });
  1279. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1280. EXPECT_TRUE(false);
  1281. res.set_content("bad request", "text/plain");
  1282. });
  1283. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1284. auto se = detail::scope_exit([&] {
  1285. svr.stop();
  1286. listen_thread.join();
  1287. ASSERT_FALSE(svr.is_running());
  1288. });
  1289. svr.wait_until_ready();
  1290. Client cli("localhost", PORT);
  1291. {
  1292. auto res = cli.Get(
  1293. "/accept_ok",
  1294. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1296. EXPECT_EQ(StatusCode::OK_200, res->status);
  1297. }
  1298. {
  1299. auto res = cli.Get("/accept_bad_request",
  1300. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1302. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1303. }
  1304. }
  1305. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1306. Server svr;
  1307. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1308. res.set_content("ok", "text/plain");
  1309. });
  1310. std::atomic<int> start_count{0};
  1311. std::atomic<bool> running_when_called{false};
  1312. svr.set_start_handler([&]() {
  1313. running_when_called = svr.is_running();
  1314. start_count++;
  1315. });
  1316. auto port = svr.bind_to_any_port(HOST);
  1317. std::thread t([&]() { svr.listen_after_bind(); });
  1318. auto se = detail::scope_exit([&] {
  1319. svr.stop();
  1320. t.join();
  1321. ASSERT_FALSE(svr.is_running());
  1322. });
  1323. svr.wait_until_ready();
  1324. // A successful request proves the accept loop is running, which the start
  1325. // handler precedes; so by now the handler must have run exactly once.
  1326. Client cli(HOST, port);
  1327. cli.set_connection_timeout(std::chrono::seconds(5));
  1328. auto res = cli.Get("/");
  1329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1330. EXPECT_EQ(StatusCode::OK_200, res->status);
  1331. EXPECT_EQ(1, start_count.load());
  1332. EXPECT_TRUE(running_when_called.load());
  1333. }
  1334. TEST(DivideTest, DivideStringTests) {
  1335. auto divide = [](const std::string &str, char d) {
  1336. std::string lhs;
  1337. std::string rhs;
  1338. detail::divide(str, d,
  1339. [&](const char *lhs_data, std::size_t lhs_size,
  1340. const char *rhs_data, std::size_t rhs_size) {
  1341. lhs.assign(lhs_data, lhs_size);
  1342. rhs.assign(rhs_data, rhs_size);
  1343. });
  1344. return std::make_pair(std::move(lhs), std::move(rhs));
  1345. };
  1346. {
  1347. const auto res = divide("", '=');
  1348. EXPECT_EQ(res.first, "");
  1349. EXPECT_EQ(res.second, "");
  1350. }
  1351. {
  1352. const auto res = divide("=", '=');
  1353. EXPECT_EQ(res.first, "");
  1354. EXPECT_EQ(res.second, "");
  1355. }
  1356. {
  1357. const auto res = divide(" ", '=');
  1358. EXPECT_EQ(res.first, " ");
  1359. EXPECT_EQ(res.second, "");
  1360. }
  1361. {
  1362. const auto res = divide("a", '=');
  1363. EXPECT_EQ(res.first, "a");
  1364. EXPECT_EQ(res.second, "");
  1365. }
  1366. {
  1367. const auto res = divide("a=", '=');
  1368. EXPECT_EQ(res.first, "a");
  1369. EXPECT_EQ(res.second, "");
  1370. }
  1371. {
  1372. const auto res = divide("=b", '=');
  1373. EXPECT_EQ(res.first, "");
  1374. EXPECT_EQ(res.second, "b");
  1375. }
  1376. {
  1377. const auto res = divide("a=b", '=');
  1378. EXPECT_EQ(res.first, "a");
  1379. EXPECT_EQ(res.second, "b");
  1380. }
  1381. {
  1382. const auto res = divide("a=b=", '=');
  1383. EXPECT_EQ(res.first, "a");
  1384. EXPECT_EQ(res.second, "b=");
  1385. }
  1386. {
  1387. const auto res = divide("a=b=c", '=');
  1388. EXPECT_EQ(res.first, "a");
  1389. EXPECT_EQ(res.second, "b=c");
  1390. }
  1391. }
  1392. TEST(SplitTest, ParseQueryString) {
  1393. string s = "key1=val1&key2=val2&key3=val3";
  1394. Params dic;
  1395. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1396. [&](const char *b, const char *e) {
  1397. string key, val;
  1398. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1399. if (key.empty()) {
  1400. key.assign(b2, e2);
  1401. } else {
  1402. val.assign(b2, e2);
  1403. }
  1404. });
  1405. dic.emplace(key, val);
  1406. });
  1407. EXPECT_EQ("val1", dic.find("key1")->second);
  1408. EXPECT_EQ("val2", dic.find("key2")->second);
  1409. EXPECT_EQ("val3", dic.find("key3")->second);
  1410. }
  1411. TEST(SplitTest, ParseInvalidQueryTests) {
  1412. {
  1413. string s = " ";
  1414. Params dict;
  1415. detail::parse_query_text(s, dict);
  1416. EXPECT_TRUE(dict.empty());
  1417. }
  1418. {
  1419. string s = " = =";
  1420. Params dict;
  1421. detail::parse_query_text(s, dict);
  1422. EXPECT_TRUE(dict.empty());
  1423. }
  1424. }
  1425. TEST(ParseQueryTest, ParseQueryString) {
  1426. {
  1427. std::string s = "key1=val1&key2=val2&key3=val3";
  1428. Params dic;
  1429. detail::parse_query_text(s, dic);
  1430. EXPECT_EQ("val1", dic.find("key1")->second);
  1431. EXPECT_EQ("val2", dic.find("key2")->second);
  1432. EXPECT_EQ("val3", dic.find("key3")->second);
  1433. }
  1434. {
  1435. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1436. Params dic;
  1437. detail::parse_query_text(s, dic);
  1438. EXPECT_EQ("", dic.find("key1")->second);
  1439. EXPECT_EQ("val1", dic.find("key2")->second);
  1440. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1441. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1442. }
  1443. }
  1444. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1445. Params dic;
  1446. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1447. dic.emplace("key1", "val1");
  1448. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1449. dic.emplace("key2", "val2");
  1450. dic.emplace("key3", "val3");
  1451. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1452. }
  1453. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1454. Params params;
  1455. params.emplace("a", "1");
  1456. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1457. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1458. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1459. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1460. // Long enough to overflow the stack when matched with std::regex.
  1461. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1462. EXPECT_EQ("/p?" + long_query + "&a=1",
  1463. append_query_params("/p?" + long_query, params));
  1464. }
  1465. // Joins every entry of a Headers or Params into "key=value " so a whole
  1466. // traversal can be compared in one assertion. Both are instantiations of the
  1467. // same insertion-ordered container, so one helper serves both.
  1468. template <typename Map> static std::string entries_to_string(const Map &m) {
  1469. std::string s;
  1470. for (const auto &entry : m) {
  1471. s += entry.first + "=" + entry.second + " ";
  1472. }
  1473. return s;
  1474. }
  1475. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1476. // Params used to be a std::multimap, which sorted by name and handed the
  1477. // caller's query back alphabetised. A client signing its query string could
  1478. // not reproduce the order it asked for.
  1479. Params dic;
  1480. dic.emplace("zulu", "1");
  1481. dic.emplace("alpha", "2");
  1482. dic.emplace("mike", "3");
  1483. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1484. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1485. }
  1486. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1487. Params dic;
  1488. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1489. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1490. }
  1491. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1492. Request req;
  1493. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1494. req.params);
  1495. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1496. EXPECT_EQ("first", req.get_param_value("tag"));
  1497. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1498. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1499. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1500. EXPECT_EQ("", req.get_param_value("tag", 3));
  1501. }
  1502. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1503. // Params shares its container with Headers, which matches field names
  1504. // case-insensitively. Parameter names must not pick that up.
  1505. Params dic;
  1506. dic.emplace("Key", "upper");
  1507. dic.emplace("key", "lower");
  1508. EXPECT_EQ(2U, dic.size());
  1509. EXPECT_EQ(1U, dic.count("Key"));
  1510. EXPECT_EQ(1U, dic.count("key"));
  1511. EXPECT_EQ("upper", dic.find("Key")->second);
  1512. EXPECT_EQ("lower", dic.find("key")->second);
  1513. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1514. }
  1515. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1516. Server svr;
  1517. std::string order;
  1518. svr.Get("/order", [&](const Request &req, Response &res) {
  1519. order = entries_to_string(req.params);
  1520. res.set_content("ok", "text/plain");
  1521. });
  1522. auto port = svr.bind_to_any_port(HOST);
  1523. thread t = thread([&] { svr.listen_after_bind(); });
  1524. auto se = detail::scope_exit([&] {
  1525. svr.stop();
  1526. t.join();
  1527. ASSERT_FALSE(svr.is_running());
  1528. });
  1529. svr.wait_until_ready();
  1530. Client cli(HOST, port);
  1531. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1532. ASSERT_TRUE(res);
  1533. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1534. }
  1535. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1536. Server svr;
  1537. std::string field_order, file_order;
  1538. svr.Post("/order", [&](const Request &req, Response &res) {
  1539. for (const auto &field : req.form.fields) {
  1540. field_order += field.first + "=" + field.second.content + " ";
  1541. }
  1542. for (const auto &file : req.form.files) {
  1543. file_order += file.first + "=" + file.second.filename + " ";
  1544. }
  1545. res.set_content("ok", "text/plain");
  1546. });
  1547. auto port = svr.bind_to_any_port(HOST);
  1548. thread t = thread([&] { svr.listen_after_bind(); });
  1549. auto se = detail::scope_exit([&] {
  1550. svr.stop();
  1551. t.join();
  1552. ASSERT_FALSE(svr.is_running());
  1553. });
  1554. svr.wait_until_ready();
  1555. UploadFormDataItems items = {
  1556. {"zulu", "1", "", ""},
  1557. {"alpha", "2", "", ""},
  1558. {"mike", "3", "", ""},
  1559. {"zebra", "z", "z.txt", "text/plain"},
  1560. {"apple", "a", "a.txt", "text/plain"},
  1561. };
  1562. Client cli(HOST, port);
  1563. auto res = cli.Post("/order", items);
  1564. ASSERT_TRUE(res);
  1565. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1566. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1567. }
  1568. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1569. Server svr;
  1570. std::vector<std::string> values;
  1571. std::string first, second, out_of_range, order;
  1572. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1573. values = req.form.get_fields("tag");
  1574. first = req.form.get_field("tag", 0);
  1575. second = req.form.get_field("tag", 1);
  1576. out_of_range = req.form.get_field("tag", 2);
  1577. for (const auto &field : req.form.fields) {
  1578. order += field.first + "=" + field.second.content + " ";
  1579. }
  1580. res.set_content("ok", "text/plain");
  1581. });
  1582. auto port = svr.bind_to_any_port(HOST);
  1583. thread t = thread([&] { svr.listen_after_bind(); });
  1584. auto se = detail::scope_exit([&] {
  1585. svr.stop();
  1586. t.join();
  1587. ASSERT_FALSE(svr.is_running());
  1588. });
  1589. svr.wait_until_ready();
  1590. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1591. // not adjacent in the container.
  1592. UploadFormDataItems items = {
  1593. {"tag", "first", "", ""},
  1594. {"other", "x", "", ""},
  1595. {"tag", "second", "", ""},
  1596. };
  1597. Client cli(HOST, port);
  1598. auto res = cli.Post("/repeated", items);
  1599. ASSERT_TRUE(res);
  1600. ASSERT_EQ(2U, values.size());
  1601. EXPECT_EQ("first", values[0]);
  1602. EXPECT_EQ("second", values[1]);
  1603. EXPECT_EQ("first", first);
  1604. EXPECT_EQ("second", second);
  1605. // std::multimap already kept entries sharing a name in insertion order, so
  1606. // everything above passes without this change too. The whole traversal is
  1607. // what tells the two apart: sorting by name would hoist "other" to the front
  1608. // and the two "tag" parts would end up adjacent.
  1609. EXPECT_EQ("tag=first other=x tag=second ", order);
  1610. // Advancing past the last entry of a name used to run off the container;
  1611. // the container's saturating increment makes it return the default instead.
  1612. EXPECT_EQ("", out_of_range);
  1613. }
  1614. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1615. Server svr;
  1616. std::string file_names;
  1617. svr.Post("/upload", [&](const Request &req, Response &res) {
  1618. for (const auto &file : req.form.files) {
  1619. file_names += file.first + "|" + file.second.filename + " ";
  1620. }
  1621. res.set_content("ok", "text/plain");
  1622. });
  1623. auto port = svr.bind_to_any_port(HOST);
  1624. thread t = thread([&] { svr.listen_after_bind(); });
  1625. auto se = detail::scope_exit([&] {
  1626. svr.stop();
  1627. t.join();
  1628. ASSERT_FALSE(svr.is_running());
  1629. });
  1630. svr.wait_until_ready();
  1631. // A trailing backslash would otherwise escape the closing quote.
  1632. UploadFormDataItems items = {
  1633. {"dir\\", "x", "a.txt", "text/plain"},
  1634. {"b", "y", "a\\\\b.txt", "text/plain"},
  1635. };
  1636. Client cli(HOST, port);
  1637. auto res = cli.Post("/upload", items);
  1638. ASSERT_TRUE(res);
  1639. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1640. }
  1641. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1642. // Server::read_content() keeps a FormFields::iterator alive across the
  1643. // content callbacks that fill the part it points at. The container is
  1644. // vector-backed, so a later emplace can reallocate and invalidate an older
  1645. // iterator; 64 parts grow the vector through seven reallocations, which
  1646. // checks that every part's content still lands in its own entry.
  1647. const size_t part_count = 64;
  1648. // One formula for both the parts sent and the values expected back, so the
  1649. // two cannot drift apart.
  1650. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1651. auto content_of = [](size_t i) {
  1652. return std::string(64, static_cast<char>('a' + (i % 26)));
  1653. };
  1654. Server svr;
  1655. std::vector<std::pair<std::string, std::string>> received;
  1656. svr.Post("/many", [&](const Request &req, Response &res) {
  1657. for (const auto &field : req.form.fields) {
  1658. received.emplace_back(field.first, field.second.content);
  1659. }
  1660. res.set_content("ok", "text/plain");
  1661. });
  1662. auto port = svr.bind_to_any_port(HOST);
  1663. thread t = thread([&] { svr.listen_after_bind(); });
  1664. auto se = detail::scope_exit([&] {
  1665. svr.stop();
  1666. t.join();
  1667. ASSERT_FALSE(svr.is_running());
  1668. });
  1669. svr.wait_until_ready();
  1670. UploadFormDataItems items;
  1671. for (size_t i = 0; i < part_count; i++) {
  1672. items.push_back({name_of(i), content_of(i), "", ""});
  1673. }
  1674. Client cli(HOST, port);
  1675. auto res = cli.Post("/many", items);
  1676. ASSERT_TRUE(res);
  1677. ASSERT_EQ(part_count, received.size());
  1678. for (size_t i = 0; i < part_count; i++) {
  1679. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1680. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1681. }
  1682. }
  1683. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1684. string content_type = "multipart/form-data; boundary=something";
  1685. string boundary;
  1686. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1687. EXPECT_TRUE(ret);
  1688. EXPECT_EQ(boundary, "something");
  1689. }
  1690. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1691. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1692. string boundary;
  1693. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1694. EXPECT_TRUE(ret);
  1695. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1696. }
  1697. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1698. string content_type =
  1699. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1700. string boundary;
  1701. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1702. EXPECT_TRUE(ret);
  1703. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1704. }
  1705. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1706. string content_type =
  1707. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1708. string boundary;
  1709. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1710. EXPECT_TRUE(ret);
  1711. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1712. }
  1713. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1714. const string boundary(70, 'a');
  1715. string content_type = "multipart/form-data; boundary=" + boundary;
  1716. string parsed;
  1717. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1718. EXPECT_TRUE(ret);
  1719. EXPECT_EQ(parsed, boundary);
  1720. }
  1721. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1722. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1723. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1724. string parsed;
  1725. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1726. EXPECT_FALSE(ret);
  1727. }
  1728. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1729. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1730. // is 72 characters on the wire and still valid.
  1731. const string boundary(70, 'a');
  1732. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1733. string parsed;
  1734. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1735. EXPECT_EQ(parsed, boundary);
  1736. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1737. parsed.clear();
  1738. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1739. }
  1740. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1741. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1742. // The parameter parser must not treat that '=' as the key/value separator.
  1743. string content_type =
  1744. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1745. "charset=UTF-8";
  1746. string parsed;
  1747. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1748. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1749. }
  1750. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1751. // A ';' inside the quoted-string is part of the value, not a parameter
  1752. // separator, so it must not truncate the boundary.
  1753. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1754. string parsed;
  1755. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1756. EXPECT_EQ(parsed, "a;b");
  1757. }
  1758. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1759. string parsed;
  1760. EXPECT_TRUE(detail::parse_multipart_boundary(
  1761. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1762. EXPECT_EQ("a\\b", parsed);
  1763. EXPECT_TRUE(detail::parse_multipart_boundary(
  1764. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1765. EXPECT_EQ("a\"b", parsed);
  1766. }
  1767. TEST(ParseDispositionParamsTest, QuotedValues) {
  1768. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1769. // ';' and '=' are ordinary characters inside one.
  1770. struct {
  1771. const char *value;
  1772. std::vector<std::pair<const char *, const char *>> expected;
  1773. } cases[] = {
  1774. {"name=\"file1\"; filename=\"a.txt\"",
  1775. {{"name", "file1"}, {"filename", "a.txt"}}},
  1776. // Whitespace around '=' and ';' is still trimmed
  1777. {"name=\"file2\" ;filename = \"a.html\"",
  1778. {{"name", "file2"}, {"filename", "a.html"}}},
  1779. // '=' inside the value used to leave only the text after the last one
  1780. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1781. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1782. {"name=\"x=y\"", {{"name", "x=y"}}},
  1783. // ';' inside the value used to truncate the pair and leave a bogus one
  1784. {"name=\"file3\"; filename=\"a;b.txt\"",
  1785. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1786. // An unquoted value keeps working, and so does filename*
  1787. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1788. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1789. // A parameter with no key is dropped rather than turned into one whose
  1790. // key is the value
  1791. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1792. // An escaped quote does not end the value
  1793. {"name=\"a\\\"; filename=evil.php\"",
  1794. {{"name", "a\"; filename=evil.php"}}},
  1795. // Other backslashes, as in a Windows path, are kept
  1796. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1797. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1798. };
  1799. for (const auto &c : cases) {
  1800. Params params;
  1801. detail::parse_disposition_params(c.value, params);
  1802. for (const auto &kv : c.expected) {
  1803. auto it = params.find(kv.first);
  1804. ASSERT_NE(it, params.end())
  1805. << "value: " << c.value << ", key: " << kv.first;
  1806. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1807. }
  1808. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1809. }
  1810. }
  1811. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1812. Server svr;
  1813. std::string filename;
  1814. std::string content;
  1815. svr.Post("/upload", [&](const Request &req, Response &) {
  1816. const auto &file = req.form.get_file("file");
  1817. filename = file.filename;
  1818. content = file.content;
  1819. });
  1820. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1821. auto se = detail::scope_exit([&] {
  1822. svr.stop();
  1823. thread.join();
  1824. ASSERT_FALSE(svr.is_running());
  1825. });
  1826. svr.wait_until_ready();
  1827. std::string body = "--B\r\n"
  1828. "Content-Disposition: form-data; name=\"file\"; "
  1829. "filename=\"a.txt\"\r\n"
  1830. "Content-Type: text/plain\r\n"
  1831. "\r\n"
  1832. "hello\r\n"
  1833. "--B--\r\n";
  1834. Client cli(HOST, PORT);
  1835. auto res = cli.Post(
  1836. "/upload",
  1837. [&](size_t offset, DataSink &sink) {
  1838. if (offset < body.size()) {
  1839. sink.write(&body[offset], 1);
  1840. } else {
  1841. sink.done();
  1842. }
  1843. return true;
  1844. },
  1845. "multipart/form-data; boundary=B");
  1846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1847. EXPECT_EQ(StatusCode::OK_200, res->status);
  1848. EXPECT_EQ("a.txt", filename);
  1849. EXPECT_EQ("hello", content);
  1850. }
  1851. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1852. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1853. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1854. Server svr;
  1855. std::string field_value, file_name, file_filename;
  1856. bool has_field = false, has_file = false;
  1857. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1858. has_field = req.form.has_field("x=y");
  1859. field_value = req.form.get_field("x=y");
  1860. has_file = req.form.has_file("file1");
  1861. const auto &file = req.form.get_file("file1");
  1862. file_name = file.name;
  1863. file_filename = file.filename;
  1864. res.set_content("ok", "text/plain");
  1865. });
  1866. auto port = svr.bind_to_any_port(HOST);
  1867. thread t = thread([&] { svr.listen_after_bind(); });
  1868. auto se = detail::scope_exit([&] {
  1869. svr.stop();
  1870. t.join();
  1871. ASSERT_FALSE(svr.is_running());
  1872. });
  1873. svr.wait_until_ready();
  1874. UploadFormDataItems items = {
  1875. {"x=y", "field-value", "", ""},
  1876. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1877. };
  1878. Client cli(HOST, port);
  1879. auto res = cli.Post("/quoted", items);
  1880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1881. ASSERT_EQ(StatusCode::OK_200, res->status);
  1882. EXPECT_TRUE(has_field);
  1883. EXPECT_EQ("field-value", field_value);
  1884. EXPECT_TRUE(has_file);
  1885. EXPECT_EQ("file1", file_name);
  1886. EXPECT_EQ("a;b=report.pdf", file_filename);
  1887. }
  1888. TEST(GetHeaderValueTest, DefaultValue) {
  1889. Headers headers = {{"Dummy", "Dummy"}};
  1890. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1891. EXPECT_STREQ("text/plain", val);
  1892. }
  1893. TEST(GetHeaderValueTest, DefaultValueInt) {
  1894. Headers headers = {{"Dummy", "Dummy"}};
  1895. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1896. EXPECT_EQ(100ull, val);
  1897. }
  1898. TEST(GetHeaderValueTest, RegularValue) {
  1899. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1900. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1901. EXPECT_STREQ("text/html", val);
  1902. }
  1903. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1904. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1905. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1906. EXPECT_STREQ("text/html", val);
  1907. }
  1908. TEST(GetHeaderValueTest, SetContent) {
  1909. Response res;
  1910. res.set_content("html", "text/html");
  1911. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1912. res.set_content("text", "text/plain");
  1913. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1914. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1915. }
  1916. TEST(GetHeaderValueTest, RegularValueInt) {
  1917. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1918. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1919. EXPECT_EQ(100ull, val);
  1920. }
  1921. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1922. Headers headers = {{"Content-Length", "x"}};
  1923. auto is_invalid_value = false;
  1924. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1925. is_invalid_value);
  1926. EXPECT_EQ(0ull, val);
  1927. EXPECT_TRUE(is_invalid_value);
  1928. }
  1929. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1930. // An all-digit value that overflows size_t must be reported as invalid, not
  1931. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1932. // a large length to a small one on 32-bit builds, leaving the framing length
  1933. // wrong while is_invalid_value stayed false.
  1934. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1935. auto is_invalid_value = false;
  1936. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1937. is_invalid_value);
  1938. EXPECT_TRUE(is_invalid_value);
  1939. // A well-formed length is unaffected.
  1940. Headers ok = {{"Content-Length", "1234"}};
  1941. is_invalid_value = false;
  1942. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1943. is_invalid_value);
  1944. EXPECT_EQ(1234ull, val);
  1945. EXPECT_FALSE(is_invalid_value);
  1946. }
  1947. TEST(GetHeaderValueTest, Range) {
  1948. {
  1949. Headers headers = {make_range_header({{1, -1}})};
  1950. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1951. EXPECT_STREQ("bytes=1-", val);
  1952. }
  1953. {
  1954. Headers headers = {make_range_header({{-1, 1}})};
  1955. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1956. EXPECT_STREQ("bytes=-1", val);
  1957. }
  1958. {
  1959. Headers headers = {make_range_header({{1, 10}})};
  1960. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1961. EXPECT_STREQ("bytes=1-10", val);
  1962. }
  1963. {
  1964. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1965. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1966. EXPECT_STREQ("bytes=1-10, 100-", val);
  1967. }
  1968. {
  1969. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1970. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1971. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1972. }
  1973. {
  1974. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1975. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1976. EXPECT_STREQ("bytes=0-0, -1", val);
  1977. }
  1978. }
  1979. TEST(BearerTokenAuthTest, SchemeValidation) {
  1980. // A value shorter than "Bearer " must not throw from the fixed-length
  1981. // substr, and a non-Bearer scheme must not be reported as a token.
  1982. struct {
  1983. const char *value;
  1984. const char *expected;
  1985. } cases[] = {
  1986. {"x", ""},
  1987. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1988. {"Bearer abc123", "abc123"},
  1989. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1990. };
  1991. for (const auto &c : cases) {
  1992. Request req;
  1993. req.set_header("Authorization", c.value);
  1994. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1995. }
  1996. }
  1997. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1998. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1999. // to depend on the standard library (libstdc++ handed back duplicates in
  2000. // reverse insertion order, libc++ in insertion order).
  2001. Request req;
  2002. req.set_header("Accept-Encoding", "gzip");
  2003. req.set_header("Accept-Encoding", "deflate");
  2004. req.set_header("Accept-Encoding", "br");
  2005. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  2006. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  2007. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  2008. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  2009. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  2010. }
  2011. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  2012. Request req;
  2013. req.set_header("X-Test", "only");
  2014. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  2015. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  2016. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  2017. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  2018. }
  2019. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  2020. Request req;
  2021. req.set_header("X-First", "1");
  2022. req.set_header("X-Test", "2");
  2023. req.params.emplace("first", "1");
  2024. req.params.emplace("test", "2");
  2025. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2026. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2027. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2028. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2029. // The second one is negative when read as a signed value
  2030. const auto max_id = (std::numeric_limits<size_t>::max)();
  2031. for (auto id : {max_id / 2, max_id}) {
  2032. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2033. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2034. EXPECT_EQ("", req.get_param_value("test", id));
  2035. EXPECT_EQ("", req.form.get_field("test", id));
  2036. EXPECT_EQ("", req.form.get_file("test", id).content);
  2037. }
  2038. }
  2039. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2040. Headers headers;
  2041. headers.emplace("Host", "example.com");
  2042. headers.emplace("Accept-Encoding", "gzip");
  2043. headers.emplace("User-Agent", "test");
  2044. headers.emplace("Accept-Encoding", "deflate");
  2045. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2046. "Accept-Encoding=deflate ",
  2047. entries_to_string(headers));
  2048. }
  2049. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2050. Headers headers = {{"Content-Type", "text/html"},
  2051. {"CONTENT-TYPE", "text/xml"}};
  2052. EXPECT_EQ(2U, headers.count("content-type"));
  2053. auto it = headers.find("content-type");
  2054. ASSERT_TRUE(it != headers.end());
  2055. EXPECT_EQ("text/html", it->second);
  2056. }
  2057. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2058. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2059. // drop only those fields and leave everything positioned between them.
  2060. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2061. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2062. auto rng = headers.equal_range("a");
  2063. headers.erase(rng.first, rng.second);
  2064. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2065. }
  2066. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2067. Headers headers = {
  2068. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2069. EXPECT_EQ(3U, headers.erase("A"));
  2070. EXPECT_EQ(0U, headers.count("A"));
  2071. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2072. }
  2073. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2074. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2075. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2076. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2077. }
  2078. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2079. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2080. headers.emplace_front("Host", "example.com");
  2081. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2082. entries_to_string(headers));
  2083. }
  2084. TEST(ParseHeaderValueTest, Range) {
  2085. {
  2086. Ranges ranges;
  2087. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2088. EXPECT_TRUE(ret);
  2089. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2090. }
  2091. {
  2092. Ranges ranges;
  2093. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2094. EXPECT_TRUE(ret);
  2095. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2096. }
  2097. {
  2098. Ranges ranges;
  2099. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2100. EXPECT_TRUE(ret);
  2101. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2102. }
  2103. {
  2104. Ranges ranges;
  2105. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2106. EXPECT_FALSE(ret);
  2107. }
  2108. {
  2109. Ranges ranges;
  2110. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2111. EXPECT_TRUE(ret);
  2112. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2113. }
  2114. {
  2115. Ranges ranges;
  2116. auto ret =
  2117. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2118. EXPECT_TRUE(ret);
  2119. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2120. }
  2121. {
  2122. Ranges ranges;
  2123. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2124. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2125. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2126. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2127. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2128. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2129. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2130. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2131. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2132. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2133. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2134. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2135. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2136. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2137. EXPECT_FALSE(
  2138. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2139. EXPECT_TRUE(ranges.empty());
  2140. }
  2141. {
  2142. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2143. // remainder of the representation, so it stays accepted.
  2144. Ranges ranges;
  2145. auto ret =
  2146. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2147. EXPECT_TRUE(ret);
  2148. ASSERT_EQ(1u, ranges.size());
  2149. EXPECT_EQ(0, ranges[0].first);
  2150. EXPECT_EQ(-1, ranges[0].second);
  2151. }
  2152. // RFC 9110 14.1: range unit names are case-insensitive.
  2153. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2154. Ranges ranges;
  2155. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2156. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2157. }
  2158. }
  2159. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2160. Request req;
  2161. req.set_header("Accept-Encoding", "gzip");
  2162. Response res;
  2163. res.set_header("Content-Type", "text/plain");
  2164. auto ret = detail::encoding_type(req, res);
  2165. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2166. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2167. #else
  2168. EXPECT_TRUE(ret == detail::EncodingType::None);
  2169. #endif
  2170. }
  2171. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2172. Request req;
  2173. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2174. Response res;
  2175. res.set_header("Content-Type", "text/plain");
  2176. auto ret = detail::encoding_type(req, res);
  2177. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2178. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2179. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2180. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2181. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2182. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2183. #else
  2184. EXPECT_TRUE(ret == detail::EncodingType::None);
  2185. #endif
  2186. }
  2187. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2188. Request req;
  2189. req.set_header("Accept-Encoding",
  2190. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2191. Response res;
  2192. res.set_header("Content-Type", "text/plain");
  2193. auto ret = detail::encoding_type(req, res);
  2194. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2195. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2196. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2197. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2198. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2199. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2200. #else
  2201. EXPECT_TRUE(ret == detail::EncodingType::None);
  2202. #endif
  2203. }
  2204. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2205. // All supported encodings rejected with q=0 should return None
  2206. Request req;
  2207. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2208. Response res;
  2209. res.set_header("Content-Type", "text/plain");
  2210. auto ret = detail::encoding_type(req, res);
  2211. EXPECT_TRUE(ret == detail::EncodingType::None);
  2212. }
  2213. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2214. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2215. Request req;
  2216. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2217. Response res;
  2218. res.set_header("Content-Type", "text/plain");
  2219. auto ret = detail::encoding_type(req, res);
  2220. EXPECT_TRUE(ret == detail::EncodingType::None);
  2221. }
  2222. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2223. Request req;
  2224. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2225. Response res;
  2226. res.set_header("Content-Type", "text/plain");
  2227. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2228. }
  2229. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2230. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2231. Request req;
  2232. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2233. Response res;
  2234. res.set_header("Content-Type", "text/plain");
  2235. auto ret = detail::encoding_type(req, res);
  2236. EXPECT_TRUE(ret == detail::EncodingType::None);
  2237. }
  2238. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2239. // RFC 7231: Accept-Encoding values are case-insensitive
  2240. Request req;
  2241. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2242. Response res;
  2243. res.set_header("Content-Type", "text/plain");
  2244. auto ret = detail::encoding_type(req, res);
  2245. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2246. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2247. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2248. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2249. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2250. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2251. #else
  2252. EXPECT_TRUE(ret == detail::EncodingType::None);
  2253. #endif
  2254. }
  2255. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2256. // q value should determine priority, not hardcoded order
  2257. Request req;
  2258. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2259. Response res;
  2260. res.set_header("Content-Type", "text/plain");
  2261. auto ret = detail::encoding_type(req, res);
  2262. // gzip has highest q=1.0, so it should be selected even though
  2263. // br and zstd are also supported
  2264. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2265. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2266. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2267. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2268. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2269. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2270. #else
  2271. EXPECT_TRUE(ret == detail::EncodingType::None);
  2272. #endif
  2273. }
  2274. TEST(BufferStreamTest, read) {
  2275. detail::BufferStream strm1;
  2276. Stream &strm = strm1;
  2277. EXPECT_EQ(5, strm.write("hello"));
  2278. char buf[512];
  2279. EXPECT_EQ(2, strm.read(buf, 2));
  2280. EXPECT_EQ('h', buf[0]);
  2281. EXPECT_EQ('e', buf[1]);
  2282. EXPECT_EQ(2, strm.read(buf, 2));
  2283. EXPECT_EQ('l', buf[0]);
  2284. EXPECT_EQ('l', buf[1]);
  2285. EXPECT_EQ(1, strm.read(buf, 1));
  2286. EXPECT_EQ('o', buf[0]);
  2287. EXPECT_EQ(0, strm.read(buf, 1));
  2288. }
  2289. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2290. auto host = "www.httpwatch.com";
  2291. auto ip = hosted_at(host);
  2292. EXPECT_EQ("23.96.13.243", ip);
  2293. std::vector<std::string> addrs;
  2294. hosted_at(host, addrs);
  2295. EXPECT_EQ(1u, addrs.size());
  2296. }
  2297. #if 0 // It depends on each test environment...
  2298. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2299. auto host = "www.youtube.com";
  2300. std::vector<std::string> addrs;
  2301. hosted_at(host, addrs);
  2302. EXPECT_EQ(20u, addrs.size());
  2303. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2304. EXPECT_TRUE(it != addrs.end());
  2305. }
  2306. #endif
  2307. class ChunkedEncodingTest : public ::testing::Test {
  2308. protected:
  2309. ChunkedEncodingTest()
  2310. : cli_(HOST, PORT)
  2311. #ifdef CPPHTTPLIB_SSL_ENABLED
  2312. ,
  2313. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2314. #endif
  2315. {
  2316. cli_.set_connection_timeout(2);
  2317. #ifdef CPPHTTPLIB_SSL_ENABLED
  2318. cli_.enable_server_certificate_verification(false);
  2319. #endif
  2320. }
  2321. virtual void SetUp() {
  2322. read_file("./image.jpg", image_data_);
  2323. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2324. res.set_content("Hello World!", "text/plain");
  2325. });
  2326. svr_.Get(
  2327. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2328. res.set_chunked_content_provider(
  2329. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2330. size_t remaining = image_data_.size() - offset;
  2331. if (remaining == 0) {
  2332. sink.done();
  2333. } else {
  2334. constexpr size_t CHUNK_SIZE = 1024;
  2335. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2336. sink.write(&image_data_[offset], send_size);
  2337. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2338. }
  2339. return true;
  2340. });
  2341. });
  2342. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2343. svr_.wait_until_ready();
  2344. }
  2345. virtual void TearDown() {
  2346. svr_.stop();
  2347. if (!request_threads_.empty()) {
  2348. std::this_thread::sleep_for(std::chrono::seconds(1));
  2349. for (auto &t : request_threads_) {
  2350. t.join();
  2351. }
  2352. }
  2353. t_.join();
  2354. }
  2355. #ifdef CPPHTTPLIB_SSL_ENABLED
  2356. SSLClient cli_;
  2357. SSLServer svr_;
  2358. #else
  2359. Client cli_;
  2360. Server svr_;
  2361. #endif
  2362. thread t_;
  2363. std::vector<thread> request_threads_;
  2364. std::string image_data_;
  2365. };
  2366. TEST_F(ChunkedEncodingTest, NormalGet) {
  2367. auto res = cli_.Get("/chunked");
  2368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2369. std::string out;
  2370. read_file("./image.jpg", out);
  2371. EXPECT_EQ(StatusCode::OK_200, res->status);
  2372. EXPECT_EQ(out, res->body);
  2373. }
  2374. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2375. std::string body;
  2376. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2377. body.append(data, data_length);
  2378. return true;
  2379. });
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. std::string out;
  2382. read_file("./image.jpg", out);
  2383. EXPECT_EQ(StatusCode::OK_200, res->status);
  2384. EXPECT_EQ(out, body);
  2385. }
  2386. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2387. std::string body;
  2388. auto res = cli_.Get(
  2389. "/chunked",
  2390. [&](const Response &response) {
  2391. EXPECT_EQ(StatusCode::OK_200, response.status);
  2392. return true;
  2393. },
  2394. [&](const char *data, size_t data_length) {
  2395. body.append(data, data_length);
  2396. return true;
  2397. });
  2398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2399. std::string out;
  2400. read_file("./image.jpg", out);
  2401. EXPECT_EQ(StatusCode::OK_200, res->status);
  2402. EXPECT_EQ(out, body);
  2403. }
  2404. TEST(RangeTest, FromHTTPBin_Online) {
  2405. auto host = "httpbingo.org";
  2406. auto path = std::string{"/range/32"};
  2407. #ifdef CPPHTTPLIB_SSL_ENABLED
  2408. auto port = 443;
  2409. SSLClient cli(host, port);
  2410. #else
  2411. auto port = 80;
  2412. Client cli(host, port);
  2413. #endif
  2414. cli.set_connection_timeout(5);
  2415. {
  2416. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  2417. SKIP_ON_GATEWAY_ERROR(res);
  2418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2419. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2420. EXPECT_EQ(StatusCode::OK_200, res->status);
  2421. }
  2422. {
  2423. Headers headers = {make_range_header({{1, -1}})};
  2424. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2425. SKIP_ON_GATEWAY_ERROR(res);
  2426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2427. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2428. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2429. }
  2430. {
  2431. Headers headers = {make_range_header({{1, 10}})};
  2432. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2433. SKIP_ON_GATEWAY_ERROR(res);
  2434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2435. EXPECT_EQ("bcdefghijk", res->body);
  2436. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2437. }
  2438. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2439. // entire resource, while the original httpbin returned 200. Both are
  2440. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2441. {
  2442. Headers headers = {make_range_header({{0, 31}})};
  2443. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2444. SKIP_ON_GATEWAY_ERROR(res);
  2445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2446. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2447. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2448. res->status == StatusCode::PartialContent_206);
  2449. }
  2450. {
  2451. Headers headers = {make_range_header({{0, -1}})};
  2452. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2453. SKIP_ON_GATEWAY_ERROR(res);
  2454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2455. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2456. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2457. res->status == StatusCode::PartialContent_206);
  2458. }
  2459. // go-httpbin returns 206 with clamped range for over-range requests,
  2460. // while the original httpbin returned 416. Both behaviors are observed
  2461. // in real servers, so we only verify the request succeeds.
  2462. {
  2463. Headers headers = {make_range_header({{0, 32}})};
  2464. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2465. SKIP_ON_GATEWAY_ERROR(res);
  2466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2467. }
  2468. }
  2469. TEST(RangeTest, IgnoredForPost) {
  2470. Server svr;
  2471. svr.Post("/", [](const Request &, Response &res) {
  2472. res.set_content("abcdefg", "text/plain");
  2473. });
  2474. auto port = svr.bind_to_any_port(HOST);
  2475. ASSERT_GT(port, 0);
  2476. thread t = thread([&] { svr.listen_after_bind(); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. t.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, port);
  2484. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2485. auto res = cli.Post("/", Headers{{"Range", range}});
  2486. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2487. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2488. EXPECT_EQ("abcdefg", res->body) << range;
  2489. }
  2490. }
  2491. TEST(RangeTest, IgnoredForUnknownUnit) {
  2492. Server svr;
  2493. svr.Get("/", [](const Request &, Response &res) {
  2494. res.set_content("abcdefg", "text/plain");
  2495. });
  2496. auto port = svr.bind_to_any_port(HOST);
  2497. ASSERT_GT(port, 0);
  2498. thread t = thread([&] { svr.listen_after_bind(); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. t.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. Client cli(HOST, port);
  2506. for (auto range : {"items=1-2", "none=x"}) {
  2507. auto res = cli.Get("/", Headers{{"Range", range}});
  2508. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2509. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2510. EXPECT_EQ("abcdefg", res->body) << range;
  2511. }
  2512. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2513. ASSERT_TRUE(res) << to_string(res.error());
  2514. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2515. }
  2516. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2517. auto host = "unresolvableaddress.local";
  2518. auto path = std::string{"/"};
  2519. #ifdef CPPHTTPLIB_SSL_ENABLED
  2520. auto port = 443;
  2521. SSLClient cli(host, port);
  2522. #else
  2523. auto port = 80;
  2524. Client cli(host, port);
  2525. #endif
  2526. cli.set_connection_timeout(1);
  2527. {
  2528. auto res = cli.Get(path);
  2529. ASSERT_FALSE(res);
  2530. }
  2531. std::this_thread::sleep_for(std::chrono::seconds(8));
  2532. }
  2533. #if defined(__linux__) && defined(__GLIBC__) && \
  2534. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2535. // Forward declaration: in split builds split.py strips `inline` and moves the
  2536. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2537. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2538. // against the symbol in both header-only and split builds.
  2539. namespace httplib {
  2540. namespace detail {
  2541. int getaddrinfo_with_timeout(const char *node, const char *service,
  2542. const struct addrinfo *hints,
  2543. struct addrinfo **res, time_t timeout_sec);
  2544. } // namespace detail
  2545. } // namespace httplib
  2546. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2547. //
  2548. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2549. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2550. // gai_suspend() call hits the connection timeout the function calls
  2551. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2552. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2553. // still alive and still references the now-destroyed stack frame.
  2554. //
  2555. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2556. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2557. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2558. // and runs them in a container.
  2559. namespace {
  2560. bool should_run_issue_2431_tests() {
  2561. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2562. return v && *v && std::string(v) != "0";
  2563. }
  2564. std::string unique_unresolvable_host(int n) {
  2565. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2566. // glibc still asks the configured nameserver — which is exactly the path
  2567. // we want to exercise. A unique label per call avoids the resolver cache.
  2568. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2569. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2570. std::to_string(n) + ".invalid";
  2571. }
  2572. } // namespace
  2573. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2574. if (!should_run_issue_2431_tests()) {
  2575. GTEST_SKIP()
  2576. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2577. }
  2578. for (int i = 0; i < 8; ++i) {
  2579. struct addrinfo hints;
  2580. memset(&hints, 0, sizeof(hints));
  2581. hints.ai_family = AF_UNSPEC;
  2582. hints.ai_socktype = SOCK_STREAM;
  2583. auto host = unique_unresolvable_host(i);
  2584. struct addrinfo *result = nullptr;
  2585. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2586. &result, /*timeout_sec=*/1);
  2587. if (rc == 0 && result) { freeaddrinfo(result); }
  2588. }
  2589. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2590. // stack region they still believe holds their gaicb.
  2591. std::this_thread::sleep_for(std::chrono::seconds(3));
  2592. }
  2593. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2594. if (!should_run_issue_2431_tests()) {
  2595. GTEST_SKIP()
  2596. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2597. }
  2598. std::atomic<bool> stop{false};
  2599. std::vector<std::thread> threads;
  2600. for (int t = 0; t < 8; ++t) {
  2601. threads.emplace_back([t, &stop] {
  2602. int i = 0;
  2603. while (!stop.load(std::memory_order_relaxed)) {
  2604. struct addrinfo hints;
  2605. memset(&hints, 0, sizeof(hints));
  2606. hints.ai_family = AF_UNSPEC;
  2607. hints.ai_socktype = SOCK_STREAM;
  2608. auto host = unique_unresolvable_host(t * 100000 + i++);
  2609. struct addrinfo *result = nullptr;
  2610. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2611. &result, /*timeout_sec=*/1);
  2612. if (rc == 0 && result) { freeaddrinfo(result); }
  2613. }
  2614. });
  2615. }
  2616. std::this_thread::sleep_for(std::chrono::seconds(8));
  2617. stop.store(true, std::memory_order_relaxed);
  2618. for (auto &th : threads) {
  2619. th.join();
  2620. }
  2621. std::this_thread::sleep_for(std::chrono::seconds(3));
  2622. }
  2623. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2624. if (!should_run_issue_2431_tests()) {
  2625. GTEST_SKIP()
  2626. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2627. }
  2628. std::atomic<bool> stop{false};
  2629. std::vector<std::thread> threads;
  2630. for (int t = 0; t < 8; ++t) {
  2631. threads.emplace_back([t, &stop] {
  2632. int i = 0;
  2633. while (!stop.load(std::memory_order_relaxed)) {
  2634. auto host = unique_unresolvable_host(t * 100000 + i++);
  2635. Client cli(host, 80);
  2636. cli.set_connection_timeout(1, 0);
  2637. cli.set_read_timeout(1, 0);
  2638. cli.set_write_timeout(1, 0);
  2639. (void)cli.Get("/");
  2640. }
  2641. });
  2642. }
  2643. std::this_thread::sleep_for(std::chrono::seconds(8));
  2644. stop.store(true, std::memory_order_relaxed);
  2645. for (auto &th : threads) {
  2646. th.join();
  2647. }
  2648. std::this_thread::sleep_for(std::chrono::seconds(3));
  2649. }
  2650. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2651. TEST(ConnectionErrorTest, InvalidHost) {
  2652. auto host = "-abcde.com";
  2653. #ifdef CPPHTTPLIB_SSL_ENABLED
  2654. auto port = 443;
  2655. SSLClient cli(host, port);
  2656. #else
  2657. auto port = 80;
  2658. Client cli(host, port);
  2659. #endif
  2660. cli.set_connection_timeout(std::chrono::seconds(2));
  2661. auto res = cli.Get("/");
  2662. ASSERT_TRUE(!res);
  2663. EXPECT_EQ(Error::Connection, res.error());
  2664. }
  2665. TEST(ConnectionErrorTest, InvalidHost2) {
  2666. auto host = "httpcan.org/";
  2667. #ifdef CPPHTTPLIB_SSL_ENABLED
  2668. SSLClient cli(host);
  2669. #else
  2670. Client cli(host);
  2671. #endif
  2672. cli.set_connection_timeout(std::chrono::seconds(2));
  2673. auto res = cli.Get("/");
  2674. ASSERT_TRUE(!res);
  2675. EXPECT_EQ(Error::Connection, res.error());
  2676. }
  2677. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2678. auto host = "httpcan.org/";
  2679. #ifdef CPPHTTPLIB_SSL_ENABLED
  2680. SSLClient cli(host);
  2681. #else
  2682. Client cli(host);
  2683. #endif
  2684. cli.set_connection_timeout(std::chrono::seconds(2));
  2685. auto res = cli.Get("/");
  2686. ASSERT_TRUE(!res);
  2687. stringstream s;
  2688. s << "error code: " << res.error();
  2689. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2690. }
  2691. TEST(ConnectionErrorTest, InvalidPort) {
  2692. auto host = "localhost";
  2693. auto port = 44380;
  2694. #ifdef CPPHTTPLIB_SSL_ENABLED
  2695. SSLClient cli(host, port);
  2696. #else
  2697. Client cli(host, port);
  2698. #endif
  2699. cli.set_connection_timeout(std::chrono::seconds(2));
  2700. auto res = cli.Get("/");
  2701. ASSERT_TRUE(!res);
  2702. EXPECT_TRUE(Error::Connection == res.error() ||
  2703. Error::ConnectionTimeout == res.error());
  2704. }
  2705. TEST(ConnectionErrorTest, Timeout_Online) {
  2706. auto host = "google.com";
  2707. #ifdef CPPHTTPLIB_SSL_ENABLED
  2708. auto port = 44380;
  2709. SSLClient cli(host, port);
  2710. #else
  2711. auto port = 8080;
  2712. Client cli(host, port);
  2713. #endif
  2714. cli.set_connection_timeout(std::chrono::seconds(2));
  2715. // only probe one address type so that the error reason
  2716. // correlates to the timed-out IPv4, not the unsupported
  2717. // IPv6 connection attempt
  2718. cli.set_address_family(AF_INET);
  2719. auto res = cli.Get("/");
  2720. ASSERT_TRUE(!res);
  2721. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2722. }
  2723. TEST(CancelTest, NoCancel_Online) {
  2724. auto host = "httpbingo.org";
  2725. auto path = std::string{"/range/32"};
  2726. #ifdef CPPHTTPLIB_SSL_ENABLED
  2727. auto port = 443;
  2728. SSLClient cli(host, port);
  2729. #else
  2730. auto port = 80;
  2731. Client cli(host, port);
  2732. #endif
  2733. cli.set_connection_timeout(std::chrono::seconds(5));
  2734. auto res = retry_gateway_errors(
  2735. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
  2736. SKIP_ON_GATEWAY_ERROR(res);
  2737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2738. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2739. EXPECT_EQ(StatusCode::OK_200, res->status);
  2740. }
  2741. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2742. // Use /bytes with a large payload so that the DownloadProgress callback
  2743. // (which only fires for Content-Length responses) is invoked before the
  2744. // entire body is received, giving cancellation a chance to fire.
  2745. auto host = "httpbingo.org";
  2746. auto path = std::string{"/bytes/524288"};
  2747. #ifdef CPPHTTPLIB_SSL_ENABLED
  2748. auto port = 443;
  2749. SSLClient cli(host, port);
  2750. #else
  2751. auto port = 80;
  2752. Client cli(host, port);
  2753. #endif
  2754. auto res = retry_gateway_errors(
  2755. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
  2756. SKIP_ON_GATEWAY_ERROR(res);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. ASSERT_TRUE(!res);
  2759. EXPECT_EQ(Error::Canceled, res.error());
  2760. }
  2761. TEST(CancelTest, WithCancelLargePayload_Online) {
  2762. auto host = "httpbingo.org";
  2763. auto path = std::string{"/bytes/524288"};
  2764. #ifdef CPPHTTPLIB_SSL_ENABLED
  2765. auto port = 443;
  2766. SSLClient cli(host, port);
  2767. #else
  2768. auto port = 80;
  2769. Client cli(host, port);
  2770. #endif
  2771. cli.set_connection_timeout(std::chrono::seconds(5));
  2772. auto res = retry_gateway_errors([&] {
  2773. auto count = 0;
  2774. return cli.Get(path,
  2775. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2776. });
  2777. SKIP_ON_GATEWAY_ERROR(res);
  2778. ASSERT_TRUE(!res);
  2779. EXPECT_EQ(Error::Canceled, res.error());
  2780. }
  2781. TEST(CancelTest, NoCancelPost) {
  2782. Server svr;
  2783. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2784. res.set_content("Hello World!", "text/plain");
  2785. });
  2786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2787. auto se = detail::scope_exit([&] {
  2788. svr.stop();
  2789. thread.join();
  2790. ASSERT_FALSE(svr.is_running());
  2791. });
  2792. svr.wait_until_ready();
  2793. Client cli(HOST, PORT);
  2794. cli.set_connection_timeout(std::chrono::seconds(5));
  2795. auto res =
  2796. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2797. "application/json", [](uint64_t, uint64_t) { return true; });
  2798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2799. EXPECT_EQ("Hello World!", res->body);
  2800. EXPECT_EQ(StatusCode::OK_200, res->status);
  2801. }
  2802. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2803. Server svr;
  2804. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2805. res.set_content("Hello World!", "text/plain");
  2806. });
  2807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2808. auto se = detail::scope_exit([&] {
  2809. svr.stop();
  2810. thread.join();
  2811. ASSERT_FALSE(svr.is_running());
  2812. });
  2813. svr.wait_until_ready();
  2814. Client cli(HOST, PORT);
  2815. cli.set_connection_timeout(std::chrono::seconds(5));
  2816. auto res =
  2817. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2818. "application/json", [](uint64_t, uint64_t) { return false; });
  2819. ASSERT_TRUE(!res);
  2820. EXPECT_EQ(Error::Canceled, res.error());
  2821. }
  2822. TEST(CancelTest, WithCancelLargePayloadPost) {
  2823. Server svr;
  2824. svr.set_payload_max_length(200 * 1024 * 1024);
  2825. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2826. res.set_content(LARGE_DATA, "text/plain");
  2827. });
  2828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2829. auto se = detail::scope_exit([&] {
  2830. svr.stop();
  2831. thread.join();
  2832. ASSERT_FALSE(svr.is_running());
  2833. });
  2834. svr.wait_until_ready();
  2835. Client cli(HOST, PORT);
  2836. cli.set_payload_max_length(200 * 1024 * 1024);
  2837. cli.set_connection_timeout(std::chrono::seconds(5));
  2838. auto res =
  2839. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2840. "application/json", [](uint64_t, uint64_t) { return false; });
  2841. ASSERT_TRUE(!res);
  2842. EXPECT_EQ(Error::Canceled, res.error());
  2843. }
  2844. TEST(CancelTest, NoCancelPut) {
  2845. Server svr;
  2846. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2847. res.set_content("Hello World!", "text/plain");
  2848. });
  2849. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2850. auto se = detail::scope_exit([&] {
  2851. svr.stop();
  2852. thread.join();
  2853. ASSERT_FALSE(svr.is_running());
  2854. });
  2855. svr.wait_until_ready();
  2856. Client cli(HOST, PORT);
  2857. cli.set_connection_timeout(std::chrono::seconds(5));
  2858. auto res =
  2859. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2860. "application/json", [](uint64_t, uint64_t) { return true; });
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. EXPECT_EQ("Hello World!", res->body);
  2863. EXPECT_EQ(StatusCode::OK_200, res->status);
  2864. }
  2865. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2866. Server svr;
  2867. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2868. res.set_content("Hello World!", "text/plain");
  2869. });
  2870. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2871. auto se = detail::scope_exit([&] {
  2872. svr.stop();
  2873. thread.join();
  2874. ASSERT_FALSE(svr.is_running());
  2875. });
  2876. svr.wait_until_ready();
  2877. Client cli(HOST, PORT);
  2878. cli.set_connection_timeout(std::chrono::seconds(5));
  2879. auto res =
  2880. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2881. "application/json", [](uint64_t, uint64_t) { return false; });
  2882. ASSERT_TRUE(!res);
  2883. EXPECT_EQ(Error::Canceled, res.error());
  2884. }
  2885. TEST(CancelTest, WithCancelLargePayloadPut) {
  2886. Server svr;
  2887. svr.set_payload_max_length(200 * 1024 * 1024);
  2888. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2889. res.set_content(LARGE_DATA, "text/plain");
  2890. });
  2891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2892. auto se = detail::scope_exit([&] {
  2893. svr.stop();
  2894. thread.join();
  2895. ASSERT_FALSE(svr.is_running());
  2896. });
  2897. svr.wait_until_ready();
  2898. Client cli(HOST, PORT);
  2899. cli.set_payload_max_length(200 * 1024 * 1024);
  2900. cli.set_connection_timeout(std::chrono::seconds(5));
  2901. auto res =
  2902. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2903. "application/json", [](uint64_t, uint64_t) { return false; });
  2904. ASSERT_TRUE(!res);
  2905. EXPECT_EQ(Error::Canceled, res.error());
  2906. }
  2907. TEST(CancelTest, NoCancelPatch) {
  2908. Server svr;
  2909. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2910. res.set_content("Hello World!", "text/plain");
  2911. });
  2912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2913. auto se = detail::scope_exit([&] {
  2914. svr.stop();
  2915. thread.join();
  2916. ASSERT_FALSE(svr.is_running());
  2917. });
  2918. svr.wait_until_ready();
  2919. Client cli(HOST, PORT);
  2920. cli.set_connection_timeout(std::chrono::seconds(5));
  2921. auto res =
  2922. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2923. "application/json", [](uint64_t, uint64_t) { return true; });
  2924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2925. EXPECT_EQ("Hello World!", res->body);
  2926. EXPECT_EQ(StatusCode::OK_200, res->status);
  2927. }
  2928. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2929. Server svr;
  2930. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2931. res.set_content("Hello World!", "text/plain");
  2932. });
  2933. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2934. auto se = detail::scope_exit([&] {
  2935. svr.stop();
  2936. thread.join();
  2937. ASSERT_FALSE(svr.is_running());
  2938. });
  2939. svr.wait_until_ready();
  2940. Client cli(HOST, PORT);
  2941. cli.set_connection_timeout(std::chrono::seconds(5));
  2942. auto res =
  2943. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2944. "application/json", [](uint64_t, uint64_t) { return false; });
  2945. ASSERT_TRUE(!res);
  2946. EXPECT_EQ(Error::Canceled, res.error());
  2947. }
  2948. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2949. Server svr;
  2950. svr.set_payload_max_length(200 * 1024 * 1024);
  2951. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2952. res.set_content(LARGE_DATA, "text/plain");
  2953. });
  2954. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2955. auto se = detail::scope_exit([&] {
  2956. svr.stop();
  2957. thread.join();
  2958. ASSERT_FALSE(svr.is_running());
  2959. });
  2960. svr.wait_until_ready();
  2961. Client cli(HOST, PORT);
  2962. cli.set_payload_max_length(200 * 1024 * 1024);
  2963. cli.set_connection_timeout(std::chrono::seconds(5));
  2964. auto res =
  2965. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2966. "application/json", [](uint64_t, uint64_t) { return false; });
  2967. ASSERT_TRUE(!res);
  2968. EXPECT_EQ(Error::Canceled, res.error());
  2969. }
  2970. TEST(CancelTest, NoCancelDelete) {
  2971. Server svr;
  2972. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2973. res.set_content("Hello World!", "text/plain");
  2974. });
  2975. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2976. auto se = detail::scope_exit([&] {
  2977. svr.stop();
  2978. thread.join();
  2979. ASSERT_FALSE(svr.is_running());
  2980. });
  2981. svr.wait_until_ready();
  2982. Client cli(HOST, PORT);
  2983. cli.set_connection_timeout(std::chrono::seconds(5));
  2984. auto res =
  2985. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2986. "application/json", [](uint64_t, uint64_t) { return true; });
  2987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2988. EXPECT_EQ("Hello World!", res->body);
  2989. EXPECT_EQ(StatusCode::OK_200, res->status);
  2990. }
  2991. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2992. Server svr;
  2993. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2994. res.set_content("Hello World!", "text/plain");
  2995. });
  2996. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2997. auto se = detail::scope_exit([&] {
  2998. svr.stop();
  2999. thread.join();
  3000. ASSERT_FALSE(svr.is_running());
  3001. });
  3002. svr.wait_until_ready();
  3003. Client cli(HOST, PORT);
  3004. cli.set_connection_timeout(std::chrono::seconds(5));
  3005. auto res =
  3006. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3007. "application/json", [](uint64_t, uint64_t) { return false; });
  3008. ASSERT_TRUE(!res);
  3009. EXPECT_EQ(Error::Canceled, res.error());
  3010. }
  3011. TEST(CancelTest, WithCancelLargePayloadDelete) {
  3012. Server svr;
  3013. svr.set_payload_max_length(200 * 1024 * 1024);
  3014. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3015. res.set_content(LARGE_DATA, "text/plain");
  3016. });
  3017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. thread.join();
  3021. ASSERT_FALSE(svr.is_running());
  3022. });
  3023. svr.wait_until_ready();
  3024. Client cli(HOST, PORT);
  3025. cli.set_payload_max_length(200 * 1024 * 1024);
  3026. cli.set_connection_timeout(std::chrono::seconds(5));
  3027. auto res =
  3028. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3029. "application/json", [](uint64_t, uint64_t) { return false; });
  3030. ASSERT_TRUE(!res);
  3031. EXPECT_EQ(Error::Canceled, res.error());
  3032. }
  3033. // One stop() from another thread ends a request that waits for the response
  3034. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3035. Server svr;
  3036. std::atomic<bool> received{false};
  3037. std::atomic<bool> done{false};
  3038. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3039. received.store(true);
  3040. while (!done.load()) {
  3041. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3042. }
  3043. res.set_content("Hello World!", "text/plain");
  3044. });
  3045. auto port = svr.bind_to_any_port(HOST);
  3046. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3047. Client cli(HOST, port);
  3048. cli.set_read_timeout(std::chrono::seconds(30));
  3049. std::future<Result> request;
  3050. auto se = detail::scope_exit([&] {
  3051. done.store(true);
  3052. svr.stop();
  3053. thread.join();
  3054. ASSERT_FALSE(svr.is_running());
  3055. });
  3056. svr.wait_until_ready();
  3057. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3058. for (int i = 0; i < 500 && !received.load(); ++i) {
  3059. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3060. }
  3061. ASSERT_TRUE(received.load());
  3062. // Let the client block in the wait for the response
  3063. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3064. auto start = std::chrono::steady_clock::now();
  3065. cli.stop();
  3066. ASSERT_EQ(std::future_status::ready,
  3067. request.wait_for(std::chrono::seconds(5)));
  3068. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3069. auto res = request.get();
  3070. ASSERT_TRUE(!res);
  3071. EXPECT_EQ(Error::Read, res.error());
  3072. }
  3073. // A listener whose backlog completes the TCP connections of clients, and that
  3074. // never answers them
  3075. struct SilentListener {
  3076. socket_t sock = INVALID_SOCKET;
  3077. sockaddr_in addr{};
  3078. int port = 0;
  3079. explicit SilentListener(int backlog = 1) {
  3080. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3081. addr.sin_family = AF_INET;
  3082. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3083. socklen_t len = sizeof(addr);
  3084. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3085. ::listen(sock, backlog) != 0 ||
  3086. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3087. detail::close_socket(sock);
  3088. sock = INVALID_SOCKET;
  3089. }
  3090. port = ntohs(addr.sin_port);
  3091. }
  3092. ~SilentListener() { detail::close_socket(sock); }
  3093. // The next connection, whose reads give up after 5 seconds
  3094. socket_t accept() const {
  3095. auto peer = ::accept(sock, nullptr, nullptr);
  3096. if (peer != INVALID_SOCKET) {
  3097. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3098. }
  3099. return peer;
  3100. }
  3101. };
  3102. static bool receives_a_byte(socket_t peer) {
  3103. char c = 0;
  3104. return detail::read_socket(peer, &c, 1, 0) == 1;
  3105. }
  3106. // Runs op, stops cli once the listener receives the first byte op sends, and
  3107. // expects op to end with error soon after
  3108. template <typename ClientType, typename Op>
  3109. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3110. Op op, Error error = Error::Canceled) {
  3111. auto ended = std::async(std::launch::async, op);
  3112. auto peer = listener.accept();
  3113. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3114. ASSERT_NE(INVALID_SOCKET, peer);
  3115. ASSERT_TRUE(receives_a_byte(peer));
  3116. cli.stop();
  3117. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3118. EXPECT_EQ(error, ended.get());
  3119. }
  3120. // Stops itself from another thread as the connection opens, the last moment a
  3121. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3122. // waits for the connection fails the test instead of hanging it.
  3123. class StoppedAsConnectedClient : public ClientImpl {
  3124. public:
  3125. using ClientImpl::ClientImpl;
  3126. protected:
  3127. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3128. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3129. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3130. stopper_.wait_for(std::chrono::seconds(1));
  3131. return true;
  3132. }
  3133. private:
  3134. std::future<void> stopper_;
  3135. };
  3136. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3137. SilentListener listener;
  3138. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3139. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3140. cli.set_read_timeout(std::chrono::seconds(3));
  3141. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3142. auto peer = listener.accept();
  3143. EXPECT_FALSE(receives_a_byte(peer));
  3144. detail::close_socket(peer);
  3145. auto handle = cli.open_stream("GET", "/");
  3146. EXPECT_FALSE(handle.is_valid());
  3147. EXPECT_EQ(Error::Canceled, handle.error);
  3148. peer = listener.accept();
  3149. EXPECT_FALSE(receives_a_byte(peer));
  3150. detail::close_socket(peer);
  3151. }
  3152. #ifdef __linux__
  3153. // A connect that a listener with a full backlog never completes
  3154. TEST(ClientStopTest, StopEndsAConnect) {
  3155. SilentListener listener(0);
  3156. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3157. std::vector<socket_t> backlog;
  3158. auto close_backlog = detail::scope_exit([&] {
  3159. for (auto sock : backlog) {
  3160. detail::close_socket(sock);
  3161. }
  3162. });
  3163. for (int i = 0; i < 8; i++) {
  3164. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3165. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3166. sizeof(listener.addr));
  3167. backlog.push_back(sock);
  3168. }
  3169. Client cli("127.0.0.1", listener.port);
  3170. cli.set_connection_timeout(std::chrono::seconds(3));
  3171. auto ended =
  3172. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3173. // A stop() before the request starts does not apply to it, so it repeats
  3174. auto status = std::future_status::timeout;
  3175. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3176. cli.stop();
  3177. status = ended.wait_for(std::chrono::milliseconds(10));
  3178. }
  3179. EXPECT_EQ(std::future_status::ready, status);
  3180. EXPECT_EQ(Error::Canceled, ended.get());
  3181. }
  3182. #endif
  3183. // The stream holds the socket while it waits for the head, out of the reach
  3184. // of shutdown()
  3185. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3186. SilentListener listener;
  3187. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3188. Client cli("127.0.0.1", listener.port);
  3189. cli.set_read_timeout(std::chrono::seconds(3));
  3190. expect_stop_ends(
  3191. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3192. Error::Read);
  3193. }
  3194. #ifdef CPPHTTPLIB_SSL_ENABLED
  3195. // A server that never answers the ClientHello
  3196. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3197. SilentListener listener;
  3198. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3199. SSLClient cli("127.0.0.1", listener.port);
  3200. cli.enable_server_certificate_verification(false);
  3201. cli.set_connection_timeout(std::chrono::seconds(3));
  3202. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3203. expect_stop_ends(cli, listener,
  3204. [&] { return cli.open_stream("GET", "/").error; });
  3205. }
  3206. // A proxy that takes the CONNECT and never answers it
  3207. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3208. SilentListener listener;
  3209. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3210. SSLClient cli("example.com", 443);
  3211. cli.set_proxy("127.0.0.1", listener.port);
  3212. cli.set_read_timeout(std::chrono::seconds(3));
  3213. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3214. }
  3215. #endif
  3216. // A read timeout past what the clock reaches waits for the response
  3217. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3218. SilentListener listener;
  3219. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3220. Client cli("127.0.0.1", listener.port);
  3221. cli.set_read_timeout(
  3222. static_cast<time_t>((std::min)(static_cast<long long>(
  3223. (std::numeric_limits<time_t>::max)()),
  3224. 10000000000LL)),
  3225. 0);
  3226. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3227. auto peer = listener.accept();
  3228. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3229. ASSERT_NE(INVALID_SOCKET, peer);
  3230. ASSERT_TRUE(receives_a_byte(peer));
  3231. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3232. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3233. "Connection: close\r\n\r\nok";
  3234. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3235. auto result = res.get();
  3236. ASSERT_TRUE(result);
  3237. EXPECT_EQ("ok", result->body);
  3238. }
  3239. static std::string remove_whitespace(const std::string &input) {
  3240. std::string output;
  3241. output.reserve(input.size());
  3242. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3243. [](unsigned char c) { return !std::isspace(c); });
  3244. return output;
  3245. }
  3246. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3247. auto host = "httpbingo.org";
  3248. auto path = std::string{"/basic-auth/hello/world"};
  3249. #ifdef CPPHTTPLIB_SSL_ENABLED
  3250. auto port = 443;
  3251. SSLClient cli(host, port);
  3252. #else
  3253. auto port = 80;
  3254. Client cli(host, port);
  3255. #endif
  3256. {
  3257. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3258. SKIP_ON_GATEWAY_ERROR(res);
  3259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3260. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3261. }
  3262. {
  3263. auto res = retry_gateway_errors([&] {
  3264. return cli.Get(
  3265. path, Headers{make_basic_authentication_header("hello", "world")});
  3266. });
  3267. SKIP_ON_GATEWAY_ERROR(res);
  3268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3269. auto body = remove_whitespace(res->body);
  3270. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3271. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3272. EXPECT_EQ(StatusCode::OK_200, res->status);
  3273. }
  3274. {
  3275. cli.set_basic_auth("hello", "world");
  3276. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3277. SKIP_ON_GATEWAY_ERROR(res);
  3278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3279. auto body = remove_whitespace(res->body);
  3280. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3281. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3282. EXPECT_EQ(StatusCode::OK_200, res->status);
  3283. }
  3284. {
  3285. cli.set_basic_auth("hello", "bad");
  3286. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3287. SKIP_ON_GATEWAY_ERROR(res);
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3290. }
  3291. {
  3292. cli.set_basic_auth("bad", "world");
  3293. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3294. SKIP_ON_GATEWAY_ERROR(res);
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3297. }
  3298. }
  3299. #ifdef CPPHTTPLIB_SSL_ENABLED
  3300. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3301. auto host = "httpbingo.org";
  3302. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3303. auto paths = std::vector<std::string>{
  3304. "/digest-auth/auth/hello/world/MD5",
  3305. "/digest-auth/auth/hello/world/SHA-256",
  3306. };
  3307. auto port = 443;
  3308. SSLClient cli(host, port);
  3309. {
  3310. auto res = retry_gateway_errors([&] { return cli.Get(unauth_path); });
  3311. SKIP_ON_GATEWAY_ERROR(res);
  3312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3313. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3314. }
  3315. {
  3316. cli.set_digest_auth("hello", "world");
  3317. for (const auto &path : paths) {
  3318. auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); });
  3319. SKIP_ON_GATEWAY_ERROR(res);
  3320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3321. auto body = remove_whitespace(res->body);
  3322. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3323. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3324. EXPECT_EQ(StatusCode::OK_200, res->status);
  3325. }
  3326. cli.set_digest_auth("hello", "bad");
  3327. for (const auto &path : paths) {
  3328. auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); });
  3329. SKIP_ON_GATEWAY_ERROR(res);
  3330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3331. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3332. }
  3333. }
  3334. }
  3335. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3336. // comma-separated list of challenges, and each challenge may itself carry a
  3337. // comma-separated auth-param list, so a server can legally offer Basic
  3338. // before Digest, either as two field lines or packed into one. Runs one 401
  3339. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3340. // value() joins them in receipt order) and checks that the retry carries a
  3341. // well-formed Digest Authorization header naming expected_realm.
  3342. static void
  3343. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3344. const std::string &expected_realm) {
  3345. std::atomic<int> hits{0};
  3346. Server svr;
  3347. svr.Get("/x", [&](const Request &req, Response &res) {
  3348. if (++hits == 1) {
  3349. res.status = StatusCode::Unauthorized_401;
  3350. for (const auto &challenge : challenges) {
  3351. res.set_header("WWW-Authenticate", challenge);
  3352. }
  3353. } else {
  3354. auto authorization = req.get_header_value("Authorization");
  3355. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3356. EXPECT_NE(std::string::npos,
  3357. authorization.find("realm=\"" + expected_realm + "\""));
  3358. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3359. res.set_content("ok", "text/plain");
  3360. }
  3361. });
  3362. auto port = svr.bind_to_any_port(HOST);
  3363. std::thread t([&]() { svr.listen_after_bind(); });
  3364. auto se = detail::scope_exit([&] {
  3365. svr.stop();
  3366. t.join();
  3367. });
  3368. svr.wait_until_ready();
  3369. Client cli(HOST, port);
  3370. cli.set_digest_auth("hello", "world");
  3371. auto res = cli.Get("/x");
  3372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3373. EXPECT_EQ(2, hits.load());
  3374. }
  3375. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3376. static const char *kDigestChallenge =
  3377. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3378. "algorithm=MD5";
  3379. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3380. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3381. "testrealm");
  3382. }
  3383. // Same challenge list with the schemes in the opposite order, to make sure
  3384. // the fix above didn't just special-case "Basic first".
  3385. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3386. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3387. "testrealm");
  3388. }
  3389. // A comma inside a quoted auth-param value must not be mistaken for the
  3390. // separator between two challenges (or two auth-params).
  3391. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3392. run_digest_challenge_list_test(
  3393. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3394. "algorithm=MD5"},
  3395. "test,realm");
  3396. }
  3397. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3398. // the params and leaves out the fragment.
  3399. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3400. Server svr;
  3401. std::string uri, target;
  3402. svr.Get("/a b", [&](const Request &req, Response &res) {
  3403. auto auth = req.get_header_value("Authorization");
  3404. if (auth.empty()) {
  3405. res.status = StatusCode::Unauthorized_401;
  3406. res.set_header("WWW-Authenticate",
  3407. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3408. return;
  3409. }
  3410. auto b = auth.find("uri=\"") + 5;
  3411. uri = auth.substr(b, auth.find('"', b) - b);
  3412. target = req.target;
  3413. });
  3414. auto port = svr.bind_to_any_port(HOST);
  3415. std::thread t([&]() { svr.listen_after_bind(); });
  3416. auto se = detail::scope_exit([&] {
  3417. svr.stop();
  3418. t.join();
  3419. });
  3420. svr.wait_until_ready();
  3421. Client cli(HOST, port);
  3422. cli.set_digest_auth("hello", "world");
  3423. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3425. EXPECT_EQ("/a%20b?x=1", target);
  3426. EXPECT_EQ(target, uri);
  3427. }
  3428. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3429. // make_digest_authentication_header() dereferences both unconditionally, so
  3430. // a server sending a challenge missing either one must not be treated as
  3431. // usable -- doing so used to crash the client with std::out_of_range.
  3432. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3433. Server svr;
  3434. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3435. res.status = StatusCode::Unauthorized_401;
  3436. res.set_header("WWW-Authenticate", challenge);
  3437. });
  3438. auto port = svr.bind_to_any_port(HOST);
  3439. std::thread t([&]() { svr.listen_after_bind(); });
  3440. auto se = detail::scope_exit([&] {
  3441. svr.stop();
  3442. t.join();
  3443. });
  3444. svr.wait_until_ready();
  3445. Client cli(HOST, port);
  3446. cli.set_digest_auth("hello", "world");
  3447. auto res = cli.Get("/x");
  3448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3449. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3450. }
  3451. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3452. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3453. }
  3454. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3455. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3456. }
  3457. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3458. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3459. }
  3460. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3461. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3462. // when storing the values, so the header builder has to re-escape them (and
  3463. // keep algorithm a bare token); otherwise the value breaks out of its
  3464. // quoted-string and injects extra auth-params into the client's Authorization.
  3465. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3466. std::atomic<int> hits{0};
  3467. std::string authorization;
  3468. Server svr;
  3469. svr.Get("/x", [&](const Request &req, Response &res) {
  3470. if (++hits == 1) {
  3471. res.status = StatusCode::Unauthorized_401;
  3472. // On the wire the quotes embedded in the values are backslash-escaped.
  3473. res.set_header("WWW-Authenticate",
  3474. "Digest realm=\"testrealm\", "
  3475. "nonce=\"n\\\"; injected=\\\"x\", "
  3476. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3477. } else {
  3478. authorization = req.get_header_value("Authorization");
  3479. res.set_content("ok", "text/plain");
  3480. }
  3481. });
  3482. auto port = svr.bind_to_any_port(HOST);
  3483. std::thread t([&]() { svr.listen_after_bind(); });
  3484. auto se = detail::scope_exit([&] {
  3485. svr.stop();
  3486. t.join();
  3487. });
  3488. svr.wait_until_ready();
  3489. Client cli(HOST, port);
  3490. cli.set_digest_auth("hello", "world");
  3491. auto res = cli.Get("/x");
  3492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3493. EXPECT_EQ(2, hits.load());
  3494. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3495. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3496. // inside its quoted-string rather than starting an "injected" auth-param.
  3497. EXPECT_NE(std::string::npos,
  3498. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3499. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3500. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3501. }
  3502. #endif
  3503. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3504. auto host = "google.com";
  3505. auto another_host = "example.com";
  3506. auto wrong_ip = "0.0.0.0";
  3507. #ifdef CPPHTTPLIB_SSL_ENABLED
  3508. SSLClient cli(host);
  3509. #else
  3510. Client cli(host);
  3511. #endif
  3512. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3513. auto res = cli.Get("/");
  3514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3515. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3516. }
  3517. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3518. auto host = "google.com";
  3519. auto wrong_ip = "0.0.0.0";
  3520. #ifdef CPPHTTPLIB_SSL_ENABLED
  3521. SSLClient cli(host);
  3522. #else
  3523. Client cli(host);
  3524. #endif
  3525. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3526. auto res = cli.Get("/");
  3527. ASSERT_TRUE(!res);
  3528. EXPECT_EQ(Error::Connection, res.error());
  3529. }
  3530. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3531. // A mapped value that is not an IP literal must be resolved. "localhost"
  3532. // resolves from the hosts file, so this test needs no external DNS.
  3533. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3534. auto host = "target.invalid";
  3535. Server svr;
  3536. std::string received_host;
  3537. svr.Get("/hi", [&](const Request &req, Response &res) {
  3538. received_host = req.get_header_value("Host");
  3539. res.set_content("Hello World!", "text/plain");
  3540. });
  3541. auto port = svr.bind_to_any_port(HOST);
  3542. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3543. auto se = detail::scope_exit([&] {
  3544. svr.stop();
  3545. thread.join();
  3546. ASSERT_FALSE(svr.is_running());
  3547. });
  3548. svr.wait_until_ready();
  3549. Client cli(host, port);
  3550. cli.set_direct_hostname_addr_map({{host, HOST}});
  3551. auto res = cli.Get("/hi");
  3552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3553. EXPECT_EQ(StatusCode::OK_200, res->status);
  3554. // The mapping only redirects the connection; the identity stays host_.
  3555. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3556. }
  3557. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3558. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3559. auto host = "target.invalid";
  3560. Server svr;
  3561. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3562. res.set_content("Hello World!", "text/plain");
  3563. });
  3564. auto port = svr.bind_to_any_port("127.0.0.1");
  3565. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3566. auto se = detail::scope_exit([&] {
  3567. svr.stop();
  3568. thread.join();
  3569. ASSERT_FALSE(svr.is_running());
  3570. });
  3571. svr.wait_until_ready();
  3572. Client cli(host, port);
  3573. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3574. auto res = cli.Get("/hi");
  3575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3576. EXPECT_EQ(StatusCode::OK_200, res->status);
  3577. }
  3578. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3579. // An empty mapped value must leave host_ as the connection target. Without
  3580. // that guard the empty value would become the host argument, getaddrinfo
  3581. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3582. // loopback - silently connecting somewhere the caller never asked for.
  3583. // The server listens on loopback, so such a fallback would succeed and is
  3584. // therefore observable as a failure of this test.
  3585. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3586. Server svr;
  3587. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3588. res.set_content("Hello World!", "text/plain");
  3589. });
  3590. auto port = svr.bind_to_any_port(HOST);
  3591. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3592. auto se = detail::scope_exit([&] {
  3593. svr.stop();
  3594. thread.join();
  3595. ASSERT_FALSE(svr.is_running());
  3596. });
  3597. svr.wait_until_ready();
  3598. Client cli(blackhole, port);
  3599. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3600. cli.set_connection_timeout(1);
  3601. auto res = cli.Get("/hi");
  3602. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3603. }
  3604. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3605. auto host = "target.invalid";
  3606. Server svr;
  3607. std::string received_host;
  3608. svr.Get("/hi", [&](const Request &req, Response &res) {
  3609. received_host = req.get_header_value("Host");
  3610. res.set_content("Hello World!", "text/plain");
  3611. });
  3612. auto port = svr.bind_to_any_port("127.0.0.1");
  3613. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3614. auto se = detail::scope_exit([&] {
  3615. svr.stop();
  3616. thread.join();
  3617. ASSERT_FALSE(svr.is_running());
  3618. });
  3619. svr.wait_until_ready();
  3620. Client cli(host, port);
  3621. #pragma GCC diagnostic push
  3622. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3623. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3624. #pragma GCC diagnostic pop
  3625. auto res = cli.Get("/hi");
  3626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3627. EXPECT_EQ(StatusCode::OK_200, res->status);
  3628. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3629. }
  3630. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3631. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3632. Server svr;
  3633. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3634. res.set_content("Hello World!", "text/plain");
  3635. });
  3636. auto port = svr.bind_to_any_port("127.0.0.1");
  3637. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3638. auto se = detail::scope_exit([&] {
  3639. svr.stop();
  3640. thread.join();
  3641. ASSERT_FALSE(svr.is_running());
  3642. });
  3643. svr.wait_until_ready();
  3644. Client cli("127.0.0.1", port);
  3645. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3646. cli.set_connection_timeout(1);
  3647. auto res = cli.Get("/hi");
  3648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3649. EXPECT_EQ(StatusCode::OK_200, res->status);
  3650. }
  3651. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3652. auto host = "httpbingo.org";
  3653. auto path = std::string{"/absolute-redirect/3"};
  3654. #ifdef CPPHTTPLIB_SSL_ENABLED
  3655. SSLClient cli(host);
  3656. #else
  3657. Client cli(host);
  3658. #endif
  3659. cli.set_follow_location(true);
  3660. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3661. SKIP_ON_GATEWAY_ERROR(res);
  3662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3663. EXPECT_EQ(StatusCode::OK_200, res->status);
  3664. }
  3665. TEST(RedirectTest, Redirect_Online) {
  3666. auto host = "httpbingo.org";
  3667. auto path = std::string{"/redirect/3"};
  3668. #ifdef CPPHTTPLIB_SSL_ENABLED
  3669. SSLClient cli(host);
  3670. #else
  3671. Client cli(host);
  3672. #endif
  3673. cli.set_follow_location(true);
  3674. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3675. SKIP_ON_GATEWAY_ERROR(res);
  3676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3677. EXPECT_EQ(StatusCode::OK_200, res->status);
  3678. }
  3679. TEST(RelativeRedirectTest, Redirect_Online) {
  3680. auto host = "httpbingo.org";
  3681. auto path = std::string{"/relative-redirect/3"};
  3682. #ifdef CPPHTTPLIB_SSL_ENABLED
  3683. SSLClient cli(host);
  3684. #else
  3685. Client cli(host);
  3686. #endif
  3687. cli.set_follow_location(true);
  3688. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3689. SKIP_ON_GATEWAY_ERROR(res);
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. }
  3693. TEST(TooManyRedirectTest, Redirect_Online) {
  3694. auto host = "httpbingo.org";
  3695. auto path = std::string{"/redirect/21"};
  3696. #ifdef CPPHTTPLIB_SSL_ENABLED
  3697. SSLClient cli(host);
  3698. #else
  3699. Client cli(host);
  3700. #endif
  3701. cli.set_follow_location(true);
  3702. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3703. SKIP_ON_GATEWAY_ERROR(res);
  3704. ASSERT_TRUE(!res);
  3705. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3706. }
  3707. #ifdef CPPHTTPLIB_SSL_ENABLED
  3708. TEST(YahooRedirectTest, Redirect_Online) {
  3709. Client cli("yahoo.com");
  3710. auto res = cli.Get("/");
  3711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3712. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3713. cli.set_follow_location(true);
  3714. res = cli.Get("/");
  3715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3716. EXPECT_EQ(StatusCode::OK_200, res->status);
  3717. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3718. }
  3719. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3720. #define REDIR_HOST "httpbingo.org"
  3721. #define REDIR_PATH "/redirect-to"
  3722. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3723. SSLClient cli(REDIR_HOST);
  3724. cli.set_follow_location(true);
  3725. auto res = retry_gateway_errors([&] {
  3726. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3727. });
  3728. SKIP_ON_GATEWAY_ERROR(res);
  3729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3730. EXPECT_EQ(StatusCode::OK_200, res->status);
  3731. }
  3732. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3733. SSLClient cli(REDIR_HOST);
  3734. cli.set_follow_location(true);
  3735. Params params;
  3736. params.emplace("url", "http://example.com");
  3737. params.emplace("status_code", "302");
  3738. auto res = retry_gateway_errors(
  3739. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3740. SKIP_ON_GATEWAY_ERROR(res);
  3741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3742. EXPECT_EQ(StatusCode::OK_200, res->status);
  3743. }
  3744. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3745. SSLClient cli(REDIR_HOST);
  3746. cli.set_follow_location(true);
  3747. Params params;
  3748. params.emplace("url", "http://example.com");
  3749. auto res = retry_gateway_errors([&] {
  3750. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3751. });
  3752. SKIP_ON_GATEWAY_ERROR(res);
  3753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3754. EXPECT_EQ(StatusCode::OK_200, res->status);
  3755. }
  3756. TEST(UrlWithSpace, Redirect_Online) {
  3757. SSLClient cli("edge.forgecdn.net");
  3758. cli.set_follow_location(true);
  3759. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3761. EXPECT_EQ(StatusCode::OK_200, res->status);
  3762. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3763. }
  3764. #endif
  3765. #if !defined(_WIN32) && !defined(_WIN64)
  3766. TEST(ReceiveSignals, Signal) {
  3767. auto setupSignalHandlers = []() {
  3768. struct sigaction act;
  3769. sigemptyset(&act.sa_mask);
  3770. act.sa_flags = SA_SIGINFO;
  3771. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3772. switch (sig) {
  3773. case SIGINT:
  3774. default: break;
  3775. }
  3776. };
  3777. ::sigaction(SIGINT, &act, nullptr);
  3778. };
  3779. Server svr;
  3780. int port = 0;
  3781. auto thread = std::thread([&]() {
  3782. setupSignalHandlers();
  3783. port = svr.bind_to_any_port(HOST);
  3784. svr.listen_after_bind();
  3785. });
  3786. auto se = detail::scope_exit([&] {
  3787. svr.stop();
  3788. thread.join();
  3789. ASSERT_FALSE(svr.is_running());
  3790. });
  3791. svr.wait_until_ready();
  3792. ASSERT_TRUE(svr.is_running());
  3793. pthread_kill(thread.native_handle(), SIGINT);
  3794. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3795. ASSERT_TRUE(svr.is_running());
  3796. }
  3797. #endif
  3798. TEST(RedirectToDifferentPort, Redirect) {
  3799. Server svr1;
  3800. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3801. res.set_content("Hello World!", "text/plain");
  3802. });
  3803. int svr1_port = 0;
  3804. auto thread1 = std::thread([&]() {
  3805. svr1_port = svr1.bind_to_any_port(HOST);
  3806. svr1.listen_after_bind();
  3807. });
  3808. Server svr2;
  3809. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3810. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3811. });
  3812. int svr2_port = 0;
  3813. auto thread2 = std::thread([&]() {
  3814. svr2_port = svr2.bind_to_any_port(HOST);
  3815. svr2.listen_after_bind();
  3816. });
  3817. auto se = detail::scope_exit([&] {
  3818. svr2.stop();
  3819. thread2.join();
  3820. svr1.stop();
  3821. thread1.join();
  3822. ASSERT_FALSE(svr2.is_running());
  3823. ASSERT_FALSE(svr1.is_running());
  3824. });
  3825. svr1.wait_until_ready();
  3826. svr2.wait_until_ready();
  3827. Client cli("localhost", svr2_port);
  3828. cli.set_follow_location(true);
  3829. auto res = cli.Get("/2");
  3830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3831. EXPECT_EQ(StatusCode::OK_200, res->status);
  3832. EXPECT_EQ("Hello World!", res->body);
  3833. }
  3834. // GET /redir on one server redirects to /target on another port, so the
  3835. // client follows it with a new client.
  3836. static Result
  3837. GetThroughRedirectToDifferentPort(Server::Handler target,
  3838. const std::function<void(Client &)> &setup,
  3839. const Headers &headers = Headers()) {
  3840. Server target_svr;
  3841. target_svr.Get("/target", target);
  3842. int target_port = 0;
  3843. auto target_thread = std::thread([&]() {
  3844. target_port = target_svr.bind_to_any_port(HOST);
  3845. target_svr.listen_after_bind();
  3846. });
  3847. Server origin_svr;
  3848. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3849. res.set_redirect(
  3850. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3851. });
  3852. int origin_port = 0;
  3853. auto origin_thread = std::thread([&]() {
  3854. origin_port = origin_svr.bind_to_any_port(HOST);
  3855. origin_svr.listen_after_bind();
  3856. });
  3857. auto se = detail::scope_exit([&] {
  3858. origin_svr.stop();
  3859. origin_thread.join();
  3860. target_svr.stop();
  3861. target_thread.join();
  3862. });
  3863. target_svr.wait_until_ready();
  3864. origin_svr.wait_until_ready();
  3865. Client cli("localhost", origin_port);
  3866. cli.set_follow_location(true);
  3867. setup(cli);
  3868. return cli.Get("/redir", headers);
  3869. }
  3870. static void
  3871. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3872. std::string captured_authorization;
  3873. auto result = GetThroughRedirectToDifferentPort(
  3874. [&](const Request &req, Response &res) {
  3875. captured_authorization = req.get_header_value("Authorization");
  3876. res.set_content("OK", "text/plain");
  3877. },
  3878. set_auth);
  3879. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3880. EXPECT_EQ(StatusCode::OK_200, result->status);
  3881. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3882. EXPECT_TRUE(captured_authorization.empty());
  3883. }
  3884. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3885. TestDoNotForwardCredentialsOnRedirect(
  3886. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3887. }
  3888. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3889. TestDoNotForwardCredentialsOnRedirect(
  3890. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3891. }
  3892. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3893. std::string captured_cookie;
  3894. auto result = GetThroughRedirectToDifferentPort(
  3895. [&](const Request &req, Response &res) {
  3896. captured_cookie = req.get_header_value("Cookie");
  3897. res.set_content("OK", "text/plain");
  3898. },
  3899. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3900. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3901. EXPECT_EQ(StatusCode::OK_200, result->status);
  3902. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3903. EXPECT_TRUE(captured_cookie.empty());
  3904. }
  3905. TEST(RedirectToSamePort, ForwardCookie) {
  3906. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3907. // header so that ordinary session flows keep working.
  3908. Server svr;
  3909. std::string captured_cookie;
  3910. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3911. res.set_redirect("/target", 302);
  3912. });
  3913. svr.Get("/target", [&](const Request &req, Response &res) {
  3914. captured_cookie = req.get_header_value("Cookie");
  3915. res.set_content("OK", "text/plain");
  3916. });
  3917. auto port = svr.bind_to_any_port(HOST);
  3918. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3919. auto se = detail::scope_exit([&] {
  3920. svr.stop();
  3921. thread.join();
  3922. ASSERT_FALSE(svr.is_running());
  3923. });
  3924. svr.wait_until_ready();
  3925. Client cli(HOST, port);
  3926. cli.set_follow_location(true);
  3927. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3928. auto res = cli.Get("/redir", headers);
  3929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3930. EXPECT_EQ(StatusCode::OK_200, res->status);
  3931. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3932. }
  3933. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3934. // The Location alone names the next target, on any origin.
  3935. Server target_svr;
  3936. std::string cross_target;
  3937. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3938. cross_target = req.target;
  3939. res.set_content("OK", "text/plain");
  3940. });
  3941. auto target_port = target_svr.bind_to_any_port(HOST);
  3942. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3943. Server origin_svr;
  3944. std::string same_target;
  3945. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3946. res.set_redirect(
  3947. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3948. });
  3949. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3950. res.set_redirect("/landing", 302);
  3951. });
  3952. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3953. same_target = req.target;
  3954. res.set_content("OK", "text/plain");
  3955. });
  3956. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3957. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3958. auto se = detail::scope_exit([&] {
  3959. origin_svr.stop();
  3960. origin_thread.join();
  3961. target_svr.stop();
  3962. target_thread.join();
  3963. });
  3964. target_svr.wait_until_ready();
  3965. origin_svr.wait_until_ready();
  3966. Client cli("localhost", origin_port);
  3967. cli.set_follow_location(true);
  3968. Request req;
  3969. req.method = "GET";
  3970. req.params = {{"api_key", "SECRET"}};
  3971. req.path = "/cross";
  3972. auto res = cli.send(req);
  3973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3974. EXPECT_EQ("/landing", cross_target);
  3975. req.path = "/same";
  3976. res = cli.send(req);
  3977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3978. EXPECT_EQ("/landing", same_target);
  3979. }
  3980. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3981. std::string authorization;
  3982. std::string trace_id;
  3983. auto result = GetThroughRedirectToDifferentPort(
  3984. [&](const Request &req, Response &res) {
  3985. authorization = req.get_header_value("Authorization");
  3986. trace_id = req.get_header_value("X-Trace-Id");
  3987. res.set_content("OK", "text/plain");
  3988. },
  3989. [](Client &cli) {
  3990. cli.set_default_headers(
  3991. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3992. });
  3993. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3994. EXPECT_EQ(StatusCode::OK_200, result->status);
  3995. // Like a header given with the request, a default one goes along unless it
  3996. // carries credentials (RFC 9110 15.4).
  3997. EXPECT_TRUE(authorization.empty());
  3998. EXPECT_EQ("42", trace_id);
  3999. }
  4000. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4001. auto result = GetThroughRedirectToDifferentPort(
  4002. [](const Request &, Response &res) {
  4003. res.set_content(std::string(2048, 'x'), "text/plain");
  4004. },
  4005. [](Client &cli) { cli.set_payload_max_length(1024); });
  4006. EXPECT_FALSE(result);
  4007. }
  4008. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4009. auto result = GetThroughRedirectToDifferentPort(
  4010. [](const Request &req, Response &res) {
  4011. // Answer after a second, or once the client gives up.
  4012. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4013. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4014. }
  4015. res.set_content("late", "text/plain");
  4016. },
  4017. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4018. ASSERT_FALSE(result);
  4019. EXPECT_EQ(Error::Read, result.error());
  4020. }
  4021. #ifdef CPPHTTPLIB_SSL_ENABLED
  4022. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4023. auto result = GetThroughRedirectToDifferentPort(
  4024. [](const Request &, Response &res) {
  4025. res.status = StatusCode::Unauthorized_401;
  4026. res.set_header("WWW-Authenticate",
  4027. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4028. },
  4029. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4030. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4031. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4032. }
  4033. #endif
  4034. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4035. Server svr;
  4036. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4037. // Port number that overflows int — should not crash
  4038. res.set_redirect("http://localhost:99999999999999999999/target");
  4039. });
  4040. auto port = svr.bind_to_any_port(HOST);
  4041. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4042. auto se = detail::scope_exit([&] {
  4043. svr.stop();
  4044. thread.join();
  4045. ASSERT_FALSE(svr.is_running());
  4046. });
  4047. svr.wait_until_ready();
  4048. Client cli(HOST, port);
  4049. cli.set_follow_location(true);
  4050. auto res = cli.Get("/redir");
  4051. // Should fail gracefully, not crash (no valid response due to bad port)
  4052. EXPECT_FALSE(res);
  4053. }
  4054. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4055. Server svr;
  4056. auto port = svr.bind_to_any_port(HOST);
  4057. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4058. // The server's own port followed by junk must not be followed
  4059. res.set_redirect("http://" + std::string(HOST) + ":" +
  4060. std::to_string(port) + "junk/target");
  4061. });
  4062. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4063. res.set_content("target", "text/plain");
  4064. });
  4065. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4066. auto se = detail::scope_exit([&] {
  4067. svr.stop();
  4068. thread.join();
  4069. ASSERT_FALSE(svr.is_running());
  4070. });
  4071. svr.wait_until_ready();
  4072. Client cli(HOST, port);
  4073. cli.set_follow_location(true);
  4074. auto res = cli.Get("/redir");
  4075. EXPECT_FALSE(res);
  4076. }
  4077. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4078. Server target_svr;
  4079. std::atomic<int> target_hits{0};
  4080. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4081. target_hits++;
  4082. res.set_content("target", "text/plain");
  4083. });
  4084. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4085. res.set_content("target", "text/plain");
  4086. });
  4087. int target_port = 0;
  4088. auto target_thread = std::thread([&]() {
  4089. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4090. target_svr.listen_after_bind();
  4091. });
  4092. Server origin_svr;
  4093. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4094. res.set_redirect(req.get_param_value("to"));
  4095. });
  4096. int origin_port = 0;
  4097. auto origin_thread = std::thread([&]() {
  4098. origin_port = origin_svr.bind_to_any_port(HOST);
  4099. origin_svr.listen_after_bind();
  4100. });
  4101. auto se = detail::scope_exit([&] {
  4102. origin_svr.stop();
  4103. origin_thread.join();
  4104. target_svr.stop();
  4105. target_thread.join();
  4106. ASSERT_FALSE(origin_svr.is_running());
  4107. ASSERT_FALSE(target_svr.is_running());
  4108. });
  4109. target_svr.wait_until_ready();
  4110. origin_svr.wait_until_ready();
  4111. auto port = std::to_string(target_port);
  4112. for (const auto &to :
  4113. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4114. Client cli(HOST, origin_port);
  4115. cli.set_follow_location(true);
  4116. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4117. EXPECT_FALSE(res) << to;
  4118. }
  4119. EXPECT_EQ(0, target_hits);
  4120. Client cli(HOST, origin_port);
  4121. cli.set_follow_location(true);
  4122. auto res = cli.Get("/redir?to=" +
  4123. encode_query_component("//127.0.0.1:" + port + "/target"));
  4124. ASSERT_TRUE(res) << to_string(res.error());
  4125. EXPECT_EQ(StatusCode::OK_200, res->status);
  4126. EXPECT_EQ("target", res->body);
  4127. }
  4128. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4129. Server svr;
  4130. std::atomic<bool> followed{false};
  4131. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4132. res.status = StatusCode::NotModified_304;
  4133. res.set_header("Location", "/target");
  4134. });
  4135. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4136. res.status = StatusCode::UseProxy_305;
  4137. res.set_header("Location", "/target");
  4138. });
  4139. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4140. followed = true;
  4141. res.set_content("target", "text/plain");
  4142. });
  4143. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4144. auto se = detail::scope_exit([&] {
  4145. svr.stop();
  4146. th.join();
  4147. ASSERT_FALSE(svr.is_running());
  4148. });
  4149. svr.wait_until_ready();
  4150. Client cli("localhost", PORT);
  4151. cli.set_follow_location(true);
  4152. auto res = cli.Get("/304");
  4153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4154. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4155. res = cli.Get("/305");
  4156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4157. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4158. EXPECT_FALSE(followed);
  4159. }
  4160. TEST(RedirectFromPageWithContent, Redirect) {
  4161. Server svr;
  4162. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4163. res.set_content("___", "text/plain");
  4164. res.set_redirect("/2");
  4165. });
  4166. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4167. res.set_content("Hello World!", "text/plain");
  4168. });
  4169. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4170. auto se = detail::scope_exit([&] {
  4171. svr.stop();
  4172. th.join();
  4173. ASSERT_FALSE(svr.is_running());
  4174. });
  4175. svr.wait_until_ready();
  4176. {
  4177. Client cli("localhost", PORT);
  4178. cli.set_follow_location(true);
  4179. std::string body;
  4180. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4181. body.append(data, data_length);
  4182. return true;
  4183. });
  4184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4185. EXPECT_EQ(StatusCode::OK_200, res->status);
  4186. EXPECT_EQ("Hello World!", body);
  4187. }
  4188. {
  4189. Client cli("localhost", PORT);
  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::Found_302, res->status);
  4197. EXPECT_EQ("___", body);
  4198. }
  4199. }
  4200. // A server can close the connection after a request with "Connection: close"
  4201. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4202. // redirected request must go out on a new connection.
  4203. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4204. #ifndef _WIN32
  4205. signal(SIGPIPE, SIG_IGN);
  4206. #endif
  4207. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4208. default_socket_options(srv);
  4209. sockaddr_in addr{};
  4210. addr.sin_family = AF_INET;
  4211. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4212. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4213. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4214. ASSERT_EQ(0, ::listen(srv, 2));
  4215. auto send_text = [](socket_t sock, const std::string &text) {
  4216. ::send(sock,
  4217. #ifdef _WIN32
  4218. static_cast<const char *>(text.c_str()),
  4219. static_cast<int>(text.size()),
  4220. #else
  4221. text.c_str(), text.size(),
  4222. #endif
  4223. 0);
  4224. };
  4225. auto reused = false;
  4226. auto server_thread = std::thread([&] {
  4227. char buf[4096];
  4228. auto first = ::accept(srv, nullptr, nullptr);
  4229. if (first == INVALID_SOCKET) { return; }
  4230. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4231. ::recv(first, buf, sizeof(buf), 0);
  4232. send_text(
  4233. first,
  4234. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4235. auto next = first;
  4236. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4237. reused = true;
  4238. } else {
  4239. detail::close_socket(first);
  4240. next = ::accept(srv, nullptr, nullptr);
  4241. if (next == INVALID_SOCKET) { return; }
  4242. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4243. ::recv(next, buf, sizeof(buf), 0);
  4244. }
  4245. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4246. "Connection: close\r\n\r\nok");
  4247. detail::close_socket(next);
  4248. });
  4249. Client cli("127.0.0.1", PORT + 2);
  4250. cli.set_follow_location(true);
  4251. cli.set_read_timeout(5, 0);
  4252. auto res = cli.Get("/1");
  4253. server_thread.join();
  4254. detail::close_socket(srv);
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. EXPECT_EQ(StatusCode::OK_200, res->status);
  4257. EXPECT_EQ("ok", res->body);
  4258. EXPECT_FALSE(reused);
  4259. }
  4260. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4261. Server svr;
  4262. auto port_str = std::to_string(PORT);
  4263. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4264. auto expected_host = "[::1]:" + port_str;
  4265. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4266. res.set_content("___", "text/plain");
  4267. // res.set_redirect("/2");
  4268. res.set_redirect(redirect_url);
  4269. });
  4270. svr.Get("/2", [&](const Request &req, Response &res) {
  4271. auto host_header = req.headers.find("Host");
  4272. ASSERT_TRUE(host_header != req.headers.end());
  4273. EXPECT_EQ(expected_host, host_header->second);
  4274. res.set_content("Hello World!", "text/plain");
  4275. });
  4276. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4277. auto se = detail::scope_exit([&] {
  4278. svr.stop();
  4279. th.join();
  4280. ASSERT_FALSE(svr.is_running());
  4281. });
  4282. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4283. // actually starts anything, so the condition !svr.is_running() will
  4284. // always remain true, and the loop never stops.
  4285. // This basically counts how many milliseconds have passed since the
  4286. // call to svr.listen(), and if after 5 seconds nothing started yet
  4287. // aborts the test.
  4288. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4289. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4290. ASSERT_LT(milliseconds, 5000U);
  4291. }
  4292. {
  4293. Client cli("::1", PORT);
  4294. cli.set_follow_location(true);
  4295. std::string body;
  4296. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4297. body.append(data, data_length);
  4298. return true;
  4299. });
  4300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. EXPECT_EQ("Hello World!", body);
  4303. }
  4304. {
  4305. Client cli("::1", PORT);
  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::Found_302, res->status);
  4313. EXPECT_EQ("___", body);
  4314. }
  4315. }
  4316. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4317. Server svr;
  4318. svr.Get("/foo", [](const Request &req, Response &res) {
  4319. auto a = req.params.find("a");
  4320. if (a != req.params.end()) {
  4321. res.set_content((*a).second, "text/plain");
  4322. res.status = StatusCode::OK_200;
  4323. } else {
  4324. res.status = StatusCode::BadRequest_400;
  4325. }
  4326. });
  4327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4328. auto se = detail::scope_exit([&] {
  4329. svr.stop();
  4330. thread.join();
  4331. ASSERT_FALSE(svr.is_running());
  4332. });
  4333. svr.wait_until_ready();
  4334. {
  4335. Client cli(HOST, PORT);
  4336. cli.set_path_encode(false);
  4337. auto res = cli.Get("/foo?a=explicitly+encoded");
  4338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4339. EXPECT_EQ(StatusCode::OK_200, res->status);
  4340. // This expects it back with a space, as the `+` won't have been
  4341. // url-encoded, and server-side the params get decoded turning `+`
  4342. // into spaces.
  4343. EXPECT_EQ("explicitly encoded", res->body);
  4344. }
  4345. }
  4346. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4347. // When path encoding is disabled the client must transmit the supplied
  4348. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4349. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4350. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4351. // than a space (0x20). Assert on the raw wire target to catch this.
  4352. Server svr;
  4353. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4354. svr.Get("/foo", [&](const Request &req, Response &res) {
  4355. EXPECT_EQ(expected_target, req.target);
  4356. res.status = StatusCode::OK_200;
  4357. });
  4358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4359. auto se = detail::scope_exit([&] {
  4360. svr.stop();
  4361. thread.join();
  4362. ASSERT_FALSE(svr.is_running());
  4363. });
  4364. svr.wait_until_ready();
  4365. {
  4366. Client cli(HOST, PORT);
  4367. cli.set_path_encode(false);
  4368. auto res = cli.Get(expected_target.c_str());
  4369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4370. EXPECT_EQ(StatusCode::OK_200, res->status);
  4371. }
  4372. }
  4373. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4374. // `open_stream()` used to skip the path encoding that the buffered send
  4375. // path applies, so the same `path` produced different bytes in the request
  4376. // line depending on which API was used. Assert the two agree.
  4377. Server svr;
  4378. std::string target;
  4379. svr.Get(".*", [&](const Request &req, Response &res) {
  4380. target = req.target;
  4381. res.status = StatusCode::OK_200;
  4382. });
  4383. auto port = svr.bind_to_any_port(HOST);
  4384. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4385. auto se = detail::scope_exit([&] {
  4386. svr.stop();
  4387. thread.join();
  4388. ASSERT_FALSE(svr.is_running());
  4389. });
  4390. svr.wait_until_ready();
  4391. struct {
  4392. const char *path;
  4393. const char *expected;
  4394. } cases[] = {
  4395. {"/a b?x=1", "/a%20b?x=1"},
  4396. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4397. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4398. };
  4399. for (const auto &c : cases) {
  4400. Client cli(HOST, port);
  4401. target.clear();
  4402. auto res = cli.Get(c.path);
  4403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4404. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4405. auto buffered_target = target;
  4406. target.clear();
  4407. auto handle = cli.open_stream("GET", c.path);
  4408. EXPECT_TRUE(handle.is_valid())
  4409. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4410. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4411. }
  4412. }
  4413. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4414. // The `set_path_encode(false)` contract — transmit the supplied target
  4415. // verbatim — must hold for the streaming API too.
  4416. Server svr;
  4417. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4418. std::string target;
  4419. svr.Get("/foo", [&](const Request &req, Response &res) {
  4420. target = req.target;
  4421. res.status = StatusCode::OK_200;
  4422. });
  4423. auto port = svr.bind_to_any_port(HOST);
  4424. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4425. auto se = detail::scope_exit([&] {
  4426. svr.stop();
  4427. thread.join();
  4428. ASSERT_FALSE(svr.is_running());
  4429. });
  4430. svr.wait_until_ready();
  4431. {
  4432. Client cli(HOST, port);
  4433. cli.set_path_encode(false);
  4434. auto handle = cli.open_stream("GET", expected_target);
  4435. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4436. EXPECT_EQ(expected_target, target);
  4437. }
  4438. }
  4439. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4440. // With path encoding enabled a CR/LF in the target is percent-encoded
  4441. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4442. // write_request_line still backstops `set_path_encode(false)`, which is
  4443. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4444. Server svr;
  4445. // Captured before routing: the decoded path contains a newline, which a
  4446. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4447. std::string target;
  4448. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4449. target = req.target;
  4450. res.status = StatusCode::OK_200;
  4451. return Server::HandlerResponse::Handled;
  4452. });
  4453. auto port = svr.bind_to_any_port(HOST);
  4454. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4455. auto se = detail::scope_exit([&] {
  4456. svr.stop();
  4457. thread.join();
  4458. ASSERT_FALSE(svr.is_running());
  4459. });
  4460. svr.wait_until_ready();
  4461. {
  4462. Client cli(HOST, port);
  4463. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4464. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4465. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4466. }
  4467. }
  4468. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4469. // Every control character is percent-encoded, not just CR/LF, so the target
  4470. // passes the request-target check in write_request_line.
  4471. Server svr;
  4472. std::string target;
  4473. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4474. target = req.target;
  4475. res.status = StatusCode::OK_200;
  4476. return Server::HandlerResponse::Handled;
  4477. });
  4478. auto port = svr.bind_to_any_port(HOST);
  4479. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4480. auto se = detail::scope_exit([&] {
  4481. svr.stop();
  4482. thread.join();
  4483. ASSERT_FALSE(svr.is_running());
  4484. });
  4485. svr.wait_until_ready();
  4486. {
  4487. Client cli(HOST, port);
  4488. auto res = cli.Get("/a\tb\x1b\x7f");
  4489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4490. EXPECT_EQ("/a%09b%1B%7F", target);
  4491. }
  4492. }
  4493. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4494. // Nothing may reach the wire: a raw CR/LF target would split the request
  4495. // line and inject headers.
  4496. Server svr;
  4497. // Pre-routing so that "not called" means nothing reached the server at all,
  4498. // rather than merely failing to match a handler pattern.
  4499. auto handler_called = false;
  4500. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4501. handler_called = true;
  4502. res.status = StatusCode::OK_200;
  4503. return Server::HandlerResponse::Handled;
  4504. });
  4505. auto port = svr.bind_to_any_port(HOST);
  4506. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4507. auto se = detail::scope_exit([&] {
  4508. svr.stop();
  4509. thread.join();
  4510. ASSERT_FALSE(svr.is_running());
  4511. });
  4512. svr.wait_until_ready();
  4513. {
  4514. Client cli(HOST, port);
  4515. cli.set_path_encode(false);
  4516. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4517. EXPECT_FALSE(handle.is_valid());
  4518. EXPECT_EQ(Error::Write, handle.error);
  4519. EXPECT_FALSE(handler_called);
  4520. }
  4521. }
  4522. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4523. // Which of the two branches runs is decided by whether the query component
  4524. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4525. // an empty query and must still fall back to building one from
  4526. // `req.params`, while a non-empty query must win over `req.params`.
  4527. Server svr;
  4528. std::string target;
  4529. svr.Get("/foo", [&](const Request &req, Response &res) {
  4530. target = req.target;
  4531. res.status = StatusCode::OK_200;
  4532. });
  4533. auto port = svr.bind_to_any_port(HOST);
  4534. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4535. auto se = detail::scope_exit([&] {
  4536. svr.stop();
  4537. thread.join();
  4538. ASSERT_FALSE(svr.is_running());
  4539. });
  4540. svr.wait_until_ready();
  4541. {
  4542. // Trailing `?` -> empty query component -> `req.params` is used.
  4543. Client cli(HOST, port);
  4544. Request req;
  4545. req.method = "GET";
  4546. req.path = "/foo?";
  4547. req.params.emplace("a", "1");
  4548. target.clear();
  4549. auto res = cli.send(req);
  4550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4551. EXPECT_EQ("/foo?a=1", target);
  4552. }
  4553. {
  4554. // Non-empty query in `req.path` -> `req.params` is not appended.
  4555. Client cli(HOST, port);
  4556. Request req;
  4557. req.method = "GET";
  4558. req.path = "/foo?b=2";
  4559. req.params.emplace("a", "1");
  4560. target.clear();
  4561. auto res = cli.send(req);
  4562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4563. EXPECT_EQ("/foo?b=2", target);
  4564. }
  4565. }
  4566. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4567. Server svr;
  4568. svr.Get("/", [](const Request &req, Response &) {
  4569. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4570. });
  4571. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4572. auto se = detail::scope_exit([&] {
  4573. svr.stop();
  4574. thread.join();
  4575. ASSERT_FALSE(svr.is_running());
  4576. });
  4577. svr.wait_until_ready();
  4578. {
  4579. Client cli(HOST, PORT);
  4580. cli.set_path_encode(false);
  4581. auto res = cli.Get("/?something=%0A");
  4582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. }
  4585. }
  4586. TEST(BindServerTest, BindDualStack) {
  4587. Server svr;
  4588. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4589. res.set_content("Hello World!", "text/plain");
  4590. });
  4591. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4592. auto se = detail::scope_exit([&] {
  4593. svr.stop();
  4594. thread.join();
  4595. ASSERT_FALSE(svr.is_running());
  4596. });
  4597. svr.wait_until_ready();
  4598. {
  4599. Client cli("127.0.0.1", PORT);
  4600. auto res = cli.Get("/1");
  4601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4602. EXPECT_EQ(StatusCode::OK_200, res->status);
  4603. EXPECT_EQ("Hello World!", res->body);
  4604. }
  4605. {
  4606. Client cli("::1", PORT);
  4607. auto res = cli.Get("/1");
  4608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. EXPECT_EQ("Hello World!", res->body);
  4611. }
  4612. }
  4613. TEST(BindServerTest, BindAndListenSeparately) {
  4614. Server svr;
  4615. int port = svr.bind_to_any_port("0.0.0.0");
  4616. ASSERT_TRUE(svr.is_valid());
  4617. ASSERT_TRUE(port > 0);
  4618. svr.stop();
  4619. }
  4620. // Reports whether anything is still listening on a loopback port. A plain
  4621. // connect() is used instead of a Client request because a socket left bound by
  4622. // mistake accepts the connection into its backlog and never answers, which
  4623. // would hang the test instead of failing it.
  4624. static bool is_loopback_port_accepting(int port) {
  4625. sockaddr_in addr{};
  4626. addr.sin_family = AF_INET;
  4627. addr.sin_port = htons(static_cast<uint16_t>(port));
  4628. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4629. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4630. EXPECT_NE(sock, INVALID_SOCKET);
  4631. if (sock == INVALID_SOCKET) { return false; }
  4632. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4633. static_cast<socklen_t>(sizeof(addr)));
  4634. detail::close_socket(sock);
  4635. return ret == 0;
  4636. }
  4637. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4638. Server svr;
  4639. auto port = svr.bind_to_any_port("127.0.0.1");
  4640. ASSERT_TRUE(port > 0);
  4641. svr.stop();
  4642. // bind_to_any_port() already called listen(2), so until stop() closed the
  4643. // descriptor the port kept accepting connections into the backlog. ASSERT
  4644. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4645. // below blocks forever in the accept loop.
  4646. ASSERT_FALSE(is_loopback_port_accepting(port));
  4647. // Nothing is left to accept on, so listen_after_bind() must report failure
  4648. // instead of returning success without ever serving.
  4649. EXPECT_FALSE(svr.listen_after_bind());
  4650. // The failed listen marks the server decommissioned, so a waiter returns
  4651. // instead of spinning forever.
  4652. svr.wait_until_ready();
  4653. }
  4654. #ifdef CPPHTTPLIB_SSL_ENABLED
  4655. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4657. CLIENT_CA_CERT_DIR);
  4658. int port = svr.bind_to_any_port("0.0.0.0");
  4659. ASSERT_TRUE(svr.is_valid());
  4660. ASSERT_TRUE(port > 0);
  4661. svr.stop();
  4662. }
  4663. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4664. // or a rejected CustomRoute() registration would not stop the server binding.
  4665. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4667. CLIENT_CA_CERT_DIR);
  4668. ASSERT_TRUE(svr.is_valid());
  4669. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4670. EXPECT_FALSE(svr.is_valid());
  4671. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4672. }
  4673. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4674. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4675. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4676. int port = svr.bind_to_any_port("0.0.0.0");
  4677. ASSERT_TRUE(svr.is_valid());
  4678. ASSERT_TRUE(port > 0);
  4679. svr.stop();
  4680. }
  4681. TEST(BindServerTest, UpdateCertsPem) {
  4682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4683. int port = svr.bind_to_any_port("0.0.0.0");
  4684. ASSERT_TRUE(svr.is_valid());
  4685. ASSERT_TRUE(port > 0);
  4686. // Read PEM files
  4687. std::string cert_pem, key_pem, ca_pem;
  4688. read_file(SERVER_CERT_FILE, cert_pem);
  4689. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4690. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4691. // Update server certificates using PEM API
  4692. ASSERT_TRUE(
  4693. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4694. ASSERT_TRUE(svr.is_valid());
  4695. svr.stop();
  4696. }
  4697. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4698. // Start server with client CA (enables client auth)
  4699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4700. ASSERT_TRUE(svr.is_valid());
  4701. bool handler_called = false;
  4702. svr.Get("/test", [&](const Request &req, Response &res) {
  4703. handler_called = true;
  4704. // Verify client certificate is present
  4705. auto cert = req.peer_cert();
  4706. EXPECT_TRUE(static_cast<bool>(cert));
  4707. res.set_content("ok", "text/plain");
  4708. });
  4709. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4710. auto se = detail::scope_exit([&] {
  4711. svr.stop();
  4712. t.join();
  4713. ASSERT_FALSE(svr.is_running());
  4714. });
  4715. svr.wait_until_ready();
  4716. // Read PEM files
  4717. std::string cert_pem, key_pem, ca_pem;
  4718. read_file(SERVER_CERT_FILE, cert_pem);
  4719. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4720. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4721. // Update server certificates and client CA using PEM API while server running
  4722. ASSERT_TRUE(
  4723. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4724. // Connect with client certificate
  4725. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4726. cli.enable_server_certificate_verification(false);
  4727. cli.set_connection_timeout(30);
  4728. auto res = cli.Get("/test");
  4729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4730. ASSERT_EQ(StatusCode::OK_200, res->status);
  4731. ASSERT_TRUE(handler_called);
  4732. EXPECT_EQ("ok", res->body);
  4733. }
  4734. // Puts a CA that did not sign the client's certificate in the old one's place.
  4735. static bool replace_client_ca(SSLServer &svr) {
  4736. std::string cert_pem, key_pem, ca_pem;
  4737. read_file(SERVER_CERT_FILE, cert_pem);
  4738. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4739. read_file(SERVER_CERT2_FILE, ca_pem);
  4740. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4741. ca_pem.c_str());
  4742. }
  4743. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4744. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4745. ASSERT_TRUE(svr.is_valid());
  4746. svr.Get("/test", [](const Request &, Response &res) {
  4747. res.set_content("ok", "text/plain");
  4748. });
  4749. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4750. auto se = detail::scope_exit([&] {
  4751. svr.stop();
  4752. t.join();
  4753. ASSERT_FALSE(svr.is_running());
  4754. });
  4755. svr.wait_until_ready();
  4756. auto get = [] {
  4757. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4758. cli.enable_server_certificate_verification(false);
  4759. return cli.Get("/test");
  4760. };
  4761. ASSERT_TRUE(get());
  4762. ASSERT_TRUE(replace_client_ca(svr));
  4763. EXPECT_FALSE(get());
  4764. }
  4765. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4766. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4767. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4768. ASSERT_TRUE(svr.is_valid());
  4769. tls::set_verify_callback(svr.tls_context(),
  4770. [](const tls::VerifyContext &) -> bool {
  4771. throw std::runtime_error("verify");
  4772. });
  4773. svr.Get("/test", [](const Request &, Response &res) {
  4774. res.set_content("ok", "text/plain");
  4775. });
  4776. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4777. auto se = detail::scope_exit([&] {
  4778. svr.stop();
  4779. t.join();
  4780. ASSERT_FALSE(svr.is_running());
  4781. });
  4782. svr.wait_until_ready();
  4783. auto get = [] {
  4784. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4785. cli.enable_server_certificate_verification(false);
  4786. return cli.Get("/test");
  4787. };
  4788. EXPECT_FALSE(get());
  4789. // The handshake is over, so an update does not wait for it.
  4790. std::string cert_pem, key_pem;
  4791. read_file(SERVER_CERT_FILE, cert_pem);
  4792. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4793. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4794. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4795. return v.preverify_ok;
  4796. });
  4797. auto res = get();
  4798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4799. EXPECT_EQ("ok", res->body);
  4800. }
  4801. #endif
  4802. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4803. // Sends each request over a new connection with a client certificate,
  4804. // resuming the session of the one before when there is one.
  4805. class ResumingClient {
  4806. public:
  4807. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4808. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4809. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4810. SSL_FILETYPE_PEM);
  4811. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4812. // callback, not through SSL_get1_session().
  4813. SSL_CTX_set_app_data(ctx_, this);
  4814. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4815. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4816. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4817. auto self = static_cast<ResumingClient *>(
  4818. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4819. SSL_SESSION_free(self->session_);
  4820. self->session_ = session;
  4821. return 1; // Keeps the reference
  4822. });
  4823. }
  4824. ~ResumingClient() {
  4825. SSL_SESSION_free(session_);
  4826. SSL_CTX_free(ctx_);
  4827. }
  4828. // Tells whether the request was answered.
  4829. bool get() {
  4830. auto error = Error::Success;
  4831. auto sock = detail::create_client_socket(
  4832. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4833. /*connection_timeout_sec=*/5, 0,
  4834. /*read_timeout_sec=*/5, 0,
  4835. /*write_timeout_sec=*/5, 0, std::string(), error);
  4836. if (sock == INVALID_SOCKET) { return false; }
  4837. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4838. auto ssl = SSL_new(ctx_);
  4839. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4840. SSL_set_fd(ssl, static_cast<int>(sock));
  4841. if (session_) { SSL_set_session(ssl, session_); }
  4842. if (SSL_connect(ssl) != 1) { return false; }
  4843. reused_ = SSL_session_reused(ssl) == 1;
  4844. // Reading the response also takes in a TLS 1.3 session ticket.
  4845. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4846. "Connection: close\r\n\r\n";
  4847. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4848. std::string res;
  4849. char buf[256];
  4850. int n;
  4851. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4852. res.append(buf, static_cast<size_t>(n));
  4853. }
  4854. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4855. SSL_shutdown(ssl);
  4856. return res.find("200 OK") != std::string::npos;
  4857. }
  4858. // Whether the last connection resumed a session
  4859. bool reused() const { return reused_; }
  4860. private:
  4861. SSL_CTX *ctx_;
  4862. SSL_SESSION *session_ = nullptr;
  4863. bool reused_ = false;
  4864. };
  4865. // A client that resumes its session gets through, but not once the client CA
  4866. // has changed, as a resumed session does not show the certificate again.
  4867. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4869. ASSERT_TRUE(svr.is_valid());
  4870. svr.Get("/test", [](const Request &, Response &res) {
  4871. res.set_content("ok", "text/plain");
  4872. });
  4873. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4874. auto se = detail::scope_exit([&] {
  4875. svr.stop();
  4876. t.join();
  4877. ASSERT_FALSE(svr.is_running());
  4878. });
  4879. svr.wait_until_ready();
  4880. ResumingClient cli;
  4881. ASSERT_TRUE(cli.get());
  4882. ASSERT_TRUE(cli.get());
  4883. EXPECT_TRUE(cli.reused());
  4884. ASSERT_TRUE(replace_client_ca(svr));
  4885. EXPECT_FALSE(cli.get());
  4886. }
  4887. // A resumed session does not show the certificate again, so the server does
  4888. // not resume one with a verify callback to run on it.
  4889. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4891. ASSERT_TRUE(svr.is_valid());
  4892. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4893. return v.preverify_ok;
  4894. });
  4895. svr.Get("/test", [](const Request &, Response &res) {
  4896. res.set_content("ok", "text/plain");
  4897. });
  4898. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4899. auto se = detail::scope_exit([&] {
  4900. svr.stop();
  4901. t.join();
  4902. ASSERT_FALSE(svr.is_running());
  4903. });
  4904. svr.wait_until_ready();
  4905. ResumingClient cli;
  4906. ASSERT_TRUE(cli.get());
  4907. ASSERT_TRUE(cli.get());
  4908. EXPECT_FALSE(cli.reused());
  4909. }
  4910. #endif
  4911. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4912. // wolfSSL shares its session cache between contexts, so a resumed session
  4913. // could carry a client certificate checked against another server's CA, or
  4914. // against a client CA since replaced.
  4915. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4917. ASSERT_TRUE(svr.is_valid());
  4918. // Trusts a CA that did not sign the client's certificate.
  4919. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4920. ASSERT_TRUE(other.is_valid());
  4921. for (auto s : {&svr, &other}) {
  4922. s->Get("/test", [](const Request &, Response &res) {
  4923. res.set_content("ok", "text/plain");
  4924. });
  4925. }
  4926. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4927. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4928. auto se = detail::scope_exit([&] {
  4929. other.stop();
  4930. svr.stop();
  4931. t2.join();
  4932. t.join();
  4933. });
  4934. svr.wait_until_ready();
  4935. other.wait_until_ready();
  4936. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4937. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4938. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4939. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4940. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4941. ASSERT_EQ(WOLFSSL_SUCCESS,
  4942. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4943. WOLFSSL_FILETYPE_PEM));
  4944. WOLFSSL_SESSION *session = nullptr;
  4945. auto session_se = detail::scope_exit([&] {
  4946. if (session) { wolfSSL_SESSION_free(session); }
  4947. });
  4948. // A request over a new connection, resuming `session` when there is one and
  4949. // keeping the connection's own in its place. Tells whether it was answered.
  4950. auto get = [&](int port) {
  4951. auto error = Error::Success;
  4952. auto sock = detail::create_client_socket(
  4953. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4954. /*connection_timeout_sec=*/5, 0,
  4955. /*read_timeout_sec=*/5, 0,
  4956. /*write_timeout_sec=*/5, 0, std::string(), error);
  4957. if (sock == INVALID_SOCKET) { return false; }
  4958. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4959. auto ssl = wolfSSL_new(ctx);
  4960. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4961. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4962. if (session) { wolfSSL_set_session(ssl, session); }
  4963. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4964. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4965. "Connection: close\r\n\r\n";
  4966. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4967. std::string res;
  4968. char buf[256];
  4969. int n;
  4970. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4971. res.append(buf, static_cast<size_t>(n));
  4972. }
  4973. wolfSSL_shutdown(ssl);
  4974. if (session) { wolfSSL_SESSION_free(session); }
  4975. session = wolfSSL_get1_session(ssl);
  4976. return res.find("200 OK") != std::string::npos;
  4977. };
  4978. ASSERT_TRUE(get(PORT));
  4979. EXPECT_FALSE(get(PORT + 1));
  4980. ASSERT_TRUE(get(PORT));
  4981. ASSERT_TRUE(replace_client_ca(svr));
  4982. EXPECT_FALSE(get(PORT));
  4983. }
  4984. #endif
  4985. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4987. ASSERT_TRUE(svr.is_valid());
  4988. // Keep-alive parking would wait for the ClientHello without a handshake.
  4989. svr.set_keep_alive_parking(false);
  4990. svr.Get("/test", [](const Request &, Response &res) {
  4991. res.set_content("ok", "text/plain");
  4992. });
  4993. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4994. auto se = detail::scope_exit([&] {
  4995. svr.stop();
  4996. t.join();
  4997. ASSERT_FALSE(svr.is_running());
  4998. });
  4999. svr.wait_until_ready();
  5000. // A connection that sends no ClientHello keeps its handshake in progress,
  5001. // once the server has had a moment to start it.
  5002. auto error = Error::Success;
  5003. auto sock = detail::create_client_socket(
  5004. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5005. /*connection_timeout_sec=*/5, 0,
  5006. /*read_timeout_sec=*/5, 0,
  5007. /*write_timeout_sec=*/5, 0, std::string(), error);
  5008. ASSERT_NE(INVALID_SOCKET, sock);
  5009. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5010. std::string cert_pem, key_pem;
  5011. read_file(SERVER_CERT_FILE, cert_pem);
  5012. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5013. auto update = std::async(std::launch::async, [&]() {
  5014. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5015. });
  5016. EXPECT_EQ(std::future_status::timeout,
  5017. update.wait_for(std::chrono::milliseconds(200)));
  5018. detail::close_socket(sock);
  5019. EXPECT_TRUE(update.get());
  5020. SSLClient cli(HOST, PORT);
  5021. cli.enable_server_certificate_verification(false);
  5022. auto res = cli.Get("/test");
  5023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5024. EXPECT_EQ(StatusCode::OK_200, res->status);
  5025. }
  5026. #endif
  5027. TEST(ErrorHandlerTest, ContentLength) {
  5028. Server svr;
  5029. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5030. res.status = StatusCode::OK_200;
  5031. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5032. "text/html"); // <= Content-Length still 13
  5033. });
  5034. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5035. res.set_content("Hello World!\n", "text/plain");
  5036. res.status = 524;
  5037. });
  5038. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5039. auto se = detail::scope_exit([&] {
  5040. svr.stop();
  5041. thread.join();
  5042. ASSERT_FALSE(svr.is_running());
  5043. });
  5044. svr.wait_until_ready();
  5045. {
  5046. Client cli(HOST, PORT);
  5047. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5049. EXPECT_EQ(StatusCode::OK_200, res->status);
  5050. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5051. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5052. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5053. }
  5054. }
  5055. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5056. TEST(ExceptionTest, WithoutExceptionHandler) {
  5057. Server svr;
  5058. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5059. throw std::runtime_error("exception...");
  5060. });
  5061. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5062. throw std::runtime_error("exception\r\n...");
  5063. });
  5064. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5065. auto se = detail::scope_exit([&] {
  5066. svr.stop();
  5067. listen_thread.join();
  5068. ASSERT_FALSE(svr.is_running());
  5069. });
  5070. svr.wait_until_ready();
  5071. Client cli("localhost", PORT);
  5072. {
  5073. auto res = cli.Get("/exception");
  5074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5075. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5076. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5077. }
  5078. {
  5079. auto res = cli.Get("/unknown");
  5080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5081. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5082. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5083. }
  5084. }
  5085. TEST(ExceptionTest, WithExceptionHandler) {
  5086. Server svr;
  5087. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5088. std::exception_ptr ep) {
  5089. EXPECT_FALSE(ep == nullptr);
  5090. try {
  5091. std::rethrow_exception(ep);
  5092. } catch (std::exception &e) {
  5093. EXPECT_EQ("abc", std::string(e.what()));
  5094. } catch (...) {}
  5095. res.status = StatusCode::InternalServerError_500;
  5096. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5097. "text/html"); // <= Content-Length still 13 at this point
  5098. });
  5099. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5100. res.set_content("Hello World!\n", "text/plain");
  5101. throw std::runtime_error("abc");
  5102. });
  5103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5104. auto se = detail::scope_exit([&] {
  5105. svr.stop();
  5106. thread.join();
  5107. ASSERT_FALSE(svr.is_running());
  5108. });
  5109. svr.wait_until_ready();
  5110. for (size_t i = 0; i < 10; i++) {
  5111. Client cli(HOST, PORT);
  5112. for (size_t j = 0; j < 100; j++) {
  5113. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5115. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5116. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5117. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5118. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5119. }
  5120. cli.set_keep_alive(true);
  5121. for (size_t j = 0; j < 100; j++) {
  5122. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5125. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5126. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5127. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5128. }
  5129. }
  5130. }
  5131. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5132. Server svr;
  5133. svr.set_exception_handler(
  5134. [](const Request &, Response &res, std::exception_ptr) {
  5135. res.set_content("oops", "text/plain");
  5136. });
  5137. svr.Get("/throw", [](const Request &, Response &) {
  5138. throw std::runtime_error("throw");
  5139. });
  5140. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5141. res.status = StatusCode::Created_201;
  5142. throw std::runtime_error("created-then-throw");
  5143. });
  5144. auto port = svr.bind_to_any_port(HOST);
  5145. ASSERT_GT(port, 0);
  5146. thread t = thread([&] { svr.listen_after_bind(); });
  5147. auto se = detail::scope_exit([&] {
  5148. svr.stop();
  5149. t.join();
  5150. ASSERT_FALSE(svr.is_running());
  5151. });
  5152. svr.wait_until_ready();
  5153. Client cli(HOST, port);
  5154. for (auto path : {"/throw", "/created-then-throw"}) {
  5155. auto res = cli.Get(path);
  5156. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5157. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5158. }
  5159. }
  5160. TEST(ExceptionTest, AndErrorHandler) {
  5161. Server svr;
  5162. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5163. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5164. });
  5165. svr.set_exception_handler(
  5166. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5167. EXPECT_FALSE(ep == nullptr);
  5168. try {
  5169. std::rethrow_exception(ep);
  5170. } catch (std::exception &e) {
  5171. res.set_content(e.what(), "text/html");
  5172. } catch (...) {}
  5173. res.status = StatusCode::InternalServerError_500;
  5174. });
  5175. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5176. throw std::runtime_error("EXCEPTION");
  5177. });
  5178. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5179. res.set_content("ERROR", "text/html");
  5180. res.status = StatusCode::InternalServerError_500;
  5181. });
  5182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5183. auto se = detail::scope_exit([&] {
  5184. svr.stop();
  5185. thread.join();
  5186. ASSERT_FALSE(svr.is_running());
  5187. });
  5188. svr.wait_until_ready();
  5189. Client cli(HOST, PORT);
  5190. {
  5191. auto res = cli.Get("/exception");
  5192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5193. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5194. EXPECT_EQ("EXCEPTION", res->body);
  5195. }
  5196. {
  5197. auto res = cli.Get("/error");
  5198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5199. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5200. EXPECT_EQ("ERROR", res->body);
  5201. }
  5202. {
  5203. auto res = cli.Get("/invalid");
  5204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5205. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5206. EXPECT_EQ("NOT_FOUND", res->body);
  5207. }
  5208. }
  5209. #endif
  5210. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5211. // An exception from a user callback outside process_request()'s try/catch
  5212. // used to unwind into the task queue - which does not catch - and terminate
  5213. // the process. Each test below runs the server on a single worker thread: a
  5214. // guard that catches the exception but still loses the thread would otherwise
  5215. // be hidden by a spare worker serving the follow-up request. Note that a
  5216. // regression here aborts the whole test binary rather than failing one test.
  5217. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5218. Server svr;
  5219. svr.new_task_queue = [] { return new ThreadPool(1); };
  5220. std::atomic<int> reported{0};
  5221. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5222. if (err == Error::UserCallbackException) { reported++; }
  5223. });
  5224. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5225. res.set_content_provider(
  5226. 1024, "text/plain",
  5227. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5228. sink.write("hello", 5);
  5229. throw std::runtime_error("from the content provider");
  5230. });
  5231. });
  5232. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5233. res.set_content("ok", "text/plain");
  5234. });
  5235. auto port = svr.bind_to_any_port(HOST);
  5236. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5237. auto se = detail::scope_exit([&] {
  5238. svr.stop();
  5239. listen_thread.join();
  5240. ASSERT_FALSE(svr.is_running());
  5241. });
  5242. svr.wait_until_ready();
  5243. {
  5244. Client cli(HOST, port);
  5245. cli.set_read_timeout(5, 0);
  5246. EXPECT_FALSE(cli.Get("/throw"));
  5247. }
  5248. EXPECT_TRUE(svr.is_running());
  5249. EXPECT_EQ(1, reported.load());
  5250. // A request on a fresh connection is still served.
  5251. {
  5252. Client cli(HOST, port);
  5253. auto res = cli.Get("/ok");
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. EXPECT_EQ("ok", res->body);
  5257. }
  5258. }
  5259. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5260. Server svr;
  5261. svr.new_task_queue = [] { return new ThreadPool(1); };
  5262. std::atomic<bool> should_throw{true};
  5263. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5264. res.set_content("hi", "text/plain");
  5265. });
  5266. svr.set_post_routing_handler(
  5267. [&](const Request & /*req*/, Response & /*res*/) {
  5268. if (should_throw) {
  5269. throw std::runtime_error("from the post-routing handler");
  5270. }
  5271. });
  5272. auto port = svr.bind_to_any_port(HOST);
  5273. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5274. auto se = detail::scope_exit([&] {
  5275. svr.stop();
  5276. listen_thread.join();
  5277. ASSERT_FALSE(svr.is_running());
  5278. });
  5279. svr.wait_until_ready();
  5280. {
  5281. Client cli(HOST, port);
  5282. cli.set_read_timeout(5, 0);
  5283. EXPECT_FALSE(cli.Get("/hi"));
  5284. }
  5285. EXPECT_TRUE(svr.is_running());
  5286. should_throw = false;
  5287. {
  5288. Client cli(HOST, port);
  5289. auto res = cli.Get("/hi");
  5290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. EXPECT_EQ("hi", res->body);
  5293. }
  5294. }
  5295. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5296. // The guard reports the caught exception through the error logger, which is
  5297. // a user callback too. A logger that throws has to be contained as well, or
  5298. // the process would terminate from inside the catch.
  5299. Server svr;
  5300. svr.new_task_queue = [] { return new ThreadPool(1); };
  5301. std::atomic<int> reported{0};
  5302. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5303. if (err == Error::UserCallbackException) {
  5304. reported++;
  5305. throw std::runtime_error("from the error logger");
  5306. }
  5307. });
  5308. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5309. res.set_content_provider(
  5310. 1024, "text/plain",
  5311. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5312. sink.write("hello", 5);
  5313. throw std::runtime_error("from the content provider");
  5314. });
  5315. });
  5316. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5317. res.set_content("ok", "text/plain");
  5318. });
  5319. auto port = svr.bind_to_any_port(HOST);
  5320. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5321. auto se = detail::scope_exit([&] {
  5322. svr.stop();
  5323. listen_thread.join();
  5324. ASSERT_FALSE(svr.is_running());
  5325. });
  5326. svr.wait_until_ready();
  5327. {
  5328. Client cli(HOST, port);
  5329. cli.set_read_timeout(5, 0);
  5330. EXPECT_FALSE(cli.Get("/throw"));
  5331. }
  5332. EXPECT_TRUE(svr.is_running());
  5333. EXPECT_EQ(1, reported.load());
  5334. {
  5335. Client cli(HOST, port);
  5336. auto res = cli.Get("/ok");
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. EXPECT_EQ(StatusCode::OK_200, res->status);
  5339. EXPECT_EQ("ok", res->body);
  5340. }
  5341. }
  5342. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5343. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5344. // so the exception unwinds through the ws::WebSocket object on its way to
  5345. // the guard. None of the HTTP cases above cross that.
  5346. Server svr;
  5347. svr.new_task_queue = [] { return new ThreadPool(1); };
  5348. std::atomic<int> reported{0};
  5349. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5350. if (err == Error::UserCallbackException) { reported++; }
  5351. });
  5352. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5353. throw std::runtime_error("from the WebSocket handler");
  5354. });
  5355. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5356. res.set_content("ok", "text/plain");
  5357. });
  5358. auto port = svr.bind_to_any_port(HOST);
  5359. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5360. auto se = detail::scope_exit([&] {
  5361. svr.stop();
  5362. listen_thread.join();
  5363. ASSERT_FALSE(svr.is_running());
  5364. });
  5365. svr.wait_until_ready();
  5366. {
  5367. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5368. "/ws");
  5369. auto res = client.connect();
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. // The server dropped the connection instead of dying.
  5372. std::string msg;
  5373. EXPECT_FALSE(client.read(msg));
  5374. client.close();
  5375. }
  5376. EXPECT_TRUE(svr.is_running());
  5377. EXPECT_EQ(1, reported.load());
  5378. {
  5379. Client cli(HOST, port);
  5380. auto res = cli.Get("/ok");
  5381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5382. EXPECT_EQ(StatusCode::OK_200, res->status);
  5383. EXPECT_EQ("ok", res->body);
  5384. }
  5385. }
  5386. #ifdef CPPHTTPLIB_SSL_ENABLED
  5387. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5388. // SSLServer::process_and_close_socket() is a separate overload with its own
  5389. // guard, so it is exercised on its own.
  5390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5391. ASSERT_TRUE(svr.is_valid());
  5392. svr.new_task_queue = [] { return new ThreadPool(1); };
  5393. std::atomic<int> reported{0};
  5394. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5395. if (err == Error::UserCallbackException) { reported++; }
  5396. });
  5397. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5398. res.set_content_provider(
  5399. 1024, "text/plain",
  5400. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5401. sink.write("hello", 5);
  5402. throw std::runtime_error("from the content provider");
  5403. });
  5404. });
  5405. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5406. res.set_content("ok", "text/plain");
  5407. });
  5408. auto port = svr.bind_to_any_port(HOST);
  5409. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5410. auto se = detail::scope_exit([&] {
  5411. svr.stop();
  5412. listen_thread.join();
  5413. ASSERT_FALSE(svr.is_running());
  5414. });
  5415. svr.wait_until_ready();
  5416. {
  5417. SSLClient cli(HOST, port);
  5418. cli.enable_server_certificate_verification(false);
  5419. cli.set_read_timeout(5, 0);
  5420. EXPECT_FALSE(cli.Get("/throw"));
  5421. }
  5422. EXPECT_TRUE(svr.is_running());
  5423. EXPECT_EQ(1, reported.load());
  5424. {
  5425. SSLClient cli(HOST, port);
  5426. cli.enable_server_certificate_verification(false);
  5427. auto res = cli.Get("/ok");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ("ok", res->body);
  5431. }
  5432. }
  5433. #endif
  5434. #endif
  5435. TEST(NoContentTest, ContentLength) {
  5436. Server svr;
  5437. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5438. res.status = StatusCode::NoContent_204;
  5439. });
  5440. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5441. auto se = detail::scope_exit([&] {
  5442. svr.stop();
  5443. thread.join();
  5444. ASSERT_FALSE(svr.is_running());
  5445. });
  5446. svr.wait_until_ready();
  5447. {
  5448. Client cli(HOST, PORT);
  5449. auto res = cli.Get("/hi");
  5450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5451. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5452. // RFC 9110 8.6: none in a 204 response
  5453. EXPECT_FALSE(res->has_header("Content-Length"));
  5454. }
  5455. }
  5456. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5457. Server svr;
  5458. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5459. res.set_header("Content-Length", "5");
  5460. res.set_content("hello world", "text/plain");
  5461. });
  5462. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5463. // A body that reads as the last chunk, were it taken as chunked
  5464. res.set_header("Transfer-Encoding", "chunked");
  5465. res.set_content("0\r\n\r\n", "text/plain");
  5466. });
  5467. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5468. res.set_header("Content-Length", "2");
  5469. res.set_content_provider(5, "text/plain",
  5470. [](size_t offset, size_t length, DataSink &sink) {
  5471. sink.write(&"hello"[offset], length);
  5472. return true;
  5473. });
  5474. });
  5475. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5476. res.set_header("Content-Length", "1234");
  5477. });
  5478. thread t = thread([&] { svr.listen(HOST, PORT); });
  5479. auto se = detail::scope_exit([&] {
  5480. svr.stop();
  5481. t.join();
  5482. ASSERT_FALSE(svr.is_running());
  5483. });
  5484. svr.wait_until_ready();
  5485. Client cli(HOST, PORT);
  5486. cli.set_read_timeout(1, 0);
  5487. auto expect_body = [&](const Result &res, const std::string &body) {
  5488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5489. EXPECT_EQ(body, res->body);
  5490. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5491. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5492. };
  5493. Headers identity{{"Accept-Encoding", ""}};
  5494. expect_body(cli.Get("/body", identity), "hello world");
  5495. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5496. expect_body(cli.Get("/body",
  5497. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5498. "he");
  5499. expect_body(cli.Get("/provider", identity), "hello");
  5500. expect_body(cli.Get("/empty", identity), "");
  5501. // A HEAD response may give the length of the body a GET would get.
  5502. auto res = cli.Head("/empty");
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5505. }
  5506. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5507. Server svr;
  5508. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5509. res.set_content("short", "text/plain");
  5510. });
  5511. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5512. res.body += " with a footer";
  5513. res.set_header("Transfer-Encoding", "chunked");
  5514. });
  5515. thread t = thread([&] { svr.listen(HOST, PORT); });
  5516. auto se = detail::scope_exit([&] {
  5517. svr.stop();
  5518. t.join();
  5519. ASSERT_FALSE(svr.is_running());
  5520. });
  5521. svr.wait_until_ready();
  5522. Client cli(HOST, PORT);
  5523. cli.set_read_timeout(1, 0);
  5524. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. EXPECT_EQ("short with a footer", res->body);
  5527. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5528. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5529. }
  5530. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5531. Server svr;
  5532. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5533. res.set_header("Content-Length", "3");
  5534. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5535. sink.write("abc", 3);
  5536. sink.done();
  5537. return true;
  5538. });
  5539. });
  5540. thread t = thread([&] { svr.listen(HOST, PORT); });
  5541. auto se = detail::scope_exit([&] {
  5542. svr.stop();
  5543. t.join();
  5544. ASSERT_FALSE(svr.is_running());
  5545. });
  5546. svr.wait_until_ready();
  5547. Client cli(HOST, PORT);
  5548. cli.set_keep_alive(true);
  5549. auto res = cli.Get("/");
  5550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5551. EXPECT_EQ("abc", res->body);
  5552. EXPECT_FALSE(res->has_header("Content-Length"));
  5553. EXPECT_EQ("close", res->get_header_value("Connection"));
  5554. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5555. // No body to delimit
  5556. auto head = cli.Head("/");
  5557. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5558. EXPECT_FALSE(head->has_header("Connection"));
  5559. }
  5560. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5561. #ifdef CPPHTTPLIB_SSL_ENABLED
  5562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5563. ASSERT_TRUE(svr.is_valid());
  5564. #else
  5565. Server svr;
  5566. #endif
  5567. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5568. if (req.path == "/routing_handler") {
  5569. res.set_header("PRE_ROUTING", "on");
  5570. res.set_content("Routing Handler", "text/plain");
  5571. return httplib::Server::HandlerResponse::Handled;
  5572. }
  5573. return httplib::Server::HandlerResponse::Unhandled;
  5574. });
  5575. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5576. res.set_content("Error", "text/html");
  5577. });
  5578. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5579. if (req.path == "/routing_handler") {
  5580. res.set_header("POST_ROUTING", "on");
  5581. }
  5582. });
  5583. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5584. res.set_content("Hello World!\n", "text/plain");
  5585. });
  5586. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5587. auto se = detail::scope_exit([&] {
  5588. svr.stop();
  5589. thread.join();
  5590. ASSERT_FALSE(svr.is_running());
  5591. });
  5592. svr.wait_until_ready();
  5593. {
  5594. #ifdef CPPHTTPLIB_SSL_ENABLED
  5595. SSLClient cli(HOST, PORT);
  5596. cli.enable_server_certificate_verification(false);
  5597. #else
  5598. Client cli(HOST, PORT);
  5599. #endif
  5600. auto res = cli.Get("/routing_handler");
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. EXPECT_EQ(StatusCode::OK_200, res->status);
  5603. EXPECT_EQ("Routing Handler", res->body);
  5604. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5605. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5606. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5607. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5608. }
  5609. {
  5610. #ifdef CPPHTTPLIB_SSL_ENABLED
  5611. SSLClient cli(HOST, PORT);
  5612. cli.enable_server_certificate_verification(false);
  5613. #else
  5614. Client cli(HOST, PORT);
  5615. #endif
  5616. auto res = cli.Get("/hi");
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. EXPECT_EQ(StatusCode::OK_200, res->status);
  5619. EXPECT_EQ("Hello World!\n", res->body);
  5620. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5621. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5622. }
  5623. {
  5624. #ifdef CPPHTTPLIB_SSL_ENABLED
  5625. SSLClient cli(HOST, PORT);
  5626. cli.enable_server_certificate_verification(false);
  5627. #else
  5628. Client cli(HOST, PORT);
  5629. #endif
  5630. auto res = cli.Get("/aaa");
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5633. EXPECT_EQ("Error", res->body);
  5634. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5635. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5636. }
  5637. }
  5638. TEST(RequestHandlerTest, PreRequestHandler) {
  5639. auto route_path = "/user/:user";
  5640. Server svr;
  5641. svr.Get("/hi", [](const Request &, Response &res) {
  5642. res.set_content("hi", "text/plain");
  5643. });
  5644. svr.Get(route_path, [](const Request &req, Response &res) {
  5645. res.set_content(req.path_params.at("user"), "text/plain");
  5646. });
  5647. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5648. if (req.matched_route == route_path) {
  5649. auto user = req.path_params.at("user");
  5650. if (user != "john") {
  5651. res.status = StatusCode::Forbidden_403;
  5652. res.set_content("error", "text/html");
  5653. return Server::HandlerResponse::Handled;
  5654. }
  5655. }
  5656. return Server::HandlerResponse::Unhandled;
  5657. });
  5658. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5659. auto se = detail::scope_exit([&] {
  5660. svr.stop();
  5661. thread.join();
  5662. ASSERT_FALSE(svr.is_running());
  5663. });
  5664. svr.wait_until_ready();
  5665. Client cli(HOST, PORT);
  5666. {
  5667. auto res = cli.Get("/hi");
  5668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5669. EXPECT_EQ(StatusCode::OK_200, res->status);
  5670. EXPECT_EQ("hi", res->body);
  5671. }
  5672. {
  5673. auto res = cli.Get("/user/john");
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. EXPECT_EQ(StatusCode::OK_200, res->status);
  5676. EXPECT_EQ("john", res->body);
  5677. }
  5678. {
  5679. auto res = cli.Get("/user/invalid-user");
  5680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5681. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5682. EXPECT_EQ("error", res->body);
  5683. }
  5684. }
  5685. // The pre-request handler must run before the request body is read, so a
  5686. // rejected request never forces the server to buffer a (potentially large)
  5687. // body. Here the posted body is larger than the payload limit: if the body
  5688. // were read first the server would answer 413, but because the pre-request
  5689. // handler runs first it answers 403 and the body is never read.
  5690. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5691. Server svr;
  5692. svr.set_payload_max_length(8);
  5693. auto handler_ran = false;
  5694. svr.Post("/reject", [&](const Request &req, Response &res) {
  5695. handler_ran = true;
  5696. res.set_content(req.body, "text/plain");
  5697. });
  5698. svr.Post("/accept", [](const Request &req, Response &res) {
  5699. res.set_content(req.body, "text/plain");
  5700. });
  5701. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5702. if (req.matched_route == "/reject") {
  5703. res.status = StatusCode::Forbidden_403;
  5704. res.set_content("denied", "text/plain");
  5705. return Server::HandlerResponse::Handled;
  5706. }
  5707. return Server::HandlerResponse::Unhandled;
  5708. });
  5709. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5710. auto se = detail::scope_exit([&] {
  5711. svr.stop();
  5712. thread.join();
  5713. ASSERT_FALSE(svr.is_running());
  5714. });
  5715. svr.wait_until_ready();
  5716. Client cli(HOST, PORT);
  5717. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5718. // rejects with 403 before the body is read, so 413 is never reached.
  5719. {
  5720. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5722. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5723. EXPECT_EQ("denied", res->body);
  5724. EXPECT_FALSE(handler_ran);
  5725. }
  5726. // An approved route still reads the body and enforces the payload limit.
  5727. {
  5728. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5731. }
  5732. }
  5733. TEST(UserDataTest, BasicOperations) {
  5734. httplib::UserData ud;
  5735. // Initially empty
  5736. EXPECT_FALSE(ud.has("key"));
  5737. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5738. // set and get
  5739. ud.set("key", 42);
  5740. EXPECT_TRUE(ud.has("key"));
  5741. auto *p = ud.get<int>("key");
  5742. ASSERT_NE(nullptr, p);
  5743. EXPECT_EQ(42, *p);
  5744. // Type mismatch → nullptr
  5745. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5746. // Overwrite with different type
  5747. ud.set("key", std::string("hello"));
  5748. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5749. auto *s = ud.get<std::string>("key");
  5750. ASSERT_NE(nullptr, s);
  5751. EXPECT_EQ("hello", *s);
  5752. // erase
  5753. ud.erase("key");
  5754. EXPECT_FALSE(ud.has("key"));
  5755. // clear
  5756. ud.set("a", 1);
  5757. ud.set("b", 2);
  5758. ud.clear();
  5759. EXPECT_FALSE(ud.has("a"));
  5760. EXPECT_FALSE(ud.has("b"));
  5761. }
  5762. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5763. struct AuthCtx {
  5764. std::string user_id;
  5765. };
  5766. Server svr;
  5767. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5768. res.user_data.set("auth", AuthCtx{"alice"});
  5769. return Server::HandlerResponse::Unhandled;
  5770. });
  5771. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5772. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5773. ASSERT_NE(nullptr, ctx);
  5774. res.set_content("Hello " + ctx->user_id, "text/plain");
  5775. });
  5776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5777. auto se = detail::scope_exit([&] {
  5778. svr.stop();
  5779. thread.join();
  5780. ASSERT_FALSE(svr.is_running());
  5781. });
  5782. svr.wait_until_ready();
  5783. Client cli(HOST, PORT);
  5784. auto res = cli.Get("/me");
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. EXPECT_EQ(StatusCode::OK_200, res->status);
  5787. EXPECT_EQ("Hello alice", res->body);
  5788. }
  5789. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5790. struct RoleCtx {
  5791. std::string role;
  5792. };
  5793. Server svr;
  5794. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5795. res.user_data.set("role", RoleCtx{"admin"});
  5796. return Server::HandlerResponse::Unhandled;
  5797. });
  5798. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5799. auto *ctx = res.user_data.get<RoleCtx>("role");
  5800. ASSERT_NE(nullptr, ctx);
  5801. res.set_content(ctx->role, "text/plain");
  5802. });
  5803. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5804. auto se = detail::scope_exit([&] {
  5805. svr.stop();
  5806. thread.join();
  5807. ASSERT_FALSE(svr.is_running());
  5808. });
  5809. svr.wait_until_ready();
  5810. Client cli(HOST, PORT);
  5811. auto res = cli.Get("/role");
  5812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5813. EXPECT_EQ(StatusCode::OK_200, res->status);
  5814. EXPECT_EQ("admin", res->body);
  5815. }
  5816. TEST(InvalidFormatTest, StatusCode) {
  5817. Server svr;
  5818. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5819. res.set_content("Hello World!\n", "text/plain");
  5820. res.status = 9999; // Status should be a three-digit code...
  5821. });
  5822. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5823. auto se = detail::scope_exit([&] {
  5824. svr.stop();
  5825. thread.join();
  5826. ASSERT_FALSE(svr.is_running());
  5827. });
  5828. svr.wait_until_ready();
  5829. {
  5830. Client cli(HOST, PORT);
  5831. auto res = cli.Get("/hi");
  5832. ASSERT_FALSE(res);
  5833. }
  5834. }
  5835. TEST(URLFragmentTest, WithFragment) {
  5836. Server svr;
  5837. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5838. EXPECT_TRUE(req.target == "/hi");
  5839. });
  5840. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5841. auto se = detail::scope_exit([&] {
  5842. svr.stop();
  5843. thread.join();
  5844. ASSERT_FALSE(svr.is_running());
  5845. });
  5846. svr.wait_until_ready();
  5847. {
  5848. Client cli(HOST, PORT);
  5849. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5850. EXPECT_TRUE(res);
  5851. EXPECT_EQ(StatusCode::OK_200, res->status);
  5852. res = cli.Get("/hi%23key1=val1=key2=val2");
  5853. EXPECT_TRUE(res);
  5854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5855. }
  5856. }
  5857. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5858. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5859. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5860. Server svr;
  5861. std::vector<std::string> targets;
  5862. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5863. targets.push_back(req.target);
  5864. });
  5865. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5866. auto se = detail::scope_exit([&] {
  5867. svr.stop();
  5868. thread.join();
  5869. ASSERT_FALSE(svr.is_running());
  5870. });
  5871. svr.wait_until_ready();
  5872. Client cli(HOST, PORT);
  5873. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5874. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5875. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5876. // A '?' after the '#' belongs to the fragment, not to the query.
  5877. Request req;
  5878. req.method = "GET";
  5879. req.path = "/hi#f?x=1";
  5880. req.params.emplace("a", "1");
  5881. Response res;
  5882. auto error = Error::Success;
  5883. EXPECT_TRUE(cli.send(req, res, error));
  5884. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5885. "/hi?a=1"}),
  5886. targets);
  5887. }
  5888. TEST(HeaderWriter, SetHeaderWriter) {
  5889. Server svr;
  5890. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5891. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5892. return detail::write_headers(strm, hdrs);
  5893. });
  5894. svr.Get("/hi", [](const Request &req, Response &res) {
  5895. auto it = req.headers.find("CustomClientHeader");
  5896. EXPECT_TRUE(it != req.headers.end());
  5897. EXPECT_EQ(it->second, "CustomClientValue");
  5898. res.set_content("Hello World!\n", "text/plain");
  5899. });
  5900. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5901. auto se = detail::scope_exit([&] {
  5902. svr.stop();
  5903. thread.join();
  5904. ASSERT_FALSE(svr.is_running());
  5905. });
  5906. svr.wait_until_ready();
  5907. {
  5908. Client cli(HOST, PORT);
  5909. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5910. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5911. return detail::write_headers(strm, hdrs);
  5912. });
  5913. auto res = cli.Get("/hi");
  5914. EXPECT_TRUE(res);
  5915. EXPECT_EQ(StatusCode::OK_200, res->status);
  5916. auto it = res->headers.find("CustomServerHeader");
  5917. EXPECT_TRUE(it != res->headers.end());
  5918. EXPECT_EQ(it->second, "CustomServerValue");
  5919. }
  5920. }
  5921. class ServerTest : public ::testing::Test {
  5922. protected:
  5923. ServerTest()
  5924. : cli_(HOST, PORT)
  5925. #ifdef CPPHTTPLIB_SSL_ENABLED
  5926. ,
  5927. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5928. #endif
  5929. {
  5930. #ifdef CPPHTTPLIB_SSL_ENABLED
  5931. cli_.enable_server_certificate_verification(false);
  5932. #endif
  5933. // Allow LARGE_DATA (100MB) responses
  5934. cli_.set_payload_max_length(200 * 1024 * 1024);
  5935. }
  5936. virtual void SetUp() {
  5937. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5938. svr_.set_payload_max_length(200 * 1024 * 1024);
  5939. svr_.set_mount_point("/", "./www");
  5940. svr_.set_mount_point("/mount", "./www2");
  5941. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5942. svr_.Get("/hi",
  5943. [&](const Request & /*req*/, Response &res) {
  5944. res.set_content("Hello World!", "text/plain");
  5945. })
  5946. .Get("/file_content",
  5947. [&](const Request & /*req*/, Response &res) {
  5948. res.set_file_content("./www/dir/test.html");
  5949. })
  5950. .Get("/file_content_with_content_type",
  5951. [&](const Request & /*req*/, Response &res) {
  5952. res.set_file_content("./www/file", "text/plain");
  5953. })
  5954. .Get("/invalid_file_content",
  5955. [&](const Request & /*req*/, Response &res) {
  5956. res.set_file_content("./www/dir/invalid_file_path");
  5957. })
  5958. .Get("/http_response_splitting",
  5959. [&](const Request & /*req*/, Response &res) {
  5960. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5961. EXPECT_EQ(0U, res.headers.size());
  5962. EXPECT_FALSE(res.has_header("a"));
  5963. res.set_header("a", "1\nSet-Cookie: a=1");
  5964. EXPECT_EQ(0U, res.headers.size());
  5965. EXPECT_FALSE(res.has_header("a"));
  5966. res.set_header("a", "1\rSet-Cookie: a=1");
  5967. EXPECT_EQ(0U, res.headers.size());
  5968. EXPECT_FALSE(res.has_header("a"));
  5969. res.set_header("a\r\nb", "0");
  5970. EXPECT_EQ(0U, res.headers.size());
  5971. EXPECT_FALSE(res.has_header("a"));
  5972. res.set_header("a\rb", "0");
  5973. EXPECT_EQ(0U, res.headers.size());
  5974. EXPECT_FALSE(res.has_header("a"));
  5975. res.set_header("a\nb", "0");
  5976. EXPECT_EQ(0U, res.headers.size());
  5977. EXPECT_FALSE(res.has_header("a"));
  5978. res.set_redirect("1\r\nSet-Cookie: a=1");
  5979. EXPECT_EQ(0U, res.headers.size());
  5980. EXPECT_FALSE(res.has_header("Location"));
  5981. })
  5982. .Get("/slow",
  5983. [&](const Request & /*req*/, Response &res) {
  5984. std::this_thread::sleep_for(std::chrono::seconds(4));
  5985. res.set_content("slow", "text/plain");
  5986. })
  5987. #if 0
  5988. .Post("/slowpost",
  5989. [&](const Request & /*req*/, Response &res) {
  5990. std::this_thread::sleep_for(std::chrono::seconds(2));
  5991. res.set_content("slow", "text/plain");
  5992. })
  5993. #endif
  5994. .Get("/remote_addr",
  5995. [&](const Request &req, Response &res) {
  5996. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5997. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5998. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5999. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6000. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6001. #endif
  6002. res.set_content(req.remote_addr, "text/plain");
  6003. })
  6004. .Get("/local_addr",
  6005. [&](const Request &req, Response &res) {
  6006. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6007. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6008. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6009. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6010. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6011. #endif
  6012. auto local_addr = req.local_addr;
  6013. auto local_port = std::to_string(req.local_port);
  6014. res.set_content(local_addr.append(":").append(local_port),
  6015. "text/plain");
  6016. })
  6017. .Get("/endwith%",
  6018. [&](const Request & /*req*/, Response &res) {
  6019. res.set_content("Hello World!", "text/plain");
  6020. })
  6021. .Get("/a\\+\\+b",
  6022. [&](const Request &req, Response &res) {
  6023. ASSERT_TRUE(req.has_param("a +b"));
  6024. auto val = req.get_param_value("a +b");
  6025. res.set_content(val, "text/plain");
  6026. })
  6027. .Get("/", [&](const Request & /*req*/,
  6028. Response &res) { res.set_redirect("/hi"); })
  6029. .Post("/1",
  6030. [](const Request & /*req*/, Response &res) {
  6031. res.set_redirect("/2", StatusCode::SeeOther_303);
  6032. })
  6033. .Get("/2",
  6034. [](const Request & /*req*/, Response &res) {
  6035. res.set_content("redirected.", "text/plain");
  6036. res.status = StatusCode::OK_200;
  6037. })
  6038. .Post("/person",
  6039. [&](const Request &req, Response &res) {
  6040. if (req.has_param("name") && req.has_param("note")) {
  6041. persons_[req.get_param_value("name")] =
  6042. req.get_param_value("note");
  6043. } else {
  6044. res.status = StatusCode::BadRequest_400;
  6045. }
  6046. })
  6047. .Put("/person",
  6048. [&](const Request &req, Response &res) {
  6049. if (req.has_param("name") && req.has_param("note")) {
  6050. persons_[req.get_param_value("name")] =
  6051. req.get_param_value("note");
  6052. } else {
  6053. res.status = StatusCode::BadRequest_400;
  6054. }
  6055. })
  6056. .Get("/person/(.*)",
  6057. [&](const Request &req, Response &res) {
  6058. string name = req.matches[1];
  6059. if (persons_.find(name) != persons_.end()) {
  6060. auto note = persons_[name];
  6061. res.set_content(note, "text/plain");
  6062. } else {
  6063. res.status = StatusCode::NotFound_404;
  6064. }
  6065. })
  6066. .Delete("/person",
  6067. [&](const Request &req, Response &res) {
  6068. if (req.has_param("name")) {
  6069. string name = req.get_param_value("name");
  6070. if (persons_.find(name) != persons_.end()) {
  6071. persons_.erase(name);
  6072. res.set_content("DELETED", "text/plain");
  6073. } else {
  6074. res.status = StatusCode::NotFound_404;
  6075. }
  6076. } else {
  6077. res.status = StatusCode::BadRequest_400;
  6078. }
  6079. })
  6080. .Post("/x-www-form-urlencoded-json",
  6081. [&](const Request &req, Response &res) {
  6082. auto json = req.get_param_value("json");
  6083. ASSERT_EQ(JSON_DATA, json);
  6084. res.set_content(json, "appliation/json");
  6085. res.status = StatusCode::OK_200;
  6086. })
  6087. .Get("/streamed-chunked",
  6088. [&](const Request & /*req*/, Response &res) {
  6089. res.set_chunked_content_provider(
  6090. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6091. sink.os << "123";
  6092. sink.os << "456";
  6093. sink.os << "789";
  6094. sink.done();
  6095. return true;
  6096. });
  6097. })
  6098. .Get("/streamed-chunked-with-prohibited-trailer",
  6099. [&](const Request & /*req*/, Response &res) {
  6100. auto i = new int(0);
  6101. // Declare both a prohibited trailer (Content-Length) and an
  6102. // allowed one
  6103. res.set_header("Trailer", "Content-Length, X-Allowed");
  6104. res.set_chunked_content_provider(
  6105. "text/plain",
  6106. [i](size_t /*offset*/, DataSink &sink) {
  6107. switch (*i) {
  6108. case 0: sink.os << "123"; break;
  6109. case 1: sink.os << "456"; break;
  6110. case 2: sink.os << "789"; break;
  6111. case 3: {
  6112. sink.done_with_trailer(
  6113. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6114. } break;
  6115. }
  6116. (*i)++;
  6117. return true;
  6118. },
  6119. [i](bool success) {
  6120. EXPECT_TRUE(success);
  6121. delete i;
  6122. });
  6123. })
  6124. .Get("/streamed-chunked2",
  6125. [&](const Request & /*req*/, Response &res) {
  6126. auto i = new int(0);
  6127. res.set_chunked_content_provider(
  6128. "text/plain",
  6129. [i](size_t /*offset*/, DataSink &sink) {
  6130. switch (*i) {
  6131. case 0: sink.os << "123"; break;
  6132. case 1: sink.os << "456"; break;
  6133. case 2: sink.os << "789"; break;
  6134. case 3: sink.done(); break;
  6135. }
  6136. (*i)++;
  6137. return true;
  6138. },
  6139. [i](bool success) {
  6140. EXPECT_TRUE(success);
  6141. delete i;
  6142. });
  6143. })
  6144. .Get("/streamed-chunked-with-trailer",
  6145. [&](const Request & /*req*/, Response &res) {
  6146. auto i = new int(0);
  6147. res.set_header("Trailer", "Dummy1, Dummy2");
  6148. res.set_chunked_content_provider(
  6149. "text/plain",
  6150. [i](size_t /*offset*/, DataSink &sink) {
  6151. switch (*i) {
  6152. case 0: sink.os << "123"; break;
  6153. case 1: sink.os << "456"; break;
  6154. case 2: sink.os << "789"; break;
  6155. case 3: {
  6156. sink.done_with_trailer(
  6157. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6158. } break;
  6159. }
  6160. (*i)++;
  6161. return true;
  6162. },
  6163. [i](bool success) {
  6164. EXPECT_TRUE(success);
  6165. delete i;
  6166. });
  6167. })
  6168. .Get("/streamed",
  6169. [&](const Request & /*req*/, Response &res) {
  6170. res.set_content_provider(
  6171. 6, "text/plain",
  6172. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6173. sink.os << (offset < 3 ? "a" : "b");
  6174. return true;
  6175. });
  6176. })
  6177. .Get("/streamed-without-length",
  6178. [&](const Request & /*req*/, Response &res) {
  6179. auto data = new std::string("abcdefg");
  6180. res.set_content_provider(
  6181. "text/plain",
  6182. [data](size_t offset, DataSink &sink) {
  6183. if (offset < data->size()) {
  6184. sink.os << data->substr(offset);
  6185. }
  6186. sink.done();
  6187. return true;
  6188. },
  6189. [data](bool success) {
  6190. EXPECT_TRUE(success);
  6191. delete data;
  6192. });
  6193. })
  6194. .Get("/streamed-with-range",
  6195. [&](const Request &req, Response &res) {
  6196. auto data = new std::string("abcdefg");
  6197. // An explicit status keeps the server from picking the 206 it
  6198. // would otherwise choose for a ranged request, so the response
  6199. // is not a partial representation.
  6200. auto status = req.get_param_value("status");
  6201. if (status == "200") {
  6202. res.status = StatusCode::OK_200;
  6203. } else if (status == "403") {
  6204. res.status = StatusCode::Forbidden_403;
  6205. }
  6206. res.set_content_provider(
  6207. data->size(), "text/plain",
  6208. [data](size_t offset, size_t length, DataSink &sink) {
  6209. size_t DATA_CHUNK_SIZE = 4;
  6210. const auto &d = *data;
  6211. auto out_len =
  6212. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6213. auto ret =
  6214. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6215. EXPECT_TRUE(ret);
  6216. return true;
  6217. },
  6218. [data, &req](bool success) {
  6219. EXPECT_EQ(success, !req.has_param("error"));
  6220. delete data;
  6221. });
  6222. })
  6223. .Get("/streamed-cancel",
  6224. [&](const Request & /*req*/, Response &res) {
  6225. res.set_content_provider(
  6226. size_t(-1), "text/plain",
  6227. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6228. sink.os << "data_chunk";
  6229. return true;
  6230. });
  6231. })
  6232. .Get("/regex-with-delimiter",
  6233. [&](const Request &req, Response & /*res*/) {
  6234. ASSERT_TRUE(req.has_param("key"));
  6235. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6236. })
  6237. .Get("/with-range",
  6238. [&](const Request & /*req*/, Response &res) {
  6239. res.set_content("abcdefg", "text/plain");
  6240. })
  6241. .Get("/test-start-time",
  6242. [&](const Request &req, Response & /*res*/) {
  6243. EXPECT_NE(req.start_time_,
  6244. std::chrono::steady_clock::time_point::min());
  6245. })
  6246. .Get("/with-range-customized-response",
  6247. [&](const Request & /*req*/, Response &res) {
  6248. res.status = StatusCode::BadRequest_400;
  6249. res.set_content(JSON_DATA, "application/json");
  6250. })
  6251. .Post("/chunked",
  6252. [&](const Request &req, Response & /*res*/) {
  6253. EXPECT_EQ(req.body, "dechunked post body");
  6254. })
  6255. .Post("/large-chunked",
  6256. [&](const Request &req, Response & /*res*/) {
  6257. std::string expected(6 * 30 * 1024u, 'a');
  6258. EXPECT_EQ(req.body, expected);
  6259. })
  6260. .Post("/multipart",
  6261. [&](const Request &req, Response & /*res*/) {
  6262. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6263. req.form.get_field_count("text2") +
  6264. req.form.get_field_count("file3") +
  6265. req.form.get_field_count("file4"));
  6266. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6267. req.form.get_file_count("file2"));
  6268. ASSERT_TRUE(!req.form.has_file("???"));
  6269. ASSERT_TRUE(!req.form.has_field("???"));
  6270. ASSERT_TRUE(req.body.empty());
  6271. {
  6272. const auto &text = req.form.get_field("text1");
  6273. EXPECT_EQ("text default", text);
  6274. }
  6275. {
  6276. const auto &text = req.form.get_field("text2");
  6277. EXPECT_EQ("aωb", text);
  6278. }
  6279. {
  6280. const auto &file = req.form.get_file("file1");
  6281. EXPECT_EQ("hello.txt", file.filename);
  6282. EXPECT_EQ("text/plain", file.content_type);
  6283. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6284. }
  6285. {
  6286. const auto &file = req.form.get_file("file2");
  6287. EXPECT_EQ("world.json", file.filename);
  6288. EXPECT_EQ("application/json", file.content_type);
  6289. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6290. }
  6291. {
  6292. const auto &text = req.form.get_field("file3");
  6293. EXPECT_EQ(0u, text.size());
  6294. }
  6295. {
  6296. const auto &text = req.form.get_field("file4");
  6297. EXPECT_EQ(0u, text.size());
  6298. }
  6299. })
  6300. .Post("/multipart/multi_file_values",
  6301. [&](const Request &req, Response & /*res*/) {
  6302. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6303. req.form.get_field_count("multi_text1"));
  6304. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6305. ASSERT_TRUE(!req.form.has_file("???"));
  6306. ASSERT_TRUE(!req.form.has_field("???"));
  6307. ASSERT_TRUE(req.body.empty());
  6308. {
  6309. const auto &text = req.form.get_field("text");
  6310. EXPECT_EQ("default text", text);
  6311. }
  6312. {
  6313. const auto &text1_values = req.form.get_fields("multi_text1");
  6314. EXPECT_EQ(2u, text1_values.size());
  6315. EXPECT_EQ("aaaaa", text1_values[0]);
  6316. EXPECT_EQ("bbbbb", text1_values[1]);
  6317. }
  6318. {
  6319. const auto &file1_values = req.form.get_files("multi_file1");
  6320. EXPECT_EQ(2u, file1_values.size());
  6321. auto file1 = file1_values[0];
  6322. EXPECT_EQ(file1.filename, "hello.txt");
  6323. EXPECT_EQ(file1.content_type, "text/plain");
  6324. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6325. auto file2 = file1_values[1];
  6326. EXPECT_EQ(file2.filename, "world.json");
  6327. EXPECT_EQ(file2.content_type, "application/json");
  6328. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6329. }
  6330. })
  6331. .Post("/empty",
  6332. [&](const Request &req, Response &res) {
  6333. EXPECT_EQ(req.body, "");
  6334. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6335. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6336. res.set_content("empty", "text/plain");
  6337. })
  6338. .Post("/empty-no-content-type",
  6339. [&](const Request &req, Response &res) {
  6340. EXPECT_EQ(req.body, "");
  6341. EXPECT_FALSE(req.has_header("Content-Type"));
  6342. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6343. res.set_content("empty-no-content-type", "text/plain");
  6344. })
  6345. .Post("/path-only",
  6346. [&](const Request &req, Response &res) {
  6347. EXPECT_EQ(req.body, "");
  6348. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6349. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6350. res.set_content("path-only", "text/plain");
  6351. })
  6352. .Post("/path-headers-only",
  6353. [&](const Request &req, Response &res) {
  6354. EXPECT_EQ(req.body, "");
  6355. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6356. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6357. EXPECT_EQ("world", req.get_header_value("hello"));
  6358. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6359. res.set_content("path-headers-only", "text/plain");
  6360. })
  6361. .Post("/post-large",
  6362. [&](const Request &req, Response &res) {
  6363. EXPECT_EQ(req.body, LARGE_DATA);
  6364. res.set_content(req.body, "text/plain");
  6365. })
  6366. .Post("/post-loopback",
  6367. [&](const Request &, Response &res,
  6368. ContentReader const &content_reader) {
  6369. std::string body;
  6370. content_reader([&](const char *data, size_t data_length) {
  6371. body.append(data, data_length);
  6372. return true;
  6373. });
  6374. res.set_content(body, "text/plain");
  6375. })
  6376. .Put("/put-loopback",
  6377. [&](const Request &, Response &res,
  6378. ContentReader const &content_reader) {
  6379. std::string body;
  6380. content_reader([&](const char *data, size_t data_length) {
  6381. body.append(data, data_length);
  6382. return true;
  6383. });
  6384. res.set_content(body, "text/plain");
  6385. })
  6386. .Patch("/patch-loopback",
  6387. [&](const Request &, Response &res,
  6388. ContentReader const &content_reader) {
  6389. std::string body;
  6390. content_reader([&](const char *data, size_t data_length) {
  6391. body.append(data, data_length);
  6392. return true;
  6393. });
  6394. res.set_content(body, "text/plain");
  6395. })
  6396. .Put("/empty-no-content-type",
  6397. [&](const Request &req, Response &res) {
  6398. EXPECT_EQ(req.body, "");
  6399. EXPECT_FALSE(req.has_header("Content-Type"));
  6400. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6401. res.set_content("empty-no-content-type", "text/plain");
  6402. })
  6403. .Put("/put",
  6404. [&](const Request &req, Response &res) {
  6405. EXPECT_EQ(req.body, "PUT");
  6406. res.set_content(req.body, "text/plain");
  6407. })
  6408. .Put("/put-large",
  6409. [&](const Request &req, Response &res) {
  6410. EXPECT_EQ(req.body, LARGE_DATA);
  6411. res.set_content(req.body, "text/plain");
  6412. })
  6413. .Patch("/patch",
  6414. [&](const Request &req, Response &res) {
  6415. EXPECT_EQ(req.body, "PATCH");
  6416. res.set_content(req.body, "text/plain");
  6417. })
  6418. .Delete("/delete",
  6419. [&](const Request & /*req*/, Response &res) {
  6420. res.set_content("DELETE", "text/plain");
  6421. })
  6422. .Delete("/delete-body",
  6423. [&](const Request &req, Response &res) {
  6424. EXPECT_EQ(req.body, "content");
  6425. res.set_content(req.body, "text/plain");
  6426. })
  6427. .Options(R"(\*)",
  6428. [&](const Request & /*req*/, Response &res) {
  6429. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6430. })
  6431. .CustomRoute("PROPFIND", "/dav/:id",
  6432. [&](const Request &req, Response &res) {
  6433. res.set_header("x-body-size",
  6434. std::to_string(req.body.size()));
  6435. res.set_header("x-matched-route", req.matched_route);
  6436. res.set_header("x-dav-id", req.path_params.at("id"));
  6437. res.status = StatusCode::MultiStatus_207;
  6438. res.set_content(req.body, "application/xml");
  6439. })
  6440. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6441. [&](const Request &req, Response &res) {
  6442. res.set_header("x-dav-match", req.matches[1]);
  6443. res.status = StatusCode::MultiStatus_207;
  6444. })
  6445. .CustomRoute("MKCOL", "/dav-mkcol",
  6446. [&](const Request &req, Response &res) {
  6447. EXPECT_TRUE(req.body.empty());
  6448. res.status = StatusCode::Created_201;
  6449. })
  6450. .CustomRoute(
  6451. "REPORT", "/dav-report",
  6452. [&](const Request & /*req*/, Response &res,
  6453. const ContentReader &content_reader) {
  6454. std::string body;
  6455. content_reader([&](const char *data, size_t data_length) {
  6456. body.append(data, data_length);
  6457. return true;
  6458. });
  6459. res.set_header("x-body-size", std::to_string(body.size()));
  6460. res.status = StatusCode::MultiStatus_207;
  6461. res.set_content(body, "application/xml");
  6462. })
  6463. .Get("/request-target",
  6464. [&](const Request &req, Response & /*res*/) {
  6465. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6466. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6467. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6468. })
  6469. .Get("/long-query-value",
  6470. [&](const Request &req, Response & /*res*/) {
  6471. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6472. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6473. })
  6474. .Get("/too-long-query-value",
  6475. [&](const Request &req, Response & /*res*/) {
  6476. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6477. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6478. })
  6479. .Get("/array-param",
  6480. [&](const Request &req, Response & /*res*/) {
  6481. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6482. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6483. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6484. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6485. })
  6486. .Get("/array-param-values",
  6487. [&](const Request &req, Response & /*res*/) {
  6488. auto values = req.get_param_values("array");
  6489. EXPECT_EQ(3u, values.size());
  6490. EXPECT_EQ("value1", values[0]);
  6491. EXPECT_EQ("value2", values[1]);
  6492. EXPECT_EQ("value3", values[2]);
  6493. auto empty = req.get_param_values("nonexistent");
  6494. EXPECT_TRUE(empty.empty());
  6495. })
  6496. .Post("/validate-no-multiple-headers",
  6497. [&](const Request &req, Response & /*res*/) {
  6498. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6499. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6500. })
  6501. .Post("/content_receiver",
  6502. [&](const Request &req, Response &res,
  6503. const ContentReader &content_reader) {
  6504. if (req.is_multipart_form_data()) {
  6505. std::vector<FormData> items;
  6506. content_reader(
  6507. [&](const FormData &file) {
  6508. items.push_back(file);
  6509. return true;
  6510. },
  6511. [&](const char *data, size_t data_length) {
  6512. items.back().content.append(data, data_length);
  6513. return true;
  6514. });
  6515. EXPECT_EQ(5u, items.size());
  6516. {
  6517. const auto &file = get_file_value(items, "text1");
  6518. EXPECT_TRUE(file.filename.empty());
  6519. EXPECT_EQ("text default", file.content);
  6520. }
  6521. {
  6522. const auto &file = get_file_value(items, "text2");
  6523. EXPECT_TRUE(file.filename.empty());
  6524. EXPECT_EQ("aωb", file.content);
  6525. }
  6526. {
  6527. const auto &file = get_file_value(items, "file1");
  6528. EXPECT_EQ("hello.txt", file.filename);
  6529. EXPECT_EQ("text/plain", file.content_type);
  6530. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6531. }
  6532. {
  6533. const auto &file = get_file_value(items, "file2");
  6534. EXPECT_EQ("world.json", file.filename);
  6535. EXPECT_EQ("application/json", file.content_type);
  6536. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6537. }
  6538. {
  6539. const auto &file = get_file_value(items, "file3");
  6540. EXPECT_TRUE(file.filename.empty());
  6541. EXPECT_EQ("application/octet-stream", file.content_type);
  6542. EXPECT_EQ(0u, file.content.size());
  6543. }
  6544. } else {
  6545. std::string body;
  6546. content_reader([&](const char *data, size_t data_length) {
  6547. EXPECT_EQ(7U, data_length);
  6548. body.append(data, data_length);
  6549. return true;
  6550. });
  6551. EXPECT_EQ(body, "content");
  6552. res.set_content(body, "text/plain");
  6553. }
  6554. })
  6555. .Put("/content_receiver",
  6556. [&](const Request & /*req*/, Response &res,
  6557. const ContentReader &content_reader) {
  6558. std::string body;
  6559. content_reader([&](const char *data, size_t data_length) {
  6560. body.append(data, data_length);
  6561. return true;
  6562. });
  6563. EXPECT_EQ(body, "content");
  6564. res.set_content(body, "text/plain");
  6565. })
  6566. .Patch("/content_receiver",
  6567. [&](const Request & /*req*/, Response &res,
  6568. const ContentReader &content_reader) {
  6569. std::string body;
  6570. content_reader([&](const char *data, size_t data_length) {
  6571. body.append(data, data_length);
  6572. return true;
  6573. });
  6574. EXPECT_EQ(body, "content");
  6575. res.set_content(body, "text/plain");
  6576. })
  6577. .Post("/query-string-and-body",
  6578. [&](const Request &req, Response & /*res*/) {
  6579. ASSERT_TRUE(req.has_param("key"));
  6580. EXPECT_EQ(req.get_param_value("key"), "value");
  6581. EXPECT_EQ(req.body, "content");
  6582. })
  6583. .Get("/last-request",
  6584. [&](const Request &req, Response & /*res*/) {
  6585. EXPECT_EQ("close", req.get_header_value("Connection"));
  6586. })
  6587. .Get(R"(/redirect/(\d+))",
  6588. [&](const Request &req, Response &res) {
  6589. auto num = std::stoi(req.matches[1]) + 1;
  6590. std::string url = "/redirect/" + std::to_string(num);
  6591. res.set_redirect(url);
  6592. })
  6593. .Post("/binary",
  6594. [&](const Request &req, Response &res) {
  6595. EXPECT_EQ(4U, req.body.size());
  6596. EXPECT_EQ("application/octet-stream",
  6597. req.get_header_value("Content-Type"));
  6598. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6599. res.set_content(req.body, "application/octet-stream");
  6600. })
  6601. .Put("/binary",
  6602. [&](const Request &req, Response &res) {
  6603. EXPECT_EQ(4U, req.body.size());
  6604. EXPECT_EQ("application/octet-stream",
  6605. req.get_header_value("Content-Type"));
  6606. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6607. res.set_content(req.body, "application/octet-stream");
  6608. })
  6609. .Patch("/binary",
  6610. [&](const Request &req, Response &res) {
  6611. EXPECT_EQ(4U, req.body.size());
  6612. EXPECT_EQ("application/octet-stream",
  6613. req.get_header_value("Content-Type"));
  6614. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6615. res.set_content(req.body, "application/octet-stream");
  6616. })
  6617. .Delete("/binary",
  6618. [&](const Request &req, Response &res) {
  6619. EXPECT_EQ(4U, req.body.size());
  6620. EXPECT_EQ("application/octet-stream",
  6621. req.get_header_value("Content-Type"));
  6622. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6623. res.set_content(req.body, "application/octet-stream");
  6624. })
  6625. .Get("/issue1772",
  6626. [&](const Request & /*req*/, Response &res) {
  6627. res.status = 401;
  6628. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6629. })
  6630. .Delete("/issue609",
  6631. [](const httplib::Request &, httplib::Response &res,
  6632. const httplib::ContentReader &) {
  6633. res.set_content("ok", "text/plain");
  6634. })
  6635. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6636. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6637. .Get("/compress",
  6638. [&](const Request & /*req*/, Response &res) {
  6639. res.set_content(
  6640. "12345678901234567890123456789012345678901234567890123456789"
  6641. "01234567890123456789012345678901234567890",
  6642. "text/plain");
  6643. })
  6644. .Get("/compress-with-charset",
  6645. [&](const Request & /*req*/, Response &res) {
  6646. res.set_content(
  6647. "12345678901234567890123456789012345678901234567890123456789"
  6648. "01234567890123456789012345678901234567890",
  6649. "application/json; charset=utf-8");
  6650. })
  6651. .Get("/nocompress",
  6652. [&](const Request & /*req*/, Response &res) {
  6653. res.set_content(
  6654. "12345678901234567890123456789012345678901234567890123456789"
  6655. "01234567890123456789012345678901234567890",
  6656. "application/octet-stream");
  6657. })
  6658. .Post("/compress-multipart",
  6659. [&](const Request &req, Response & /*res*/) {
  6660. EXPECT_EQ(2u, req.form.fields.size());
  6661. ASSERT_TRUE(!req.form.has_field("???"));
  6662. {
  6663. const auto &text = req.form.get_field("key1");
  6664. EXPECT_EQ("test", text);
  6665. }
  6666. {
  6667. const auto &text = req.form.get_field("key2");
  6668. EXPECT_EQ("--abcdefg123", text);
  6669. }
  6670. })
  6671. #endif
  6672. ;
  6673. persons_["john"] = "programmer";
  6674. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6675. svr_.wait_until_ready();
  6676. }
  6677. virtual void TearDown() {
  6678. svr_.stop();
  6679. if (!request_threads_.empty()) {
  6680. std::this_thread::sleep_for(std::chrono::seconds(1));
  6681. for (auto &t : request_threads_) {
  6682. t.join();
  6683. }
  6684. }
  6685. t_.join();
  6686. }
  6687. map<string, string> persons_;
  6688. #ifdef CPPHTTPLIB_SSL_ENABLED
  6689. SSLClient cli_;
  6690. SSLServer svr_;
  6691. #else
  6692. Client cli_;
  6693. Server svr_;
  6694. #endif
  6695. thread t_;
  6696. std::vector<thread> request_threads_;
  6697. };
  6698. TEST_F(ServerTest, GetMethod200) {
  6699. auto res = cli_.Get("/hi");
  6700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6701. EXPECT_EQ("HTTP/1.1", res->version);
  6702. EXPECT_EQ(StatusCode::OK_200, res->status);
  6703. EXPECT_EQ("OK", res->reason);
  6704. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6705. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6706. EXPECT_EQ("Hello World!", res->body);
  6707. }
  6708. TEST_F(ServerTest, GetEmptyFile) {
  6709. auto res = cli_.Get("/empty_file");
  6710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6711. EXPECT_EQ(StatusCode::OK_200, res->status);
  6712. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6713. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6714. EXPECT_EQ("", res->body);
  6715. }
  6716. TEST_F(ServerTest, GetFileContent) {
  6717. auto res = cli_.Get("/file_content");
  6718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6719. EXPECT_EQ(StatusCode::OK_200, res->status);
  6720. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6721. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6722. EXPECT_EQ("test.html", res->body);
  6723. }
  6724. TEST_F(ServerTest, GetFileContentWithRange) {
  6725. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6727. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6728. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6729. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6730. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6731. EXPECT_EQ("est", res->body);
  6732. }
  6733. TEST_F(ServerTest, GetFileContentWithContentType) {
  6734. auto res = cli_.Get("/file_content_with_content_type");
  6735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6736. EXPECT_EQ(StatusCode::OK_200, res->status);
  6737. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6738. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6739. EXPECT_EQ("file\n", res->body);
  6740. }
  6741. TEST_F(ServerTest, GetInvalidFileContent) {
  6742. auto res = cli_.Get("/invalid_file_content");
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6745. }
  6746. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6747. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. EXPECT_EQ("HTTP/1.1", res->version);
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6752. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6753. EXPECT_EQ("Hello World!", res->body);
  6754. }
  6755. TEST_F(ServerTest, GetMethod302) {
  6756. auto res = cli_.Get("/");
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::Found_302, res->status);
  6759. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6760. }
  6761. TEST_F(ServerTest, GetMethod302Redirect) {
  6762. cli_.set_follow_location(true);
  6763. auto res = cli_.Get("/");
  6764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. EXPECT_EQ("Hello World!", res->body);
  6767. EXPECT_EQ("/hi", res->location);
  6768. }
  6769. TEST_F(ServerTest, GetMethod404) {
  6770. auto res = cli_.Get("/invalid");
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6773. }
  6774. TEST_F(ServerTest, HeadMethod200) {
  6775. auto res = cli_.Head("/hi");
  6776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6777. EXPECT_EQ(StatusCode::OK_200, res->status);
  6778. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6779. EXPECT_TRUE(res->body.empty());
  6780. }
  6781. TEST_F(ServerTest, HeadMethod200Static) {
  6782. auto res = cli_.Head("/mount/dir/index.html");
  6783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6786. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6787. EXPECT_TRUE(res->body.empty());
  6788. }
  6789. TEST_F(ServerTest, HeadMethod404) {
  6790. auto res = cli_.Head("/invalid");
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6793. EXPECT_TRUE(res->body.empty());
  6794. }
  6795. TEST_F(ServerTest, GetMethodPersonJohn) {
  6796. auto res = cli_.Get("/person/john");
  6797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6798. EXPECT_EQ(StatusCode::OK_200, res->status);
  6799. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6800. EXPECT_EQ("programmer", res->body);
  6801. }
  6802. TEST_F(ServerTest, PostMethod1) {
  6803. auto res = cli_.Get("/person/john1");
  6804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6805. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6806. res = cli_.Post("/person", "name=john1&note=coder",
  6807. "application/x-www-form-urlencoded");
  6808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6809. ASSERT_EQ(StatusCode::OK_200, res->status);
  6810. res = cli_.Get("/person/john1");
  6811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6812. ASSERT_EQ(StatusCode::OK_200, res->status);
  6813. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6814. ASSERT_EQ("coder", res->body);
  6815. }
  6816. TEST_F(ServerTest, PostMethod2) {
  6817. auto res = cli_.Get("/person/john2");
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6820. Params params;
  6821. params.emplace("name", "john2");
  6822. params.emplace("note", "coder");
  6823. res = cli_.Post("/person", params);
  6824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6825. ASSERT_EQ(StatusCode::OK_200, res->status);
  6826. res = cli_.Get("/person/john2");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. ASSERT_EQ(StatusCode::OK_200, res->status);
  6829. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6830. ASSERT_EQ("coder", res->body);
  6831. }
  6832. TEST_F(ServerTest, PutMethod3) {
  6833. auto res = cli_.Get("/person/john3");
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6836. Params params;
  6837. params.emplace("name", "john3");
  6838. params.emplace("note", "coder");
  6839. res = cli_.Put("/person", params);
  6840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6841. ASSERT_EQ(StatusCode::OK_200, res->status);
  6842. res = cli_.Get("/person/john3");
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. ASSERT_EQ(StatusCode::OK_200, res->status);
  6845. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6846. ASSERT_EQ("coder", res->body);
  6847. }
  6848. TEST_F(ServerTest, DeleteMethod1) {
  6849. auto res = cli_.Get("/person/john4");
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6852. Params params;
  6853. params.emplace("name", "john4");
  6854. params.emplace("note", "coder");
  6855. res = cli_.Post("/person", params);
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. ASSERT_EQ(StatusCode::OK_200, res->status);
  6858. res = cli_.Get("/person/john4");
  6859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6860. ASSERT_EQ(StatusCode::OK_200, res->status);
  6861. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6862. ASSERT_EQ("coder", res->body);
  6863. Params delete_params;
  6864. delete_params.emplace("name", "john4");
  6865. res = cli_.Delete("/person", delete_params);
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. ASSERT_EQ(StatusCode::OK_200, res->status);
  6868. ASSERT_EQ("DELETED", res->body);
  6869. res = cli_.Get("/person/john4");
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6872. }
  6873. TEST_F(ServerTest, DeleteMethod2) {
  6874. auto res = cli_.Get("/person/john5");
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6877. Params params;
  6878. params.emplace("name", "john5");
  6879. params.emplace("note", "developer");
  6880. res = cli_.Post("/person", params);
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. ASSERT_EQ(StatusCode::OK_200, res->status);
  6883. res = cli_.Get("/person/john5");
  6884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6885. ASSERT_EQ(StatusCode::OK_200, res->status);
  6886. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6887. ASSERT_EQ("developer", res->body);
  6888. Params delete_params;
  6889. delete_params.emplace("name", "john5");
  6890. Headers headers;
  6891. headers.emplace("Custom-Header", "test-value");
  6892. res = cli_.Delete("/person", headers, delete_params);
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. ASSERT_EQ(StatusCode::OK_200, res->status);
  6895. ASSERT_EQ("DELETED", res->body);
  6896. res = cli_.Get("/person/john5");
  6897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6898. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6899. }
  6900. TEST_F(ServerTest, DeleteMethod3) {
  6901. auto res = cli_.Get("/person/john6");
  6902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6903. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6904. Params params;
  6905. params.emplace("name", "john6");
  6906. params.emplace("note", "tester");
  6907. res = cli_.Post("/person", params);
  6908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6909. ASSERT_EQ(StatusCode::OK_200, res->status);
  6910. res = cli_.Get("/person/john6");
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. ASSERT_EQ(StatusCode::OK_200, res->status);
  6913. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6914. ASSERT_EQ("tester", res->body);
  6915. Params delete_params;
  6916. delete_params.emplace("name", "john6");
  6917. Headers headers;
  6918. headers.emplace("Custom-Header", "test-value");
  6919. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. ASSERT_EQ(StatusCode::OK_200, res->status);
  6922. ASSERT_EQ("DELETED", res->body);
  6923. res = cli_.Get("/person/john6");
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6926. }
  6927. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6928. Params params;
  6929. params.emplace("json", JSON_DATA);
  6930. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6932. ASSERT_EQ(StatusCode::OK_200, res->status);
  6933. ASSERT_EQ(JSON_DATA, res->body);
  6934. }
  6935. TEST_F(ServerTest, PostEmptyContent) {
  6936. auto res = cli_.Post("/empty", "", "text/plain");
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. ASSERT_EQ(StatusCode::OK_200, res->status);
  6939. ASSERT_EQ("empty", res->body);
  6940. }
  6941. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6942. auto res = cli_.Post("/empty-no-content-type");
  6943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6944. ASSERT_EQ(StatusCode::OK_200, res->status);
  6945. ASSERT_EQ("empty-no-content-type", res->body);
  6946. }
  6947. TEST_F(ServerTest, PostPathOnly) {
  6948. auto res = cli_.Post("/path-only");
  6949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6950. ASSERT_EQ(StatusCode::OK_200, res->status);
  6951. ASSERT_EQ("path-only", res->body);
  6952. }
  6953. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6954. auto res = cli_.Post("/path-headers-only",
  6955. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6957. ASSERT_EQ(StatusCode::OK_200, res->status);
  6958. ASSERT_EQ("path-headers-only", res->body);
  6959. }
  6960. TEST_F(ServerTest, PostLarge) {
  6961. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6963. ASSERT_EQ(StatusCode::OK_200, res->status);
  6964. EXPECT_EQ(LARGE_DATA, res->body);
  6965. }
  6966. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6967. auto res = cli_.Put("/empty-no-content-type");
  6968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6969. ASSERT_EQ(StatusCode::OK_200, res->status);
  6970. ASSERT_EQ("empty-no-content-type", res->body);
  6971. }
  6972. TEST_F(ServerTest, GetMethodDir) {
  6973. auto res = cli_.Get("/dir/");
  6974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6975. EXPECT_EQ(StatusCode::OK_200, res->status);
  6976. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6977. auto body = R"(<html>
  6978. <head>
  6979. </head>
  6980. <body>
  6981. <a href="/dir/test.html">Test</a>
  6982. <a href="/hi">hi</a>
  6983. </body>
  6984. </html>
  6985. )";
  6986. EXPECT_EQ(body, res->body);
  6987. }
  6988. TEST_F(ServerTest, GetMethodDirTest) {
  6989. auto res = cli_.Get("/dir/test.html");
  6990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6991. EXPECT_EQ(StatusCode::OK_200, res->status);
  6992. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6993. EXPECT_EQ("test.html", res->body);
  6994. }
  6995. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6996. auto res = cli_.Get("/dir/../dir/test.html");
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6999. }
  7000. TEST_F(ServerTest, GetMethodInvalidPath) {
  7001. auto res = cli_.Get("/dir/../test.html");
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7004. }
  7005. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7006. auto res = cli_.Get("/../www/dir/test.html");
  7007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7008. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7009. }
  7010. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7011. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7013. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7014. }
  7015. TEST_F(ServerTest, GetMethodDirMountTest) {
  7016. auto res = cli_.Get("/mount/dir/test.html");
  7017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7018. EXPECT_EQ(StatusCode::OK_200, res->status);
  7019. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7020. EXPECT_EQ("test.html", res->body);
  7021. }
  7022. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7023. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7025. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7026. }
  7027. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7028. auto res = cli_.Get("/mount/dir/../test.html");
  7029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7030. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7031. }
  7032. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7033. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7035. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7036. }
  7037. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7038. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7041. }
  7042. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7043. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7046. }
  7047. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7048. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7050. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7051. }
  7052. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7053. auto res = cli_.Get("/mount/dir");
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7056. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7057. }
  7058. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7059. auto res = cli_.Get("//dir");
  7060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7061. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7062. EXPECT_FALSE(res->has_header("Location"));
  7063. }
  7064. TEST_F(ServerTest, PostMethod303) {
  7065. auto res = cli_.Post("/1", "body", "text/plain");
  7066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7067. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7068. EXPECT_EQ("/2", res->get_header_value("Location"));
  7069. }
  7070. TEST_F(ServerTest, PostMethod303Redirect) {
  7071. cli_.set_follow_location(true);
  7072. auto res = cli_.Post("/1", "body", "text/plain");
  7073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7074. EXPECT_EQ(StatusCode::OK_200, res->status);
  7075. EXPECT_EQ("redirected.", res->body);
  7076. EXPECT_EQ("/2", res->location);
  7077. }
  7078. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7079. auto res = cli_.Get("/dir/test.abcde");
  7080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7081. EXPECT_EQ(StatusCode::OK_200, res->status);
  7082. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7083. EXPECT_EQ("abcde", res->body);
  7084. }
  7085. TEST_F(ServerTest, StaticFileRange) {
  7086. auto res =
  7087. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7089. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7090. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7091. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7092. EXPECT_EQ(true, res->has_header("Content-Range"));
  7093. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7094. EXPECT_EQ(std::string("cd"), res->body);
  7095. }
  7096. TEST_F(ServerTest, StaticFileRanges) {
  7097. auto res = cli_.Get("/dir/test.abcde",
  7098. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7101. EXPECT_TRUE(
  7102. res->get_header_value("Content-Type")
  7103. .find(
  7104. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7105. 0);
  7106. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7107. }
  7108. TEST_F(ServerTest, StaticFileRangeHead) {
  7109. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7112. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7113. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7114. EXPECT_EQ(true, res->has_header("Content-Range"));
  7115. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7116. }
  7117. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7118. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7121. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7122. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7123. EXPECT_EQ(true, res->has_header("Content-Range"));
  7124. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7125. res->get_header_value("Content-Range"));
  7126. EXPECT_EQ("LAST\n", res->body);
  7127. }
  7128. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7129. auto res =
  7130. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7134. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7135. EXPECT_EQ(true, res->has_header("Content-Range"));
  7136. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7137. }
  7138. TEST_F(ServerTest, StaticFileBigFile) {
  7139. auto res = cli_.Get("/dir/1MB.txt");
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::OK_200, res->status);
  7142. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7143. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7144. }
  7145. TEST_F(ServerTest, InvalidBaseDirMount) {
  7146. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7147. }
  7148. TEST_F(ServerTest, Binary) {
  7149. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7150. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7151. "application/octet-stream");
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. ASSERT_EQ(StatusCode::OK_200, res->status);
  7154. ASSERT_EQ(4U, res->body.size());
  7155. res = cli_.Put("/binary", binary.data(), binary.size(),
  7156. "application/octet-stream");
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. ASSERT_EQ(StatusCode::OK_200, res->status);
  7159. ASSERT_EQ(4U, res->body.size());
  7160. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7161. "application/octet-stream");
  7162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7163. ASSERT_EQ(StatusCode::OK_200, res->status);
  7164. ASSERT_EQ(4U, res->body.size());
  7165. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7166. "application/octet-stream");
  7167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7168. ASSERT_EQ(StatusCode::OK_200, res->status);
  7169. ASSERT_EQ(4U, res->body.size());
  7170. }
  7171. TEST_F(ServerTest, BinaryString) {
  7172. auto binary = std::string("\x00\x01\x02\x03", 4);
  7173. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. ASSERT_EQ(StatusCode::OK_200, res->status);
  7176. ASSERT_EQ(4U, res->body.size());
  7177. res = cli_.Put("/binary", binary, "application/octet-stream");
  7178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7179. ASSERT_EQ(StatusCode::OK_200, res->status);
  7180. ASSERT_EQ(4U, res->body.size());
  7181. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. ASSERT_EQ(StatusCode::OK_200, res->status);
  7184. ASSERT_EQ(4U, res->body.size());
  7185. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7187. ASSERT_EQ(StatusCode::OK_200, res->status);
  7188. ASSERT_EQ(4U, res->body.size());
  7189. }
  7190. TEST_F(ServerTest, EmptyRequest) {
  7191. auto res = cli_.Get("");
  7192. ASSERT_TRUE(!res);
  7193. EXPECT_EQ(Error::Connection, res.error());
  7194. }
  7195. TEST_F(ServerTest, LongRequest) {
  7196. std::string request;
  7197. for (size_t i = 0; i < 545; i++) {
  7198. request += "/TooLongRequest";
  7199. }
  7200. request += "OK";
  7201. auto res = cli_.Get(request.c_str());
  7202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7203. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7204. }
  7205. TEST_F(ServerTest, TooLongRequest) {
  7206. std::string request;
  7207. for (size_t i = 0; i < 546; i++) {
  7208. request += "/TooLongRequest";
  7209. }
  7210. request += "_NG";
  7211. auto start = std::chrono::high_resolution_clock::now();
  7212. cli_.set_keep_alive(true);
  7213. auto res = cli_.Get(request.c_str());
  7214. auto end = std::chrono::high_resolution_clock::now();
  7215. auto elapsed =
  7216. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7217. .count();
  7218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7219. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7220. EXPECT_LE(elapsed, 1000);
  7221. EXPECT_EQ("close", res->get_header_value("Connection"));
  7222. EXPECT_FALSE(cli_.is_socket_open());
  7223. }
  7224. TEST_F(ServerTest, AlmostTooLongRequest) {
  7225. // test for #2046 - URI length check shouldn't include other content on req
  7226. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7227. // leading /, space, HTTP/1.1)
  7228. std::string request =
  7229. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7230. auto res = cli_.Get(request.c_str());
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7233. }
  7234. TEST_F(ServerTest, LongHeader) {
  7235. Request req;
  7236. req.method = "GET";
  7237. req.path = "/hi";
  7238. std::string host_and_port;
  7239. host_and_port += HOST;
  7240. host_and_port += ":";
  7241. host_and_port += std::to_string(PORT);
  7242. req.headers.emplace("Host", host_and_port.c_str());
  7243. req.headers.emplace("Accept", "*/*");
  7244. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7245. req.headers.emplace(
  7246. "Header-Name",
  7247. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7248. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7249. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7250. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7251. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7252. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7253. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7254. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7255. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7275. "@@@@@@@@@@@@@@@@");
  7276. auto res = std::make_shared<Response>();
  7277. auto error = Error::Success;
  7278. auto ret = cli_.send(req, *res, error);
  7279. ASSERT_TRUE(ret);
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. }
  7282. TEST_F(ServerTest, LongQueryValue) {
  7283. auto start = std::chrono::high_resolution_clock::now();
  7284. cli_.set_keep_alive(true);
  7285. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7286. auto end = std::chrono::high_resolution_clock::now();
  7287. auto elapsed =
  7288. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7289. .count();
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7292. EXPECT_LE(elapsed, 1000);
  7293. EXPECT_EQ("close", res->get_header_value("Connection"));
  7294. EXPECT_FALSE(cli_.is_socket_open());
  7295. }
  7296. TEST_F(ServerTest, TooLongQueryValue) {
  7297. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7298. ASSERT_FALSE(res);
  7299. EXPECT_EQ(Error::Read, res.error());
  7300. }
  7301. TEST_F(ServerTest, TooLongHeader) {
  7302. Request req;
  7303. req.method = "GET";
  7304. req.path = "/hi";
  7305. std::string host_and_port;
  7306. host_and_port += HOST;
  7307. host_and_port += ":";
  7308. host_and_port += std::to_string(PORT);
  7309. req.headers.emplace("Host", host_and_port.c_str());
  7310. req.headers.emplace("Accept", "*/*");
  7311. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7312. req.headers.emplace(
  7313. "Header-Name",
  7314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7320. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7321. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7322. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7323. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7324. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7325. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7326. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7327. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7328. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7329. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7330. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7331. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7332. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7333. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7334. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7335. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7336. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7338. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7339. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7340. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7341. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7342. "@@@@@@@@@@@@@@@@@");
  7343. auto res = std::make_shared<Response>();
  7344. auto error = Error::Success;
  7345. auto ret = cli_.send(req, *res, error);
  7346. ASSERT_TRUE(ret);
  7347. EXPECT_EQ(StatusCode::OK_200, res->status);
  7348. }
  7349. TEST_F(ServerTest, HeaderCountAtLimit) {
  7350. // Test with headers just under the 100 limit
  7351. httplib::Headers headers;
  7352. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7353. // This should keep us just under the 100 header limit
  7354. for (int i = 0; i < 95; i++) {
  7355. std::string name = "X-Test-Header-" + std::to_string(i);
  7356. std::string value = "value" + std::to_string(i);
  7357. headers.emplace(name, value);
  7358. }
  7359. // This should work fine as we're under the limit
  7360. auto res = cli_.Get("/hi", headers);
  7361. EXPECT_TRUE(res);
  7362. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7363. }
  7364. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7365. // Test with many headers to exceed the 100 limit
  7366. httplib::Headers headers;
  7367. // Add 150 headers to definitely exceed the 100 limit
  7368. for (int i = 0; i < 150; i++) {
  7369. std::string name = "X-Test-Header-" + std::to_string(i);
  7370. std::string value = "value" + std::to_string(i);
  7371. headers.emplace(name, value);
  7372. }
  7373. // This should fail due to exceeding header count limit
  7374. cli_.set_keep_alive(true);
  7375. auto res = cli_.Get("/hi", headers);
  7376. // The server should respond with 400 Bad Request
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7379. EXPECT_EQ("close", res->get_header_value("Connection"));
  7380. EXPECT_FALSE(cli_.is_socket_open());
  7381. }
  7382. TEST_F(ServerTest, PercentEncoding) {
  7383. auto res = cli_.Get("/e%6edwith%");
  7384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7385. EXPECT_EQ(StatusCode::OK_200, res->status);
  7386. }
  7387. TEST_F(ServerTest, PercentEncodingUnicode) {
  7388. auto res = cli_.Get("/e%u006edwith%");
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. }
  7392. TEST_F(ServerTest, InvalidPercentEncoding) {
  7393. auto res = cli_.Get("/%endwith%");
  7394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7395. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7396. }
  7397. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7398. auto res = cli_.Get("/%uendwith%");
  7399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7400. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7401. }
  7402. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7403. auto res = cli_.Get("/hello?aaa=bbb%");
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7406. }
  7407. TEST_F(ServerTest, PlusSignEncoding) {
  7408. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7410. EXPECT_EQ(StatusCode::OK_200, res->status);
  7411. EXPECT_EQ("a +b", res->body);
  7412. }
  7413. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7414. // This test simulates a potential DoS attack using many headers
  7415. // to verify our security fix prevents memory exhaustion
  7416. httplib::Headers attack_headers;
  7417. // Attempt to add many headers like an attacker would (200 headers to far
  7418. // exceed limit)
  7419. for (int i = 0; i < 200; i++) {
  7420. std::string name = "X-Attack-Header-" + std::to_string(i);
  7421. std::string value = "attack_payload_" + std::to_string(i);
  7422. attack_headers.emplace(name, value);
  7423. }
  7424. // Try to POST with excessive headers
  7425. cli_.set_keep_alive(true);
  7426. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7427. // Should either fail or return 400 Bad Request due to security limit
  7428. if (res) {
  7429. // If we get a response, it should be 400 Bad Request
  7430. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7431. EXPECT_EQ("close", res->get_header_value("Connection"));
  7432. }
  7433. EXPECT_FALSE(cli_.is_socket_open());
  7434. }
  7435. TEST_F(ServerTest, MultipartFormData) {
  7436. UploadFormDataItems items = {
  7437. {"text1", "text default", "", ""},
  7438. {"text2", "aωb", "", ""},
  7439. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7440. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7441. {"file3", "", "", "application/octet-stream"},
  7442. {"file4", "", "", " application/json tmp-string "}};
  7443. auto res = cli_.Post("/multipart", items);
  7444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7445. EXPECT_EQ(StatusCode::OK_200, res->status);
  7446. }
  7447. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7448. UploadFormDataItems items = {
  7449. {"text", "default text", "", ""},
  7450. {"multi_text1", "aaaaa", "", ""},
  7451. {"multi_text1", "bbbbb", "", ""},
  7452. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7453. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7454. "application/json"},
  7455. };
  7456. auto res = cli_.Post("/multipart/multi_file_values", items);
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. }
  7460. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7461. auto res = cli_.Get("/hi");
  7462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7463. EXPECT_EQ(StatusCode::OK_200, res->status);
  7464. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7465. EXPECT_EQ("Hello World!", res->body);
  7466. }
  7467. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7468. Request req;
  7469. req.method = "POST";
  7470. req.path = "/chunked";
  7471. std::string host_and_port;
  7472. host_and_port += HOST;
  7473. host_and_port += ":";
  7474. host_and_port += std::to_string(PORT);
  7475. req.headers.emplace("Host", host_and_port.c_str());
  7476. req.headers.emplace("Accept", "*/*");
  7477. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7478. req.headers.emplace("Content-Type", "text/plain");
  7479. req.headers.emplace("Content-Length", "0");
  7480. req.headers.emplace(
  7481. "Transfer-Encoding",
  7482. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7483. // Client does not chunk, so make a chunked body manually.
  7484. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7485. auto res = std::make_shared<Response>();
  7486. auto error = Error::Success;
  7487. auto ret = cli_.send(req, *res, error);
  7488. ASSERT_TRUE(ret);
  7489. EXPECT_EQ(StatusCode::OK_200, res->status);
  7490. }
  7491. template <typename ClientT>
  7492. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7493. int expected_status) {
  7494. Request req;
  7495. req.method = "POST";
  7496. req.path = "/chunked";
  7497. std::string host_and_port;
  7498. host_and_port += HOST;
  7499. host_and_port += ":";
  7500. host_and_port += std::to_string(PORT);
  7501. req.headers.emplace("Host", host_and_port.c_str());
  7502. req.headers.emplace("Content-Length", "0");
  7503. req.headers.emplace("Transfer-Encoding", "chunked");
  7504. req.body = body;
  7505. auto res = std::make_shared<Response>();
  7506. auto error = Error::Success;
  7507. ASSERT_TRUE(cli.send(req, *res, error));
  7508. EXPECT_EQ(expected_status, res->status);
  7509. }
  7510. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7511. // rather than treat them as valid lengths.
  7512. template <typename ClientT>
  7513. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7514. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7515. }
  7516. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7517. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7518. }
  7519. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7520. expect_chunked_body_rejected(
  7521. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7522. }
  7523. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7524. // chunk-size line carries no CR, LF or other control character ahead of its
  7525. // terminator. Such a line must be refused rather than read as extension text.
  7526. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7527. expect_chunked_body_rejected(
  7528. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7529. }
  7530. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7531. expect_chunked_body_rejected(
  7532. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7533. }
  7534. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7535. expect_chunked_body_rejected(
  7536. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7537. }
  7538. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7539. // The literal stays split: a hex escape consumes every hex digit that
  7540. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7541. expect_chunked_body_rejected(
  7542. cli_, "4;a\x01"
  7543. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7544. }
  7545. // The bytes around chunk data are no payload, so they cannot ride on the
  7546. // payload limit
  7547. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7548. // Small enough that the whole request is sent before the server turns it
  7549. // down, yet past the limit by the last chunks
  7550. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7551. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7552. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7553. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7554. SCOPED_TRACE(size_line.substr(0, 2));
  7555. std::string body;
  7556. for (auto c : std::string("dechunked post body")) {
  7557. body += size_line + "\r\n" + c + "\r\n";
  7558. }
  7559. body += "0\r\n\r\n";
  7560. expect_chunked_body_rejected(cli_, body.c_str());
  7561. }
  7562. }
  7563. TEST_F(ServerTest, AcceptsChunkExtension) {
  7564. expect_chunked_body_status(cli_,
  7565. "4;name=value\r\ndech\r\n"
  7566. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7567. "0;last\r\n\r\n",
  7568. StatusCode::OK_200);
  7569. }
  7570. TEST_F(ServerTest, GetStreamed2) {
  7571. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7573. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7574. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7575. EXPECT_EQ(true, res->has_header("Content-Range"));
  7576. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7577. EXPECT_EQ(std::string("ab"), res->body);
  7578. }
  7579. TEST_F(ServerTest, GetStreamed) {
  7580. auto res = cli_.Get("/streamed");
  7581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7582. EXPECT_EQ(StatusCode::OK_200, res->status);
  7583. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7584. EXPECT_EQ(std::string("aaabbb"), res->body);
  7585. }
  7586. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7587. auto res = cli_.Get("/streamed-without-length",
  7588. Headers{make_range_header({{0, -1}})});
  7589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7590. EXPECT_EQ(StatusCode::OK_200, res->status);
  7591. EXPECT_EQ(false, res->has_header("Content-Length"));
  7592. EXPECT_EQ(false, res->has_header("Content-Range"));
  7593. EXPECT_EQ(std::string("abcdefg"), res->body);
  7594. }
  7595. TEST_F(ServerTest, GetStreamedWithRange1) {
  7596. auto res =
  7597. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7600. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7601. EXPECT_EQ(true, res->has_header("Content-Range"));
  7602. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7603. EXPECT_EQ(std::string("def"), res->body);
  7604. }
  7605. TEST_F(ServerTest, GetStreamedWithRange2) {
  7606. auto res =
  7607. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7609. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7610. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7611. EXPECT_EQ(true, res->has_header("Content-Range"));
  7612. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7613. EXPECT_EQ(std::string("bcdefg"), res->body);
  7614. }
  7615. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7616. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7618. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7619. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7620. EXPECT_EQ(true, res->has_header("Content-Range"));
  7621. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7622. EXPECT_EQ(std::string("efg"), res->body);
  7623. }
  7624. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7625. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7626. // the entire representation.
  7627. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7628. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7630. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7631. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7632. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7633. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7634. }
  7635. }
  7636. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7637. auto res =
  7638. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7640. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7641. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7642. EXPECT_EQ(false, res->has_header("Content-Range"));
  7643. EXPECT_EQ(0U, res->body.size());
  7644. }
  7645. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7646. // Only a 206 is served as a partial representation. Under any other status
  7647. // `apply_ranges()` reported the full content length, so the body must match
  7648. // that header, and the content provider must never be asked for an offset
  7649. // outside the representation.
  7650. auto check = [&](int status, const char *range) {
  7651. auto path =
  7652. std::string("/streamed-with-range?status=") + std::to_string(status);
  7653. auto ctx = path + " Range: " + range;
  7654. auto res = cli_.Get(path, Headers{{"Range", range}});
  7655. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7656. EXPECT_EQ(status, res->status) << ctx;
  7657. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7658. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7659. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7660. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7661. };
  7662. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7663. check(403, "bytes=3-5");
  7664. // The offset is far past the representation.
  7665. check(403, "bytes=100000-100200");
  7666. // `first_pos` is still -1 here, and the bounds asserts in
  7667. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7668. check(403, "bytes=-3");
  7669. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7670. // multipart branch would have written one that is empty.
  7671. check(403, "bytes=1-2, 4-5");
  7672. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7673. // covers the whole representation.
  7674. check(200, "bytes=3-5");
  7675. check(200, "bytes=1-2, 4-5");
  7676. }
  7677. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7678. auto res =
  7679. cli_.Get("/streamed-with-range",
  7680. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7681. "92233720368547758079223372036854775807"}});
  7682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7683. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7684. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7685. EXPECT_EQ(false, res->has_header("Content-Range"));
  7686. EXPECT_EQ(0U, res->body.size());
  7687. }
  7688. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7689. auto res = cli_.Get(
  7690. "/with-range",
  7691. Headers{{"Range",
  7692. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7693. {"Accept-Encoding", ""}});
  7694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7695. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7696. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7697. EXPECT_EQ(true, res->has_header("Content-Range"));
  7698. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7699. EXPECT_EQ(std::string("abcdefg"), res->body);
  7700. }
  7701. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7702. auto res = cli_.Get("/with-range", Headers{
  7703. {"Range", "bytes=0-"},
  7704. {"Accept-Encoding", ""},
  7705. });
  7706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7707. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7708. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7709. EXPECT_EQ(true, res->has_header("Content-Range"));
  7710. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7711. EXPECT_EQ(std::string("abcdefg"), res->body);
  7712. }
  7713. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7714. auto res = cli_.Get("/streamed-with-range",
  7715. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7717. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7718. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7719. EXPECT_EQ(false, res->has_header("Content-Range"));
  7720. EXPECT_EQ(267U, res->body.size());
  7721. // Check that both range contents are present
  7722. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7723. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7724. // Check that Content-Range headers are present for both ranges
  7725. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7726. std::string::npos);
  7727. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7728. std::string::npos);
  7729. }
  7730. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7731. Ranges ranges;
  7732. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7733. ranges.emplace_back(0, -1);
  7734. }
  7735. auto res = cli_.Get("/streamed-with-range?error",
  7736. Headers{{make_range_header(ranges)}});
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7739. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7740. EXPECT_EQ(false, res->has_header("Content-Range"));
  7741. EXPECT_EQ(0U, res->body.size());
  7742. }
  7743. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7744. auto res = cli_.Get("/streamed-with-range",
  7745. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7748. EXPECT_EQ(5U, res->body.size());
  7749. // Check that overlapping ranges are coalesced into a single range
  7750. EXPECT_EQ("bcdef", res->body);
  7751. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7752. // Should be single range, not multipart
  7753. EXPECT_TRUE(res->has_header("Content-Range"));
  7754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7755. }
  7756. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7757. auto res = cli_.Get("/streamed-with-range",
  7758. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7761. EXPECT_EQ(268U, res->body.size());
  7762. // Check that both range contents are present
  7763. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7764. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7765. // Check that Content-Range headers are present for both ranges
  7766. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7767. std::string::npos);
  7768. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7769. std::string::npos);
  7770. }
  7771. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7772. auto res = cli_.Get("/streamed-with-range",
  7773. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7776. EXPECT_EQ(269U, res->body.size());
  7777. // Check that both duplicate range contents are present
  7778. size_t first_abc = res->body.find("abc\r\n");
  7779. EXPECT_TRUE(first_abc != std::string::npos);
  7780. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7781. EXPECT_TRUE(second_abc != std::string::npos);
  7782. // Check that Content-Range headers are present for both ranges
  7783. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7784. EXPECT_TRUE(first_range != std::string::npos);
  7785. size_t second_range =
  7786. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7787. EXPECT_TRUE(second_range != std::string::npos);
  7788. }
  7789. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7790. auto res =
  7791. cli_.Get("/streamed-with-range?error",
  7792. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7795. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7796. EXPECT_EQ(false, res->has_header("Content-Range"));
  7797. EXPECT_EQ(0U, res->body.size());
  7798. }
  7799. TEST_F(ServerTest, GetStreamedEndless) {
  7800. uint64_t offset = 0;
  7801. auto res = cli_.Get("/streamed-cancel",
  7802. [&](const char * /*data*/, uint64_t data_length) {
  7803. if (offset < 100) {
  7804. offset += data_length;
  7805. return true;
  7806. }
  7807. return false;
  7808. });
  7809. ASSERT_TRUE(!res);
  7810. EXPECT_EQ(Error::Canceled, res.error());
  7811. }
  7812. TEST_F(ServerTest, ClientStop) {
  7813. std::atomic_size_t count{4};
  7814. std::vector<std::thread> threads;
  7815. for (auto i = count.load(); i != 0; --i) {
  7816. threads.emplace_back([&]() {
  7817. auto res = cli_.Get("/streamed-cancel",
  7818. [&](const char *, uint64_t) { return true; });
  7819. --count;
  7820. ASSERT_TRUE(!res);
  7821. EXPECT_TRUE(res.error() == Error::Canceled ||
  7822. res.error() == Error::Read || res.error() == Error::Write);
  7823. });
  7824. }
  7825. std::this_thread::sleep_for(std::chrono::seconds(2));
  7826. while (count != 0) {
  7827. cli_.stop();
  7828. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7829. }
  7830. for (auto &t : threads) {
  7831. t.join();
  7832. }
  7833. }
  7834. TEST_F(ServerTest, GetWithRange1) {
  7835. auto res = cli_.Get("/with-range", Headers{
  7836. make_range_header({{3, 5}}),
  7837. {"Accept-Encoding", ""},
  7838. });
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7841. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7842. EXPECT_EQ(true, res->has_header("Content-Range"));
  7843. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7844. EXPECT_EQ(std::string("def"), res->body);
  7845. }
  7846. TEST_F(ServerTest, GetWithRange2) {
  7847. auto res = cli_.Get("/with-range", Headers{
  7848. make_range_header({{1, -1}}),
  7849. {"Accept-Encoding", ""},
  7850. });
  7851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7852. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7853. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7854. EXPECT_EQ(true, res->has_header("Content-Range"));
  7855. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7856. EXPECT_EQ(std::string("bcdefg"), res->body);
  7857. }
  7858. TEST_F(ServerTest, GetWithRange3) {
  7859. auto res = cli_.Get("/with-range", Headers{
  7860. make_range_header({{0, 0}}),
  7861. {"Accept-Encoding", ""},
  7862. });
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7865. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7866. EXPECT_EQ(true, res->has_header("Content-Range"));
  7867. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7868. EXPECT_EQ(std::string("a"), res->body);
  7869. }
  7870. TEST_F(ServerTest, GetWithRange4) {
  7871. auto res = cli_.Get("/with-range", Headers{
  7872. make_range_header({{-1, 2}}),
  7873. {"Accept-Encoding", ""},
  7874. });
  7875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7876. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7877. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7878. EXPECT_EQ(true, res->has_header("Content-Range"));
  7879. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7880. EXPECT_EQ(std::string("fg"), res->body);
  7881. }
  7882. TEST_F(ServerTest, GetWithRange5) {
  7883. auto res = cli_.Get("/with-range", Headers{
  7884. make_range_header({{0, 5}}),
  7885. {"Accept-Encoding", ""},
  7886. });
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7889. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7890. EXPECT_EQ(true, res->has_header("Content-Range"));
  7891. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7892. EXPECT_EQ(std::string("abcdef"), res->body);
  7893. }
  7894. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7895. auto res =
  7896. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7898. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7899. }
  7900. TEST_F(ServerTest, GetWithRangeMultipart) {
  7901. auto res =
  7902. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7904. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7905. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7906. EXPECT_EQ(false, res->has_header("Content-Range"));
  7907. EXPECT_EQ(267U, res->body.size());
  7908. }
  7909. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7910. auto res = cli_.Get("/with-range",
  7911. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7913. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7914. }
  7915. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7916. auto res = cli_.Get("/with-range-customized-response",
  7917. Headers{{make_range_header({{1, 2}})}});
  7918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7919. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7920. EXPECT_EQ(true, res->has_header("Content-Length"));
  7921. EXPECT_EQ(false, res->has_header("Content-Range"));
  7922. EXPECT_EQ(JSON_DATA, res->body);
  7923. }
  7924. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7925. auto res = cli_.Get("/with-range-customized-response",
  7926. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7929. EXPECT_EQ(true, res->has_header("Content-Length"));
  7930. EXPECT_EQ(false, res->has_header("Content-Range"));
  7931. EXPECT_EQ(JSON_DATA, res->body);
  7932. }
  7933. TEST_F(ServerTest, Issue1772) {
  7934. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7936. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7937. }
  7938. TEST_F(ServerTest, Issue609) {
  7939. auto res = cli_.Delete("/issue609");
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ(StatusCode::OK_200, res->status);
  7942. EXPECT_EQ(std::string("ok"), res->body);
  7943. }
  7944. TEST_F(ServerTest, GetStreamedChunked) {
  7945. auto res = cli_.Get("/streamed-chunked");
  7946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. EXPECT_EQ(std::string("123456789"), res->body);
  7949. }
  7950. TEST_F(ServerTest, GetStreamedChunked2) {
  7951. auto res = cli_.Get("/streamed-chunked2");
  7952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7953. EXPECT_EQ(StatusCode::OK_200, res->status);
  7954. EXPECT_EQ(std::string("123456789"), res->body);
  7955. }
  7956. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7957. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7959. EXPECT_EQ(StatusCode::OK_200, res->status);
  7960. EXPECT_EQ(std::string("123456789"), res->body);
  7961. EXPECT_TRUE(res->has_header("Trailer"));
  7962. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7963. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7964. // Trailers are now stored separately from headers (security fix)
  7965. EXPECT_EQ(2U, res->trailers.size());
  7966. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7967. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7968. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7969. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7970. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7971. // Verify trailers are NOT in headers (security verification)
  7972. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7973. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7974. }
  7975. TEST_F(ServerTest, LargeChunkedPost) {
  7976. Request req;
  7977. req.method = "POST";
  7978. req.path = "/large-chunked";
  7979. std::string host_and_port;
  7980. host_and_port += HOST;
  7981. host_and_port += ":";
  7982. host_and_port += std::to_string(PORT);
  7983. req.headers.emplace("Host", host_and_port.c_str());
  7984. req.headers.emplace("Accept", "*/*");
  7985. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7986. req.headers.emplace("Content-Type", "text/plain");
  7987. req.headers.emplace("Content-Length", "0");
  7988. req.headers.emplace("Transfer-Encoding", "chunked");
  7989. std::string long_string(30 * 1024u, 'a');
  7990. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7991. // Attempt to make a large enough post to exceed OS buffers, to test that
  7992. // the server handles short reads if the full chunk data isn't available.
  7993. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7994. auto res = std::make_shared<Response>();
  7995. auto error = Error::Success;
  7996. auto ret = cli_.send(req, *res, error);
  7997. ASSERT_TRUE(ret);
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. }
  8000. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8001. auto res = cli_.Get("/remote_addr");
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::OK_200, res->status);
  8004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8005. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8006. }
  8007. TEST_F(ServerTest, GetMethodLocalAddr) {
  8008. auto res = cli_.Get("/local_addr");
  8009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8010. EXPECT_EQ(StatusCode::OK_200, res->status);
  8011. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8012. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8013. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8014. }
  8015. TEST_F(ServerTest, HTTPResponseSplitting) {
  8016. auto res = cli_.Get("/http_response_splitting");
  8017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8018. EXPECT_EQ(StatusCode::OK_200, res->status);
  8019. }
  8020. TEST_F(ServerTest, SlowRequest) {
  8021. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8022. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8023. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8024. }
  8025. #if 0
  8026. TEST_F(ServerTest, SlowPost) {
  8027. char buffer[64 * 1024];
  8028. memset(buffer, 0x42, sizeof(buffer));
  8029. auto res = cli_.Post(
  8030. "/slowpost", 64 * 1024 * 1024,
  8031. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8032. auto ret = sink.write(buffer, sizeof(buffer));
  8033. EXPECT_TRUE(ret);
  8034. return true;
  8035. },
  8036. "text/plain");
  8037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8038. EXPECT_EQ(StatusCode::OK_200, res->status);
  8039. }
  8040. TEST_F(ServerTest, SlowPostFail) {
  8041. char buffer[64 * 1024];
  8042. memset(buffer, 0x42, sizeof(buffer));
  8043. cli_.set_write_timeout(std::chrono::seconds(0));
  8044. auto res = cli_.Post(
  8045. "/slowpost", 64 * 1024 * 1024,
  8046. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8047. sink.write(buffer, sizeof(buffer));
  8048. return true;
  8049. },
  8050. "text/plain");
  8051. ASSERT_TRUE(!res);
  8052. EXPECT_EQ(Error::Write, res.error());
  8053. }
  8054. #endif
  8055. TEST_F(ServerTest, Put) {
  8056. auto res = cli_.Put("/put", "PUT", "text/plain");
  8057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8058. EXPECT_EQ(StatusCode::OK_200, res->status);
  8059. EXPECT_EQ("PUT", res->body);
  8060. }
  8061. TEST_F(ServerTest, PutWithContentProvider) {
  8062. auto res = cli_.Put(
  8063. "/put", 3,
  8064. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8065. sink.os << "PUT";
  8066. return true;
  8067. },
  8068. "text/plain");
  8069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8070. EXPECT_EQ(StatusCode::OK_200, res->status);
  8071. EXPECT_EQ("PUT", res->body);
  8072. }
  8073. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8074. auto res = cli_.Post(
  8075. "/post", 42,
  8076. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8077. return false;
  8078. },
  8079. "text/plain");
  8080. ASSERT_TRUE(!res);
  8081. EXPECT_EQ(Error::Canceled, res.error());
  8082. }
  8083. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8084. auto res = cli_.Put(
  8085. "/put",
  8086. [](size_t /*offset*/, DataSink &sink) {
  8087. sink.os << "PUT";
  8088. sink.done();
  8089. return true;
  8090. },
  8091. "text/plain");
  8092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8093. EXPECT_EQ(StatusCode::OK_200, res->status);
  8094. EXPECT_EQ("PUT", res->body);
  8095. }
  8096. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8097. auto res = cli_.Post(
  8098. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8099. "text/plain");
  8100. ASSERT_TRUE(!res);
  8101. EXPECT_EQ(Error::Canceled, res.error());
  8102. }
  8103. TEST_F(ServerTest, PostLoopBack) {
  8104. std::string body;
  8105. auto res = cli_.Post(
  8106. "/post-loopback", 9,
  8107. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8108. EXPECT_EQ(9u, length);
  8109. sink.write("123", 3);
  8110. sink.write("456", 3);
  8111. sink.write("789", 3);
  8112. return true;
  8113. },
  8114. "text/plain",
  8115. [&body](const char *data, size_t data_length) {
  8116. body.append(data, data_length);
  8117. return true;
  8118. });
  8119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8120. EXPECT_EQ(StatusCode::OK_200, res->status);
  8121. EXPECT_EQ("123456789", body);
  8122. }
  8123. TEST_F(ServerTest, PutLoopBack) {
  8124. std::string body;
  8125. auto res = cli_.Put(
  8126. "/put-loopback", 9,
  8127. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8128. EXPECT_EQ(9u, length);
  8129. sink.write("123", 3);
  8130. sink.write("456", 3);
  8131. sink.write("789", 3);
  8132. return true;
  8133. },
  8134. "text/plain",
  8135. [&body](const char *data, size_t data_length) {
  8136. body.append(data, data_length);
  8137. return true;
  8138. });
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(StatusCode::OK_200, res->status);
  8141. EXPECT_EQ("123456789", body);
  8142. }
  8143. TEST_F(ServerTest, PatchLoopBack) {
  8144. std::string body;
  8145. auto res = cli_.Patch(
  8146. "/patch-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, PostLoopBackWithoutRequestContentLength) {
  8164. std::string body;
  8165. auto res = cli_.Post(
  8166. "/post-loopback",
  8167. [](size_t /*offset*/, DataSink &sink) {
  8168. sink.write("123", 3);
  8169. sink.write("456", 3);
  8170. sink.write("789", 3);
  8171. sink.done();
  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. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8184. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8185. cli_.set_compress(true);
  8186. auto res = cli_.Put(
  8187. "/put", 3,
  8188. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8189. sink.os << "PUT";
  8190. return true;
  8191. },
  8192. "text/plain");
  8193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8194. EXPECT_EQ(StatusCode::OK_200, res->status);
  8195. EXPECT_EQ("PUT", res->body);
  8196. }
  8197. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8198. cli_.set_compress(true);
  8199. auto res = cli_.Post(
  8200. "/post", 42,
  8201. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8202. return false;
  8203. },
  8204. "text/plain");
  8205. ASSERT_TRUE(!res);
  8206. EXPECT_EQ(Error::Canceled, res.error());
  8207. }
  8208. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8209. cli_.set_compress(true);
  8210. auto res = cli_.Put(
  8211. "/put",
  8212. [](size_t /*offset*/, DataSink &sink) {
  8213. sink.os << "PUT";
  8214. sink.done();
  8215. return true;
  8216. },
  8217. "text/plain");
  8218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8219. EXPECT_EQ(StatusCode::OK_200, res->status);
  8220. EXPECT_EQ("PUT", res->body);
  8221. }
  8222. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8223. cli_.set_compress(true);
  8224. auto res = cli_.Post(
  8225. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8226. "text/plain");
  8227. ASSERT_TRUE(!res);
  8228. EXPECT_EQ(Error::Canceled, res.error());
  8229. }
  8230. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8231. cli_.set_compress(true);
  8232. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::OK_200, res->status);
  8235. EXPECT_EQ(LARGE_DATA, res->body);
  8236. }
  8237. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8238. #ifdef CPPHTTPLIB_SSL_ENABLED
  8239. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8240. Client cli(s.c_str());
  8241. cli.enable_server_certificate_verification(false);
  8242. #else
  8243. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8244. Client cli(s.c_str());
  8245. #endif
  8246. cli.set_compress(true);
  8247. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8249. EXPECT_EQ(StatusCode::OK_200, res->status);
  8250. EXPECT_EQ(LARGE_DATA, res->body);
  8251. // The compressed size should be less than a 10th of the original. May vary
  8252. // depending on the zlib library.
  8253. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8254. static_cast<uint64_t>(10 * 1024 * 1024));
  8255. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8256. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8257. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8258. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8259. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8260. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8261. #endif
  8262. }
  8263. TEST_F(ServerTest, PutContentWithDeflate) {
  8264. cli_.set_compress(false);
  8265. Headers headers;
  8266. headers.emplace("Content-Encoding", "deflate");
  8267. // PUT in deflate format:
  8268. auto res = cli_.Put("/put", headers,
  8269. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8271. EXPECT_EQ(StatusCode::OK_200, res->status);
  8272. EXPECT_EQ("PUT", res->body);
  8273. }
  8274. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8275. Headers headers;
  8276. headers.emplace("Accept-Encoding", "gzip, deflate");
  8277. auto res = cli_.Get("/streamed-chunked", headers);
  8278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8279. EXPECT_EQ(StatusCode::OK_200, res->status);
  8280. EXPECT_EQ(std::string("123456789"), res->body);
  8281. }
  8282. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8283. Headers headers;
  8284. headers.emplace("Accept-Encoding", "gzip, deflate");
  8285. auto res = cli_.Get("/streamed-chunked2", headers);
  8286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8287. EXPECT_EQ(StatusCode::OK_200, res->status);
  8288. EXPECT_EQ(std::string("123456789"), res->body);
  8289. }
  8290. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8291. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8293. EXPECT_EQ(StatusCode::OK_200, res->status);
  8294. }
  8295. TEST(GzipDecompressor, ChunkedDecompression) {
  8296. std::string data;
  8297. for (size_t i = 0; i < 32 * 1024; ++i) {
  8298. data.push_back(static_cast<char>('a' + i % 26));
  8299. }
  8300. std::string compressed_data;
  8301. {
  8302. httplib::detail::gzip_compressor compressor;
  8303. bool result = compressor.compress(
  8304. data.data(), data.size(),
  8305. /*last=*/true,
  8306. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8307. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8308. compressed_data_size);
  8309. return true;
  8310. });
  8311. ASSERT_TRUE(result);
  8312. }
  8313. std::string decompressed_data;
  8314. {
  8315. httplib::detail::gzip_decompressor decompressor;
  8316. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8317. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8318. size_t chunk_size = 130;
  8319. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8320. chunk_begin += chunk_size) {
  8321. size_t current_chunk_size =
  8322. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8323. bool result = decompressor.decompress(
  8324. compressed_data.data() + chunk_begin, current_chunk_size,
  8325. [&](const char *decompressed_data_chunk,
  8326. size_t decompressed_data_chunk_size) {
  8327. decompressed_data.insert(decompressed_data.size(),
  8328. decompressed_data_chunk,
  8329. decompressed_data_chunk_size);
  8330. return true;
  8331. });
  8332. ASSERT_TRUE(result);
  8333. }
  8334. }
  8335. ASSERT_EQ(data, decompressed_data);
  8336. }
  8337. TEST(GzipDecompressor, DeflateDecompression) {
  8338. std::string original_text = "Raw deflate without gzip";
  8339. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8340. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8341. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8342. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8343. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8344. std::string decompressed_data;
  8345. {
  8346. httplib::detail::gzip_decompressor decompressor;
  8347. bool result = decompressor.decompress(
  8348. compressed_data.data(), compressed_data.size(),
  8349. [&](const char *decompressed_data_chunk,
  8350. size_t decompressed_data_chunk_size) {
  8351. decompressed_data.insert(decompressed_data.size(),
  8352. decompressed_data_chunk,
  8353. decompressed_data_chunk_size);
  8354. return true;
  8355. });
  8356. ASSERT_TRUE(result);
  8357. }
  8358. ASSERT_EQ(original_text, decompressed_data);
  8359. }
  8360. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8361. std::string original_text = "Raw deflate without gzip";
  8362. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8363. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8364. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8365. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8366. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8367. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8368. std::string decompressed_data;
  8369. {
  8370. httplib::detail::gzip_decompressor decompressor;
  8371. bool result = decompressor.decompress(
  8372. compressed_data.data(), compressed_data.size(),
  8373. [&](const char *decompressed_data_chunk,
  8374. size_t decompressed_data_chunk_size) {
  8375. decompressed_data.insert(decompressed_data.size(),
  8376. decompressed_data_chunk,
  8377. decompressed_data_chunk_size);
  8378. return true;
  8379. });
  8380. ASSERT_TRUE(result);
  8381. }
  8382. ASSERT_EQ(original_text, decompressed_data);
  8383. }
  8384. #endif
  8385. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8386. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8387. Headers headers;
  8388. headers.emplace("Accept-Encoding", "br");
  8389. auto res = cli_.Get("/streamed-chunked", headers);
  8390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8391. EXPECT_EQ(StatusCode::OK_200, res->status);
  8392. EXPECT_EQ(std::string("123456789"), res->body);
  8393. }
  8394. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8395. Headers headers;
  8396. headers.emplace("Accept-Encoding", "br");
  8397. auto res = cli_.Get("/streamed-chunked2", headers);
  8398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8399. EXPECT_EQ(StatusCode::OK_200, res->status);
  8400. EXPECT_EQ(std::string("123456789"), res->body);
  8401. }
  8402. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8403. cli_.set_compress(true);
  8404. auto res = cli_.Put(
  8405. "/put", 3,
  8406. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8407. sink.os << "PUT";
  8408. return true;
  8409. },
  8410. "text/plain");
  8411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8412. EXPECT_EQ(StatusCode::OK_200, res->status);
  8413. EXPECT_EQ("PUT", res->body);
  8414. }
  8415. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8416. cli_.set_compress(true);
  8417. auto res = cli_.Put(
  8418. "/put",
  8419. [](size_t /*offset*/, DataSink &sink) {
  8420. sink.os << "PUT";
  8421. sink.done();
  8422. return true;
  8423. },
  8424. "text/plain");
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ(StatusCode::OK_200, res->status);
  8427. EXPECT_EQ("PUT", res->body);
  8428. }
  8429. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8430. cli_.set_compress(true);
  8431. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8433. EXPECT_EQ(StatusCode::OK_200, res->status);
  8434. EXPECT_EQ(LARGE_DATA, res->body);
  8435. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8436. }
  8437. #endif
  8438. TEST_F(ServerTest, Patch) {
  8439. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8441. EXPECT_EQ(StatusCode::OK_200, res->status);
  8442. EXPECT_EQ("PATCH", res->body);
  8443. }
  8444. TEST_F(ServerTest, Delete) {
  8445. auto res = cli_.Delete("/delete");
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_EQ(StatusCode::OK_200, res->status);
  8448. EXPECT_EQ("DELETE", res->body);
  8449. }
  8450. TEST_F(ServerTest, DeleteContentReceiver) {
  8451. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8453. EXPECT_EQ(StatusCode::OK_200, res->status);
  8454. EXPECT_EQ("content", res->body);
  8455. }
  8456. TEST_F(ServerTest, Options) {
  8457. auto res = cli_.Options("*");
  8458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8459. EXPECT_EQ(StatusCode::OK_200, res->status);
  8460. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8461. EXPECT_TRUE(res->body.empty());
  8462. }
  8463. TEST_F(ServerTest, URL) {
  8464. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(StatusCode::OK_200, res->status);
  8467. }
  8468. TEST_F(ServerTest, ArrayParam) {
  8469. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8471. EXPECT_EQ(StatusCode::OK_200, res->status);
  8472. }
  8473. TEST_F(ServerTest, ArrayParamValues) {
  8474. auto res =
  8475. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8477. EXPECT_EQ(StatusCode::OK_200, res->status);
  8478. }
  8479. TEST_F(ServerTest, NoMultipleHeaders) {
  8480. Headers headers = {{"Content-Length", "5"}};
  8481. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8482. "text/plain");
  8483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8484. EXPECT_EQ(StatusCode::OK_200, res->status);
  8485. }
  8486. TEST_F(ServerTest, PostContentReceiver) {
  8487. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8489. ASSERT_EQ(StatusCode::OK_200, res->status);
  8490. ASSERT_EQ("content", res->body);
  8491. }
  8492. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8493. UploadFormDataItems items = {
  8494. {"text1", "text default", "", ""},
  8495. {"text2", "aωb", "", ""},
  8496. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8497. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8498. {"file3", "", "", "application/octet-stream"},
  8499. };
  8500. auto res = cli_.Post("/content_receiver", items);
  8501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8502. EXPECT_EQ(StatusCode::OK_200, res->status);
  8503. }
  8504. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8505. UploadFormDataItems items = {
  8506. {"text1", "text default", "", ""},
  8507. {"text2", "aωb", "", ""},
  8508. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8509. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8510. {"file3", "", "", "application/octet-stream"},
  8511. };
  8512. auto boundary = std::string("+++++");
  8513. std::string body;
  8514. for (const auto &item : items) {
  8515. body += "--" + boundary + "\r\n";
  8516. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8517. if (!item.filename.empty()) {
  8518. body += "; filename=\"" + item.filename + "\"";
  8519. }
  8520. body += "\r\n";
  8521. if (!item.content_type.empty()) {
  8522. body += "Content-Type: " + item.content_type + "\r\n";
  8523. }
  8524. body += "\r\n";
  8525. body += item.content + "\r\n";
  8526. }
  8527. body += "--" + boundary + "--\r\n";
  8528. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8529. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8531. EXPECT_EQ(StatusCode::OK_200, res->status);
  8532. }
  8533. TEST(MultipartFormDataTest, FieldEscaping) {
  8534. Server svr;
  8535. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8536. const ContentReader &content_reader) {
  8537. ASSERT_TRUE(req.is_multipart_form_data());
  8538. std::vector<FormData> received;
  8539. content_reader(
  8540. [&](const FormData &file) {
  8541. received.push_back(file);
  8542. return true;
  8543. },
  8544. [&](const char *data, size_t data_length) {
  8545. received.back().content.append(data, data_length);
  8546. return true;
  8547. });
  8548. // '"', CR and LF in names and filenames are escaped following the
  8549. // WHATWG HTML standard, so each part still parses as a single part
  8550. // with no injected headers. Content types get CR/LF escaped too,
  8551. // while '"' (legal there, e.g. quoted charset) is preserved.
  8552. ASSERT_EQ(4U, received.size());
  8553. EXPECT_EQ("na%22me", received[0].name);
  8554. EXPECT_EQ("quoted name", received[0].content);
  8555. EXPECT_EQ("file", received[1].name);
  8556. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8557. received[1].filename);
  8558. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8559. EXPECT_EQ("injected", received[1].content);
  8560. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8561. EXPECT_EQ("my%22file.txt", received[2].filename);
  8562. EXPECT_EQ("cr lf name", received[2].content);
  8563. EXPECT_EQ("typed", received[3].name);
  8564. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8565. received[3].content_type);
  8566. EXPECT_EQ("typed content", received[3].content);
  8567. });
  8568. auto port = svr.bind_to_any_port("localhost");
  8569. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8570. auto se = detail::scope_exit([&] {
  8571. svr.stop();
  8572. t.join();
  8573. ASSERT_FALSE(svr.is_running());
  8574. });
  8575. svr.wait_until_ready();
  8576. Client cli("localhost", port);
  8577. UploadFormDataItems items = {
  8578. {"na\"me", "quoted name", "", ""},
  8579. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8580. "application/octet-stream"},
  8581. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8582. {"typed", "typed content", "",
  8583. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8584. };
  8585. auto res = cli.Post("/post", items);
  8586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8587. EXPECT_EQ(StatusCode::OK_200, res->status);
  8588. }
  8589. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8590. const UploadFormDataItems items = {
  8591. {"name1", "Content 1", "", ""},
  8592. {"name2", "Content 2", "file2.txt", "text/plain"},
  8593. };
  8594. Server svr;
  8595. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8596. const ContentReader &content_reader) {
  8597. ASSERT_TRUE(req.is_multipart_form_data());
  8598. std::vector<FormData> received;
  8599. content_reader(
  8600. [&](const FormData &file) {
  8601. received.push_back(file);
  8602. return true;
  8603. },
  8604. [&](const char *data, size_t data_length) {
  8605. received.back().content.append(data, data_length);
  8606. return true;
  8607. });
  8608. ASSERT_EQ(2U, received.size());
  8609. EXPECT_EQ("name1", received[0].name);
  8610. EXPECT_EQ("Content 1", received[0].content);
  8611. EXPECT_EQ("name2", received[1].name);
  8612. EXPECT_EQ("Content 2", received[1].content);
  8613. EXPECT_EQ("file2.txt", received[1].filename);
  8614. EXPECT_EQ("text/plain", received[1].content_type);
  8615. });
  8616. auto port = svr.bind_to_any_port("localhost");
  8617. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8618. auto se = detail::scope_exit([&] {
  8619. svr.stop();
  8620. t.join();
  8621. ASSERT_FALSE(svr.is_running());
  8622. });
  8623. svr.wait_until_ready();
  8624. Client cli("localhost", port);
  8625. // Whole-body serialization with a generated boundary
  8626. {
  8627. MultipartFormDataWriter writer;
  8628. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8629. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8630. writer.content_type());
  8631. auto body = writer.serialize(items);
  8632. EXPECT_EQ(body.size(), writer.content_length(items));
  8633. auto res = cli.Post("/post", body, writer.content_type());
  8634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8635. EXPECT_EQ(StatusCode::OK_200, res->status);
  8636. }
  8637. // Per-part framing with a custom boundary via a content provider
  8638. {
  8639. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8640. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8641. MultipartFormDataWriter writer("custom-boundary_123");
  8642. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8643. std::string body;
  8644. for (const auto &item : items) {
  8645. body += writer.item_begin(item);
  8646. body += item.content;
  8647. body += MultipartFormDataWriter::item_end();
  8648. }
  8649. body += writer.finish();
  8650. EXPECT_EQ(body.size(), writer.content_length(items));
  8651. auto res = cli.Post(
  8652. "/post", body.size(),
  8653. [&](size_t offset, size_t length, DataSink &sink) {
  8654. sink.write(body.data() + offset, length);
  8655. return true;
  8656. },
  8657. writer.content_type());
  8658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8659. EXPECT_EQ(StatusCode::OK_200, res->status);
  8660. }
  8661. }
  8662. TEST_F(ServerTest, PostContentReceiverGzip) {
  8663. cli_.set_compress(true);
  8664. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. ASSERT_EQ(StatusCode::OK_200, res->status);
  8667. ASSERT_EQ("content", res->body);
  8668. }
  8669. TEST_F(ServerTest, PutContentReceiver) {
  8670. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8672. ASSERT_EQ(StatusCode::OK_200, res->status);
  8673. ASSERT_EQ("content", res->body);
  8674. }
  8675. TEST_F(ServerTest, PatchContentReceiver) {
  8676. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8678. ASSERT_EQ(StatusCode::OK_200, res->status);
  8679. ASSERT_EQ("content", res->body);
  8680. }
  8681. template <typename ClientType>
  8682. void TestWithHeadersAndContentReceiver(
  8683. ClientType &cli,
  8684. std::function<Result(ClientType &, const std::string &, const Headers &,
  8685. const std::string &, const std::string &,
  8686. ContentReceiver, DownloadProgress)>
  8687. request_func) {
  8688. Headers headers;
  8689. headers.emplace("X-Custom-Header", "test-value");
  8690. std::string received_body;
  8691. auto res = request_func(
  8692. cli, "/content_receiver", headers, "content", "application/json",
  8693. [&](const char *data, size_t data_length) {
  8694. received_body.append(data, data_length);
  8695. return true;
  8696. },
  8697. nullptr);
  8698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8699. EXPECT_EQ(StatusCode::OK_200, res->status);
  8700. EXPECT_EQ("content", received_body);
  8701. }
  8702. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8703. #ifdef CPPHTTPLIB_SSL_ENABLED
  8704. using ClientT = SSLClient;
  8705. #else
  8706. using ClientT = Client;
  8707. #endif
  8708. TestWithHeadersAndContentReceiver<ClientT>(
  8709. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8710. const std::string &body, const std::string &content_type,
  8711. ContentReceiver receiver, DownloadProgress progress) {
  8712. return cli.Post(path, headers, body, content_type, receiver, progress);
  8713. });
  8714. }
  8715. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8716. #ifdef CPPHTTPLIB_SSL_ENABLED
  8717. using ClientT = SSLClient;
  8718. #else
  8719. using ClientT = Client;
  8720. #endif
  8721. TestWithHeadersAndContentReceiver<ClientT>(
  8722. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8723. const std::string &body, const std::string &content_type,
  8724. ContentReceiver receiver, DownloadProgress progress) {
  8725. return cli.Put(path, headers, body, content_type, receiver, progress);
  8726. });
  8727. }
  8728. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8729. #ifdef CPPHTTPLIB_SSL_ENABLED
  8730. using ClientT = SSLClient;
  8731. #else
  8732. using ClientT = Client;
  8733. #endif
  8734. TestWithHeadersAndContentReceiver<ClientT>(
  8735. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8736. const std::string &body, const std::string &content_type,
  8737. ContentReceiver receiver, DownloadProgress progress) {
  8738. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8739. });
  8740. }
  8741. template <typename ClientType>
  8742. void TestWithHeadersAndContentReceiverWithProgress(
  8743. ClientType &cli,
  8744. std::function<Result(ClientType &, const std::string &, const Headers &,
  8745. const std::string &, const std::string &,
  8746. ContentReceiver, DownloadProgress)>
  8747. request_func) {
  8748. Headers headers;
  8749. headers.emplace("X-Test-Header", "progress-test");
  8750. std::string received_body;
  8751. auto progress_called = false;
  8752. auto res = request_func(
  8753. cli, "/content_receiver", headers, "content", "text/plain",
  8754. [&](const char *data, size_t data_length) {
  8755. received_body.append(data, data_length);
  8756. return true;
  8757. },
  8758. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8759. progress_called = true;
  8760. return true;
  8761. });
  8762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8763. EXPECT_EQ(StatusCode::OK_200, res->status);
  8764. EXPECT_EQ("content", received_body);
  8765. EXPECT_TRUE(progress_called);
  8766. }
  8767. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8768. #ifdef CPPHTTPLIB_SSL_ENABLED
  8769. using ClientT = SSLClient;
  8770. #else
  8771. using ClientT = Client;
  8772. #endif
  8773. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8774. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8775. const std::string &body, const std::string &content_type,
  8776. ContentReceiver receiver, DownloadProgress progress) {
  8777. return cli.Post(path, headers, body, content_type, receiver, progress);
  8778. });
  8779. }
  8780. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8781. #ifdef CPPHTTPLIB_SSL_ENABLED
  8782. using ClientT = SSLClient;
  8783. #else
  8784. using ClientT = Client;
  8785. #endif
  8786. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8787. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8788. const std::string &body, const std::string &content_type,
  8789. ContentReceiver receiver, DownloadProgress progress) {
  8790. return cli.Put(path, headers, body, content_type, receiver, progress);
  8791. });
  8792. }
  8793. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8794. #ifdef CPPHTTPLIB_SSL_ENABLED
  8795. using ClientT = SSLClient;
  8796. #else
  8797. using ClientT = Client;
  8798. #endif
  8799. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8800. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8801. const std::string &body, const std::string &content_type,
  8802. ContentReceiver receiver, DownloadProgress progress) {
  8803. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8804. });
  8805. }
  8806. template <typename ClientType>
  8807. void TestWithHeadersAndContentReceiverError(
  8808. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8809. const Headers &, const std::string &,
  8810. const std::string &, ContentReceiver)>
  8811. request_func) {
  8812. Headers headers;
  8813. headers.emplace("X-Error-Test", "true");
  8814. std::string received_body;
  8815. auto receiver_failed = false;
  8816. auto res =
  8817. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8818. [&](const char *data, size_t data_length) {
  8819. received_body.append(data, data_length);
  8820. receiver_failed = true;
  8821. return false;
  8822. });
  8823. ASSERT_FALSE(res);
  8824. EXPECT_TRUE(receiver_failed);
  8825. }
  8826. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8827. #ifdef CPPHTTPLIB_SSL_ENABLED
  8828. using ClientT = SSLClient;
  8829. #else
  8830. using ClientT = Client;
  8831. #endif
  8832. TestWithHeadersAndContentReceiverError<ClientT>(
  8833. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8834. const std::string &body, const std::string &content_type,
  8835. ContentReceiver receiver) {
  8836. return cli.Post(path, headers, body, content_type, receiver);
  8837. });
  8838. }
  8839. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8840. #ifdef CPPHTTPLIB_SSL_ENABLED
  8841. using ClientT = SSLClient;
  8842. #else
  8843. using ClientT = Client;
  8844. #endif
  8845. TestWithHeadersAndContentReceiverError<ClientT>(
  8846. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8847. const std::string &body, const std::string &content_type,
  8848. ContentReceiver receiver) {
  8849. return cli.Put(path, headers, body, content_type, receiver);
  8850. });
  8851. }
  8852. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8853. #ifdef CPPHTTPLIB_SSL_ENABLED
  8854. using ClientT = SSLClient;
  8855. #else
  8856. using ClientT = Client;
  8857. #endif
  8858. TestWithHeadersAndContentReceiverError<ClientT>(
  8859. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8860. const std::string &body, const std::string &content_type,
  8861. ContentReceiver receiver) {
  8862. return cli.Patch(path, headers, body, content_type, receiver);
  8863. });
  8864. }
  8865. TEST_F(ServerTest, PostQueryStringAndBody) {
  8866. auto res =
  8867. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8869. ASSERT_EQ(StatusCode::OK_200, res->status);
  8870. }
  8871. TEST_F(ServerTest, HTTP2Magic) {
  8872. Request req;
  8873. req.method = "PRI";
  8874. req.path = "*";
  8875. req.body = "SM";
  8876. auto res = std::make_shared<Response>();
  8877. auto error = Error::Success;
  8878. auto ret = cli_.send(req, *res, error);
  8879. ASSERT_TRUE(ret);
  8880. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8881. }
  8882. TEST_F(ServerTest, KeepAlive) {
  8883. auto res = cli_.Get("/hi");
  8884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8885. EXPECT_EQ(StatusCode::OK_200, res->status);
  8886. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8887. EXPECT_EQ("Hello World!", res->body);
  8888. res = cli_.Get("/hi");
  8889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8890. EXPECT_EQ(StatusCode::OK_200, res->status);
  8891. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8892. EXPECT_EQ("Hello World!", res->body);
  8893. res = cli_.Get("/hi");
  8894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8895. EXPECT_EQ(StatusCode::OK_200, res->status);
  8896. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8897. EXPECT_EQ("Hello World!", res->body);
  8898. res = cli_.Get("/not-exist");
  8899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8900. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8901. res = cli_.Post("/empty", "", "text/plain");
  8902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8903. EXPECT_EQ(StatusCode::OK_200, res->status);
  8904. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8905. EXPECT_EQ("empty", res->body);
  8906. EXPECT_EQ("close", res->get_header_value("Connection"));
  8907. res = cli_.Post(
  8908. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8909. "text/plain");
  8910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8911. EXPECT_EQ(StatusCode::OK_200, res->status);
  8912. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8913. EXPECT_EQ("empty", res->body);
  8914. cli_.set_keep_alive(false);
  8915. res = cli_.Get("/last-request");
  8916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8917. EXPECT_EQ(StatusCode::OK_200, res->status);
  8918. EXPECT_EQ("close", res->get_header_value("Connection"));
  8919. }
  8920. TEST_F(ServerTest, TooManyRedirect) {
  8921. cli_.set_follow_location(true);
  8922. auto res = cli_.Get("/redirect/0");
  8923. ASSERT_TRUE(!res);
  8924. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8925. }
  8926. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8927. Request req;
  8928. req.method = "FOOBAR";
  8929. req.path = "/hi";
  8930. cli_.set_keep_alive(true);
  8931. auto res = cli_.send(req);
  8932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8933. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8934. EXPECT_EQ("close", res->get_header_value("Connection"));
  8935. EXPECT_FALSE(cli_.is_socket_open());
  8936. }
  8937. TEST_F(ServerTest, CustomRouteReadsBody) {
  8938. const std::string xml =
  8939. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8940. Request req;
  8941. req.method = "PROPFIND";
  8942. req.path = "/dav/dir";
  8943. req.set_header("Depth", "1");
  8944. req.body = xml;
  8945. auto res = cli_.send(req);
  8946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8947. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8948. EXPECT_EQ(xml, res->body);
  8949. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8950. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8951. }
  8952. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8953. Request req;
  8954. req.method = "PROPFIND";
  8955. req.path = "/dav/42";
  8956. auto res = cli_.send(req);
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8959. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8960. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8961. }
  8962. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8963. Request req;
  8964. req.method = "PROPFIND";
  8965. req.path = "/dav-re/123";
  8966. auto res = cli_.send(req);
  8967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8968. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8969. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8970. }
  8971. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8972. Request req;
  8973. req.method = "MKCOL";
  8974. req.path = "/dav-mkcol";
  8975. auto res = cli_.send(req);
  8976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8977. EXPECT_EQ(StatusCode::Created_201, res->status);
  8978. }
  8979. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8980. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8981. Request req;
  8982. req.method = "REPORT";
  8983. req.path = "/dav-report";
  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. }
  8990. // A content reader route must fire even when the request carries no body,
  8991. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8992. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8993. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8994. Request req;
  8995. req.method = "REPORT";
  8996. req.path = "/dav-report";
  8997. auto res = cli_.send(req);
  8998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8999. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9000. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9001. }
  9002. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9003. Request req;
  9004. req.method = "PROPFIND";
  9005. req.path = "/not-dav";
  9006. auto res = cli_.send(req);
  9007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9008. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9009. }
  9010. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9011. Request req;
  9012. req.method = "UNLOCK";
  9013. req.path = "/dav/dir";
  9014. cli_.set_keep_alive(true);
  9015. auto res = cli_.send(req);
  9016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9017. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9018. EXPECT_EQ("close", res->get_header_value("Connection"));
  9019. EXPECT_FALSE(cli_.is_socket_open());
  9020. }
  9021. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9022. // The mount point serves this path, but only for GET and HEAD.
  9023. auto get_res = cli_.Get("/dir/index.html");
  9024. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9025. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9026. Request req;
  9027. req.method = "PROPFIND";
  9028. req.path = "/dir/index.html";
  9029. auto res = cli_.send(req);
  9030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9031. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9032. }
  9033. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9034. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9035. cli_.set_keep_alive(true);
  9036. for (auto i = 0; i < 2; i++) {
  9037. Request req;
  9038. req.method = "PROPFIND";
  9039. req.path = "/dav/dir";
  9040. req.body = xml;
  9041. auto res = cli_.send(req);
  9042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9043. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9044. EXPECT_EQ(xml, res->body);
  9045. EXPECT_TRUE(cli_.is_socket_open());
  9046. }
  9047. // A built-in method must still be served on the same connection.
  9048. cli_.set_keep_alive(false);
  9049. auto res = cli_.Get("/hi");
  9050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9051. EXPECT_EQ(StatusCode::OK_200, res->status);
  9052. EXPECT_EQ("close", res->get_header_value("Connection"));
  9053. }
  9054. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9055. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9056. Request req;
  9057. req.method = "PROPFIND";
  9058. req.path = "/dav/dir";
  9059. req.set_header("Expect", "100-continue");
  9060. req.body = xml;
  9061. auto res = cli_.send(req);
  9062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9063. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9064. EXPECT_EQ(xml, res->body);
  9065. }
  9066. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9067. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9068. TEST_F(ServerTest, Gzip) {
  9069. Headers headers;
  9070. headers.emplace("Accept-Encoding", "gzip, deflate");
  9071. auto res = cli_.Get("/compress", headers);
  9072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9073. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9074. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9075. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9076. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9077. "7890123456789012345678901234567890",
  9078. res->body);
  9079. EXPECT_EQ(StatusCode::OK_200, res->status);
  9080. }
  9081. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9082. Headers headers;
  9083. headers.emplace("Accept-Encoding", "gzip, deflate");
  9084. auto res = cli_.Get("/compress-with-charset", headers);
  9085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9086. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9087. EXPECT_EQ("application/json; charset=utf-8",
  9088. res->get_header_value("Content-Type"));
  9089. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9090. "7890123456789012345678901234567890",
  9091. res->body);
  9092. EXPECT_EQ(StatusCode::OK_200, res->status);
  9093. }
  9094. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9095. Headers headers;
  9096. headers.emplace("Accept-Encoding", "");
  9097. auto res = cli_.Get("/compress", headers);
  9098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9099. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9101. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9102. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9103. "7890123456789012345678901234567890",
  9104. res->body);
  9105. EXPECT_EQ(StatusCode::OK_200, res->status);
  9106. }
  9107. TEST_F(ServerTest, GzipWithContentReceiver) {
  9108. Headers headers;
  9109. headers.emplace("Accept-Encoding", "gzip, deflate");
  9110. std::string body;
  9111. auto res =
  9112. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9113. EXPECT_EQ(100U, data_length);
  9114. body.append(data, data_length);
  9115. return true;
  9116. });
  9117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9118. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9119. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9120. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9121. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9122. "7890123456789012345678901234567890",
  9123. body);
  9124. EXPECT_EQ(StatusCode::OK_200, res->status);
  9125. }
  9126. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9127. Headers headers;
  9128. headers.emplace("Accept-Encoding", "gzip, deflate");
  9129. cli_.set_decompress(false);
  9130. auto res = cli_.Get("/compress", headers);
  9131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9132. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9134. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9135. EXPECT_EQ(33U, res->body.size());
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. }
  9138. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9139. Headers headers;
  9140. headers.emplace("Accept-Encoding", "");
  9141. std::string body;
  9142. auto res =
  9143. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9144. EXPECT_EQ(100U, data_length);
  9145. body.append(data, data_length);
  9146. return true;
  9147. });
  9148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9149. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9150. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9151. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9152. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9153. "7890123456789012345678901234567890",
  9154. body);
  9155. EXPECT_EQ(StatusCode::OK_200, res->status);
  9156. }
  9157. TEST_F(ServerTest, NoGzip) {
  9158. Headers headers;
  9159. headers.emplace("Accept-Encoding", "gzip, deflate");
  9160. auto res = cli_.Get("/nocompress", headers);
  9161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9162. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9163. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9164. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9165. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9166. "7890123456789012345678901234567890",
  9167. res->body);
  9168. EXPECT_EQ(StatusCode::OK_200, res->status);
  9169. }
  9170. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9171. Headers headers;
  9172. headers.emplace("Accept-Encoding", "gzip, deflate");
  9173. std::string body;
  9174. auto res = cli_.Get("/nocompress", headers,
  9175. [&](const char *data, size_t data_length) {
  9176. EXPECT_EQ(100U, data_length);
  9177. body.append(data, data_length);
  9178. return true;
  9179. });
  9180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9181. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9182. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9183. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9184. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9185. "7890123456789012345678901234567890",
  9186. body);
  9187. EXPECT_EQ(StatusCode::OK_200, res->status);
  9188. }
  9189. TEST_F(ServerTest, MultipartFormDataGzip) {
  9190. UploadFormDataItems items = {
  9191. {"key1", "test", "", ""},
  9192. {"key2", "--abcdefg123", "", ""},
  9193. };
  9194. cli_.set_compress(true);
  9195. auto res = cli_.Post("/compress-multipart", items);
  9196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9197. EXPECT_EQ(StatusCode::OK_200, res->status);
  9198. }
  9199. #endif
  9200. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9201. // Static file compression is opt-in, so these run their own server rather than
  9202. // flipping it on for the shared ServerTest fixture, which would silently
  9203. // rewrite what every other static file test is asserting.
  9204. class StaticFileCompressionTest : public ::testing::Test {
  9205. protected:
  9206. void TearDown() override {
  9207. if (t_.joinable()) {
  9208. svr_.stop();
  9209. t_.join();
  9210. }
  9211. }
  9212. int start(const std::function<void(Server &)> &configure = nullptr) {
  9213. // Serves the same tree as a directory of build-time compressed assets
  9214. // would be served: the mount point names the coding the files are already
  9215. // stored in. Registered before "/" so it is the one that matches.
  9216. svr_.set_mount_point("/pre-encoded", "./www",
  9217. {{"Content-Encoding", "gzip"}});
  9218. svr_.set_mount_point("/", "./www");
  9219. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9220. res.set_file_content("./www/dir/index.html", "text/html");
  9221. });
  9222. svr_.Get("/pre-encoded-file-content",
  9223. [](const Request & /*req*/, Response &res) {
  9224. res.set_header("Content-Encoding", "gzip");
  9225. res.set_file_content("./www/dir/index.html", "text/html");
  9226. });
  9227. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9228. res.set_content_provider(
  9229. 6, "text/plain",
  9230. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9231. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9232. return true;
  9233. });
  9234. });
  9235. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9236. res.set_content_provider(
  9237. 1000, "text/plain",
  9238. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9239. if (offset < 100) {
  9240. std::string data(100, 'A');
  9241. sink.write(data.data(), data.size());
  9242. return true;
  9243. }
  9244. std::this_thread::sleep_for(std::chrono::seconds(2));
  9245. std::string data(900, 'B');
  9246. sink.write(data.data(), data.size());
  9247. return true;
  9248. });
  9249. });
  9250. if (configure) { configure(svr_); }
  9251. auto port = svr_.bind_to_any_port(HOST);
  9252. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9253. svr_.wait_until_ready();
  9254. return port;
  9255. }
  9256. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9257. // Every file under ./www except 1MB.txt is smaller than the default
  9258. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9259. // it out of the way.
  9260. static void enable_without_floor(Server &svr) {
  9261. svr.set_static_file_compression(true);
  9262. svr.set_static_file_compression_min_length(0);
  9263. }
  9264. Server svr_;
  9265. std::thread t_;
  9266. };
  9267. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9268. auto port = start();
  9269. Client cli(HOST, port);
  9270. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9272. EXPECT_EQ(StatusCode::OK_200, res->status);
  9273. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9274. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9275. EXPECT_EQ(1048576U, res->body.size());
  9276. }
  9277. TEST_F(StaticFileCompressionTest, MountPoint) {
  9278. auto port = start(enable);
  9279. Client cli(HOST, port);
  9280. cli.set_decompress(false);
  9281. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9283. EXPECT_EQ(StatusCode::OK_200, res->status);
  9284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9285. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9286. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9287. // The response stays self-delimiting: a length, not a chunked body.
  9288. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9289. EXPECT_EQ(std::to_string(res->body.size()),
  9290. res->get_header_value("Content-Length"));
  9291. EXPECT_LT(res->body.size(), 1048576U);
  9292. EXPECT_FALSE(res->body.empty());
  9293. }
  9294. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9295. auto port = start(enable);
  9296. Client cli(HOST, port);
  9297. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9299. EXPECT_EQ(StatusCode::OK_200, res->status);
  9300. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9301. EXPECT_EQ(1048576U, res->body.size());
  9302. }
  9303. TEST_F(StaticFileCompressionTest, FileContent) {
  9304. auto port = start(enable_without_floor);
  9305. Client cli(HOST, port);
  9306. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9308. EXPECT_EQ(StatusCode::OK_200, res->status);
  9309. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9310. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9311. EXPECT_EQ(104U, res->body.size());
  9312. }
  9313. // A handler that serves an already-encoded file names the coding itself. The
  9314. // file-backed path decided its coding from Accept-Encoding and the content
  9315. // type alone, so it compressed the stored bytes a second time and appended a
  9316. // second Content-Encoding field line.
  9317. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9318. auto port = start(enable_without_floor);
  9319. Client cli(HOST, port);
  9320. cli.set_decompress(false);
  9321. auto res = cli.Get("/pre-encoded-file-content",
  9322. Headers{{"Accept-Encoding", "gzip"}});
  9323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9324. EXPECT_EQ(StatusCode::OK_200, res->status);
  9325. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9326. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9327. // Vary belongs to a coding the server chose, and it chose none here.
  9328. EXPECT_FALSE(res->has_header("Vary"));
  9329. // The file travels exactly as it is stored on disk.
  9330. EXPECT_EQ(104U, res->body.size());
  9331. }
  9332. // The 1MB file clears the default floor, so this one runs the configuration a
  9333. // deployment would actually have.
  9334. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9335. auto port = start(enable);
  9336. Client cli(HOST, port);
  9337. cli.set_decompress(false);
  9338. auto res =
  9339. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9341. EXPECT_EQ(StatusCode::OK_200, res->status);
  9342. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9343. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9344. EXPECT_FALSE(res->has_header("Vary"));
  9345. EXPECT_EQ(1048576U, res->body.size());
  9346. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9347. }
  9348. TEST_F(StaticFileCompressionTest, Head) {
  9349. auto port = start(enable);
  9350. Client cli(HOST, port);
  9351. cli.set_decompress(false);
  9352. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9353. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9354. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9356. EXPECT_EQ(StatusCode::OK_200, res->status);
  9357. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9358. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9359. // HEAD still reports the size a GET would return.
  9360. EXPECT_EQ(get->get_header_value("Content-Length"),
  9361. res->get_header_value("Content-Length"));
  9362. EXPECT_TRUE(res->body.empty());
  9363. }
  9364. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9365. auto port = start(enable);
  9366. Client cli(HOST, port);
  9367. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9368. {"Accept-Encoding", "gzip"}});
  9369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9370. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9371. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9372. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9373. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9374. EXPECT_EQ("cd", res->body);
  9375. }
  9376. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9377. auto port = start(enable);
  9378. Client cli(HOST, port);
  9379. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9381. EXPECT_EQ(StatusCode::OK_200, res->status);
  9382. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9383. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9384. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9385. }
  9386. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9387. auto port = start(enable);
  9388. Client cli(HOST, port);
  9389. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9391. EXPECT_EQ(StatusCode::OK_200, res->status);
  9392. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9393. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9394. EXPECT_TRUE(res->body.empty());
  9395. }
  9396. TEST_F(StaticFileCompressionTest, MinLength) {
  9397. auto port = start(enable);
  9398. Client cli(HOST, port);
  9399. // 104 bytes, well under the default floor. Compressing it would add the
  9400. // gzip header and trailer to a body that already fits in one packet.
  9401. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9403. EXPECT_EQ(StatusCode::OK_200, res->status);
  9404. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9405. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9406. }
  9407. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9408. auto port = start([](Server &svr) {
  9409. svr.set_static_file_compression(true);
  9410. svr.set_static_file_compression_min_length(1);
  9411. });
  9412. Client cli(HOST, port);
  9413. cli.set_decompress(false);
  9414. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9416. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9417. // A 9-byte file comes back larger than it went in, because gzip's header and
  9418. // trailer outweigh anything deflate can save. That is the end of the range
  9419. // the floor exists to keep out.
  9420. EXPECT_GT(res->body.size(), 9U);
  9421. }
  9422. TEST_F(StaticFileCompressionTest, MaxLength) {
  9423. auto port = start([](Server &svr) {
  9424. svr.set_static_file_compression(true);
  9425. svr.set_static_file_compression_min_length(0);
  9426. svr.set_static_file_compression_max_length(1024);
  9427. });
  9428. Client cli(HOST, port);
  9429. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9430. // defines `small` as a macro on Windows.
  9431. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9432. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9433. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9434. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9435. // Under it: compressed.
  9436. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9437. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9438. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9439. }
  9440. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9441. auto port = start(enable_without_floor);
  9442. Client cli(HOST, port);
  9443. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9444. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9445. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9446. auto identity_etag = identity->get_header_value("ETag");
  9447. ASSERT_FALSE(identity_etag.empty());
  9448. auto gzipped =
  9449. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9450. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9451. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9452. auto gzip_etag = gzipped->get_header_value("ETag");
  9453. ASSERT_FALSE(gzip_etag.empty());
  9454. // Two representations, two validators.
  9455. EXPECT_NE(identity_etag, gzip_etag);
  9456. // Each one revalidates against the request that would produce it...
  9457. auto fresh =
  9458. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9459. {"If-None-Match", gzip_etag}});
  9460. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9461. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9462. auto fresh_identity =
  9463. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9464. {"If-None-Match", identity_etag}});
  9465. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9466. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9467. // ...and not against the other representation.
  9468. auto crossed =
  9469. cli.Get("/dir/index.html",
  9470. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9471. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9472. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9473. }
  9474. // The opt-in covers responses the server reads off disk itself. A caller's own
  9475. // known-length provider keeps its Content-Length and, more importantly, keeps
  9476. // delivering incrementally: routing it through a compressor would hold every
  9477. // write back until zlib's window filled.
  9478. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9479. auto port = start(enable);
  9480. Client cli(HOST, port);
  9481. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_EQ(StatusCode::OK_200, res->status);
  9484. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9485. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9486. EXPECT_EQ("aaabbb", res->body);
  9487. }
  9488. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9489. auto port = start(enable);
  9490. Client cli(HOST, port);
  9491. cli.set_read_timeout(1, 0);
  9492. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9493. Headers{{"Accept-Encoding", "gzip"}});
  9494. ASSERT_TRUE(handle.is_valid());
  9495. // The provider writes 100 bytes and then stalls for longer than the read
  9496. // timeout. Those first bytes have to arrive anyway: run the response through
  9497. // a compressor and zlib holds them until its window fills, so the read would
  9498. // come back empty instead.
  9499. char buf[256];
  9500. auto n = handle.read(buf, sizeof(buf));
  9501. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9502. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9503. }
  9504. #endif
  9505. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9506. TEST_F(ServerTest, Brotli) {
  9507. Headers headers;
  9508. headers.emplace("Accept-Encoding", "br");
  9509. auto res = cli_.Get("/compress", headers);
  9510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9511. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9513. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9514. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9515. "7890123456789012345678901234567890",
  9516. res->body);
  9517. EXPECT_EQ(StatusCode::OK_200, res->status);
  9518. }
  9519. #endif
  9520. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9521. TEST_F(ServerTest, Zstd) {
  9522. Headers headers;
  9523. headers.emplace("Accept-Encoding", "zstd");
  9524. auto res = cli_.Get("/compress", headers);
  9525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9526. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9527. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9528. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9529. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9530. "7890123456789012345678901234567890",
  9531. res->body);
  9532. EXPECT_EQ(StatusCode::OK_200, res->status);
  9533. }
  9534. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9535. Headers headers;
  9536. headers.emplace("Accept-Encoding", "");
  9537. auto res = cli_.Get("/compress", headers);
  9538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9539. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9540. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9541. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9542. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9543. "7890123456789012345678901234567890",
  9544. res->body);
  9545. EXPECT_EQ(StatusCode::OK_200, res->status);
  9546. }
  9547. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9548. Headers headers;
  9549. headers.emplace("Accept-Encoding", "zstd");
  9550. std::string body;
  9551. auto res =
  9552. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9553. EXPECT_EQ(100U, data_length);
  9554. body.append(data, data_length);
  9555. return true;
  9556. });
  9557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9558. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9559. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9560. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9561. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9562. "7890123456789012345678901234567890",
  9563. body);
  9564. EXPECT_EQ(StatusCode::OK_200, res->status);
  9565. }
  9566. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9567. Headers headers;
  9568. headers.emplace("Accept-Encoding", "zstd");
  9569. cli_.set_decompress(false);
  9570. auto res = cli_.Get("/compress", headers);
  9571. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9572. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9573. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9574. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9576. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9577. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9578. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9579. EXPECT_EQ(StatusCode::OK_200, res->status);
  9580. ASSERT_EQ(26U, res->body.size());
  9581. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9582. 0);
  9583. }
  9584. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9585. Headers headers;
  9586. headers.emplace("Accept-Encoding", "");
  9587. std::string body;
  9588. auto res =
  9589. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9590. EXPECT_EQ(100U, data_length);
  9591. body.append(data, data_length);
  9592. return true;
  9593. });
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9597. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9598. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9599. "7890123456789012345678901234567890",
  9600. body);
  9601. EXPECT_EQ(StatusCode::OK_200, res->status);
  9602. }
  9603. TEST_F(ServerTest, NoZstd) {
  9604. Headers headers;
  9605. headers.emplace("Accept-Encoding", "zstd");
  9606. auto res = cli_.Get("/nocompress", headers);
  9607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9608. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9609. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9610. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9611. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9612. "7890123456789012345678901234567890",
  9613. res->body);
  9614. EXPECT_EQ(StatusCode::OK_200, res->status);
  9615. }
  9616. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9617. Headers headers;
  9618. headers.emplace("Accept-Encoding", "zstd");
  9619. std::string body;
  9620. auto res = cli_.Get("/nocompress", headers,
  9621. [&](const char *data, size_t data_length) {
  9622. EXPECT_EQ(100U, data_length);
  9623. body.append(data, data_length);
  9624. return true;
  9625. });
  9626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9627. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9628. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9629. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9630. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9631. "7890123456789012345678901234567890",
  9632. body);
  9633. EXPECT_EQ(StatusCode::OK_200, res->status);
  9634. }
  9635. // TODO: How to enable zstd ??
  9636. TEST_F(ServerTest, MultipartFormDataZstd) {
  9637. UploadFormDataItems items = {
  9638. {"key1", "test", "", ""},
  9639. {"key2", "--abcdefg123", "", ""},
  9640. };
  9641. Headers headers;
  9642. headers.emplace("Accept-Encoding", "zstd");
  9643. cli_.set_compress(true);
  9644. auto res = cli_.Post("/compress-multipart", headers, items);
  9645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9646. EXPECT_EQ(StatusCode::OK_200, res->status);
  9647. }
  9648. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9649. Headers headers;
  9650. headers.emplace("Accept-Encoding", "zstd");
  9651. cli_.set_compress(true);
  9652. auto res = cli_.Put(
  9653. "/put", headers, 3,
  9654. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9655. sink.os << "PUT";
  9656. return true;
  9657. },
  9658. "text/plain");
  9659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9660. EXPECT_EQ(StatusCode::OK_200, res->status);
  9661. EXPECT_EQ("PUT", res->body);
  9662. }
  9663. // Pre-compression logging tests
  9664. TEST_F(ServerTest, PreCompressionLogging) {
  9665. // Test data for compression (matches the actual /compress endpoint content)
  9666. const std::string test_content =
  9667. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9668. "3456789012345678901234567890";
  9669. // Variables to capture logging data
  9670. std::string pre_compression_body;
  9671. std::string pre_compression_content_type;
  9672. std::string pre_compression_content_encoding;
  9673. std::string post_compression_body;
  9674. std::string post_compression_content_type;
  9675. std::string post_compression_content_encoding;
  9676. // Set up pre-compression logger
  9677. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9678. const Response &res) {
  9679. pre_compression_body = res.body;
  9680. pre_compression_content_type = res.get_header_value("Content-Type");
  9681. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9682. });
  9683. // Set up post-compression logger
  9684. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9685. post_compression_body = res.body;
  9686. post_compression_content_type = res.get_header_value("Content-Type");
  9687. post_compression_content_encoding =
  9688. res.get_header_value("Content-Encoding");
  9689. });
  9690. // Test with gzip compression
  9691. Headers headers;
  9692. headers.emplace("Accept-Encoding", "gzip");
  9693. auto res = cli_.Get("/compress", headers);
  9694. // Verify response was compressed
  9695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9696. EXPECT_EQ(StatusCode::OK_200, res->status);
  9697. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9698. // Verify pre-compression logger captured uncompressed content
  9699. EXPECT_EQ(test_content, pre_compression_body);
  9700. EXPECT_EQ("text/plain", pre_compression_content_type);
  9701. EXPECT_TRUE(pre_compression_content_encoding
  9702. .empty()); // No encoding header before compression
  9703. // Verify post-compression logger captured compressed content
  9704. EXPECT_NE(test_content,
  9705. post_compression_body); // Should be different after compression
  9706. EXPECT_EQ("text/plain", post_compression_content_type);
  9707. EXPECT_EQ("gzip", post_compression_content_encoding);
  9708. // Verify compressed content is smaller
  9709. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9710. }
  9711. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9712. const std::string test_content =
  9713. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9714. "3456789012345678901234567890";
  9715. std::string pre_compression_body;
  9716. std::string post_compression_body;
  9717. svr_.set_pre_compression_logger(
  9718. [&](const Request & /*req*/, const Response &res) {
  9719. pre_compression_body = res.body;
  9720. });
  9721. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9722. post_compression_body = res.body;
  9723. });
  9724. Headers headers;
  9725. headers.emplace("Accept-Encoding", "br");
  9726. auto res = cli_.Get("/compress", headers);
  9727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9728. EXPECT_EQ(StatusCode::OK_200, res->status);
  9729. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9730. // Verify pre-compression content is uncompressed
  9731. EXPECT_EQ(test_content, pre_compression_body);
  9732. // Verify post-compression content is compressed
  9733. EXPECT_NE(test_content, post_compression_body);
  9734. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9735. }
  9736. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9737. const std::string test_content =
  9738. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9739. "3456789012345678901234567890";
  9740. std::string pre_compression_body;
  9741. std::string post_compression_body;
  9742. svr_.set_pre_compression_logger(
  9743. [&](const Request & /*req*/, const Response &res) {
  9744. pre_compression_body = res.body;
  9745. });
  9746. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9747. post_compression_body = res.body;
  9748. });
  9749. // Request without compression (use /nocompress endpoint)
  9750. Headers headers;
  9751. auto res = cli_.Get("/nocompress", headers);
  9752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9753. EXPECT_EQ(StatusCode::OK_200, res->status);
  9754. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9755. // Pre-compression logger should not be called when no compression is applied
  9756. EXPECT_TRUE(
  9757. pre_compression_body.empty()); // Pre-compression logger not called
  9758. EXPECT_EQ(
  9759. test_content,
  9760. post_compression_body); // Post-compression logger captures final content
  9761. }
  9762. TEST_F(ServerTest, LoggerSeesContentLength) {
  9763. size_t logged_content_length = 0;
  9764. std::string logged_content_length_header;
  9765. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9766. logged_content_length = res.content_length_;
  9767. logged_content_length_header = res.get_header_value("Content-Length");
  9768. });
  9769. auto res = cli_.Get("/nocompress");
  9770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9771. EXPECT_EQ(StatusCode::OK_200, res->status);
  9772. EXPECT_EQ(res->body.size(), logged_content_length);
  9773. EXPECT_EQ(std::to_string(logged_content_length),
  9774. logged_content_length_header);
  9775. }
  9776. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9777. const std::string test_content =
  9778. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9779. "3456789012345678901234567890";
  9780. std::string pre_compression_body;
  9781. bool pre_logger_called = false;
  9782. // Set only pre-compression logger
  9783. svr_.set_pre_compression_logger(
  9784. [&](const Request & /*req*/, const Response &res) {
  9785. pre_compression_body = res.body;
  9786. pre_logger_called = true;
  9787. });
  9788. Headers headers;
  9789. headers.emplace("Accept-Encoding", "gzip");
  9790. auto res = cli_.Get("/compress", headers);
  9791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9792. EXPECT_EQ(StatusCode::OK_200, res->status);
  9793. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9794. // Verify pre-compression logger was called
  9795. EXPECT_TRUE(pre_logger_called);
  9796. EXPECT_EQ(test_content, pre_compression_body);
  9797. }
  9798. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9799. {
  9800. // Test with Expect: 100-continue header - success case
  9801. // Server returns 100 Continue, client sends body, server returns 200 OK
  9802. Request req;
  9803. req.method = "POST";
  9804. req.path = "/post-large";
  9805. req.set_header("Expect", "100-continue");
  9806. req.body = LARGE_DATA;
  9807. Response res;
  9808. auto error = Error::Success;
  9809. cli_.set_keep_alive(true);
  9810. auto ret = cli_.send(req, res, error);
  9811. EXPECT_TRUE(ret);
  9812. EXPECT_EQ(StatusCode::OK_200, res.status);
  9813. EXPECT_EQ(LARGE_DATA, res.body);
  9814. }
  9815. {
  9816. // Test with Expect: 100-continue header - error case
  9817. // Client should not send the body when server returns an error
  9818. Request req;
  9819. req.method = "POST";
  9820. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9821. req.set_header("Expect", "100-continue");
  9822. req.body = LARGE_DATA;
  9823. Response res;
  9824. auto error = Error::Success;
  9825. auto start = std::chrono::high_resolution_clock::now();
  9826. cli_.set_keep_alive(true);
  9827. auto ret = cli_.send(req, res, error);
  9828. auto end = std::chrono::high_resolution_clock::now();
  9829. auto elapsed =
  9830. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9831. .count();
  9832. // With Expect: 100-continue, request completes successfully but with error
  9833. EXPECT_TRUE(ret);
  9834. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9835. EXPECT_EQ("close", res.get_header_value("Connection"));
  9836. EXPECT_FALSE(cli_.is_socket_open());
  9837. EXPECT_LE(elapsed, 2000);
  9838. }
  9839. {
  9840. // Send an extra GET request to ensure error recovery without hanging
  9841. Request req;
  9842. req.method = "GET";
  9843. req.path = "/hi";
  9844. auto start = std::chrono::high_resolution_clock::now();
  9845. auto res = cli_.send(req);
  9846. auto end = std::chrono::high_resolution_clock::now();
  9847. auto elapsed =
  9848. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9849. .count();
  9850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9851. EXPECT_EQ(StatusCode::OK_200, res->status);
  9852. EXPECT_EQ("Hello World!", res->body);
  9853. EXPECT_LE(elapsed, 500);
  9854. }
  9855. }
  9856. TEST(ZstdDecompressor, ChunkedDecompression) {
  9857. std::string data;
  9858. for (size_t i = 0; i < 32 * 1024; ++i) {
  9859. data.push_back(static_cast<char>('a' + i % 26));
  9860. }
  9861. std::string compressed_data;
  9862. {
  9863. httplib::detail::zstd_compressor compressor;
  9864. bool result = compressor.compress(
  9865. data.data(), data.size(),
  9866. /*last=*/true,
  9867. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9868. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9869. compressed_data_size);
  9870. return true;
  9871. });
  9872. ASSERT_TRUE(result);
  9873. }
  9874. std::string decompressed_data;
  9875. {
  9876. httplib::detail::zstd_decompressor decompressor;
  9877. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9878. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9879. size_t chunk_size = 130;
  9880. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9881. chunk_begin += chunk_size) {
  9882. size_t current_chunk_size =
  9883. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9884. bool result = decompressor.decompress(
  9885. compressed_data.data() + chunk_begin, current_chunk_size,
  9886. [&](const char *decompressed_data_chunk,
  9887. size_t decompressed_data_chunk_size) {
  9888. decompressed_data.insert(decompressed_data.size(),
  9889. decompressed_data_chunk,
  9890. decompressed_data_chunk_size);
  9891. return true;
  9892. });
  9893. ASSERT_TRUE(result);
  9894. }
  9895. }
  9896. ASSERT_EQ(data, decompressed_data);
  9897. }
  9898. TEST(ZstdDecompressor, Decompress) {
  9899. std::string original_text = "Compressed with ZSTD";
  9900. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9901. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9902. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9903. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9904. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9905. std::string decompressed_data;
  9906. {
  9907. httplib::detail::zstd_decompressor decompressor;
  9908. bool result = decompressor.decompress(
  9909. compressed_data.data(), compressed_data.size(),
  9910. [&](const char *decompressed_data_chunk,
  9911. size_t decompressed_data_chunk_size) {
  9912. decompressed_data.insert(decompressed_data.size(),
  9913. decompressed_data_chunk,
  9914. decompressed_data_chunk_size);
  9915. return true;
  9916. });
  9917. ASSERT_TRUE(result);
  9918. }
  9919. ASSERT_EQ(original_text, decompressed_data);
  9920. }
  9921. #endif
  9922. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9923. // separate chunks so that the server sees each part in its own read(). Used to
  9924. // place a read boundary at a specific offset of a request body.
  9925. static bool send_request_in_parts(time_t read_timeout_sec,
  9926. const std::vector<std::string> &parts,
  9927. std::string *resp = nullptr,
  9928. int port = PORT) {
  9929. auto error = Error::Success;
  9930. auto client_sock = detail::create_client_socket(
  9931. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9932. /*connection_timeout_sec=*/5, 0,
  9933. /*read_timeout_sec=*/5, 0,
  9934. /*write_timeout_sec=*/5, 0, std::string(), error);
  9935. if (client_sock == INVALID_SOCKET) { return false; }
  9936. auto ret = detail::process_client_socket(
  9937. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9938. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9939. for (size_t i = 0; i < parts.size(); i++) {
  9940. const auto &part = parts[i];
  9941. if (part.size() !=
  9942. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9943. return false;
  9944. }
  9945. if (i + 1 < parts.size()) {
  9946. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9947. }
  9948. }
  9949. char buf[512];
  9950. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9951. while (line_reader.getline()) {
  9952. if (resp) { *resp += line_reader.ptr(); }
  9953. }
  9954. return true;
  9955. });
  9956. detail::close_socket(client_sock);
  9957. return ret;
  9958. }
  9959. // Sends a raw request to a server listening at HOST:PORT.
  9960. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9961. std::string *resp = nullptr, int port = PORT) {
  9962. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9963. }
  9964. #ifdef CPPHTTPLIB_SSL_ENABLED
  9965. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9967. ASSERT_TRUE(svr.is_valid());
  9968. svr.set_read_timeout(1, 0);
  9969. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9970. auto se = detail::scope_exit([&] {
  9971. svr.stop();
  9972. t.join();
  9973. ASSERT_FALSE(svr.is_running());
  9974. });
  9975. svr.wait_until_ready();
  9976. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9977. // keeps each wait well within the read timeout. The server gives up a
  9978. // second in, so the bytes sent after that fail.
  9979. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9980. parts.resize(26, std::string(1, '\0'));
  9981. EXPECT_FALSE(send_request_in_parts(5, parts));
  9982. }
  9983. #endif
  9984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9985. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9986. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9987. const std::vector<std::string> &parts,
  9988. std::string *resp = nullptr,
  9989. int port = PORT) {
  9990. auto error = Error::Success;
  9991. auto sock = detail::create_client_socket(
  9992. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9993. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9994. /*write_timeout_sec=*/5, 0, std::string(), error);
  9995. if (sock == INVALID_SOCKET) { return false; }
  9996. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9997. auto ctx = SSL_CTX_new(TLS_client_method());
  9998. auto ssl = SSL_new(ctx);
  9999. auto ssl_se = detail::scope_exit([&] {
  10000. SSL_free(ssl);
  10001. SSL_CTX_free(ctx);
  10002. });
  10003. SSL_set_fd(ssl, static_cast<int>(sock));
  10004. if (SSL_connect(ssl) != 1) { return false; }
  10005. for (size_t i = 0; i < parts.size(); i++) {
  10006. const auto &part = parts[i];
  10007. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10008. static_cast<int>(part.size())) {
  10009. return false;
  10010. }
  10011. if (i + 1 < parts.size()) {
  10012. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10013. }
  10014. }
  10015. char buf[512];
  10016. int n;
  10017. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10018. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10019. }
  10020. return true;
  10021. }
  10022. #endif
  10023. // The request line, then a header value a byte at a time.
  10024. static std::vector<std::string> slow_request_head_parts() {
  10025. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10026. parts.resize(26, "a");
  10027. parts.emplace_back("\r\n\r\n");
  10028. return parts;
  10029. }
  10030. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10031. // within the one-second read timeout. The server gives up a second in, before
  10032. // the head is complete.
  10033. static void
  10034. expect_slow_request_head_dropped(Server &svr,
  10035. const std::function<std::string()> &send) {
  10036. std::atomic<bool> handled(false);
  10037. svr.Get("/", [&](const Request &, Response &res) {
  10038. handled = true;
  10039. res.set_content("ok", "text/plain");
  10040. });
  10041. svr.set_read_timeout(1, 0);
  10042. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10043. auto se = detail::scope_exit([&] {
  10044. svr.stop();
  10045. t.join();
  10046. ASSERT_FALSE(svr.is_running());
  10047. });
  10048. svr.wait_until_ready();
  10049. auto resp = send();
  10050. EXPECT_FALSE(handled);
  10051. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10052. }
  10053. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10054. Server svr;
  10055. expect_slow_request_head_dropped(svr, [] {
  10056. std::string resp;
  10057. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10058. return resp;
  10059. });
  10060. }
  10061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10062. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10063. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10064. ASSERT_TRUE(svr.is_valid());
  10065. expect_slow_request_head_dropped(svr, [] {
  10066. std::string resp;
  10067. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10068. return resp;
  10069. });
  10070. }
  10071. #endif
  10072. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10073. Server svr;
  10074. std::string header_value;
  10075. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10076. header_value = req.get_header_value("foo");
  10077. res.set_content("ok", "text/plain");
  10078. });
  10079. thread t = thread([&] { svr.listen(HOST, PORT); });
  10080. auto se = detail::scope_exit([&] {
  10081. svr.stop();
  10082. t.join();
  10083. ASSERT_FALSE(svr.is_running());
  10084. });
  10085. svr.wait_until_ready();
  10086. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10087. // like characters are not treated the same - use vertical tab and escape.
  10088. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10089. "foo: \t \v bar \x1B\t \r\n"
  10090. "Connection: close\r\n"
  10091. "\r\n";
  10092. std::string res;
  10093. ASSERT_TRUE(send_request(5, req, &res));
  10094. EXPECT_EQ(header_value, "");
  10095. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10096. }
  10097. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10098. Server svr;
  10099. std::string received;
  10100. svr.Get("/order", [&](const Request &req, Response &res) {
  10101. received = entries_to_string(req.headers);
  10102. res.set_content("ok", "text/plain");
  10103. });
  10104. auto port = svr.bind_to_any_port(HOST);
  10105. thread t = thread([&] { svr.listen_after_bind(); });
  10106. auto se = detail::scope_exit([&] {
  10107. svr.stop();
  10108. t.join();
  10109. ASSERT_FALSE(svr.is_running());
  10110. });
  10111. svr.wait_until_ready();
  10112. const std::string req = "GET /order HTTP/1.1\r\n"
  10113. "Host: localhost\r\n"
  10114. "X-First: 1\r\n"
  10115. "X-Dup: a\r\n"
  10116. "X-Second: 2\r\n"
  10117. "X-Dup: b\r\n"
  10118. "Connection: close\r\n"
  10119. "\r\n";
  10120. std::string res;
  10121. ASSERT_TRUE(send_request(5, req, &res, port));
  10122. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10123. EXPECT_EQ(
  10124. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10125. received);
  10126. }
  10127. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10128. Server svr;
  10129. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10130. res.set_header("Set-Cookie", "first=1");
  10131. res.set_header("X-Between", "y");
  10132. res.set_header("Set-Cookie", "second=2");
  10133. res.set_content("ok", "text/plain");
  10134. });
  10135. auto port = svr.bind_to_any_port(HOST);
  10136. thread t = thread([&] { svr.listen_after_bind(); });
  10137. auto se = detail::scope_exit([&] {
  10138. svr.stop();
  10139. t.join();
  10140. ASSERT_FALSE(svr.is_running());
  10141. });
  10142. svr.wait_until_ready();
  10143. Client cli(HOST, port);
  10144. auto res = cli.Get("/cookies");
  10145. ASSERT_TRUE(res);
  10146. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10147. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10148. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10149. }
  10150. // A stream may send a byte at a time with a small extension on each chunk,
  10151. // however long it runs
  10152. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10153. Server svr;
  10154. svr.Post("/count", [](const Request &req, Response &res) {
  10155. res.set_content(std::to_string(req.body.size()), "text/plain");
  10156. });
  10157. auto port = svr.bind_to_any_port(HOST);
  10158. ASSERT_LT(0, port);
  10159. thread t = thread([&] { svr.listen_after_bind(); });
  10160. auto se = detail::scope_exit([&] {
  10161. svr.stop();
  10162. t.join();
  10163. ASSERT_FALSE(svr.is_running());
  10164. });
  10165. svr.wait_until_ready();
  10166. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10167. "\r\nTransfer-Encoding: chunked\r\n"
  10168. "Connection: close\r\n\r\n";
  10169. for (auto i = 0; i < 4096; i++) {
  10170. req += "1;a=b\r\nx\r\n";
  10171. }
  10172. req += "0\r\n\r\n";
  10173. std::string res;
  10174. ASSERT_TRUE(send_request(5, req, &res, port));
  10175. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10176. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10177. }
  10178. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10179. Server svr;
  10180. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10181. auto i = new int(0);
  10182. res.set_header("Trailer", "X-Safe, X-Reflected");
  10183. res.set_chunked_content_provider(
  10184. "text/plain",
  10185. [i](size_t /*offset*/, DataSink &sink) {
  10186. if (*i == 0) {
  10187. sink.os << "body";
  10188. } else {
  10189. Headers trailer;
  10190. // A valid trailer that must survive.
  10191. trailer.emplace("X-Safe", "safe");
  10192. // Attacker-controlled value carrying CR/LF (response splitting).
  10193. trailer.emplace("X-Reflected",
  10194. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10195. // Attacker-controlled name carrying CR/LF.
  10196. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10197. sink.done_with_trailer(trailer);
  10198. }
  10199. (*i)++;
  10200. return true;
  10201. },
  10202. [i](bool /*success*/) { delete i; });
  10203. });
  10204. thread t = thread([&] { svr.listen(HOST, PORT); });
  10205. auto se = detail::scope_exit([&] {
  10206. svr.stop();
  10207. t.join();
  10208. ASSERT_FALSE(svr.is_running());
  10209. });
  10210. svr.wait_until_ready();
  10211. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10212. "Host: " + HOST +
  10213. "\r\n"
  10214. "Connection: close\r\n"
  10215. "\r\n";
  10216. std::string res;
  10217. ASSERT_TRUE(send_request(5, req, &res));
  10218. // The injected fields must not appear anywhere in the raw response.
  10219. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10220. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10221. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10222. // Invalid trailers are dropped entirely, matching set_header().
  10223. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10224. // The valid trailer still passes through.
  10225. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10226. }
  10227. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10228. // A custom header writer gets only the fields the default one writes
  10229. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10230. std::string s;
  10231. for (const auto &h : hdrs) {
  10232. s += h.first + ": " + h.second + "\r\n";
  10233. }
  10234. s += "\r\n";
  10235. return strm.write(s.data(), s.size());
  10236. };
  10237. for (auto custom_writer : {false, true}) {
  10238. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10239. Server svr;
  10240. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10241. svr.set_post_routing_handler([](const Request &, Response &res) {
  10242. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10243. });
  10244. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10245. // res.headers is a public field an application can populate directly,
  10246. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10247. // A valid header that must survive.
  10248. res.headers.emplace("X-Safe", "safe");
  10249. // Attacker-controlled value carrying CR/LF (response splitting).
  10250. res.headers.emplace("X-Reflected",
  10251. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10252. // Attacker-controlled name carrying CR/LF.
  10253. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10254. res.set_content("body", "text/plain");
  10255. });
  10256. thread t = thread([&] { svr.listen(HOST, PORT); });
  10257. auto se = detail::scope_exit([&] {
  10258. svr.stop();
  10259. t.join();
  10260. ASSERT_FALSE(svr.is_running());
  10261. });
  10262. svr.wait_until_ready();
  10263. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10264. "Host: " + HOST +
  10265. "\r\n"
  10266. "Connection: close\r\n"
  10267. "\r\n";
  10268. std::string res;
  10269. ASSERT_TRUE(send_request(5, req, &res));
  10270. // The injected fields must not appear anywhere in the raw response.
  10271. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10272. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10273. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10274. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10275. // Invalid headers are dropped entirely, matching set_header().
  10276. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10277. // The valid header still passes through.
  10278. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10279. }
  10280. }
  10281. // Forward declaration: in split builds split.py strips `inline` and moves the
  10282. // definition into httplib.cc, so detail::write_request_line is not visible from
  10283. // the public httplib.h. Re-declaring it here lets the tests link against the
  10284. // symbol in both header-only and split builds.
  10285. namespace httplib {
  10286. namespace detail {
  10287. ssize_t write_request_line(Stream &strm, const std::string &method,
  10288. const std::string &path);
  10289. } // namespace detail
  10290. } // namespace httplib
  10291. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10292. // A well-formed target is written verbatim.
  10293. {
  10294. detail::BufferStream strm;
  10295. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10296. EXPECT_GT(n, 0);
  10297. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10298. }
  10299. // A target carrying CR/LF, SP or other control octets must be rejected
  10300. // before anything reaches the wire, otherwise it splits the request line and
  10301. // injects a header or a whole request.
  10302. const std::string evil_targets[] = {
  10303. "/a\r\nInjected: pwned",
  10304. "/a\rInjected",
  10305. "/a\nInjected",
  10306. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10307. "/a b",
  10308. "/a\tb",
  10309. "/a\x7f",
  10310. };
  10311. for (const auto &evil : evil_targets) {
  10312. detail::BufferStream strm;
  10313. auto n = detail::write_request_line(strm, "GET", evil);
  10314. EXPECT_LT(n, 0);
  10315. EXPECT_TRUE(strm.get_buffer().empty());
  10316. }
  10317. }
  10318. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10319. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10320. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10321. // target reaches write_request. The client must fail cleanly with
  10322. // Error::Write instead of putting a request-line-less, header-injecting
  10323. // request on the wire.
  10324. Server svr;
  10325. svr.Get("/a", [](const Request &, Response &res) {
  10326. res.set_content("ok", "text/plain");
  10327. });
  10328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10329. auto se = detail::scope_exit([&] {
  10330. svr.stop();
  10331. thread.join();
  10332. ASSERT_FALSE(svr.is_running());
  10333. });
  10334. svr.wait_until_ready();
  10335. {
  10336. Client cli(HOST, PORT);
  10337. cli.set_path_encode(false);
  10338. // The request is rejected before anything is written, so the connection
  10339. // stays silent and the subsequent response read would otherwise block for
  10340. // the full default read timeout. Shorten it -- the assertion is on the
  10341. // error, not the timeout.
  10342. cli.set_read_timeout(1, 0);
  10343. auto res = cli.Get("/a\r\nInjected: pwned");
  10344. EXPECT_FALSE(res);
  10345. EXPECT_EQ(Error::Write, res.error());
  10346. }
  10347. }
  10348. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10349. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10350. // including extension methods.
  10351. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10352. for (const auto &method : good_methods) {
  10353. detail::BufferStream strm;
  10354. auto n = detail::write_request_line(strm, method, "/");
  10355. EXPECT_GT(n, 0);
  10356. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10357. }
  10358. // A method carrying CR/LF would split the request line and smuggle a whole
  10359. // request ahead of the real one. A space or an empty method corrupts the
  10360. // request line. All must be rejected before anything reaches the wire.
  10361. const std::string evil_methods[] = {
  10362. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10363. "GET\r\nInjected: pwned",
  10364. "GET\r",
  10365. "GET\n",
  10366. "GE T",
  10367. "",
  10368. };
  10369. for (const auto &evil : evil_methods) {
  10370. detail::BufferStream strm;
  10371. auto n = detail::write_request_line(strm, evil, "/");
  10372. EXPECT_LT(n, 0);
  10373. EXPECT_TRUE(strm.get_buffer().empty());
  10374. }
  10375. }
  10376. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10377. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10378. // through Client::send must fail with Error::Write and no request, neither
  10379. // the smuggled one nor the real one, may reach the server.
  10380. Server svr;
  10381. std::atomic<int> request_count(0);
  10382. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10383. request_count++;
  10384. res.status = StatusCode::OK_200;
  10385. return Server::HandlerResponse::Handled;
  10386. });
  10387. auto port = svr.bind_to_any_port(HOST);
  10388. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10389. auto se = detail::scope_exit([&] {
  10390. svr.stop();
  10391. thread.join();
  10392. ASSERT_FALSE(svr.is_running());
  10393. });
  10394. svr.wait_until_ready();
  10395. {
  10396. Client cli(HOST, port);
  10397. const std::string evil_methods[] = {
  10398. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10399. "GE T",
  10400. "",
  10401. };
  10402. for (const auto &evil : evil_methods) {
  10403. Request req;
  10404. req.method = evil;
  10405. req.path = "/";
  10406. auto res = cli.send(req);
  10407. EXPECT_FALSE(res);
  10408. EXPECT_EQ(Error::Write, res.error());
  10409. }
  10410. auto handle =
  10411. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10412. EXPECT_FALSE(handle.is_valid());
  10413. EXPECT_EQ(Error::Write, handle.error);
  10414. // A valid request on the same client still goes through.
  10415. auto res = cli.Get("/");
  10416. ASSERT_TRUE(res);
  10417. EXPECT_EQ(StatusCode::OK_200, res->status);
  10418. }
  10419. EXPECT_EQ(1, request_count.load());
  10420. }
  10421. // Sends a raw request and verifies that there isn't a crash or exception.
  10422. static void test_raw_request(const std::string &req,
  10423. std::string *out = nullptr) {
  10424. Server svr;
  10425. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10426. res.set_content("ok", "text/plain");
  10427. });
  10428. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10429. res.set_content("ok", "text/plain");
  10430. });
  10431. svr.Get("/header_field_value_check",
  10432. [&](const Request & /*req*/, Response &res) {
  10433. res.set_content("ok", "text/plain");
  10434. });
  10435. svr.CustomRoute("PROPFIND", "/dav",
  10436. [&](const Request & /*req*/, Response &res) {
  10437. res.status = StatusCode::MultiStatus_207;
  10438. });
  10439. // Server read timeout must be longer than the client read timeout for the
  10440. // bug to reproduce, probably to force the server to process a request
  10441. // without a trailing blank line.
  10442. const time_t client_read_timeout_sec = 1;
  10443. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10444. bool listen_thread_ok = false;
  10445. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10446. auto se = detail::scope_exit([&] {
  10447. svr.stop();
  10448. t.join();
  10449. ASSERT_FALSE(svr.is_running());
  10450. EXPECT_TRUE(listen_thread_ok);
  10451. });
  10452. svr.wait_until_ready();
  10453. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10454. }
  10455. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10456. // A certain header line causes an exception if the header property is parsed
  10457. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10458. test_raw_request(
  10459. "GET /hi HTTP/1.1\r\n"
  10460. " : "
  10461. " "
  10462. " ");
  10463. }
  10464. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10465. // A certain header line causes an exception if the header property *name* is
  10466. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10467. // greedy matcher and requires backtracking when there are a lot of ":"
  10468. // characters.
  10469. // This occurs with libc++ but not libstdc++.
  10470. test_raw_request(
  10471. "GET /hi HTTP/1.1\r\n"
  10472. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10473. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10474. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10475. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10476. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10477. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10478. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10479. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10480. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10481. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10482. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10483. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10484. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10485. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10486. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10487. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10488. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10489. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10490. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10491. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10492. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10493. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10494. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10495. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10496. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10497. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10498. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10499. "&&&%%%");
  10500. }
  10501. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10502. // Make sure this doesn't crash the server.
  10503. // In a previous version of the header line regex, the "\r" rendered the line
  10504. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10505. // a new position where the leading white space ended and the field value
  10506. // began.
  10507. // The crash occurs with libc++ but not libstdc++.
  10508. test_raw_request("GET /hi HTTP/1.1\r\n"
  10509. "a:" +
  10510. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10511. "\r\n"
  10512. "\r\n");
  10513. }
  10514. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10515. const char *rejected[] = {
  10516. // RFC 9112 §3: one SP between the parts, and nothing else
  10517. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10518. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10519. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10520. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10521. // A request-target has no fragment
  10522. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10523. // An HTTP/1.1 request needs a Host
  10524. "GET /hi HTTP/1.1\r\n\r\n",
  10525. };
  10526. for (auto request : rejected) {
  10527. std::string out;
  10528. test_raw_request(request, &out);
  10529. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10530. }
  10531. std::string out;
  10532. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10533. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10534. }
  10535. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10536. // RFC 9112 §6.1
  10537. const char *requests[] = {
  10538. "PUT /put_hi HTTP/1.1\r\n"
  10539. "Host: localhost\r\n"
  10540. "Content-Length: 0\r\n"
  10541. "Transfer-Encoding: chunked\r\n"
  10542. "\r\n"
  10543. "0\r\n\r\n",
  10544. "PUT /put_hi HTTP/1.0\r\n"
  10545. "Connection: keep-alive\r\n"
  10546. "Transfer-Encoding: chunked\r\n"
  10547. "\r\n"
  10548. "0\r\n\r\n",
  10549. };
  10550. for (auto request : requests) {
  10551. std::string out;
  10552. test_raw_request(request, &out);
  10553. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10554. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10555. }
  10556. }
  10557. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10558. std::string out;
  10559. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10560. "Content-Type: text/plain\r\n"
  10561. "Transfer-Encoding: chunked\r\n"
  10562. "\r\n"
  10563. "nothex\r\n",
  10564. &out);
  10565. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10566. }
  10567. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10568. std::string out;
  10569. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10570. "Content-Type: text/plain\r\n"
  10571. "Transfer-Encoding: chunked\r\n"
  10572. "\r\n"
  10573. "3\r\n"
  10574. "xyz\r\n"
  10575. "NaN\r\n",
  10576. &out);
  10577. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10578. }
  10579. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10580. std::string out;
  10581. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10582. "Content-Type: text/plain\r\n"
  10583. "Transfer-Encoding: chunked\r\n"
  10584. "\r\n"
  10585. // Length is too large for 64 bits.
  10586. "1ffffffffffffffff\r\n"
  10587. "xyz\r\n",
  10588. &out);
  10589. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10590. }
  10591. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10592. test_raw_request("GET /hi HTTP/1.1\r\n"
  10593. "Content-Type: text/plain\r\n\r");
  10594. }
  10595. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10596. std::string out;
  10597. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10598. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10599. }
  10600. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10601. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10602. std::string out;
  10603. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10604. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10605. }
  10606. }
  10607. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10608. std::string out;
  10609. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10610. "Host: localhost\r\n"
  10611. "Connection: close\r\n\r\n",
  10612. &out);
  10613. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10614. }
  10615. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10616. Server svr;
  10617. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10618. EXPECT_TRUE(!req.remote_addr.empty());
  10619. });
  10620. thread t = thread([&] { svr.listen(HOST, PORT); });
  10621. auto se = detail::scope_exit([&] {
  10622. svr.stop();
  10623. t.join();
  10624. ASSERT_FALSE(svr.is_running());
  10625. });
  10626. svr.wait_until_ready();
  10627. // Send an invalid request line to trigger Bad Request
  10628. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10629. std::string out;
  10630. ASSERT_TRUE(send_request(5, bad_req, &out));
  10631. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10632. }
  10633. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10634. // answered right away rather than blocking on a read that waits for EOF.
  10635. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10636. std::string out;
  10637. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10638. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10639. }
  10640. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10641. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10642. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10643. for (const auto *method : methods) {
  10644. Server svr;
  10645. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10646. EXPECT_FALSE(svr.is_valid()) << method;
  10647. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10648. }
  10649. }
  10650. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10651. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10652. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10653. for (const auto *method : methods) {
  10654. Server svr;
  10655. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10656. EXPECT_FALSE(svr.is_valid()) << method;
  10657. }
  10658. }
  10659. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10660. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10661. "COPY", "MOVE", "LOCK",
  10662. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10663. Server svr;
  10664. for (const auto *method : methods) {
  10665. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10666. }
  10667. EXPECT_TRUE(svr.is_valid());
  10668. }
  10669. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10670. Server svr;
  10671. svr.CustomRoute("POST", "/x",
  10672. [](const Request &, Response &, const ContentReader &) {});
  10673. EXPECT_FALSE(svr.is_valid());
  10674. }
  10675. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10676. Server svr;
  10677. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10678. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10679. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10680. EXPECT_FALSE(svr.is_valid());
  10681. }
  10682. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10683. Server svr;
  10684. auto captured = Error::Success;
  10685. svr.set_error_logger(
  10686. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10687. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10688. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10689. }
  10690. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10691. std::string out;
  10692. std::string request(
  10693. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10694. test_raw_request(request, &out);
  10695. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10696. }
  10697. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10698. std::string out;
  10699. std::string request(
  10700. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10701. test_raw_request(request, &out);
  10702. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10703. }
  10704. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10705. std::string out;
  10706. std::string request(
  10707. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10708. test_raw_request(request, &out);
  10709. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10710. }
  10711. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10712. std::string out;
  10713. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10714. "Host: localhost\r\n"
  10715. "Test: \r\n\r\n",
  10716. &out);
  10717. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10718. }
  10719. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10720. Server svr;
  10721. std::string x_custom;
  10722. std::string cookie;
  10723. std::string xff;
  10724. std::string x_unicode;
  10725. std::string x_iis;
  10726. svr.Get("/check", [&](const Request &req, Response &res) {
  10727. x_custom = req.get_header_value("X-Custom");
  10728. cookie = req.get_header_value("Cookie");
  10729. xff = req.get_header_value("X-Forwarded-For");
  10730. x_unicode = req.get_header_value("X-Unicode");
  10731. x_iis = req.get_header_value("X-IIS");
  10732. res.set_content("ok", "text/plain");
  10733. });
  10734. thread t = thread([&] { svr.listen(HOST, PORT); });
  10735. auto se = detail::scope_exit([&] {
  10736. svr.stop();
  10737. t.join();
  10738. ASSERT_FALSE(svr.is_running());
  10739. });
  10740. svr.wait_until_ready();
  10741. const std::string req = "GET /check HTTP/1.1\r\n"
  10742. "Host: localhost\r\n"
  10743. "X-Custom: a%0D%0AInjected: b\r\n"
  10744. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10745. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10746. "X-Unicode: %E3%81%82\r\n"
  10747. "X-IIS: %u00E9\r\n"
  10748. "Connection: close\r\n"
  10749. "\r\n";
  10750. std::string res;
  10751. ASSERT_TRUE(send_request(5, req, &res));
  10752. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10753. // Every value must be returned verbatim (wire form), with no decoding.
  10754. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10755. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10756. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10757. EXPECT_EQ("%E3%81%82", x_unicode);
  10758. EXPECT_EQ("%u00E9", x_iis);
  10759. }
  10760. // Applications that previously relied on automatic percent-decoding can
  10761. // reproduce the old behavior by explicitly calling decode_path_component()
  10762. // or, for RFC 3986 conformance, decode_uri_component().
  10763. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10764. Server svr;
  10765. std::string decoded;
  10766. svr.Get("/check", [&](const Request &req, Response &res) {
  10767. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10768. res.set_content("ok", "text/plain");
  10769. });
  10770. thread t = thread([&] { svr.listen(HOST, PORT); });
  10771. auto se = detail::scope_exit([&] {
  10772. svr.stop();
  10773. t.join();
  10774. ASSERT_FALSE(svr.is_running());
  10775. });
  10776. svr.wait_until_ready();
  10777. const std::string req = "GET /check HTTP/1.1\r\n"
  10778. "Host: localhost\r\n"
  10779. "X-Custom: hello%20world\r\n"
  10780. "Connection: close\r\n"
  10781. "\r\n";
  10782. std::string res;
  10783. ASSERT_TRUE(send_request(5, req, &res));
  10784. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10785. EXPECT_EQ("hello world", decoded);
  10786. }
  10787. // Regression test for #2033. Browsers send Referer values that include
  10788. // percent-encoded characters such as %0A inside the URL. Decoding the
  10789. // header value would either trip the post-decode CR/LF/NUL guard (the
  10790. // original bug, returning 400) or, after that guard was relaxed, silently
  10791. // store a literal LF — both unacceptable. The wire form must round-trip.
  10792. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10793. Server svr;
  10794. std::string referer;
  10795. svr.Get("/check", [&](const Request &req, Response &res) {
  10796. referer = req.get_header_value("Referer");
  10797. res.set_content("ok", "text/plain");
  10798. });
  10799. thread t = thread([&] { svr.listen(HOST, PORT); });
  10800. auto se = detail::scope_exit([&] {
  10801. svr.stop();
  10802. t.join();
  10803. ASSERT_FALSE(svr.is_running());
  10804. });
  10805. svr.wait_until_ready();
  10806. const std::string req = "GET /check HTTP/1.1\r\n"
  10807. "Host: localhost\r\n"
  10808. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10809. "Connection: close\r\n"
  10810. "\r\n";
  10811. std::string res;
  10812. ASSERT_TRUE(send_request(5, req, &res));
  10813. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10814. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10815. }
  10816. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10817. Server svr;
  10818. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10819. res.set_header("Cache-Control", "no-cache");
  10820. res.set_chunked_content_provider(
  10821. "text/event-stream", [](size_t offset, DataSink &sink) {
  10822. std::string s = "data:";
  10823. s += std::to_string(offset);
  10824. s += "\n\n";
  10825. auto ret = sink.write(s.data(), s.size());
  10826. EXPECT_TRUE(ret);
  10827. std::this_thread::sleep_for(std::chrono::seconds(1));
  10828. return true;
  10829. });
  10830. });
  10831. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10832. svr.wait_until_ready();
  10833. Client client(HOST, PORT);
  10834. const Headers headers = {{"Accept", "text/event-stream"}};
  10835. auto get_thread = std::thread([&client, &headers]() {
  10836. auto res = client.Get(
  10837. "/events", headers,
  10838. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10839. });
  10840. auto se = detail::scope_exit([&] {
  10841. svr.stop();
  10842. get_thread.join();
  10843. listen_thread.join();
  10844. ASSERT_FALSE(svr.is_running());
  10845. });
  10846. // Give GET time to get a few messages.
  10847. std::this_thread::sleep_for(std::chrono::seconds(2));
  10848. }
  10849. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10850. httplib::Server svr;
  10851. svr.Post("/hi",
  10852. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10853. res.status = StatusCode::OK_200;
  10854. });
  10855. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10856. svr.wait_until_ready();
  10857. Client cli(HOST, PORT);
  10858. auto res = cli.Post("/hi", "data", "text/plain");
  10859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10860. EXPECT_EQ(StatusCode::OK_200, res->status);
  10861. svr.stop();
  10862. thread.join();
  10863. ASSERT_FALSE(svr.is_running());
  10864. res = cli.Post("/hi", "data", "text/plain");
  10865. ASSERT_FALSE(res);
  10866. }
  10867. TEST(ServerStopTest, ListenFailure) {
  10868. Server svr;
  10869. auto t = thread([&]() {
  10870. auto ret = svr.listen("????", PORT);
  10871. EXPECT_FALSE(ret);
  10872. });
  10873. svr.wait_until_ready();
  10874. svr.stop();
  10875. t.join();
  10876. }
  10877. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10878. TEST(ServerStopTest, Decommision) {
  10879. Server svr;
  10880. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10881. for (int i = 0; i < 4; i++) {
  10882. auto is_even = !(i % 2);
  10883. std::thread t{[&] {
  10884. try {
  10885. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10886. if (is_even) {
  10887. throw std::runtime_error("Some thing that happens to go wrong.");
  10888. }
  10889. svr.listen(HOST, PORT);
  10890. } catch (...) { svr.decommission(); }
  10891. }};
  10892. svr.wait_until_ready();
  10893. // Server is up
  10894. {
  10895. Client cli(HOST, PORT);
  10896. auto res = cli.Get("/hi");
  10897. if (is_even) {
  10898. EXPECT_FALSE(res);
  10899. } else {
  10900. EXPECT_TRUE(res);
  10901. EXPECT_EQ("hi...", res->body);
  10902. }
  10903. }
  10904. svr.stop();
  10905. t.join();
  10906. // Server is down...
  10907. {
  10908. Client cli(HOST, PORT);
  10909. auto res = cli.Get("/hi");
  10910. EXPECT_FALSE(res);
  10911. }
  10912. }
  10913. }
  10914. #endif
  10915. // Helper function for string body upload progress tests
  10916. template <typename SetupHandler, typename ClientCall>
  10917. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10918. ClientCall &&client_call,
  10919. const string &body) {
  10920. Server svr;
  10921. setup_handler(svr);
  10922. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10923. auto se = detail::scope_exit([&] {
  10924. svr.stop();
  10925. t.join();
  10926. });
  10927. svr.wait_until_ready();
  10928. Client cli(HOST, PORT);
  10929. vector<uint64_t> progress_values;
  10930. bool progress_called = false;
  10931. auto res =
  10932. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10933. progress_values.push_back(current);
  10934. progress_called = true;
  10935. return true;
  10936. });
  10937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10938. EXPECT_EQ(200, res->status);
  10939. EXPECT_TRUE(progress_called);
  10940. }
  10941. TEST(UploadProgressTest, PostStringBodyBasic) {
  10942. TestStringBodyUploadProgress(
  10943. [](Server &svr) {
  10944. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10945. res.set_content("received", "text/plain");
  10946. });
  10947. },
  10948. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10949. return cli.Post("/test", body, "text/plain", progress_callback);
  10950. },
  10951. "test data for upload progress");
  10952. }
  10953. TEST(UploadProgressTest, PutStringBodyBasic) {
  10954. TestStringBodyUploadProgress(
  10955. [](Server &svr) {
  10956. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10957. res.set_content("put received", "text/plain");
  10958. });
  10959. },
  10960. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10961. return cli.Put("/test", body, "text/plain", progress_callback);
  10962. },
  10963. "put test data for upload progress");
  10964. }
  10965. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10966. TestStringBodyUploadProgress(
  10967. [](Server &svr) {
  10968. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10969. res.set_content("patch received", "text/plain");
  10970. });
  10971. },
  10972. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10973. return cli.Patch("/test", body, "text/plain", progress_callback);
  10974. },
  10975. "patch test data for upload progress");
  10976. }
  10977. // Helper function for content provider upload progress tests
  10978. template <typename SetupHandler, typename ClientCall>
  10979. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10980. ClientCall &&client_call) {
  10981. Server svr;
  10982. setup_handler(svr);
  10983. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10984. auto se = detail::scope_exit([&] {
  10985. svr.stop();
  10986. t.join();
  10987. });
  10988. svr.wait_until_ready();
  10989. Client cli(HOST, PORT);
  10990. vector<uint64_t> progress_values;
  10991. auto res =
  10992. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10993. progress_values.push_back(current);
  10994. return true;
  10995. });
  10996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10997. EXPECT_EQ(200, res->status);
  10998. EXPECT_FALSE(progress_values.empty());
  10999. }
  11000. TEST(UploadProgressTest, PostContentProviderProgress) {
  11001. TestContentProviderUploadProgress(
  11002. [](Server &svr) {
  11003. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11004. res.set_content("provider received", "text/plain");
  11005. });
  11006. },
  11007. [](Client &cli, UploadProgress progress_callback) {
  11008. return cli.Post(
  11009. "/test", 9,
  11010. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11011. sink.os << "test data";
  11012. return true;
  11013. },
  11014. "text/plain", progress_callback);
  11015. });
  11016. }
  11017. // Helper function for multipart upload progress tests
  11018. template <typename SetupHandler, typename ClientCall>
  11019. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11020. ClientCall &&client_call,
  11021. const string &endpoint) {
  11022. Server svr;
  11023. setup_handler(svr);
  11024. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11025. auto se = detail::scope_exit([&] {
  11026. svr.stop();
  11027. t.join();
  11028. });
  11029. svr.wait_until_ready();
  11030. Client cli(HOST, PORT);
  11031. vector<uint64_t> progress_values;
  11032. UploadFormDataItems items = {
  11033. {"field1", "value1", "", ""},
  11034. {"field2", "longer value for progress tracking test", "", ""},
  11035. {"file1", "file content data for upload progress", "test.txt",
  11036. "text/plain"}};
  11037. auto res = client_call(cli, endpoint, items,
  11038. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11039. progress_values.push_back(current);
  11040. return true;
  11041. });
  11042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11043. EXPECT_EQ(200, res->status);
  11044. EXPECT_FALSE(progress_values.empty());
  11045. }
  11046. TEST(UploadProgressTest, PostMultipartProgress) {
  11047. TestMultipartUploadProgress(
  11048. [](Server &svr) {
  11049. svr.Post("/multipart", [](const Request &req, Response &res) {
  11050. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11051. res.set_content("multipart received", "text/plain");
  11052. });
  11053. },
  11054. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11055. UploadProgress progress_callback) {
  11056. return cli.Post(endpoint, items, progress_callback);
  11057. },
  11058. "/multipart");
  11059. }
  11060. // Helper function for basic download progress tests
  11061. template <typename SetupHandler, typename ClientCall>
  11062. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11063. ClientCall &&client_call, const string &endpoint,
  11064. size_t expected_content_size) {
  11065. Server svr;
  11066. setup_handler(svr);
  11067. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11068. auto se = detail::scope_exit([&] {
  11069. svr.stop();
  11070. t.join();
  11071. });
  11072. svr.wait_until_ready();
  11073. Client cli(HOST, PORT);
  11074. vector<uint64_t> progress_values;
  11075. auto res = client_call(cli, endpoint,
  11076. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11077. progress_values.push_back(current);
  11078. return true;
  11079. });
  11080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11081. EXPECT_EQ(200, res->status);
  11082. EXPECT_FALSE(progress_values.empty());
  11083. EXPECT_EQ(expected_content_size, res->body.size());
  11084. }
  11085. TEST(DownloadProgressTest, GetBasic) {
  11086. TestBasicDownloadProgress(
  11087. [](Server &svr) {
  11088. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11089. string content(1000, 'D');
  11090. res.set_content(content, "text/plain");
  11091. });
  11092. },
  11093. [](Client &cli, const string &endpoint,
  11094. DownloadProgress progress_callback) {
  11095. return cli.Get(endpoint, progress_callback);
  11096. },
  11097. "/download", 1000u);
  11098. }
  11099. // Helper function for content receiver download progress tests
  11100. template <typename SetupHandler, typename ClientCall>
  11101. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11102. ClientCall &&client_call,
  11103. 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. string received_body;
  11116. auto res = client_call(
  11117. cli, endpoint,
  11118. [&](const char *data, size_t data_length) -> bool {
  11119. received_body.append(data, data_length);
  11120. return true;
  11121. },
  11122. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11123. progress_values.push_back(current);
  11124. return true;
  11125. });
  11126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11127. EXPECT_EQ(200, res->status);
  11128. EXPECT_FALSE(progress_values.empty());
  11129. EXPECT_EQ(expected_content_size, received_body.size());
  11130. EXPECT_TRUE(res->body.empty());
  11131. }
  11132. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11133. TestContentReceiverDownloadProgress(
  11134. [](Server &svr) {
  11135. svr.Get("/download-receiver",
  11136. [](const Request & /*req*/, Response &res) {
  11137. string content(2000, 'R');
  11138. res.set_content(content, "text/plain");
  11139. });
  11140. },
  11141. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11142. DownloadProgress progress_callback) {
  11143. return cli.Get(endpoint, content_receiver, progress_callback);
  11144. },
  11145. "/download-receiver", 2000u);
  11146. }
  11147. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11148. // A provider reaching a pass with nothing to hand over - an empty buffer
  11149. // popped off a queue, say - must not be taken to mean the body is finished.
  11150. // It used to end the loop with the terminating chunk unwritten while the
  11151. // server still considered the response complete, so the peer waited for an
  11152. // end that never arrived.
  11153. Server svr;
  11154. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11155. auto step = std::make_shared<int>(0);
  11156. res.set_chunked_content_provider("text/plain",
  11157. [step](size_t /*offset*/, DataSink &sink) {
  11158. switch ((*step)++) {
  11159. case 0: sink.write("", 0); break;
  11160. case 1: sink.write("hello", 5); break;
  11161. default: sink.done(); break;
  11162. }
  11163. return true;
  11164. });
  11165. });
  11166. auto port = svr.bind_to_any_port(HOST);
  11167. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11168. auto listen_se = detail::scope_exit([&] {
  11169. svr.stop();
  11170. listen_thread.join();
  11171. ASSERT_FALSE(svr.is_running());
  11172. });
  11173. svr.wait_until_ready();
  11174. Client cli(HOST, port);
  11175. // Without the fix the body is never terminated, so bound the wait rather
  11176. // than letting the test hang on the default read timeout.
  11177. cli.set_read_timeout(5, 0);
  11178. auto res = cli.Get("/stream");
  11179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11180. EXPECT_EQ(StatusCode::OK_200, res->status);
  11181. EXPECT_EQ("hello", res->body);
  11182. }
  11183. TEST(StreamingTest, NoContentLengthStreaming) {
  11184. Server svr;
  11185. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11186. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11187. if (offset < 6) {
  11188. sink.os << (offset < 3 ? "a" : "b");
  11189. } else {
  11190. sink.done();
  11191. }
  11192. return true;
  11193. });
  11194. });
  11195. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11196. auto listen_se = detail::scope_exit([&] {
  11197. svr.stop();
  11198. listen_thread.join();
  11199. ASSERT_FALSE(svr.is_running());
  11200. });
  11201. svr.wait_until_ready();
  11202. Client client(HOST, PORT);
  11203. auto get_thread = std::thread([&client]() {
  11204. std::string s;
  11205. auto res =
  11206. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11207. s += std::string(data, len);
  11208. return true;
  11209. });
  11210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11211. EXPECT_EQ(StatusCode::OK_200, res->status);
  11212. EXPECT_EQ("aaabbb", s);
  11213. });
  11214. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11215. // Give GET time to get a few messages.
  11216. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11217. }
  11218. TEST(MountTest, Unmount) {
  11219. Server svr;
  11220. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11221. auto se = detail::scope_exit([&] {
  11222. svr.stop();
  11223. listen_thread.join();
  11224. ASSERT_FALSE(svr.is_running());
  11225. });
  11226. svr.wait_until_ready();
  11227. Client cli("localhost", PORT);
  11228. svr.set_mount_point("/mount2", "./www2");
  11229. auto res = cli.Get("/");
  11230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11231. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11232. res = cli.Get("/mount2/dir/test.html");
  11233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11234. EXPECT_EQ(StatusCode::OK_200, res->status);
  11235. svr.set_mount_point("/", "./www");
  11236. res = cli.Get("/dir/");
  11237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11238. EXPECT_EQ(StatusCode::OK_200, res->status);
  11239. svr.remove_mount_point("/");
  11240. res = cli.Get("/dir/");
  11241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11242. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11243. svr.remove_mount_point("/mount2");
  11244. res = cli.Get("/mount2/dir/test.html");
  11245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11247. }
  11248. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11249. Server svr;
  11250. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11251. svr.Get("/api/hello", [](const Request &, Response &res) {
  11252. res.set_content("api", "text/plain");
  11253. });
  11254. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11255. auto se = detail::scope_exit([&] {
  11256. svr.stop();
  11257. listen_thread.join();
  11258. ASSERT_FALSE(svr.is_running());
  11259. });
  11260. svr.wait_until_ready();
  11261. Client cli(HOST, PORT);
  11262. auto res = cli.Get("/dir/test.html");
  11263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11264. EXPECT_EQ(StatusCode::OK_200, res->status);
  11265. res = cli.Get("/api/hello");
  11266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11267. EXPECT_EQ(StatusCode::OK_200, res->status);
  11268. EXPECT_EQ("api", res->body);
  11269. }
  11270. TEST(MountTest, PathSegmentBoundary) {
  11271. Server svr;
  11272. svr.set_mount_point("/mount2", "./www2");
  11273. svr.set_mount_point("/", "./www");
  11274. auto port = svr.bind_to_any_port(HOST);
  11275. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11276. auto se = detail::scope_exit([&] {
  11277. svr.stop();
  11278. listen_thread.join();
  11279. ASSERT_FALSE(svr.is_running());
  11280. });
  11281. svr.wait_until_ready();
  11282. Client cli(HOST, port);
  11283. auto res = cli.Get("/mount2/dir/test.html");
  11284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11285. EXPECT_EQ(StatusCode::OK_200, res->status);
  11286. // "/mount2" must not match part-way through a path segment.
  11287. res = cli.Get("/mount2dir/test.html");
  11288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11289. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11290. // A mount point ending in '/' keeps matching every path below it.
  11291. res = cli.Get("/dir/test.html");
  11292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11293. EXPECT_EQ(StatusCode::OK_200, res->status);
  11294. }
  11295. TEST(MountTest, Redicect) {
  11296. Server svr;
  11297. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. listen_thread.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.set_mount_point("/", "./www");
  11304. svr.wait_until_ready();
  11305. Client cli("localhost", PORT);
  11306. auto res = cli.Get("/dir/");
  11307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11308. EXPECT_EQ(StatusCode::OK_200, res->status);
  11309. res = cli.Get("/dir");
  11310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11311. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11312. res = cli.Get("/file");
  11313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11314. EXPECT_EQ(StatusCode::OK_200, res->status);
  11315. res = cli.Get("/file/");
  11316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11317. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11318. cli.set_follow_location(true);
  11319. res = cli.Get("/dir");
  11320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11321. EXPECT_EQ(StatusCode::OK_200, res->status);
  11322. }
  11323. TEST(MountTest, MultibytesPathName) {
  11324. Server svr;
  11325. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11326. auto se = detail::scope_exit([&] {
  11327. svr.stop();
  11328. listen_thread.join();
  11329. ASSERT_FALSE(svr.is_running());
  11330. });
  11331. svr.set_mount_point("/", "./www");
  11332. svr.wait_until_ready();
  11333. Client cli("localhost", PORT);
  11334. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11336. EXPECT_EQ(StatusCode::OK_200, res->status);
  11337. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11338. }
  11339. // A mount point serves no path with an empty segment or one ending in '.' or
  11340. // a space, so a guard in the pre-routing handler sees the path of every file
  11341. // that is served
  11342. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11343. Server svr;
  11344. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11345. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11346. if (req.path == "/dir/test.html") {
  11347. res.status = StatusCode::Unauthorized_401;
  11348. return Server::HandlerResponse::Handled;
  11349. }
  11350. return Server::HandlerResponse::Unhandled;
  11351. });
  11352. auto port = svr.bind_to_any_port(HOST);
  11353. ASSERT_LT(0, port);
  11354. thread t = thread([&] { svr.listen_after_bind(); });
  11355. auto se = detail::scope_exit([&] {
  11356. svr.stop();
  11357. t.join();
  11358. ASSERT_FALSE(svr.is_running());
  11359. });
  11360. svr.wait_until_ready();
  11361. Client cli(HOST, port);
  11362. for (auto path :
  11363. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11364. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11365. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11366. "/dir/test.html%3A%3A$DATA"}) {
  11367. SCOPED_TRACE(path);
  11368. auto res = cli.Get(path);
  11369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11371. }
  11372. }
  11373. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11374. Server svr;
  11375. svr.set_mount_point("/", "./www");
  11376. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11377. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11378. auto port = svr.bind_to_any_port(HOST);
  11379. ASSERT_GT(port, 0);
  11380. thread t = thread([&] { svr.listen_after_bind(); });
  11381. auto se = detail::scope_exit([&] {
  11382. svr.stop();
  11383. t.join();
  11384. ASSERT_FALSE(svr.is_running());
  11385. });
  11386. svr.wait_until_ready();
  11387. Client cli(HOST, port);
  11388. auto res = cli.Get("/dir/test.abcde");
  11389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11390. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11391. res = cli.Get("/dir/test.html");
  11392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11393. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11394. }
  11395. #ifdef _WIN32
  11396. // Issue #2435: mmap::open() must succeed even when another handle holds
  11397. // the file open for writing (e.g. an active log file).
  11398. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11399. const char *path = "mmap_concurrent_writer_test.txt";
  11400. const char *content = "hello";
  11401. {
  11402. std::ofstream f(path, std::ios::binary);
  11403. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11404. }
  11405. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11406. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11407. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11408. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11409. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11410. detail::mmap m(path);
  11411. ASSERT_TRUE(m.is_open());
  11412. EXPECT_EQ(strlen(content), m.size());
  11413. char buf[8];
  11414. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11415. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11416. }
  11417. #endif
  11418. #ifndef _WIN32
  11419. // A directory or a device has no size to serve.
  11420. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11421. const char *path = "./mmap_not_regular_test_dir";
  11422. ASSERT_EQ(0, ::mkdir(path, 0755));
  11423. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11424. for (auto p : {path, "/dev/null"}) {
  11425. detail::mmap m(p);
  11426. EXPECT_FALSE(m.is_open()) << p;
  11427. EXPECT_EQ(0U, m.size()) << p;
  11428. }
  11429. Server svr;
  11430. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11431. res.set_file_content("/dev/null");
  11432. });
  11433. auto port = svr.bind_to_any_port(HOST);
  11434. thread t = thread([&] { svr.listen_after_bind(); });
  11435. auto se = detail::scope_exit([&] {
  11436. svr.stop();
  11437. t.join();
  11438. });
  11439. svr.wait_until_ready();
  11440. auto res = Client(HOST, port).Get("/null");
  11441. ASSERT_TRUE(res);
  11442. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11443. }
  11444. #endif
  11445. #ifdef __linux__
  11446. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11447. TEST(MmapTest, FileIsNotMapped) {
  11448. const char *path = "mmap_not_mapped_test.txt";
  11449. {
  11450. std::ofstream f(path, std::ios::binary);
  11451. f << "hello";
  11452. }
  11453. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11454. detail::mmap m(path);
  11455. ASSERT_TRUE(m.is_open());
  11456. std::ifstream maps("/proc/self/maps");
  11457. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11458. std::istreambuf_iterator<char>());
  11459. EXPECT_EQ(std::string::npos, mappings.find(path));
  11460. }
  11461. #endif
  11462. TEST(KeepAliveTest, ReadTimeout) {
  11463. Server svr;
  11464. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11465. std::this_thread::sleep_for(std::chrono::seconds(2));
  11466. res.set_content("a", "text/plain");
  11467. });
  11468. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11469. res.set_content("b", "text/plain");
  11470. });
  11471. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11472. auto se = detail::scope_exit([&] {
  11473. svr.stop();
  11474. listen_thread.join();
  11475. ASSERT_FALSE(svr.is_running());
  11476. });
  11477. svr.wait_until_ready();
  11478. Client cli("localhost", PORT);
  11479. cli.set_keep_alive(true);
  11480. cli.set_read_timeout(std::chrono::seconds(1));
  11481. auto resa = cli.Get("/a");
  11482. ASSERT_FALSE(resa);
  11483. EXPECT_EQ(Error::Read, resa.error());
  11484. auto resb = cli.Get("/b");
  11485. ASSERT_TRUE(resb);
  11486. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11487. EXPECT_EQ("b", resb->body);
  11488. }
  11489. TEST(KeepAliveTest, MaxCount) {
  11490. size_t keep_alive_max_count = 3;
  11491. Server svr;
  11492. svr.set_keep_alive_max_count(keep_alive_max_count);
  11493. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11494. res.set_content("Hello World!", "text/plain");
  11495. });
  11496. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11497. auto se = detail::scope_exit([&] {
  11498. svr.stop();
  11499. listen_thread.join();
  11500. ASSERT_FALSE(svr.is_running());
  11501. });
  11502. svr.wait_until_ready();
  11503. Client cli(HOST, PORT);
  11504. cli.set_keep_alive(true);
  11505. for (size_t i = 0; i < 5; i++) {
  11506. auto result = cli.Get("/hi");
  11507. ASSERT_TRUE(result);
  11508. EXPECT_EQ(StatusCode::OK_200, result->status);
  11509. if (i == keep_alive_max_count - 1) {
  11510. EXPECT_EQ("close", result->get_header_value("Connection"));
  11511. } else {
  11512. EXPECT_FALSE(result->has_header("Connection"));
  11513. }
  11514. }
  11515. }
  11516. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11517. // can pull the next one into the server's buffer. The server must serve it
  11518. // without waiting for the socket to become readable again. The keep-alive
  11519. // timeout outlasts the client's read timeout, so a request left waiting for it
  11520. // shows up as a missing response.
  11521. static void serve_pipelining_routes(Server &svr,
  11522. const std::function<void(int)> &client) {
  11523. svr.set_keep_alive_timeout(5);
  11524. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11525. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11526. });
  11527. svr.Post("/echo", [](const Request &req, Response &res) {
  11528. res.set_content("echo " + req.body, "text/plain");
  11529. });
  11530. auto port = svr.bind_to_any_port(HOST);
  11531. thread t = thread([&] { svr.listen_after_bind(); });
  11532. auto se = detail::scope_exit([&] {
  11533. svr.stop();
  11534. t.join();
  11535. });
  11536. svr.wait_until_ready();
  11537. client(port);
  11538. }
  11539. static std::string
  11540. send_pipelined_requests(const std::vector<std::string> &parts) {
  11541. Server svr;
  11542. std::string res;
  11543. serve_pipelining_routes(svr, [&](int port) {
  11544. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11545. });
  11546. return res;
  11547. }
  11548. static void expect_in_order(const std::string &res,
  11549. const std::vector<std::string> &bodies) {
  11550. size_t pos = 0;
  11551. for (const auto &body : bodies) {
  11552. pos = res.find(body, pos);
  11553. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11554. pos += body.size();
  11555. }
  11556. }
  11557. TEST(KeepAliveTest, PipelinedRequests) {
  11558. auto res = send_pipelined_requests(
  11559. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11560. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11561. "Content-Length: 4\r\n\r\nbody"
  11562. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11563. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11564. }
  11565. // The second request starts in the server's buffer and ends on the socket.
  11566. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11567. auto res =
  11568. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11569. "GET /hi/2 HTTP/1.1\r\nHo",
  11570. "st: localhost\r\nConnection: close\r\n\r\n"});
  11571. expect_in_order(res, {"hi 1", "hi 2"});
  11572. }
  11573. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11574. // CRLF after a body does not turn into a 400 for the next request.
  11575. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11576. auto res = send_pipelined_requests(
  11577. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11578. "Content-Length: 4\r\n\r\nbody\r\n"
  11579. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11580. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11581. expect_in_order(res, {"echo body", "hi 2"});
  11582. }
  11583. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11584. // must not be served as the next request.
  11585. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11586. auto res = send_pipelined_requests(
  11587. {"INVALID REQUEST LINE\r\n\r\n"
  11588. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11589. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11590. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11591. }
  11592. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11593. // Over TLS, the next request is held by the TLS library as already decrypted
  11594. // data rather than on the socket.
  11595. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11597. std::string res;
  11598. serve_pipelining_routes(svr, [&](int port) {
  11599. // One part, so all three requests arrive in one TLS record
  11600. EXPECT_TRUE(send_ssl_request_in_parts(
  11601. 2,
  11602. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11603. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11604. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11605. &res, port));
  11606. });
  11607. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11608. }
  11609. #endif
  11610. TEST(KeepAliveTest, Issue1041) {
  11611. Server svr;
  11612. svr.set_keep_alive_timeout(3);
  11613. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11614. res.set_content("Hello World!", "text/plain");
  11615. });
  11616. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11617. auto se = detail::scope_exit([&] {
  11618. svr.stop();
  11619. listen_thread.join();
  11620. ASSERT_FALSE(svr.is_running());
  11621. });
  11622. svr.wait_until_ready();
  11623. Client cli(HOST, PORT);
  11624. cli.set_keep_alive(true);
  11625. auto result = cli.Get("/hi");
  11626. ASSERT_TRUE(result);
  11627. EXPECT_EQ(StatusCode::OK_200, result->status);
  11628. std::this_thread::sleep_for(std::chrono::seconds(5));
  11629. result = cli.Get("/hi");
  11630. ASSERT_TRUE(result);
  11631. EXPECT_EQ(StatusCode::OK_200, result->status);
  11632. }
  11633. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11634. Server svr;
  11635. svr.set_keep_alive_max_count(0);
  11636. std::set<int> remote_ports;
  11637. svr.Get("/hi", [&](const Request &req, Response &res) {
  11638. remote_ports.insert(req.remote_port);
  11639. res.set_content("hi", "text/plain");
  11640. });
  11641. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11642. auto se = detail::scope_exit([&] {
  11643. svr.stop();
  11644. listen_thread.join();
  11645. ASSERT_FALSE(svr.is_running());
  11646. });
  11647. svr.wait_until_ready();
  11648. Client cli(HOST, PORT);
  11649. cli.set_keep_alive(true);
  11650. for (int i = 0; i < 3; i++) {
  11651. auto res = cli.Get("/hi");
  11652. ASSERT_TRUE(res);
  11653. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11654. }
  11655. // All three over one connection
  11656. EXPECT_EQ(1u, remote_ports.size());
  11657. }
  11658. // Forward declaration (see the base64_encode note).
  11659. namespace httplib {
  11660. namespace detail {
  11661. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11662. } // namespace detail
  11663. } // namespace httplib
  11664. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11665. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11666. #ifndef _WIN32
  11667. signal(SIGPIPE, SIG_IGN);
  11668. #endif
  11669. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11670. ASSERT_NE(INVALID_SOCKET, srv);
  11671. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11672. default_socket_options(srv);
  11673. sockaddr_in addr{};
  11674. addr.sin_family = AF_INET;
  11675. addr.sin_port = 0;
  11676. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11677. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11678. ASSERT_EQ(0, ::listen(srv, 2));
  11679. socklen_t addr_len = sizeof(addr);
  11680. ASSERT_EQ(0,
  11681. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11682. auto port = ntohs(addr.sin_port);
  11683. struct Peer {
  11684. socket_t sock = INVALID_SOCKET;
  11685. #ifdef CPPHTTPLIB_SSL_ENABLED
  11686. tls::session_t session = nullptr;
  11687. #endif
  11688. };
  11689. #ifdef CPPHTTPLIB_SSL_ENABLED
  11690. tls::ctx_t ctx = nullptr;
  11691. if (use_tls) {
  11692. ctx = tls::create_server_context();
  11693. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11694. nullptr);
  11695. }
  11696. auto ctx_se = detail::scope_exit([&] {
  11697. if (ctx) { tls::free_context(ctx); }
  11698. });
  11699. #endif
  11700. auto close_peer = [](Peer &peer) {
  11701. #ifdef CPPHTTPLIB_SSL_ENABLED
  11702. if (peer.session) { tls::free_session(peer.session); }
  11703. #endif
  11704. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11705. };
  11706. auto accept_peer = [&]() {
  11707. Peer peer;
  11708. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11709. peer.sock = ::accept(srv, nullptr, nullptr);
  11710. if (peer.sock == INVALID_SOCKET) { return peer; }
  11711. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11712. #ifdef CPPHTTPLIB_SSL_ENABLED
  11713. if (use_tls) {
  11714. peer.session = tls::create_session(ctx, peer.sock);
  11715. tls::TlsError err;
  11716. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err)) {
  11717. close_peer(peer);
  11718. return Peer();
  11719. }
  11720. }
  11721. #endif
  11722. return peer;
  11723. };
  11724. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11725. #ifdef CPPHTTPLIB_SSL_ENABLED
  11726. tls::TlsError err;
  11727. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11728. #endif
  11729. return detail::read_socket(peer.sock, buf, len, 0);
  11730. };
  11731. auto read_head = [&](const Peer &peer) {
  11732. std::string head;
  11733. char buf[1024];
  11734. while (head.find("\r\n\r\n") == std::string::npos) {
  11735. auto n = read_some(peer, buf, sizeof(buf));
  11736. if (n <= 0) { break; }
  11737. head.append(buf, static_cast<size_t>(n));
  11738. }
  11739. };
  11740. auto send_text = [](const Peer &peer, const std::string &text) {
  11741. #ifdef CPPHTTPLIB_SSL_ENABLED
  11742. tls::TlsError err;
  11743. if (peer.session) {
  11744. tls::write(peer.session, text.data(), text.size(), err);
  11745. return;
  11746. }
  11747. #endif
  11748. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11749. };
  11750. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11751. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11752. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11753. // Sent once the first response is read, so that it lands on an idle socket
  11754. std::promise<void> first_response_read;
  11755. auto first_response_read_future = first_response_read.get_future();
  11756. auto server_thread = std::thread([&] {
  11757. auto peer1 = accept_peer();
  11758. if (peer1.sock == INVALID_SOCKET) { return; }
  11759. read_head(peer1);
  11760. if (same_write) {
  11761. send_text(peer1, first + stray);
  11762. } else {
  11763. send_text(peer1, first);
  11764. first_response_read_future.wait_for(std::chrono::seconds(5));
  11765. send_text(peer1, stray);
  11766. }
  11767. // peer1 stays open, so only the unread data can tell the client
  11768. auto peer2 = accept_peer();
  11769. if (peer2.sock != INVALID_SOCKET) {
  11770. read_head(peer2);
  11771. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11772. "Connection: close\r\n\r\nsecond");
  11773. close_peer(peer2);
  11774. }
  11775. close_peer(peer1);
  11776. });
  11777. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11778. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11779. std::to_string(port));
  11780. #ifdef CPPHTTPLIB_SSL_ENABLED
  11781. cli.enable_server_certificate_verification(false);
  11782. #endif
  11783. cli.set_keep_alive(true);
  11784. cli.set_read_timeout(5, 0);
  11785. auto res = cli.Get("/1");
  11786. first_response_read.set_value();
  11787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11788. EXPECT_EQ("first", res->body);
  11789. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11790. res = cli.Get("/2");
  11791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11792. EXPECT_EQ(StatusCode::OK_200, res->status);
  11793. EXPECT_EQ("second", res->body);
  11794. }
  11795. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11796. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11797. }
  11798. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11799. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11800. }
  11801. #ifdef CPPHTTPLIB_SSL_ENABLED
  11802. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11803. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11804. }
  11805. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11806. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11807. }
  11808. #endif
  11809. TEST(KeepAliveTest, Issue1959) {
  11810. Server svr;
  11811. svr.set_keep_alive_timeout(5);
  11812. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11813. res.set_content("a", "text/plain");
  11814. });
  11815. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11816. auto se = detail::scope_exit([&] {
  11817. if (!svr.is_running()) return;
  11818. svr.stop();
  11819. listen_thread.join();
  11820. ASSERT_FALSE(svr.is_running());
  11821. });
  11822. svr.wait_until_ready();
  11823. Client cli("localhost", PORT);
  11824. cli.set_keep_alive(true);
  11825. using namespace std::chrono;
  11826. auto start = steady_clock::now();
  11827. cli.Get("/a");
  11828. svr.stop();
  11829. listen_thread.join();
  11830. auto end = steady_clock::now();
  11831. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11832. EXPECT_LT(elapsed, 5000);
  11833. }
  11834. #ifdef CPPHTTPLIB_SSL_ENABLED
  11835. TEST(KeepAliveTest, SSLClientReconnection) {
  11836. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11837. ASSERT_TRUE(svr.is_valid());
  11838. svr.set_keep_alive_timeout(1);
  11839. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11840. res.set_content("Hello World!", "text/plain");
  11841. });
  11842. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11843. auto se = detail::scope_exit([&] {
  11844. svr.stop();
  11845. listen_thread.join();
  11846. ASSERT_FALSE(svr.is_running());
  11847. });
  11848. svr.wait_until_ready();
  11849. SSLClient cli(HOST, PORT);
  11850. cli.enable_server_certificate_verification(false);
  11851. cli.set_keep_alive(true);
  11852. auto result = cli.Get("/hi");
  11853. ASSERT_TRUE(result);
  11854. EXPECT_EQ(StatusCode::OK_200, result->status);
  11855. result = cli.Get("/hi");
  11856. ASSERT_TRUE(result);
  11857. EXPECT_EQ(StatusCode::OK_200, result->status);
  11858. std::this_thread::sleep_for(std::chrono::seconds(2));
  11859. // Recoonect
  11860. result = cli.Get("/hi");
  11861. ASSERT_TRUE(result);
  11862. EXPECT_EQ(StatusCode::OK_200, result->status);
  11863. result = cli.Get("/hi");
  11864. ASSERT_TRUE(result);
  11865. EXPECT_EQ(StatusCode::OK_200, result->status);
  11866. }
  11867. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11869. ASSERT_TRUE(svr.is_valid());
  11870. svr.set_keep_alive_timeout(1);
  11871. std::string content = "reconnect";
  11872. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11873. res.set_content("Hello World!", "text/plain");
  11874. });
  11875. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11876. auto se = detail::scope_exit([&] {
  11877. svr.stop();
  11878. listen_thread.join();
  11879. ASSERT_FALSE(svr.is_running());
  11880. });
  11881. svr.wait_until_ready();
  11882. SSLClient cli(HOST, PORT);
  11883. cli.enable_server_certificate_verification(false);
  11884. cli.set_keep_alive(true);
  11885. auto result = cli.Post(
  11886. "/hi", content.size(),
  11887. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11888. sink.write(content.c_str(), content.size());
  11889. return true;
  11890. },
  11891. "text/plain");
  11892. ASSERT_TRUE(result);
  11893. EXPECT_EQ(200, result->status);
  11894. std::this_thread::sleep_for(std::chrono::seconds(2));
  11895. // Recoonect
  11896. result = cli.Post(
  11897. "/hi", content.size(),
  11898. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11899. sink.write(content.c_str(), content.size());
  11900. return true;
  11901. },
  11902. "text/plain");
  11903. ASSERT_TRUE(result);
  11904. EXPECT_EQ(200, result->status);
  11905. result = cli.Post(
  11906. "/hi", content.size(),
  11907. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11908. sink.write(content.c_str(), content.size());
  11909. return true;
  11910. },
  11911. "text/plain");
  11912. ASSERT_TRUE(result);
  11913. EXPECT_EQ(200, result->status);
  11914. }
  11915. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11916. using namespace httplib::tls;
  11917. {
  11918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11919. ASSERT_TRUE(svr.is_valid());
  11920. svr.Get("/sni", [&](const Request &req, Response &res) {
  11921. std::string expected = req.sni();
  11922. EXPECT_EQ(expected, req.get_param_value("expected"));
  11923. res.set_content("ok", "text/plain");
  11924. });
  11925. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11926. auto se = detail::scope_exit([&] {
  11927. svr.stop();
  11928. listen_thread.join();
  11929. ASSERT_FALSE(svr.is_running());
  11930. });
  11931. svr.wait_until_ready();
  11932. {
  11933. SSLClient cli("localhost", PORT);
  11934. cli.enable_server_certificate_verification(false);
  11935. auto res = cli.Get("/sni?expected=localhost");
  11936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11937. }
  11938. {
  11939. SSLClient cli("::1", PORT);
  11940. cli.enable_server_certificate_verification(false);
  11941. auto res = cli.Get("/sni?expected=");
  11942. // NOTE: This may fail if the server is listening on IPv4 only
  11943. // (e.g., when localhost resolves to 127.0.0.1 only)
  11944. if (res) {
  11945. EXPECT_EQ(StatusCode::OK_200, res->status);
  11946. } else {
  11947. EXPECT_EQ(Error::Connection, res.error());
  11948. }
  11949. }
  11950. }
  11951. }
  11952. // The SNI of a failed handshake does not reach the next connection that the
  11953. // same worker thread serves
  11954. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11956. ASSERT_TRUE(svr.is_valid());
  11957. svr.new_task_queue = [] { return new ThreadPool(1); };
  11958. svr.Get("/sni", [](const Request &req, Response &res) {
  11959. res.set_content(req.sni(), "text/plain");
  11960. });
  11961. auto port = svr.bind_to_any_port("127.0.0.1");
  11962. ASSERT_LT(0, port);
  11963. thread t = thread([&] { svr.listen_after_bind(); });
  11964. auto se = detail::scope_exit([&] {
  11965. svr.stop();
  11966. t.join();
  11967. ASSERT_FALSE(svr.is_running());
  11968. });
  11969. svr.wait_until_ready();
  11970. {
  11971. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11972. SSLClient cli("localhost", port);
  11973. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11974. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11975. auto res = cli.Get("/sni");
  11976. ASSERT_FALSE(res);
  11977. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11978. }
  11979. // An IP host sends no SNI (RFC 6066)
  11980. SSLClient cli("127.0.0.1", port);
  11981. cli.enable_server_certificate_verification(false);
  11982. auto res = cli.Get("/sni");
  11983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11984. EXPECT_EQ("", res->body);
  11985. }
  11986. #endif
  11987. TEST(ClientProblemDetectionTest, ContentProvider) {
  11988. Server svr;
  11989. size_t content_length = 1024 * 1024;
  11990. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11991. res.set_content_provider(
  11992. content_length, "text/plain",
  11993. [&](size_t offset, size_t length, DataSink &sink) {
  11994. auto out_len = std::min(length, static_cast<size_t>(1024));
  11995. std::string out(out_len, '@');
  11996. sink.write(out.data(), out_len);
  11997. return offset < 4096;
  11998. },
  11999. [](bool success) { ASSERT_FALSE(success); });
  12000. });
  12001. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12002. res.set_content_provider(
  12003. 0, "text/plain",
  12004. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12005. EXPECT_TRUE(false);
  12006. return true;
  12007. },
  12008. [](bool success) { ASSERT_FALSE(success); });
  12009. });
  12010. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12011. auto se = detail::scope_exit([&] {
  12012. svr.stop();
  12013. listen_thread.join();
  12014. ASSERT_FALSE(svr.is_running());
  12015. });
  12016. svr.wait_until_ready();
  12017. Client cli("localhost", PORT);
  12018. {
  12019. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12020. size_t /*data_length*/) { return false; });
  12021. ASSERT_FALSE(res);
  12022. }
  12023. {
  12024. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12025. size_t /*data_length*/) { return false; });
  12026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12027. }
  12028. }
  12029. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12030. // A provider that reports success without writing anything and without
  12031. // calling done() used to be handed the same offset and length again on every
  12032. // pass, so it spun for as long as the peer stayed connected.
  12033. Server svr;
  12034. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12035. res.set_content("ok", "text/plain");
  12036. });
  12037. auto port = svr.bind_to_any_port(HOST);
  12038. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12039. auto se = detail::scope_exit([&] {
  12040. svr.stop();
  12041. listen_thread.join();
  12042. ASSERT_FALSE(svr.is_running());
  12043. });
  12044. svr.wait_until_ready();
  12045. std::atomic<int> call_count{0};
  12046. Client cli(HOST, port);
  12047. auto res = cli.Post(
  12048. "/", 1024,
  12049. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12050. // Give up after enough passes to show the spin, so that losing the
  12051. // check below fails this test instead of hanging it.
  12052. return ++call_count < 100;
  12053. },
  12054. "text/plain");
  12055. ASSERT_FALSE(res);
  12056. EXPECT_EQ(Error::Write, res.error());
  12057. EXPECT_EQ(1, call_count.load());
  12058. }
  12059. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12060. // A writer only has to assign `write`. The other three used to be left as
  12061. // empty std::functions, so a provider calling one threw
  12062. // std::bad_function_call out of the thread running it and took the whole
  12063. // process down.
  12064. DataSink sink;
  12065. std::string written;
  12066. sink.write = [&](const char *data, size_t data_len) {
  12067. written.append(data, data_len);
  12068. return true;
  12069. };
  12070. EXPECT_TRUE(sink.is_writable());
  12071. sink.done();
  12072. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12073. EXPECT_TRUE(written.empty());
  12074. }
  12075. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12076. // A sink that cannot carry trailers still has to finish.
  12077. DataSink sink;
  12078. auto done_count = 0;
  12079. sink.done = [&]() { done_count++; };
  12080. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12081. EXPECT_EQ(1, done_count);
  12082. }
  12083. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12084. Server svr;
  12085. const std::string body(4096, 'x');
  12086. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12087. res.set_content_provider(body.size(), "text/plain",
  12088. [&](size_t offset, size_t length, DataSink &sink) {
  12089. sink.write(body.data() + offset, length);
  12090. sink.done();
  12091. return true;
  12092. });
  12093. });
  12094. auto port = svr.bind_to_any_port(HOST);
  12095. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12096. auto se = detail::scope_exit([&] {
  12097. svr.stop();
  12098. listen_thread.join();
  12099. ASSERT_FALSE(svr.is_running());
  12100. });
  12101. svr.wait_until_ready();
  12102. Client cli(HOST, port);
  12103. auto res = cli.Get("/");
  12104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12105. EXPECT_EQ(StatusCode::OK_200, res->status);
  12106. EXPECT_EQ(body, res->body);
  12107. }
  12108. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12109. Server svr;
  12110. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12111. res.set_content_provider(
  12112. 1024, "text/plain",
  12113. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12114. sink.write("hello", 5);
  12115. sink.done(); // short of the 1024 bytes the response promised
  12116. return true;
  12117. });
  12118. });
  12119. auto port = svr.bind_to_any_port(HOST);
  12120. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12121. auto se = detail::scope_exit([&] {
  12122. svr.stop();
  12123. listen_thread.join();
  12124. ASSERT_FALSE(svr.is_running());
  12125. });
  12126. svr.wait_until_ready();
  12127. Client cli(HOST, port);
  12128. cli.set_read_timeout(5, 0);
  12129. // The response is short of its Content-Length, so the client cannot read a
  12130. // complete body. What matters is that this returns at all: a no-op done()
  12131. // would leave the writer looping over a provider that never makes progress.
  12132. auto res = cli.Get("/");
  12133. EXPECT_FALSE(res);
  12134. }
  12135. // Read as the next response by a peer that sees it after a framed body.
  12136. static const std::string smuggled_response =
  12137. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12138. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12139. Server svr;
  12140. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12141. res.set_content_provider(
  12142. 5, "text/plain",
  12143. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12144. auto data = "AAAAA" + smuggled_response;
  12145. sink.write(data.data(), data.size());
  12146. return true;
  12147. });
  12148. });
  12149. thread t = thread([&] { svr.listen(HOST, PORT); });
  12150. auto se = detail::scope_exit([&] {
  12151. svr.stop();
  12152. t.join();
  12153. ASSERT_FALSE(svr.is_running());
  12154. });
  12155. svr.wait_until_ready();
  12156. std::string resp;
  12157. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12158. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12159. resp.clear();
  12160. ASSERT_TRUE(send_request(
  12161. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12162. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12163. }
  12164. TEST(NoContentTest, BodyIsNotSent) {
  12165. Server svr;
  12166. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12167. res.status = StatusCode::NoContent_204;
  12168. res.set_content(smuggled_response, "text/plain");
  12169. });
  12170. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12171. res.status = StatusCode::NotModified_304;
  12172. res.set_chunked_content_provider(
  12173. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12174. sink.write(smuggled_response.data(), smuggled_response.size());
  12175. sink.done();
  12176. return true;
  12177. });
  12178. });
  12179. thread t = thread([&] { svr.listen(HOST, PORT); });
  12180. auto se = detail::scope_exit([&] {
  12181. svr.stop();
  12182. t.join();
  12183. ASSERT_FALSE(svr.is_running());
  12184. });
  12185. svr.wait_until_ready();
  12186. for (auto path : {"/204", "/304"}) {
  12187. std::string resp;
  12188. ASSERT_TRUE(send_request(
  12189. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12190. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12191. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12192. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12193. }
  12194. }
  12195. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12196. Server svr;
  12197. std::atomic<bool> smuggled(false);
  12198. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12199. res.set_content("ok", "text/plain");
  12200. });
  12201. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12202. smuggled = true;
  12203. });
  12204. auto port = svr.bind_to_any_port(HOST);
  12205. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12206. auto se = detail::scope_exit([&] {
  12207. svr.stop();
  12208. listen_thread.join();
  12209. ASSERT_FALSE(svr.is_running());
  12210. });
  12211. svr.wait_until_ready();
  12212. // What follows the body would be read as the next request.
  12213. Client cli(HOST, port);
  12214. auto res = cli.Post(
  12215. "/", 5,
  12216. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12217. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12218. sink.write(data.data(), data.size());
  12219. return true;
  12220. },
  12221. "text/plain");
  12222. ASSERT_FALSE(res);
  12223. EXPECT_EQ(Error::Write, res.error());
  12224. EXPECT_FALSE(smuggled);
  12225. }
  12226. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12227. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12228. // The compressed path builds the whole body before connecting, so this
  12229. // fails client-side and never reaches a server.
  12230. Client cli(HOST, PORT);
  12231. cli.set_compress(true);
  12232. auto res = cli.Post(
  12233. "/", 1024,
  12234. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12235. sink.write("hello", 5);
  12236. sink.done(); // short of the 1024 bytes the request announced
  12237. return true;
  12238. },
  12239. "text/plain");
  12240. ASSERT_FALSE(res);
  12241. EXPECT_EQ(Error::Write, res.error());
  12242. }
  12243. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12244. Server svr;
  12245. std::string received;
  12246. size_t content_length_count = 0;
  12247. bool has_transfer_encoding = true;
  12248. svr.Post("/echo", [&](const Request &req, Response &res) {
  12249. received = req.body;
  12250. content_length_count = req.get_header_value_count("Content-Length");
  12251. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12252. res.set_content("ok", "text/plain");
  12253. });
  12254. svr.Get("/next", [](const Request &, Response &res) {
  12255. res.set_content("next", "text/plain");
  12256. });
  12257. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12258. auto se = detail::scope_exit([&] {
  12259. svr.stop();
  12260. listen_thread.join();
  12261. ASSERT_FALSE(svr.is_running());
  12262. });
  12263. svr.wait_until_ready();
  12264. Client cli(HOST, PORT);
  12265. cli.set_keep_alive(true);
  12266. cli.set_compress(true);
  12267. const std::string body = "hello world";
  12268. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12269. auto res = cli.Post("/echo", headers, body, "text/plain");
  12270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12271. EXPECT_EQ(StatusCode::OK_200, res->status);
  12272. EXPECT_EQ(body, received);
  12273. EXPECT_EQ(1u, content_length_count);
  12274. EXPECT_FALSE(has_transfer_encoding);
  12275. // The rest of a truncated body would be read as this request
  12276. auto res2 = cli.Get("/next");
  12277. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12278. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12279. EXPECT_EQ("next", res2->body);
  12280. }
  12281. #endif
  12282. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12283. Server svr;
  12284. std::string received;
  12285. size_t content_length_count = 1;
  12286. bool has_transfer_encoding = false;
  12287. svr.Post("/echo", [&](const Request &req, Response &res) {
  12288. received = req.body;
  12289. content_length_count = req.get_header_value_count("Content-Length");
  12290. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12291. res.set_content("ok", "text/plain");
  12292. });
  12293. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12294. auto se = detail::scope_exit([&] {
  12295. svr.stop();
  12296. listen_thread.join();
  12297. ASSERT_FALSE(svr.is_running());
  12298. });
  12299. svr.wait_until_ready();
  12300. Client cli(HOST, PORT);
  12301. cli.set_keep_alive(true);
  12302. const std::string body = "hello world";
  12303. Headers headers = {{"Content-Length", "5"}};
  12304. auto res = cli.Post(
  12305. "/echo", headers,
  12306. [&](size_t /*offset*/, DataSink &sink) {
  12307. sink.write(body.data(), body.size());
  12308. sink.done();
  12309. return true;
  12310. },
  12311. "text/plain");
  12312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12313. EXPECT_EQ(StatusCode::OK_200, res->status);
  12314. EXPECT_EQ(body, received);
  12315. EXPECT_EQ(0u, content_length_count);
  12316. EXPECT_TRUE(has_transfer_encoding);
  12317. }
  12318. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12319. Server svr;
  12320. svr.set_error_handler([](Request const &, Response &res) -> void {
  12321. res.set_chunked_content_provider(
  12322. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12323. sink.os << "hello";
  12324. sink.os << "world";
  12325. sink.done();
  12326. return true;
  12327. });
  12328. });
  12329. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12330. auto se = detail::scope_exit([&] {
  12331. svr.stop();
  12332. listen_thread.join();
  12333. ASSERT_FALSE(svr.is_running());
  12334. });
  12335. svr.wait_until_ready();
  12336. Client cli("localhost", PORT);
  12337. auto res = cli.Get("/");
  12338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12340. EXPECT_EQ("helloworld", res->body);
  12341. }
  12342. // A body set after a content provider must replace it, not be sent through it.
  12343. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12344. Server svr;
  12345. svr.set_mount_point("/", "./www");
  12346. svr.set_file_request_handler([](const Request &req, Response &res) {
  12347. if (req.path == "/dir/test.html") {
  12348. res.status = StatusCode::Forbidden_403;
  12349. res.set_content(std::string(5000, 'D'), "text/plain");
  12350. } else if (req.path == "/file") {
  12351. res.status = StatusCode::Forbidden_403;
  12352. res.body = "Denied";
  12353. }
  12354. });
  12355. auto port = svr.bind_to_any_port(HOST);
  12356. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12357. auto se = detail::scope_exit([&] {
  12358. svr.stop();
  12359. t.join();
  12360. ASSERT_FALSE(svr.is_running());
  12361. });
  12362. svr.wait_until_ready();
  12363. Client cli(HOST, port);
  12364. {
  12365. auto res = cli.Get("/dir/test.html");
  12366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12367. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12368. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12369. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12370. }
  12371. {
  12372. auto res = cli.Get("/file");
  12373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12374. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12375. EXPECT_EQ("Denied", res->body);
  12376. }
  12377. {
  12378. auto res = cli.Get("/dir/index.html");
  12379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12380. EXPECT_EQ(StatusCode::OK_200, res->status);
  12381. EXPECT_EQ(0U, res->body.find("<html>"));
  12382. }
  12383. }
  12384. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12385. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12386. Server svr;
  12387. std::vector<bool> released;
  12388. std::mutex released_mutex;
  12389. auto releaser = [&](bool success) {
  12390. std::lock_guard<std::mutex> guard(released_mutex);
  12391. released.push_back(success);
  12392. };
  12393. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12394. return sink.write(&"hello"[offset], length);
  12395. };
  12396. svr.Get("/sized", [&](const Request &, Response &res) {
  12397. res.status = StatusCode::NotFound_404;
  12398. res.set_content_provider(5, "text/plain", provider, releaser);
  12399. });
  12400. svr.Get("/chunked", [&](const Request &, Response &res) {
  12401. res.status = StatusCode::ServiceUnavailable_503;
  12402. res.set_chunked_content_provider(
  12403. "text/plain",
  12404. [](size_t, DataSink &sink) {
  12405. sink.os << "chunk";
  12406. sink.done();
  12407. return true;
  12408. },
  12409. releaser);
  12410. });
  12411. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12412. res.set_content_provider(5, "text/plain", provider, releaser);
  12413. throw std::runtime_error("after the provider");
  12414. });
  12415. svr.set_error_handler([](const Request &req, Response &res) {
  12416. // Leave the exception handler's content to it.
  12417. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12418. res.set_content(std::string(1000, 'E'), "text/html");
  12419. return Server::HandlerResponse::Handled;
  12420. });
  12421. svr.set_exception_handler(
  12422. [](const Request &, Response &res, std::exception_ptr) {
  12423. res.status = StatusCode::InternalServerError_500;
  12424. res.set_content(std::string(1000, 'X'), "text/html");
  12425. });
  12426. auto port = svr.bind_to_any_port(HOST);
  12427. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12428. auto se = detail::scope_exit([&] {
  12429. svr.stop();
  12430. t.join();
  12431. ASSERT_FALSE(svr.is_running());
  12432. });
  12433. svr.wait_until_ready();
  12434. Client cli(HOST, port);
  12435. {
  12436. auto res = cli.Get("/sized");
  12437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12438. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12439. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12440. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12441. }
  12442. {
  12443. auto res = cli.Get("/chunked");
  12444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12445. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12446. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12447. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12448. }
  12449. {
  12450. auto res = cli.Get("/throw");
  12451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12452. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12453. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12454. }
  12455. std::lock_guard<std::mutex> guard(released_mutex);
  12456. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12457. }
  12458. #endif
  12459. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12460. Server svr;
  12461. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12462. return sink.write(&"abc"[offset], length);
  12463. };
  12464. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12465. res.set_file_content("./www/dir/test.html");
  12466. res.set_content("body", "text/plain");
  12467. });
  12468. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12469. res.set_content(std::string(100, 'B'), "text/plain");
  12470. res.set_file_content("./www/dir/test.html");
  12471. });
  12472. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12473. res.set_content(std::string(100, 'B'), "text/plain");
  12474. res.set_content_provider(3, "text/x-provider", abc);
  12475. });
  12476. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12477. res.set_content_provider(3, "text/x-provider", abc);
  12478. res.set_content(std::string(100, 'B'), "text/plain");
  12479. });
  12480. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12481. res.set_content_provider(3, "text/x-provider", abc);
  12482. res.set_file_content("./www/dir/test.html", "text/x-file");
  12483. });
  12484. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12485. res.set_file_content("./www/dir/test.html");
  12486. res.set_header("Content-Type", "text/x-handler");
  12487. });
  12488. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12489. res.set_content_provider(3, "text/plain", abc);
  12490. res.body = "direct";
  12491. });
  12492. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12493. res.set_file_content("./www/dir/test.html");
  12494. res.body = "direct";
  12495. });
  12496. auto port = svr.bind_to_any_port(HOST);
  12497. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12498. auto se = detail::scope_exit([&] {
  12499. svr.stop();
  12500. t.join();
  12501. ASSERT_FALSE(svr.is_running());
  12502. });
  12503. svr.wait_until_ready();
  12504. Client cli(HOST, port);
  12505. auto expect_body = [&](const char *path, const std::string &body,
  12506. const std::string &type) {
  12507. // Uncompressed, so Content-Length can be compared with the body.
  12508. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12509. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12510. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12511. EXPECT_EQ(body, res->body) << path;
  12512. EXPECT_EQ(std::to_string(body.size()),
  12513. res->get_header_value("Content-Length"))
  12514. << path;
  12515. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12516. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12517. };
  12518. expect_body("/file-then-body", "body", "text/plain");
  12519. expect_body("/body-then-file", "test.html", "text/html");
  12520. expect_body("/body-then-provider", "abc", "text/x-provider");
  12521. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12522. expect_body("/provider-then-file", "test.html", "text/x-file");
  12523. expect_body("/file-then-header", "test.html", "text/x-handler");
  12524. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12525. expect_body("/file-then-direct-body", "direct", "text/plain");
  12526. // Ranges are checked against the body, not the dropped provider.
  12527. {
  12528. auto res = cli.Get("/provider-then-direct-body",
  12529. Headers{{make_range_header({{1, 2}})}});
  12530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12532. EXPECT_EQ("ir", res->body);
  12533. }
  12534. {
  12535. auto res = cli.Get("/file-then-direct-body",
  12536. Headers{{make_range_header({{7, 8}})}});
  12537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12538. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12539. }
  12540. }
  12541. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12542. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12543. const char *path = "./truncated_while_served.txt";
  12544. const size_t size = 32 * 1024 * 1024;
  12545. {
  12546. std::ofstream f(path, std::ios::binary);
  12547. f << std::string(size, 'x');
  12548. }
  12549. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12550. // Over TLS, where the bytes are encrypted in this process rather than
  12551. // copied by send().
  12552. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12553. svr.Get("/file", [&](const Request &, Response &res) {
  12554. res.set_file_content(path, "text/plain");
  12555. });
  12556. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12557. auto se = detail::scope_exit([&] {
  12558. svr.stop();
  12559. thread.join();
  12560. ASSERT_FALSE(svr.is_running());
  12561. });
  12562. svr.wait_until_ready();
  12563. // The file shrinks once the first bytes are in, as a rewrite in place
  12564. // would, and reading the mapping past its new end used to raise SIGBUS.
  12565. SSLClient cli(HOST, PORT);
  12566. cli.enable_server_certificate_verification(false);
  12567. size_t received = 0;
  12568. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12569. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12570. received += len;
  12571. return true;
  12572. });
  12573. EXPECT_FALSE(res);
  12574. EXPECT_LT(received, size);
  12575. }
  12576. #endif
  12577. // Forward declaration (see the base64_encode note).
  12578. namespace httplib {
  12579. namespace detail {
  12580. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12581. const std::string &content_type,
  12582. EncodingType encoding);
  12583. } // namespace detail
  12584. } // namespace httplib
  12585. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12586. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12587. ASSERT_TRUE(mm->is_open());
  12588. Response res;
  12589. detail::set_file_content_provider(res, mm, "text/html",
  12590. detail::EncodingType::None);
  12591. std::string out;
  12592. DataSink sink;
  12593. sink.write = [&](const char *d, size_t l) {
  12594. out.append(d, l);
  12595. return true;
  12596. };
  12597. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12598. EXPECT_EQ("test.html", out);
  12599. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12600. EXPECT_EQ("test.html", out);
  12601. }
  12602. TEST(LongPollingTest, ClientCloseDetection) {
  12603. Server svr;
  12604. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12605. res.set_chunked_content_provider(
  12606. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12607. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12608. sink.os << "hello";
  12609. auto count = 10;
  12610. while (count > 0 && sink.is_writable()) {
  12611. this_thread::sleep_for(chrono::milliseconds(10));
  12612. count--;
  12613. }
  12614. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12615. return true;
  12616. });
  12617. });
  12618. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12619. auto se = detail::scope_exit([&] {
  12620. svr.stop();
  12621. listen_thread.join();
  12622. ASSERT_FALSE(svr.is_running());
  12623. });
  12624. svr.wait_until_ready();
  12625. Client cli("localhost", PORT);
  12626. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12627. EXPECT_EQ("hello", string(data, data_length));
  12628. return false; // close the socket immediately.
  12629. });
  12630. ASSERT_FALSE(res);
  12631. }
  12632. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12633. Server svr;
  12634. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12635. res.set_chunked_content_provider(
  12636. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12637. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12638. sink.os << "hello";
  12639. EXPECT_TRUE(sink.os.good());
  12640. // Wait for the client to close the connection
  12641. auto count = 10;
  12642. while (count > 0 && sink.is_writable()) {
  12643. this_thread::sleep_for(chrono::milliseconds(10));
  12644. count--;
  12645. }
  12646. // After client disconnect, write repeatedly until the socket
  12647. // write actually fails (small writes may be absorbed by the
  12648. // kernel buffer)
  12649. std::string chunk(1024, 'x');
  12650. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12651. sink.os << chunk;
  12652. }
  12653. EXPECT_TRUE(sink.os.fail());
  12654. return true;
  12655. });
  12656. });
  12657. auto port = svr.bind_to_any_port("localhost");
  12658. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12659. auto se = detail::scope_exit([&] {
  12660. svr.stop();
  12661. listen_thread.join();
  12662. ASSERT_FALSE(svr.is_running());
  12663. });
  12664. svr.wait_until_ready();
  12665. Client cli("localhost", port);
  12666. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12667. EXPECT_EQ("hello", string(data, data_length));
  12668. return false; // close the socket immediately.
  12669. });
  12670. ASSERT_FALSE(res);
  12671. }
  12672. TEST(GetWithParametersTest, GetWithParameters) {
  12673. Server svr;
  12674. svr.Get("/", [&](const Request &req, Response &) {
  12675. EXPECT_EQ("world", req.get_param_value("hello"));
  12676. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12677. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12678. });
  12679. svr.Get("/params", [&](const Request &req, Response &) {
  12680. EXPECT_EQ("world", req.get_param_value("hello"));
  12681. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12682. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12683. });
  12684. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12685. EXPECT_EQ("resource-id", req.matches[1]);
  12686. EXPECT_EQ("foo", req.get_param_value("param1"));
  12687. EXPECT_EQ("bar", req.get_param_value("param2"));
  12688. });
  12689. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12690. EXPECT_EQ("user-id", req.path_params.at("id"));
  12691. EXPECT_EQ("foo", req.get_param_value("param1"));
  12692. EXPECT_EQ("bar", req.get_param_value("param2"));
  12693. });
  12694. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12695. auto se = detail::scope_exit([&] {
  12696. svr.stop();
  12697. listen_thread.join();
  12698. ASSERT_FALSE(svr.is_running());
  12699. });
  12700. svr.wait_until_ready();
  12701. {
  12702. Client cli(HOST, PORT);
  12703. Params params;
  12704. params.emplace("hello", "world");
  12705. params.emplace("hello2", "world2");
  12706. params.emplace("hello3", "world3");
  12707. auto res = cli.Get("/", params, Headers{});
  12708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12709. EXPECT_EQ(StatusCode::OK_200, res->status);
  12710. }
  12711. {
  12712. Client cli(HOST, PORT);
  12713. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12715. EXPECT_EQ(StatusCode::OK_200, res->status);
  12716. }
  12717. {
  12718. Client cli(HOST, PORT);
  12719. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12721. EXPECT_EQ(StatusCode::OK_200, res->status);
  12722. }
  12723. {
  12724. Client cli(HOST, PORT);
  12725. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12727. EXPECT_EQ(StatusCode::OK_200, res->status);
  12728. }
  12729. }
  12730. TEST(GetWithParametersTest, GetWithParameters2) {
  12731. Server svr;
  12732. svr.Get("/", [&](const Request &req, Response &res) {
  12733. auto text = req.get_param_value("hello");
  12734. res.set_content(text, "text/plain");
  12735. });
  12736. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12737. auto se = detail::scope_exit([&] {
  12738. svr.stop();
  12739. listen_thread.join();
  12740. ASSERT_FALSE(svr.is_running());
  12741. });
  12742. svr.wait_until_ready();
  12743. Client cli("localhost", PORT);
  12744. Params params;
  12745. params.emplace("hello", "world");
  12746. std::string body;
  12747. auto res = cli.Get("/", params, Headers{},
  12748. [&](const char *data, size_t data_length) {
  12749. body.append(data, data_length);
  12750. return true;
  12751. });
  12752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12753. EXPECT_EQ(StatusCode::OK_200, res->status);
  12754. EXPECT_EQ("world", body);
  12755. }
  12756. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12757. Server svr;
  12758. svr.Get("/search", [&](const Request &req, Response &res) {
  12759. auto q = req.get_param_value("q");
  12760. res.set_content(q, "text/plain");
  12761. });
  12762. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12763. auto se = detail::scope_exit([&] {
  12764. svr.stop();
  12765. listen_thread.join();
  12766. ASSERT_FALSE(svr.is_running());
  12767. });
  12768. svr.wait_until_ready();
  12769. Client cli("localhost", PORT);
  12770. // Verify that Get(path, params) works without requiring Headers argument
  12771. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12773. EXPECT_EQ(StatusCode::OK_200, res->status);
  12774. EXPECT_EQ("cpp-httplib", res->body);
  12775. }
  12776. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12777. auto host = "httpbingo.org";
  12778. auto path = std::string{"/range/32"};
  12779. #ifdef CPPHTTPLIB_SSL_ENABLED
  12780. SSLClient cli(host);
  12781. #else
  12782. Client cli(host);
  12783. #endif
  12784. cli.set_default_headers({make_range_header({{1, 10}})});
  12785. cli.set_connection_timeout(5);
  12786. {
  12787. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  12788. SKIP_ON_GATEWAY_ERROR(res);
  12789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12790. EXPECT_EQ("bcdefghijk", res->body);
  12791. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12792. }
  12793. {
  12794. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  12795. SKIP_ON_GATEWAY_ERROR(res);
  12796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12797. EXPECT_EQ("bcdefghijk", res->body);
  12798. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12799. }
  12800. }
  12801. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12802. Server svr;
  12803. svr.set_default_headers({{"Hello", "World"}});
  12804. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12805. res.set_content("ok", "text/plain");
  12806. });
  12807. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12808. auto se = detail::scope_exit([&] {
  12809. svr.stop();
  12810. listen_thread.join();
  12811. ASSERT_FALSE(svr.is_running());
  12812. });
  12813. svr.wait_until_ready();
  12814. Client cli("localhost", PORT);
  12815. auto res = cli.Get("/");
  12816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12817. EXPECT_EQ(StatusCode::OK_200, res->status);
  12818. EXPECT_EQ("ok", res->body);
  12819. EXPECT_EQ("World", res->get_header_value("Hello"));
  12820. }
  12821. #ifdef CPPHTTPLIB_SSL_ENABLED
  12822. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12824. ASSERT_TRUE(svr.is_valid());
  12825. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12826. std::this_thread::sleep_for(std::chrono::seconds(2));
  12827. res.set_content("a", "text/plain");
  12828. });
  12829. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12830. res.set_content("b", "text/plain");
  12831. });
  12832. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12833. auto se = detail::scope_exit([&] {
  12834. svr.stop();
  12835. listen_thread.join();
  12836. ASSERT_FALSE(svr.is_running());
  12837. });
  12838. svr.wait_until_ready();
  12839. SSLClient cli("localhost", PORT);
  12840. cli.enable_server_certificate_verification(false);
  12841. cli.set_keep_alive(true);
  12842. cli.set_read_timeout(std::chrono::seconds(1));
  12843. auto resa = cli.Get("/a");
  12844. ASSERT_TRUE(!resa);
  12845. EXPECT_EQ(Error::Read, resa.error());
  12846. auto resb = cli.Get("/b");
  12847. ASSERT_TRUE(resb);
  12848. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12849. EXPECT_EQ("b", resb->body);
  12850. }
  12851. // Closing an idle keep-alive connection sends close_notify and returns. The
  12852. // server must not wait for the client's close_notify: an idle client never
  12853. // sends one, so the worker would be held until the read timeout expires, and
  12854. // stop() would wait for it.
  12855. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12856. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12857. ASSERT_TRUE(svr.is_valid());
  12858. svr.set_keep_alive_timeout(1);
  12859. svr.set_read_timeout(10, 0);
  12860. svr.Get("/", [](const Request &, Response &res) {
  12861. res.set_content("ok", "text/plain");
  12862. });
  12863. auto port = svr.bind_to_any_port(HOST);
  12864. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12865. auto se = detail::scope_exit([&] {
  12866. if (listen_thread.joinable()) {
  12867. svr.stop();
  12868. listen_thread.join();
  12869. }
  12870. });
  12871. svr.wait_until_ready();
  12872. SSLClient cli(HOST, port);
  12873. cli.enable_server_certificate_verification(false);
  12874. cli.set_keep_alive(true);
  12875. auto res = cli.Get("/");
  12876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12877. EXPECT_EQ(StatusCode::OK_200, res->status);
  12878. // Stay idle past the keep-alive timeout so the server closes the connection.
  12879. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12880. auto start = std::chrono::steady_clock::now();
  12881. svr.stop();
  12882. listen_thread.join();
  12883. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12884. std::chrono::steady_clock::now() - start)
  12885. .count();
  12886. EXPECT_LT(elapsed, 3000);
  12887. }
  12888. #endif
  12889. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12890. protected:
  12891. ServerTestWithAI_PASSIVE()
  12892. : cli_(HOST, PORT)
  12893. #ifdef CPPHTTPLIB_SSL_ENABLED
  12894. ,
  12895. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12896. #endif
  12897. {
  12898. #ifdef CPPHTTPLIB_SSL_ENABLED
  12899. cli_.enable_server_certificate_verification(false);
  12900. #endif
  12901. }
  12902. virtual void SetUp() {
  12903. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12904. res.set_content("Hello World!", "text/plain");
  12905. });
  12906. t_ = thread(
  12907. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12908. svr_.wait_until_ready();
  12909. }
  12910. virtual void TearDown() {
  12911. svr_.stop();
  12912. t_.join();
  12913. }
  12914. #ifdef CPPHTTPLIB_SSL_ENABLED
  12915. SSLClient cli_;
  12916. SSLServer svr_;
  12917. #else
  12918. Client cli_;
  12919. Server svr_;
  12920. #endif
  12921. thread t_;
  12922. };
  12923. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12924. auto res = cli_.Get("/hi");
  12925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12926. EXPECT_EQ(StatusCode::OK_200, res->status);
  12927. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12928. EXPECT_EQ("Hello World!", res->body);
  12929. }
  12930. class ServerUpDownTest : public ::testing::Test {
  12931. protected:
  12932. ServerUpDownTest() : cli_(HOST, PORT) {}
  12933. virtual void SetUp() {
  12934. t_ = thread([&]() {
  12935. svr_.bind_to_any_port(HOST);
  12936. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12937. ASSERT_TRUE(svr_.listen_after_bind());
  12938. });
  12939. svr_.wait_until_ready();
  12940. }
  12941. virtual void TearDown() {
  12942. svr_.stop();
  12943. t_.join();
  12944. }
  12945. Client cli_;
  12946. Server svr_;
  12947. thread t_;
  12948. };
  12949. TEST_F(ServerUpDownTest, QuickStartStop) {
  12950. // Should not crash, especially when run with
  12951. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12952. }
  12953. class PayloadMaxLengthTest : public ::testing::Test {
  12954. protected:
  12955. PayloadMaxLengthTest()
  12956. : cli_(HOST, PORT)
  12957. #ifdef CPPHTTPLIB_SSL_ENABLED
  12958. ,
  12959. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12960. #endif
  12961. {
  12962. #ifdef CPPHTTPLIB_SSL_ENABLED
  12963. cli_.enable_server_certificate_verification(false);
  12964. #endif
  12965. }
  12966. virtual void SetUp() {
  12967. svr_.set_payload_max_length(8);
  12968. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12969. res.set_content("test", "text/plain");
  12970. });
  12971. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12972. svr_.wait_until_ready();
  12973. }
  12974. virtual void TearDown() {
  12975. svr_.stop();
  12976. t_.join();
  12977. }
  12978. #ifdef CPPHTTPLIB_SSL_ENABLED
  12979. SSLClient cli_;
  12980. SSLServer svr_;
  12981. #else
  12982. Client cli_;
  12983. Server svr_;
  12984. #endif
  12985. thread t_;
  12986. };
  12987. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12988. auto res = cli_.Post("/test", "123456789", "text/plain");
  12989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12990. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12991. res = cli_.Post("/test", "12345678", "text/plain");
  12992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12993. EXPECT_EQ(StatusCode::OK_200, res->status);
  12994. }
  12995. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12996. // Test chunked encoding with payload exceeding the 8-byte limit
  12997. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12998. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13000. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13001. }
  13002. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13003. // Test chunked encoding with payload within the 8-byte limit
  13004. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13005. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13007. EXPECT_EQ(StatusCode::OK_200, res->status);
  13008. }
  13009. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13010. // Test using send_request to send chunked data exceeding payload limit
  13011. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13012. "Host: " +
  13013. std::string(HOST) + ":" + std::to_string(PORT) +
  13014. "\r\n"
  13015. "Transfer-Encoding: chunked\r\n"
  13016. "Connection: close\r\n"
  13017. "\r\n"
  13018. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13019. "0123456789\r\n"
  13020. "0\r\n" // End chunk
  13021. "\r\n";
  13022. std::string response;
  13023. bool result = send_request(1, chunked_request, &response);
  13024. if (!result) {
  13025. // If send_request fails, it might be because the server closed the
  13026. // connection due to payload limit enforcement, which is acceptable
  13027. SUCCEED()
  13028. << "Server rejected oversized chunked request (connection closed)";
  13029. } else {
  13030. // If we got a response, check if it's an error response or connection was
  13031. // closed early Short response length indicates connection was closed due to
  13032. // payload limit
  13033. if (response.length() <= 10) {
  13034. SUCCEED() << "Server closed connection for oversized chunked request";
  13035. } else {
  13036. // Check for error status codes
  13037. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13038. response.find("Payload Too Large") != std::string::npos ||
  13039. response.find("400") != std::string::npos);
  13040. }
  13041. }
  13042. }
  13043. class LargePayloadMaxLengthTest : public ::testing::Test {
  13044. protected:
  13045. LargePayloadMaxLengthTest()
  13046. : cli_(HOST, PORT)
  13047. #ifdef CPPHTTPLIB_SSL_ENABLED
  13048. ,
  13049. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13050. #endif
  13051. {
  13052. #ifdef CPPHTTPLIB_SSL_ENABLED
  13053. cli_.enable_server_certificate_verification(false);
  13054. #endif
  13055. }
  13056. virtual void SetUp() {
  13057. // Set 10MB payload limit
  13058. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13059. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13060. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13061. res.set_content("Large payload test", "text/plain");
  13062. });
  13063. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13064. svr_.wait_until_ready();
  13065. }
  13066. virtual void TearDown() {
  13067. svr_.stop();
  13068. t_.join();
  13069. }
  13070. #ifdef CPPHTTPLIB_SSL_ENABLED
  13071. SSLClient cli_;
  13072. SSLServer svr_;
  13073. #else
  13074. Client cli_;
  13075. Server svr_;
  13076. #endif
  13077. thread t_;
  13078. };
  13079. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13080. // Test chunked encoding with payload within 10MB limit
  13081. std::string medium_payload(5 * 1024 * 1024,
  13082. 'A'); // 5MB payload, within 10MB limit
  13083. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13085. EXPECT_EQ(StatusCode::OK_200, res->status);
  13086. }
  13087. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13088. // Test chunked encoding with payload exceeding 10MB limit
  13089. std::string large_payload(12 * 1024 * 1024,
  13090. 'B'); // 12MB payload, exceeds 10MB limit
  13091. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13092. // Server may either return 413 or close the connection
  13093. if (res) {
  13094. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13095. } else {
  13096. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13097. }
  13098. }
  13099. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13100. Server svr;
  13101. svr.Get("/", [](const Request &, Response &res) {
  13102. // Claims the most the client accepts, far more than it sends, then drops
  13103. // the connection.
  13104. res.set_content_provider(std::string().max_size(), "text/plain",
  13105. [](size_t, size_t, DataSink &sink) {
  13106. sink.write("abc", 3);
  13107. return false;
  13108. });
  13109. });
  13110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13111. auto se = detail::scope_exit([&] {
  13112. svr.stop();
  13113. thread.join();
  13114. ASSERT_FALSE(svr.is_running());
  13115. });
  13116. svr.wait_until_ready();
  13117. Client cli(HOST, PORT);
  13118. cli.set_payload_max_length(0);
  13119. EXPECT_FALSE(cli.Get("/"));
  13120. }
  13121. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13122. // Stream API does, not as a plain read failure
  13123. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13124. Server svr;
  13125. svr.Get("/big", [](const Request &, Response &res) {
  13126. res.set_content(std::string(100000, 'b'), "text/plain");
  13127. });
  13128. auto port = svr.bind_to_any_port(HOST);
  13129. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13130. auto se = detail::scope_exit([&] {
  13131. svr.stop();
  13132. thread.join();
  13133. });
  13134. svr.wait_until_ready();
  13135. Client cli(HOST, port);
  13136. cli.set_payload_max_length(1000);
  13137. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13138. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13139. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13140. [](const char *, size_t) { return true; });
  13141. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13142. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13143. // Small on the wire, over the limit once decompressed
  13144. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13145. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13146. #endif
  13147. }
  13148. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13149. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13150. // path.
  13151. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13152. Server svr;
  13153. const size_t LIMIT = 64 * 1024; // 64KB
  13154. svr.set_payload_max_length(LIMIT);
  13155. size_t total = 0;
  13156. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13157. const ContentReader &content_reader) {
  13158. content_reader([&](const char * /*data*/, size_t len) {
  13159. total += len;
  13160. return true;
  13161. });
  13162. res.status = 200;
  13163. res.set_content("stream_ok", "text/plain");
  13164. });
  13165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13166. auto se = detail::scope_exit([&] {
  13167. svr.stop();
  13168. thread.join();
  13169. ASSERT_FALSE(svr.is_running());
  13170. });
  13171. svr.wait_until_ready();
  13172. // Prepare 256KB raw data and gzip-compress it
  13173. std::string raw(256 * 1024, 'A');
  13174. std::string gz;
  13175. {
  13176. z_stream zs{};
  13177. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13178. Z_DEFAULT_STRATEGY);
  13179. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13180. zs.avail_in = static_cast<uInt>(raw.size());
  13181. char outbuf[4096];
  13182. int ret;
  13183. do {
  13184. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13185. zs.avail_out = sizeof(outbuf);
  13186. ret = deflate(&zs, Z_FINISH);
  13187. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13188. } while (ret != Z_STREAM_END);
  13189. deflateEnd(&zs);
  13190. }
  13191. Client cli(HOST, PORT);
  13192. cli.set_connection_timeout(std::chrono::seconds(5));
  13193. Headers headers = {{"Content-Encoding", "gzip"}};
  13194. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13195. "application/octet-stream");
  13196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13197. // Server must reject oversized decompressed payloads with 413.
  13198. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13199. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13200. EXPECT_LE(total, LIMIT);
  13201. }
  13202. #endif
  13203. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13204. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13205. // the payload must be passed through untouched instead of being rejected.
  13206. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13207. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13208. Server svr;
  13209. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13210. res.set_content(body, "image/jpeg");
  13211. res.set_header("Content-Encoding", "UTF-8");
  13212. });
  13213. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13214. res.set_content(body, "image/jpeg");
  13215. res.set_header("Content-Encoding", "identity");
  13216. });
  13217. svr.Post("/echo", [](const Request &req, Response &res) {
  13218. res.set_content(req.body, "image/jpeg");
  13219. });
  13220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13221. auto se = detail::scope_exit([&] {
  13222. svr.stop();
  13223. t.join();
  13224. ASSERT_FALSE(svr.is_running());
  13225. });
  13226. svr.wait_until_ready();
  13227. Client cli(HOST, PORT);
  13228. {
  13229. auto res = cli.Get("/image");
  13230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13231. EXPECT_EQ(StatusCode::OK_200, res->status);
  13232. EXPECT_EQ(body, res->body);
  13233. }
  13234. {
  13235. auto res = cli.Get("/identity");
  13236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13237. EXPECT_EQ(StatusCode::OK_200, res->status);
  13238. EXPECT_EQ(body, res->body);
  13239. }
  13240. {
  13241. // The same applies to a request body reaching the server.
  13242. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13243. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13245. EXPECT_EQ(StatusCode::OK_200, res->status);
  13246. EXPECT_EQ(body, res->body);
  13247. }
  13248. }
  13249. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13250. // gzip-encoded response even when the build has no zlib support.
  13251. static const char GZIPPED_HELLO_WORLD[] = {
  13252. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13253. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13254. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13255. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13256. // A content coding is a whole token, not something the field value merely
  13257. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13258. // as "fibre" look like Brotli, and turned a multi-coding value like
  13259. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13260. // it was never meant to see.
  13261. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13262. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13263. Server svr;
  13264. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13265. res.set_content(body, "image/jpeg");
  13266. res.set_header("Content-Encoding", "fibre");
  13267. });
  13268. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13269. res.set_content(body, "image/jpeg");
  13270. res.set_header("Content-Encoding", "gzip, br");
  13271. });
  13272. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13273. res.set_content(body, "image/jpeg");
  13274. res.set_header("Content-Encoding", "x-zstd-ish");
  13275. });
  13276. auto port = svr.bind_to_any_port(HOST);
  13277. thread t = thread([&]() { svr.listen_after_bind(); });
  13278. auto se = detail::scope_exit([&] {
  13279. svr.stop();
  13280. t.join();
  13281. ASSERT_FALSE(svr.is_running());
  13282. });
  13283. svr.wait_until_ready();
  13284. Client cli(HOST, port);
  13285. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13286. auto res = cli.Get(path);
  13287. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13288. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13289. // Not a coding we recognize, so the payload comes back untouched
  13290. EXPECT_EQ(body, res->body) << path;
  13291. }
  13292. }
  13293. // A content coding cpp-httplib recognizes but was not built with must be
  13294. // reported as such. Handing the still-compressed payload back to the caller
  13295. // would silently corrupt it.
  13296. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13297. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13298. Server svr;
  13299. // "image/jpeg" keeps the server from applying a content coding of its own,
  13300. // so the hand-crafted Content-Encoding below survives.
  13301. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13302. res.set_content(gzipped, "image/jpeg");
  13303. res.set_header("Content-Encoding", "gzip");
  13304. });
  13305. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13306. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13307. res.set_content(gzipped, "image/jpeg");
  13308. res.set_header("Content-Encoding", "GZIP");
  13309. });
  13310. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13311. auto se = detail::scope_exit([&] {
  13312. svr.stop();
  13313. t.join();
  13314. ASSERT_FALSE(svr.is_running());
  13315. });
  13316. svr.wait_until_ready();
  13317. Client cli(HOST, PORT);
  13318. {
  13319. auto res = cli.Get("/gzipped");
  13320. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13322. EXPECT_EQ("Hello World!", res->body);
  13323. #else
  13324. ASSERT_FALSE(res);
  13325. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13326. #endif
  13327. }
  13328. {
  13329. // open_stream() must behave the same way.
  13330. auto handle = cli.open_stream("GET", "/gzipped");
  13331. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13332. ASSERT_TRUE(handle.is_valid());
  13333. std::string received;
  13334. char buf[256];
  13335. ssize_t n;
  13336. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13337. received.append(buf, static_cast<size_t>(n));
  13338. }
  13339. EXPECT_EQ("Hello World!", received);
  13340. #else
  13341. EXPECT_FALSE(handle.is_valid());
  13342. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13343. #endif
  13344. }
  13345. {
  13346. // A differently-cased coding must not be mistaken for an unknown one, or
  13347. // the body would be handed back still compressed.
  13348. auto res = cli.Get("/gzipped-uppercase");
  13349. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13351. EXPECT_EQ("Hello World!", res->body);
  13352. #else
  13353. ASSERT_FALSE(res);
  13354. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13355. #endif
  13356. }
  13357. }
  13358. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13359. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13360. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13361. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13362. // body a second time and appending a second Content-Encoding field line, so
  13363. // clients that decode one coding per listed value handed back raw gzip bytes.
  13364. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13365. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13366. Server svr;
  13367. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13368. // keeps the server from applying a coding of its own.
  13369. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13370. res.set_content(gzipped, "text/plain");
  13371. res.set_header("Content-Encoding", "gzip");
  13372. });
  13373. auto port = svr.bind_to_any_port(HOST);
  13374. thread t = thread([&]() { svr.listen_after_bind(); });
  13375. auto se = detail::scope_exit([&] {
  13376. svr.stop();
  13377. t.join();
  13378. ASSERT_FALSE(svr.is_running());
  13379. });
  13380. svr.wait_until_ready();
  13381. Client cli(HOST, port);
  13382. Headers headers = {{"Accept-Encoding", "gzip"}};
  13383. auto res = cli.Get("/pre-gzipped", headers);
  13384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13385. EXPECT_EQ(StatusCode::OK_200, res->status);
  13386. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13387. EXPECT_EQ("Hello World!", res->body);
  13388. }
  13389. // set_compress(false) sends every handler response as it is, buffered or
  13390. // streamed
  13391. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13392. const std::string text(1000, 'a');
  13393. Server svr;
  13394. svr.set_compress(false);
  13395. svr.Get("/buffered", [&](const Request &, Response &res) {
  13396. res.set_content(text, "text/plain");
  13397. });
  13398. svr.Get("/streamed", [&](const Request &, Response &res) {
  13399. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13400. sink.write(text.data(), text.size());
  13401. sink.done();
  13402. return true;
  13403. });
  13404. });
  13405. auto port = svr.bind_to_any_port(HOST);
  13406. ASSERT_LT(0, port);
  13407. thread t = thread([&] { svr.listen_after_bind(); });
  13408. auto se = detail::scope_exit([&] {
  13409. svr.stop();
  13410. t.join();
  13411. ASSERT_FALSE(svr.is_running());
  13412. });
  13413. svr.wait_until_ready();
  13414. Client cli(HOST, port);
  13415. cli.set_decompress(false);
  13416. for (auto path : {"/buffered", "/streamed"}) {
  13417. SCOPED_TRACE(path);
  13418. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13420. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13421. EXPECT_EQ(text, res->body);
  13422. }
  13423. }
  13424. // A chunked provider settles its coding where the headers are written and
  13425. // reuses it at write time. Both ends of that have to hold: a handler's own
  13426. // Content-Encoding suppresses the coding, and a response without one is still
  13427. // compressed as it always was.
  13428. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13429. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13430. const std::string plain = "Hello World! Hello World! Hello World!";
  13431. Server svr;
  13432. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13433. res.set_header("Content-Encoding", "gzip");
  13434. res.set_chunked_content_provider(
  13435. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13436. sink.write(gzipped.data(), gzipped.size());
  13437. sink.done();
  13438. return true;
  13439. });
  13440. });
  13441. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13442. res.set_chunked_content_provider(
  13443. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13444. sink.write(plain.data(), plain.size());
  13445. sink.done();
  13446. return true;
  13447. });
  13448. });
  13449. auto port = svr.bind_to_any_port(HOST);
  13450. thread t = thread([&]() { svr.listen_after_bind(); });
  13451. auto se = detail::scope_exit([&] {
  13452. svr.stop();
  13453. t.join();
  13454. ASSERT_FALSE(svr.is_running());
  13455. });
  13456. svr.wait_until_ready();
  13457. Client cli(HOST, port);
  13458. Headers headers = {{"Accept-Encoding", "gzip"}};
  13459. {
  13460. auto res = cli.Get("/pre-gzipped", headers);
  13461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13462. EXPECT_EQ(StatusCode::OK_200, res->status);
  13463. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13464. EXPECT_EQ("Hello World!", res->body);
  13465. }
  13466. {
  13467. auto res = cli.Get("/negotiated", headers);
  13468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13469. EXPECT_EQ(StatusCode::OK_200, res->status);
  13470. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13471. EXPECT_EQ(plain, res->body);
  13472. }
  13473. }
  13474. #endif
  13475. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13476. // the same message as the comma-joined one, so both have to be read the same
  13477. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13478. // single gzip coding, and a body the sender says was encoded twice was handed
  13479. // back after one pass, still compressed but presented as decoded.
  13480. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13481. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13482. Server svr;
  13483. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13484. res.set_content(body, "image/jpeg");
  13485. res.headers.emplace("Content-Encoding", "gzip");
  13486. res.headers.emplace("Content-Encoding", "gzip");
  13487. });
  13488. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13489. res.set_content(body, "image/jpeg");
  13490. res.set_header("Content-Encoding", "gzip, gzip");
  13491. });
  13492. auto port = svr.bind_to_any_port(HOST);
  13493. thread t = thread([&]() { svr.listen_after_bind(); });
  13494. auto se = detail::scope_exit([&] {
  13495. svr.stop();
  13496. t.join();
  13497. ASSERT_FALSE(svr.is_running());
  13498. });
  13499. svr.wait_until_ready();
  13500. Client cli(HOST, port);
  13501. // Two codings is not something cpp-httplib decodes, so both representations
  13502. // take the pass-through path rather than one of them being gunzipped once.
  13503. for (const char *path : {"/split", "/joined"}) {
  13504. auto res = cli.Get(path);
  13505. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13506. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13507. EXPECT_EQ(body, res->body) << path;
  13508. }
  13509. }
  13510. // Regression test for DoS vulnerability: a malicious server sending a response
  13511. // without Content-Length header must not cause unbounded memory consumption on
  13512. // the client side. The client should stop reading after a reasonable limit,
  13513. // similar to the server-side set_payload_max_length protection.
  13514. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13515. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13516. #ifndef _WIN32
  13517. signal(SIGPIPE, SIG_IGN);
  13518. #endif
  13519. auto server_thread = std::thread([] {
  13520. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13521. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13522. default_socket_options(srv);
  13523. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13524. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13525. sockaddr_in addr{};
  13526. addr.sin_family = AF_INET;
  13527. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13528. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13529. int opt = 1;
  13530. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13531. #ifdef _WIN32
  13532. reinterpret_cast<const char *>(&opt),
  13533. #else
  13534. &opt,
  13535. #endif
  13536. sizeof(opt));
  13537. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13538. ::listen(srv, 1);
  13539. sockaddr_in cli_addr{};
  13540. socklen_t cli_len = sizeof(cli_addr);
  13541. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13542. if (cli != INVALID_SOCKET) {
  13543. char buf[4096];
  13544. ::recv(cli, buf, sizeof(buf), 0);
  13545. // Malicious response: no Content-Length, no chunked encoding
  13546. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13547. "Connection: close\r\n"
  13548. "\r\n";
  13549. ::send(cli,
  13550. #ifdef _WIN32
  13551. static_cast<const char *>(response_header.c_str()),
  13552. static_cast<int>(response_header.size()),
  13553. #else
  13554. response_header.c_str(), response_header.size(),
  13555. #endif
  13556. 0);
  13557. // Send 10MB of data
  13558. std::string chunk(64 * 1024, 'A');
  13559. size_t total_sent = 0;
  13560. while (total_sent < MALICIOUS_DATA_SIZE) {
  13561. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13562. auto sent = ::send(cli,
  13563. #ifdef _WIN32
  13564. static_cast<const char *>(chunk.c_str()),
  13565. static_cast<int>(to_send),
  13566. #else
  13567. chunk.c_str(), to_send,
  13568. #endif
  13569. 0);
  13570. if (sent <= 0) break;
  13571. total_sent += static_cast<size_t>(sent);
  13572. }
  13573. detail::close_socket(cli);
  13574. }
  13575. detail::close_socket(srv);
  13576. });
  13577. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13578. size_t total_read = 0;
  13579. {
  13580. Client cli("127.0.0.1", PORT + 2);
  13581. cli.set_read_timeout(5, 0);
  13582. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13583. auto stream = cli.open_stream("GET", "/malicious");
  13584. ASSERT_TRUE(stream.is_valid());
  13585. char buffer[64 * 1024];
  13586. ssize_t n;
  13587. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13588. total_read += static_cast<size_t>(n);
  13589. }
  13590. } // StreamHandle and Client destroyed here, closing the socket
  13591. server_thread.join();
  13592. // With set_payload_max_length, the client must stop reading before consuming
  13593. // all 10MB. The read loop should be cut off at or near the configured limit.
  13594. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13595. << "Client read " << total_read << " bytes, exceeding the configured "
  13596. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13597. }
  13598. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13599. // the entire response body without truncation.
  13600. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13601. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13602. #ifndef _WIN32
  13603. signal(SIGPIPE, SIG_IGN);
  13604. #endif
  13605. auto server_thread = std::thread([] {
  13606. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13607. default_socket_options(srv);
  13608. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13609. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13610. sockaddr_in addr{};
  13611. addr.sin_family = AF_INET;
  13612. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13613. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13614. int opt = 1;
  13615. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13616. #ifdef _WIN32
  13617. reinterpret_cast<const char *>(&opt),
  13618. #else
  13619. &opt,
  13620. #endif
  13621. sizeof(opt));
  13622. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13623. ::listen(srv, 1);
  13624. sockaddr_in cli_addr{};
  13625. socklen_t cli_len = sizeof(cli_addr);
  13626. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13627. if (cli != INVALID_SOCKET) {
  13628. char buf[4096];
  13629. ::recv(cli, buf, sizeof(buf), 0);
  13630. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13631. "Connection: close\r\n"
  13632. "\r\n";
  13633. ::send(cli,
  13634. #ifdef _WIN32
  13635. static_cast<const char *>(response_header.c_str()),
  13636. static_cast<int>(response_header.size()),
  13637. #else
  13638. response_header.c_str(), response_header.size(),
  13639. #endif
  13640. 0);
  13641. std::string chunk(64 * 1024, 'A');
  13642. size_t total_sent = 0;
  13643. while (total_sent < DATA_SIZE) {
  13644. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13645. auto sent = ::send(cli,
  13646. #ifdef _WIN32
  13647. static_cast<const char *>(chunk.c_str()),
  13648. static_cast<int>(to_send),
  13649. #else
  13650. chunk.c_str(), to_send,
  13651. #endif
  13652. 0);
  13653. if (sent <= 0) break;
  13654. total_sent += static_cast<size_t>(sent);
  13655. }
  13656. #ifdef _WIN32
  13657. ::shutdown(cli, SD_SEND);
  13658. #else
  13659. ::shutdown(cli, SHUT_WR);
  13660. #endif
  13661. // Drain until the client closes its end, ensuring all data is delivered
  13662. char drain[1024];
  13663. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13664. detail::close_socket(cli);
  13665. }
  13666. detail::close_socket(srv);
  13667. });
  13668. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13669. size_t total_read = 0;
  13670. {
  13671. Client cli("127.0.0.1", PORT + 2);
  13672. cli.set_read_timeout(5, 0);
  13673. cli.set_payload_max_length(0); // 0 means no limit
  13674. auto stream = cli.open_stream("GET", "/data");
  13675. ASSERT_TRUE(stream.is_valid());
  13676. char buffer[64 * 1024];
  13677. ssize_t n;
  13678. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13679. total_read += static_cast<size_t>(n);
  13680. }
  13681. }
  13682. server_thread.join();
  13683. EXPECT_EQ(total_read, DATA_SIZE)
  13684. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13685. << " bytes without truncation, but only read " << total_read << " bytes.";
  13686. }
  13687. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13688. // enormous Content-Length must not cause the client to pre-allocate a huge
  13689. // response body buffer. The reservation is capped at payload_max_length_, and
  13690. // the read itself fails when the body exceeds the limit.
  13691. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13692. #ifndef _WIN32
  13693. signal(SIGPIPE, SIG_IGN);
  13694. #endif
  13695. auto server_thread = std::thread([] {
  13696. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13697. default_socket_options(srv);
  13698. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13699. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13700. sockaddr_in addr{};
  13701. addr.sin_family = AF_INET;
  13702. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13703. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13704. int opt = 1;
  13705. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13706. #ifdef _WIN32
  13707. reinterpret_cast<const char *>(&opt),
  13708. #else
  13709. &opt,
  13710. #endif
  13711. sizeof(opt));
  13712. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13713. ::listen(srv, 1);
  13714. sockaddr_in cli_addr{};
  13715. socklen_t cli_len = sizeof(cli_addr);
  13716. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13717. if (cli != INVALID_SOCKET) {
  13718. char buf[4096];
  13719. ::recv(cli, buf, sizeof(buf), 0);
  13720. // Malicious response: claim a 20GB body but send only a tiny payload.
  13721. std::string response = "HTTP/1.1 200 OK\r\n"
  13722. "Content-Length: 20000000000\r\n"
  13723. "\r\n"
  13724. "abc";
  13725. ::send(cli,
  13726. #ifdef _WIN32
  13727. static_cast<const char *>(response.c_str()),
  13728. static_cast<int>(response.size()),
  13729. #else
  13730. response.c_str(), response.size(),
  13731. #endif
  13732. 0);
  13733. detail::close_socket(cli);
  13734. }
  13735. detail::close_socket(srv);
  13736. });
  13737. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13738. {
  13739. Client cli("127.0.0.1", PORT + 2);
  13740. cli.set_read_timeout(5, 0);
  13741. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13742. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13743. // (server claims more bytes than payload_max_length permits), but it must
  13744. // not exhaust memory before getting there.
  13745. auto res = cli.Get("/malicious");
  13746. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13747. }
  13748. server_thread.join();
  13749. }
  13750. // Verify that content_receiver bypasses the default payload_max_length,
  13751. // allowing streaming downloads larger than 100MB without requiring an explicit
  13752. // set_payload_max_length call.
  13753. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13754. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13755. #ifndef _WIN32
  13756. signal(SIGPIPE, SIG_IGN);
  13757. #endif
  13758. auto server_thread = std::thread([] {
  13759. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13760. default_socket_options(srv);
  13761. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13763. sockaddr_in addr{};
  13764. addr.sin_family = AF_INET;
  13765. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13766. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13767. int opt = 1;
  13768. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13769. #ifdef _WIN32
  13770. reinterpret_cast<const char *>(&opt),
  13771. #else
  13772. &opt,
  13773. #endif
  13774. sizeof(opt));
  13775. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13776. ::listen(srv, 1);
  13777. sockaddr_in cli_addr{};
  13778. socklen_t cli_len = sizeof(cli_addr);
  13779. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13780. if (cli != INVALID_SOCKET) {
  13781. char buf[4096];
  13782. ::recv(cli, buf, sizeof(buf), 0);
  13783. // Response with Content-Length larger than default 100MB limit
  13784. auto content_length = std::to_string(DATA_SIZE);
  13785. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13786. "Content-Length: " +
  13787. content_length +
  13788. "\r\n"
  13789. "Connection: close\r\n"
  13790. "\r\n";
  13791. ::send(cli,
  13792. #ifdef _WIN32
  13793. static_cast<const char *>(response_header.c_str()),
  13794. static_cast<int>(response_header.size()),
  13795. #else
  13796. response_header.c_str(), response_header.size(),
  13797. #endif
  13798. 0);
  13799. std::string chunk(64 * 1024, 'A');
  13800. size_t total_sent = 0;
  13801. while (total_sent < DATA_SIZE) {
  13802. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13803. auto sent = ::send(cli,
  13804. #ifdef _WIN32
  13805. static_cast<const char *>(chunk.c_str()),
  13806. static_cast<int>(to_send),
  13807. #else
  13808. chunk.c_str(), to_send,
  13809. #endif
  13810. 0);
  13811. if (sent <= 0) break;
  13812. total_sent += static_cast<size_t>(sent);
  13813. }
  13814. detail::close_socket(cli);
  13815. }
  13816. detail::close_socket(srv);
  13817. });
  13818. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13819. size_t total_received = 0;
  13820. {
  13821. Client cli("127.0.0.1", PORT + 2);
  13822. cli.set_read_timeout(10, 0);
  13823. // Do NOT call set_payload_max_length — use the default 100MB limit
  13824. auto res =
  13825. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13826. total_received += data_length;
  13827. return true;
  13828. });
  13829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13830. EXPECT_EQ(StatusCode::OK_200, res->status);
  13831. }
  13832. server_thread.join();
  13833. EXPECT_EQ(total_received, DATA_SIZE)
  13834. << "With content_receiver, the client should read all " << DATA_SIZE
  13835. << " bytes despite the default 100MB payload_max_length, but only read "
  13836. << total_received << " bytes.";
  13837. }
  13838. // Verify that an explicit set_payload_max_length smaller than the response is
  13839. // enforced even when a content_receiver is used.
  13840. TEST(ClientVulnerabilityTest,
  13841. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13842. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13843. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13844. #ifndef _WIN32
  13845. signal(SIGPIPE, SIG_IGN);
  13846. #endif
  13847. auto server_thread = std::thread([] {
  13848. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13849. default_socket_options(srv);
  13850. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13851. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13852. sockaddr_in addr{};
  13853. addr.sin_family = AF_INET;
  13854. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13855. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13856. int opt = 1;
  13857. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13858. #ifdef _WIN32
  13859. reinterpret_cast<const char *>(&opt),
  13860. #else
  13861. &opt,
  13862. #endif
  13863. sizeof(opt));
  13864. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13865. ::listen(srv, 1);
  13866. sockaddr_in cli_addr{};
  13867. socklen_t cli_len = sizeof(cli_addr);
  13868. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13869. if (cli != INVALID_SOCKET) {
  13870. char buf[4096];
  13871. ::recv(cli, buf, sizeof(buf), 0);
  13872. auto content_length = std::to_string(DATA_SIZE);
  13873. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13874. "Content-Length: " +
  13875. content_length +
  13876. "\r\n"
  13877. "Connection: close\r\n"
  13878. "\r\n";
  13879. ::send(cli,
  13880. #ifdef _WIN32
  13881. static_cast<const char *>(response_header.c_str()),
  13882. static_cast<int>(response_header.size()),
  13883. #else
  13884. response_header.c_str(), response_header.size(),
  13885. #endif
  13886. 0);
  13887. std::string chunk(64 * 1024, 'A');
  13888. size_t total_sent = 0;
  13889. while (total_sent < DATA_SIZE) {
  13890. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13891. auto sent = ::send(cli,
  13892. #ifdef _WIN32
  13893. static_cast<const char *>(chunk.c_str()),
  13894. static_cast<int>(to_send),
  13895. #else
  13896. chunk.c_str(), to_send,
  13897. #endif
  13898. 0);
  13899. if (sent <= 0) break;
  13900. total_sent += static_cast<size_t>(sent);
  13901. }
  13902. detail::close_socket(cli);
  13903. }
  13904. detail::close_socket(srv);
  13905. });
  13906. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13907. size_t total_received = 0;
  13908. {
  13909. Client cli("127.0.0.1", PORT + 2);
  13910. cli.set_read_timeout(10, 0);
  13911. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13912. auto res =
  13913. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13914. total_received += data_length;
  13915. return true;
  13916. });
  13917. // Should fail because 200MB exceeds the explicit 150MB limit
  13918. EXPECT_FALSE(res);
  13919. }
  13920. server_thread.join();
  13921. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13922. << "Client with content_receiver should respect the explicit "
  13923. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13924. << total_received << " bytes.";
  13925. }
  13926. // Verify that an explicit set_payload_max_length larger than the response
  13927. // allows the content_receiver to read all data successfully.
  13928. TEST(ClientVulnerabilityTest,
  13929. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13930. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13931. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13932. #ifndef _WIN32
  13933. signal(SIGPIPE, SIG_IGN);
  13934. #endif
  13935. auto server_thread = std::thread([] {
  13936. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13937. default_socket_options(srv);
  13938. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13939. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13940. sockaddr_in addr{};
  13941. addr.sin_family = AF_INET;
  13942. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13943. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13944. int opt = 1;
  13945. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13946. #ifdef _WIN32
  13947. reinterpret_cast<const char *>(&opt),
  13948. #else
  13949. &opt,
  13950. #endif
  13951. sizeof(opt));
  13952. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13953. ::listen(srv, 1);
  13954. sockaddr_in cli_addr{};
  13955. socklen_t cli_len = sizeof(cli_addr);
  13956. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13957. if (cli != INVALID_SOCKET) {
  13958. char buf[4096];
  13959. ::recv(cli, buf, sizeof(buf), 0);
  13960. auto content_length = std::to_string(DATA_SIZE);
  13961. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13962. "Content-Length: " +
  13963. content_length +
  13964. "\r\n"
  13965. "Connection: close\r\n"
  13966. "\r\n";
  13967. ::send(cli,
  13968. #ifdef _WIN32
  13969. static_cast<const char *>(response_header.c_str()),
  13970. static_cast<int>(response_header.size()),
  13971. #else
  13972. response_header.c_str(), response_header.size(),
  13973. #endif
  13974. 0);
  13975. std::string chunk(64 * 1024, 'A');
  13976. size_t total_sent = 0;
  13977. while (total_sent < DATA_SIZE) {
  13978. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13979. auto sent = ::send(cli,
  13980. #ifdef _WIN32
  13981. static_cast<const char *>(chunk.c_str()),
  13982. static_cast<int>(to_send),
  13983. #else
  13984. chunk.c_str(), to_send,
  13985. #endif
  13986. 0);
  13987. if (sent <= 0) break;
  13988. total_sent += static_cast<size_t>(sent);
  13989. }
  13990. #ifdef _WIN32
  13991. ::shutdown(cli, SD_SEND);
  13992. #else
  13993. ::shutdown(cli, SHUT_WR);
  13994. #endif
  13995. char drain[1024];
  13996. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13997. detail::close_socket(cli);
  13998. }
  13999. detail::close_socket(srv);
  14000. });
  14001. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14002. size_t total_received = 0;
  14003. {
  14004. Client cli("127.0.0.1", PORT + 2);
  14005. cli.set_read_timeout(10, 0);
  14006. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14007. auto res =
  14008. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14009. total_received += data_length;
  14010. return true;
  14011. });
  14012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14013. EXPECT_EQ(StatusCode::OK_200, res->status);
  14014. }
  14015. server_thread.join();
  14016. EXPECT_EQ(total_received, DATA_SIZE)
  14017. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14018. << " bytes (larger than " << DATA_SIZE
  14019. << " bytes response), content_receiver should read all data, but only "
  14020. "read "
  14021. << total_received << " bytes.";
  14022. }
  14023. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14024. // Regression test for "zip bomb" attack on the client side: a malicious server
  14025. // sends a small gzip-compressed response that decompresses to a huge payload.
  14026. // The client must enforce payload_max_length on the decompressed size.
  14027. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14028. constexpr size_t DECOMPRESSED_SIZE =
  14029. 10 * 1024 * 1024; // 10MB after decompression
  14030. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14031. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14032. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14033. std::string compressed;
  14034. {
  14035. httplib::detail::gzip_compressor compressor;
  14036. bool ok =
  14037. compressor.compress(uncompressed.data(), uncompressed.size(),
  14038. /*last=*/true, [&](const char *buf, size_t len) {
  14039. compressed.append(buf, len);
  14040. return true;
  14041. });
  14042. ASSERT_TRUE(ok);
  14043. }
  14044. // Sanity: compressed data should be much smaller than the decompressed size
  14045. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14046. #ifndef _WIN32
  14047. signal(SIGPIPE, SIG_IGN);
  14048. #endif
  14049. // Set up the listening socket in the main thread so the server is guaranteed
  14050. // to be ready before the client connects (eliminates race condition).
  14051. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14052. default_socket_options(srv);
  14053. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14054. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14055. sockaddr_in addr{};
  14056. addr.sin_family = AF_INET;
  14057. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14058. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14059. int opt = 1;
  14060. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14061. #ifdef _WIN32
  14062. reinterpret_cast<const char *>(&opt),
  14063. #else
  14064. &opt,
  14065. #endif
  14066. sizeof(opt));
  14067. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14068. ASSERT_EQ(0, ::listen(srv, 1));
  14069. auto server_thread = std::thread([&compressed, srv] {
  14070. sockaddr_in cli_addr{};
  14071. socklen_t cli_len = sizeof(cli_addr);
  14072. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14073. if (cli != INVALID_SOCKET) {
  14074. // Read the full HTTP request (until \r\n\r\n)
  14075. char buf[4096];
  14076. size_t total = 0;
  14077. while (total < sizeof(buf)) {
  14078. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14079. if (n <= 0) break;
  14080. total += static_cast<size_t>(n);
  14081. // Check for end of headers
  14082. if (total >= 4) {
  14083. std::string req(buf, total);
  14084. if (req.find("\r\n\r\n") != std::string::npos) break;
  14085. }
  14086. }
  14087. // Malicious response: gzip-compressed body, no Content-Length
  14088. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14089. "Content-Encoding: gzip\r\n"
  14090. "Connection: close\r\n"
  14091. "\r\n";
  14092. ::send(cli,
  14093. #ifdef _WIN32
  14094. static_cast<const char *>(response_header.c_str()),
  14095. static_cast<int>(response_header.size()),
  14096. #else
  14097. response_header.c_str(), response_header.size(),
  14098. #endif
  14099. 0);
  14100. // Send the compressed payload (small on the wire, huge when decompressed)
  14101. size_t total_sent = 0;
  14102. while (total_sent < compressed.size()) {
  14103. auto to_send = std::min(compressed.size() - total_sent,
  14104. static_cast<size_t>(64 * 1024));
  14105. auto sent =
  14106. ::send(cli,
  14107. #ifdef _WIN32
  14108. static_cast<const char *>(compressed.c_str() + total_sent),
  14109. static_cast<int>(to_send),
  14110. #else
  14111. compressed.c_str() + total_sent, to_send,
  14112. #endif
  14113. 0);
  14114. if (sent <= 0) break;
  14115. total_sent += static_cast<size_t>(sent);
  14116. }
  14117. detail::close_socket(cli);
  14118. }
  14119. });
  14120. auto se = detail::scope_exit([&] {
  14121. detail::close_socket(srv);
  14122. server_thread.join();
  14123. });
  14124. size_t total_decompressed = 0;
  14125. {
  14126. Client cli("127.0.0.1", PORT + 3);
  14127. cli.set_read_timeout(5, 0);
  14128. cli.set_decompress(true);
  14129. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14130. auto stream = cli.open_stream("GET", "/zipbomb");
  14131. ASSERT_TRUE(stream.is_valid());
  14132. char buffer[64 * 1024];
  14133. ssize_t n;
  14134. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14135. total_decompressed += static_cast<size_t>(n);
  14136. }
  14137. }
  14138. // The decompressed size must be capped by payload_max_length. Without
  14139. // protection, the client would decompress the full 10MB from a tiny
  14140. // compressed payload, enabling a zip bomb DoS attack.
  14141. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14142. << "Client decompressed " << total_decompressed
  14143. << " bytes from a gzip response. The decompressed size should be "
  14144. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14145. }
  14146. #endif
  14147. TEST(HostAndPortPropertiesTest, NoSSL) {
  14148. httplib::Client cli("www.google.com", 1234);
  14149. ASSERT_EQ("www.google.com", cli.host());
  14150. ASSERT_EQ(1234, cli.port());
  14151. }
  14152. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14153. httplib::Client cli("www.google.com:1234");
  14154. ASSERT_EQ("www.google.com", cli.host());
  14155. ASSERT_EQ(1234, cli.port());
  14156. }
  14157. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14158. // Port number that overflows int — should not crash, client becomes invalid
  14159. httplib::Client cli("http://www.google.com:99999999999999999999");
  14160. ASSERT_FALSE(cli.is_valid());
  14161. }
  14162. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14163. // Port 99999 exceeds valid range (1-65535) — should not crash
  14164. httplib::Client cli("http://www.google.com:99999");
  14165. ASSERT_FALSE(cli.is_valid());
  14166. auto res = cli.Get("/");
  14167. EXPECT_FALSE(res);
  14168. EXPECT_EQ(Error::Connection, res.error());
  14169. }
  14170. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14171. httplib::Client cli("http://user:pass@localhost:1234");
  14172. ASSERT_FALSE(cli.is_valid());
  14173. EXPECT_FALSE(cli.Get("/"));
  14174. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14175. }
  14176. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14177. httplib::Client cli("http://www.google.com:80abc");
  14178. ASSERT_FALSE(cli.is_valid());
  14179. }
  14180. #ifdef CPPHTTPLIB_SSL_ENABLED
  14181. TEST(HostAndPortPropertiesTest, SSL) {
  14182. httplib::SSLClient cli("www.google.com");
  14183. ASSERT_EQ("www.google.com", cli.host());
  14184. ASSERT_EQ(443, cli.port());
  14185. }
  14186. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14187. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14188. std::string cert;
  14189. read_file(CA_CERT_FILE, cert);
  14190. httplib::SSLClient httplib_client("www.google.com");
  14191. // Load CA store first time
  14192. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14193. // Load CA store second time (update)
  14194. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14195. // Verify client is still valid and can make connections
  14196. httplib_client.enable_server_certificate_verification(true);
  14197. auto res = httplib_client.Get("/");
  14198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14199. // Google may return 200 or 301 depending on various factors
  14200. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  14201. res->status == StatusCode::MovedPermanently_301);
  14202. }
  14203. TEST(SSLClientTest, ServerNameIndication_Online) {
  14204. auto host = "httpbingo.org";
  14205. auto path = std::string{"/get"};
  14206. SSLClient cli(host, 443);
  14207. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  14208. SKIP_ON_GATEWAY_ERROR(res);
  14209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14210. ASSERT_EQ(StatusCode::OK_200, res->status);
  14211. }
  14212. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14213. // Use a site that will cause SSL verification failure due to self-signed cert
  14214. SSLClient cli("self-signed.badssl.com", 443);
  14215. cli.enable_server_certificate_verification(true);
  14216. auto res = cli.Get("/");
  14217. ASSERT_TRUE(!res);
  14218. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14219. // Verify backend error is captured for SSLServerVerification
  14220. // This occurs when certificate verification fails
  14221. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14222. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14223. EXPECT_NE(0UL, res.ssl_backend_error());
  14224. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14225. res.ssl_error());
  14226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14227. #if !defined(_WIN32) || \
  14228. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14229. // On non-Windows or when Windows Schannel is disabled, the error comes
  14230. // from OpenSSL's verification
  14231. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14232. res.ssl_backend_error());
  14233. #endif
  14234. #endif
  14235. }
  14236. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14237. // Use a site where hostname doesn't match the certificate
  14238. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14239. SSLClient cli("wrong.host.badssl.com", 443);
  14240. cli.enable_server_certificate_verification(true);
  14241. cli.enable_server_hostname_verification(true);
  14242. auto res = cli.Get("/");
  14243. ASSERT_TRUE(!res);
  14244. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14245. // Verify backend error is captured for hostname verification failure
  14246. EXPECT_NE(0UL, res.ssl_backend_error());
  14247. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14248. res.ssl_error());
  14249. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14250. #if !defined(_WIN32) || \
  14251. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14252. // On non-Windows or when Windows Schannel is disabled, the error comes
  14253. // from OpenSSL's hostname verification
  14254. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14255. res.ssl_backend_error());
  14256. #endif
  14257. #endif
  14258. }
  14259. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14260. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14261. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14262. SSLClient cli("www.google.com", 443);
  14263. cli.enable_server_certificate_verification(true);
  14264. auto res = cli.Get("/");
  14265. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14266. }
  14267. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14268. SSLClient cli("www.google.com", 443);
  14269. cli.enable_server_certificate_verification(true);
  14270. cli.enable_windows_certificate_verification(false);
  14271. auto res = cli.Get("/");
  14272. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14273. }
  14274. // The server sends an intermediate cross-signed by a root Windows trusts,
  14275. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14276. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14277. SSLClient cli("accounts.spotify.com", 443);
  14278. auto res = cli.Get("/");
  14279. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14280. << " ssl_backend_error=" << res.ssl_backend_error();
  14281. }
  14282. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14283. // policy status, which no backend reports for a self-signed certificate.
  14284. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14285. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14286. ASSERT_TRUE(svr.is_valid());
  14287. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14288. auto se = detail::scope_exit([&] {
  14289. svr.stop();
  14290. t.join();
  14291. ASSERT_FALSE(svr.is_running());
  14292. });
  14293. svr.wait_until_ready();
  14294. SSLClient cli("127.0.0.1", PORT);
  14295. cli.set_connection_timeout(30);
  14296. auto res = cli.Get("/");
  14297. ASSERT_FALSE(res);
  14298. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14299. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14300. }
  14301. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14302. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14303. ASSERT_TRUE(svr.is_valid());
  14304. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14305. auto se = detail::scope_exit([&] {
  14306. svr.stop();
  14307. t.join();
  14308. ASSERT_FALSE(svr.is_running());
  14309. });
  14310. svr.wait_until_ready();
  14311. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14312. {
  14313. ws::WebSocketClient client(url);
  14314. auto res = client.connect();
  14315. ASSERT_FALSE(res);
  14316. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14317. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14318. res.ssl_backend_error());
  14319. }
  14320. {
  14321. ws::WebSocketClient client(url);
  14322. client.enable_windows_certificate_verification(false);
  14323. auto res = client.connect();
  14324. ASSERT_FALSE(res);
  14325. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14326. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14327. res.ssl_backend_error());
  14328. }
  14329. }
  14330. #endif
  14331. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14332. Client cli("https://google.com");
  14333. auto res = cli.Get("/");
  14334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14335. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14336. }
  14337. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14338. SSLClient cli("google.com");
  14339. cli.set_ca_cert_path(CA_CERT_FILE);
  14340. auto res = cli.Get("/");
  14341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14342. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14343. }
  14344. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14345. SSLClient cli("google.com");
  14346. cli.enable_server_certificate_verification(true);
  14347. cli.set_ca_cert_path("hello");
  14348. auto res = cli.Get("/");
  14349. ASSERT_TRUE(!res);
  14350. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14351. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14352. // should be set
  14353. EXPECT_EQ(0, res.ssl_error());
  14354. // Verify backend error is captured for SSLLoadingCerts
  14355. // This error occurs when loading CA certificates fails
  14356. EXPECT_NE(0UL, res.ssl_backend_error());
  14357. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14358. // OpenSSL specific error codes:
  14359. // > openssl errstr 0x80000002
  14360. // error:80000002:system library::No such file or directory
  14361. // > openssl errstr 0xA000126
  14362. // error:0A000126:SSL routines::unexpected eof while reading
  14363. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14364. res.ssl_backend_error() == 0xA000126);
  14365. #endif
  14366. }
  14367. TEST(SSLClientTest, ServerCertificateVerification4) {
  14368. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14369. ASSERT_TRUE(svr.is_valid());
  14370. svr.Get("/test", [&](const Request &, Response &res) {
  14371. res.set_content("test", "text/plain");
  14372. svr.stop();
  14373. ASSERT_TRUE(true);
  14374. });
  14375. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14376. auto se = detail::scope_exit([&] {
  14377. t.join();
  14378. ASSERT_FALSE(svr.is_running());
  14379. });
  14380. svr.wait_until_ready();
  14381. SSLClient cli("127.0.0.1", PORT);
  14382. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14383. cli.enable_server_certificate_verification(true);
  14384. cli.set_connection_timeout(30);
  14385. auto res = cli.Get("/test");
  14386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14387. ASSERT_EQ(StatusCode::OK_200, res->status);
  14388. }
  14389. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14390. std::string cert;
  14391. read_file(CA_CERT_FILE, cert);
  14392. SSLClient cli("google.com");
  14393. cli.load_ca_cert_store(cert.data(), cert.size());
  14394. const auto res = cli.Get("/");
  14395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14396. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14397. }
  14398. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14399. // clang-format off
  14400. static constexpr char cert[] =
  14401. "GlobalSign Root CA\n"
  14402. "==================\n"
  14403. "-----BEGIN CERTIFICATE-----\n"
  14404. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14405. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14406. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14407. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14408. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14409. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14410. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14411. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14412. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14413. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14414. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14415. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14416. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14417. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14418. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14419. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14420. "-----END CERTIFICATE-----\n";
  14421. // clang-format on
  14422. SSLClient cli("google.com");
  14423. cli.load_ca_cert_store(cert, sizeof(cert));
  14424. const auto res = cli.Get("/");
  14425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14426. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14427. }
  14428. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14429. SSLClient cli("www.youtube.com");
  14430. cli.set_ca_cert_path(CA_CERT_FILE);
  14431. cli.enable_server_certificate_verification(true);
  14432. cli.set_follow_location(true);
  14433. auto res = cli.Get("/");
  14434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14435. ASSERT_EQ(StatusCode::OK_200, res->status);
  14436. }
  14437. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14438. SSLClient cli("wWw.YouTube.Com");
  14439. cli.set_ca_cert_path(CA_CERT_FILE);
  14440. cli.enable_server_certificate_verification(true);
  14441. cli.enable_server_hostname_verification(true);
  14442. cli.set_follow_location(true);
  14443. auto res = cli.Get("/");
  14444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14445. ASSERT_EQ(StatusCode::OK_200, res->status);
  14446. }
  14447. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14448. SSLClient cli("gOoGlE.COm");
  14449. cli.enable_server_certificate_verification(true);
  14450. cli.enable_server_hostname_verification(true);
  14451. cli.set_follow_location(true);
  14452. auto res = cli.Get("/");
  14453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14454. ASSERT_EQ(StatusCode::OK_200, res->status);
  14455. }
  14456. TEST(SSLClientTest, Issue2004_Online) {
  14457. Client client("https://google.com");
  14458. client.set_follow_location(true);
  14459. auto res = client.Get("/");
  14460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14461. ASSERT_EQ(StatusCode::OK_200, res->status);
  14462. auto body = res->body;
  14463. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  14464. }
  14465. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14466. // Create SSLClient with invalid cert/key to make is_valid() return false
  14467. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14468. "nonexistent_key.pem");
  14469. // is_valid() should be false due to cert loading failure
  14470. ASSERT_FALSE(cli.is_valid());
  14471. auto res = cli.Get("/");
  14472. ASSERT_FALSE(res);
  14473. EXPECT_EQ(Error::SSLConnection, res.error());
  14474. }
  14475. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14476. // Test for Issue #2251: SSL error not properly reported when client cert
  14477. // and key paths are swapped or mismatched
  14478. // This simulates the scenario where user accidentally swaps the cert and key
  14479. // files
  14480. // Using client cert file as private key and vice versa (completely wrong)
  14481. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14482. // Should fail validation due to cert/key mismatch
  14483. ASSERT_FALSE(cli.is_valid());
  14484. // Attempt to make a request should fail with proper error
  14485. auto res = cli.Get("/");
  14486. ASSERT_FALSE(res);
  14487. EXPECT_EQ(Error::SSLConnection, res.error());
  14488. // SSL error should be recorded in the Result object (this is the key fix for
  14489. // Issue #2251)
  14490. auto backend_error = res.ssl_backend_error();
  14491. EXPECT_NE(0u, backend_error);
  14492. }
  14493. // Tests cert/key mismatch detection at the TLS context level
  14494. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14495. // Test that using mismatched cert/key causes connection failure.
  14496. // We verify this at the SSLClient level rather than through internal
  14497. // TLS API functions.
  14498. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14499. cli.enable_server_certificate_verification(false);
  14500. cli.set_connection_timeout(2);
  14501. // The mismatch should cause a connection or handshake error
  14502. auto res = cli.Get("/test");
  14503. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14504. // Either way, the request should fail
  14505. EXPECT_FALSE(res);
  14506. }
  14507. #endif
  14508. #if 0
  14509. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14510. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14511. ASSERT_TRUE(cli != nullptr);
  14512. cli->set_address_family(AF_INET6);
  14513. cli->set_interface("en0");
  14514. auto res = cli->Get("/get");
  14515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14516. ASSERT_EQ(StatusCode::OK_200, res->status);
  14517. }
  14518. #endif
  14519. // Client certificate tests - work with all TLS backends
  14520. #ifdef CPPHTTPLIB_SSL_ENABLED
  14521. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14522. void ClientCertPresent(
  14523. const std::string &client_cert_file,
  14524. const std::string &client_private_key_file,
  14525. const std::string &client_encrypted_private_key_pass = std::string(),
  14526. const ClientCertServerSetup &setup = nullptr) {
  14527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14528. ASSERT_TRUE(svr.is_valid());
  14529. if (setup) { setup(svr); }
  14530. svr.Get("/test", [&](const Request &req, Response &res) {
  14531. res.set_content("test", "text/plain");
  14532. auto cert = req.peer_cert();
  14533. ASSERT_TRUE(static_cast<bool>(cert));
  14534. std::string common_name = cert.subject_cn();
  14535. EXPECT_EQ("Common Name", common_name);
  14536. });
  14537. auto port = svr.bind_to_any_port(HOST);
  14538. ASSERT_LT(0, port);
  14539. thread t = thread([&]() { svr.listen_after_bind(); });
  14540. auto se = detail::scope_exit([&] {
  14541. svr.stop();
  14542. t.join();
  14543. ASSERT_FALSE(svr.is_running());
  14544. });
  14545. svr.wait_until_ready();
  14546. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14547. client_encrypted_private_key_pass);
  14548. cli.enable_server_certificate_verification(false);
  14549. cli.set_connection_timeout(30);
  14550. auto res = cli.Get("/test");
  14551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14552. ASSERT_EQ(StatusCode::OK_200, res->status);
  14553. }
  14554. TEST(SSLClientServerTest, ClientCertPresent) {
  14555. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14556. }
  14557. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14558. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14559. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14560. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14561. }
  14562. // Expects svr, which must require client certificates, to reject a client
  14563. // that has none
  14564. void RejectsClientWithoutCert(SSLServer &svr) {
  14565. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14566. auto port = svr.bind_to_any_port(HOST);
  14567. ASSERT_LT(0, port);
  14568. thread t = thread([&]() { svr.listen_after_bind(); });
  14569. auto se = detail::scope_exit([&] {
  14570. svr.stop();
  14571. t.join();
  14572. ASSERT_FALSE(svr.is_running());
  14573. });
  14574. svr.wait_until_ready();
  14575. SSLClient cli(HOST, port);
  14576. cli.set_connection_timeout(30);
  14577. // Skip the server certificate check, so that the request fails because the
  14578. // client certificate is missing rather than because cert.pem is not trusted
  14579. cli.enable_server_certificate_verification(false);
  14580. auto res = cli.Get("/test");
  14581. ASSERT_FALSE(res);
  14582. // The server rejects the client during the handshake, or on TLS 1.3 right
  14583. // after it, which the client notices on its first write or read
  14584. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14585. res.error() == Error::Write || res.error() == Error::Read)
  14586. << to_string(res.error());
  14587. if (res.error() == Error::SSLConnection) {
  14588. EXPECT_NE(0UL, res.ssl_backend_error());
  14589. }
  14590. // A rejection noticed on the write keeps the TLS error the write hit
  14591. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14592. }
  14593. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14594. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14595. ASSERT_TRUE(svr.is_valid());
  14596. if (setup) { setup(svr); }
  14597. RejectsClientWithoutCert(svr);
  14598. }
  14599. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14600. // A server that requires client certificates must keep requiring them after
  14601. // setup changes it, and keep accepting a client that has one
  14602. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14603. ClientCertMissing(setup);
  14604. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14605. setup);
  14606. }
  14607. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14608. ClientCertStillRequired([](SSLServer &svr) {
  14609. ASSERT_TRUE(tls::set_verify_callback(
  14610. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14611. });
  14612. }
  14613. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14614. ClientCertStillRequired([](SSLServer &svr) {
  14615. ASSERT_TRUE(tls::set_verify_callback(
  14616. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14617. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14618. });
  14619. }
  14620. // The client verifies the server certificate during the handshake, so a
  14621. // server that fails the check never gets the client certificate, even when a
  14622. // verifier of the client's own accepts it
  14623. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14624. struct Case {
  14625. const char *trusted_ca;
  14626. const char *host;
  14627. Error error;
  14628. };
  14629. // cert2.pem names localhost: the first client does not trust it, and the
  14630. // second trusts it but asks for another name
  14631. for (const auto &c :
  14632. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14633. Case{SERVER_CERT2_FILE, "example.com",
  14634. Error::SSLServerHostnameVerification}}) {
  14635. for (auto with_verifier : {false, true}) {
  14636. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14637. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14638. CLIENT_CA_CERT_FILE);
  14639. ASSERT_TRUE(svr.is_valid());
  14640. std::atomic<bool> got_client_cert{false};
  14641. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14642. [&](const tls::VerifyContext &) {
  14643. got_client_cert = true;
  14644. return true;
  14645. }));
  14646. auto port = svr.bind_to_any_port("127.0.0.1");
  14647. ASSERT_LT(0, port);
  14648. thread t = thread([&] { svr.listen_after_bind(); });
  14649. svr.wait_until_ready();
  14650. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14651. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14652. cli.set_ca_cert_path(c.trusted_ca);
  14653. if (with_verifier) {
  14654. cli.set_server_certificate_verifier(
  14655. [](const tls::VerifyContext &) { return true; });
  14656. }
  14657. auto res = cli.Get("/");
  14658. EXPECT_FALSE(res);
  14659. EXPECT_EQ(c.error, res.error());
  14660. svr.stop();
  14661. t.join();
  14662. EXPECT_FALSE(got_client_cert);
  14663. }
  14664. }
  14665. }
  14666. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14667. std::string cert_pem, key_pem, ca_pem;
  14668. read_file(SERVER_CERT_FILE, cert_pem);
  14669. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14670. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14671. ASSERT_TRUE(
  14672. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14673. }
  14674. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14676. ASSERT_TRUE(svr.is_valid());
  14677. UpdateCertsPemWithClientCA(svr);
  14678. RejectsClientWithoutCert(svr);
  14679. }
  14680. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14681. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14682. }
  14683. // A TLS error from one request must not show up in a later request's Result
  14684. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14685. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14686. ASSERT_TRUE(svr.is_valid());
  14687. svr.Get("/test", [](const Request &, Response &res) {
  14688. res.set_content("test", "text/plain");
  14689. });
  14690. auto port = svr.bind_to_any_port(HOST);
  14691. ASSERT_LT(0, port);
  14692. thread t = thread([&]() { svr.listen_after_bind(); });
  14693. auto se = detail::scope_exit([&] {
  14694. svr.stop();
  14695. t.join();
  14696. ASSERT_FALSE(svr.is_running());
  14697. });
  14698. svr.wait_until_ready();
  14699. SSLClient cli(HOST, port);
  14700. cli.set_connection_timeout(30);
  14701. cli.enable_server_hostname_verification(false);
  14702. // cert.pem is not trusted, so the handshake fails
  14703. ASSERT_FALSE(cli.Get("/test"));
  14704. cli.enable_server_certificate_verification(false);
  14705. auto res = cli.Get("/test");
  14706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14707. EXPECT_EQ(0, res.ssl_error());
  14708. EXPECT_EQ(0UL, res.ssl_backend_error());
  14709. }
  14710. // PEM memory-based constructor tests (works with all TLS backends).
  14711. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14712. // terminator after it.
  14713. void PemMemoryClientCertPresent(
  14714. const std::string &client_cert_file,
  14715. const std::string &client_private_key_file,
  14716. const std::string &client_encrypted_private_key_pass = std::string(),
  14717. bool exact_size = false) {
  14718. // Read PEM files into memory
  14719. std::string server_cert_pem, server_key_pem;
  14720. std::string client_ca_pem;
  14721. std::string client_cert_pem, client_key_pem;
  14722. read_file(SERVER_CERT_FILE, server_cert_pem);
  14723. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14724. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14725. read_file(client_cert_file, client_cert_pem);
  14726. read_file(client_private_key_file, client_key_pem);
  14727. std::list<std::vector<char>> exact_copies;
  14728. auto data = [&](const std::string &pem) -> const char * {
  14729. if (!exact_size) { return pem.c_str(); }
  14730. exact_copies.emplace_back(pem.begin(), pem.end());
  14731. return exact_copies.back().data();
  14732. };
  14733. // Create server with PEM memory
  14734. SSLServer::PemMemory server_pem = {
  14735. data(server_cert_pem),
  14736. server_cert_pem.size(),
  14737. data(server_key_pem),
  14738. server_key_pem.size(),
  14739. data(client_ca_pem),
  14740. client_ca_pem.size(),
  14741. nullptr // no password for server key
  14742. };
  14743. SSLServer svr(server_pem);
  14744. ASSERT_TRUE(svr.is_valid());
  14745. svr.Get("/test", [&](const Request &req, Response &res) {
  14746. res.set_content("test", "text/plain");
  14747. auto cert = req.peer_cert();
  14748. ASSERT_TRUE(static_cast<bool>(cert));
  14749. EXPECT_EQ("Common Name", cert.subject_cn());
  14750. });
  14751. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14752. auto se = detail::scope_exit([&] {
  14753. svr.stop();
  14754. t.join();
  14755. ASSERT_FALSE(svr.is_running());
  14756. });
  14757. svr.wait_until_ready();
  14758. // Create client with PEM memory
  14759. const char *password = client_encrypted_private_key_pass.empty()
  14760. ? nullptr
  14761. : client_encrypted_private_key_pass.c_str();
  14762. SSLClient::PemMemory client_pem = {
  14763. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14764. client_key_pem.size(), password};
  14765. SSLClient cli(HOST, PORT, client_pem);
  14766. cli.enable_server_certificate_verification(false);
  14767. cli.set_connection_timeout(30);
  14768. auto res = cli.Get("/test");
  14769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14770. ASSERT_EQ(StatusCode::OK_200, res->status);
  14771. }
  14772. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14773. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14774. }
  14775. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14776. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14777. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14778. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14779. }
  14780. // A server built from PEM memory with a client CA requires client certificates,
  14781. // also when the CA is a NUL-terminated string passed with a length of 0
  14782. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14783. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14784. read_file(SERVER_CERT_FILE, server_cert_pem);
  14785. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14786. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14787. SSLServer::PemMemory server_pem = {
  14788. server_cert_pem.c_str(),
  14789. server_cert_pem.size(),
  14790. server_key_pem.c_str(),
  14791. server_key_pem.size(),
  14792. client_ca_pem.c_str(),
  14793. client_ca_pem.size(),
  14794. nullptr // no password for server key
  14795. };
  14796. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14797. SCOPED_TRACE(client_ca_pem_len);
  14798. server_pem.client_ca_pem_len = client_ca_pem_len;
  14799. SSLServer svr(server_pem);
  14800. ASSERT_TRUE(svr.is_valid());
  14801. RejectsClientWithoutCert(svr);
  14802. }
  14803. // An empty CA fails to load instead of turning the check off
  14804. server_pem.client_ca_pem = "";
  14805. server_pem.client_ca_pem_len = 0;
  14806. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14807. }
  14808. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14809. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14810. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14811. true);
  14812. }
  14813. // A length shorter than the PEM cuts it short, so it no longer loads
  14814. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14815. std::string cert, key;
  14816. read_file(SERVER_CERT_FILE, cert);
  14817. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14818. for (auto cut_cert : {true, false}) {
  14819. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14820. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14821. SSLServer::PemMemory server_pem = {
  14822. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14823. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14824. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14825. key_len, nullptr};
  14826. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14827. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14828. key.c_str(), key_len, nullptr};
  14829. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14830. }
  14831. }
  14832. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14833. class NoListenSSLServer : public SSLServer {
  14834. public:
  14835. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14836. const char *client_ca_cert_file_path,
  14837. const char *client_ca_cert_dir_path = nullptr)
  14838. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14839. client_ca_cert_dir_path),
  14840. stop_(false) {}
  14841. std::atomic_bool stop_;
  14842. private:
  14843. bool process_and_close_socket(socket_t /*sock*/) override {
  14844. // Don't create SSL context
  14845. while (!stop_.load()) {
  14846. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14847. }
  14848. return true;
  14849. }
  14850. };
  14851. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14852. CLIENT_CA_CERT_FILE);
  14853. ASSERT_TRUE(svr.is_valid());
  14854. // Keep-alive parking would bypass the override.
  14855. svr.set_keep_alive_parking(false);
  14856. svr.Get("/test", [&](const Request &, Response &res) {
  14857. res.set_content("test", "text/plain");
  14858. });
  14859. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14860. auto se = detail::scope_exit([&] {
  14861. svr.stop_ = true;
  14862. svr.stop();
  14863. t.join();
  14864. ASSERT_FALSE(svr.is_running());
  14865. });
  14866. svr.wait_until_ready();
  14867. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14868. cli.enable_server_certificate_verification(false);
  14869. cli.set_connection_timeout(1);
  14870. auto res = cli.Get("/test");
  14871. ASSERT_TRUE(!res);
  14872. EXPECT_EQ(Error::SSLConnection, res.error());
  14873. // Timeout results in WantRead error code (maps to backend-specific value)
  14874. EXPECT_NE(0, res.ssl_error());
  14875. }
  14876. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14877. // Test SSLServer with client certificate verification using the standard
  14878. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14879. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14880. CLIENT_CA_CERT_DIR);
  14881. ASSERT_TRUE(svr.is_valid());
  14882. svr.Get("/test", [&](const Request &req, Response &res) {
  14883. res.set_content("test", "text/plain");
  14884. auto cert = req.peer_cert();
  14885. ASSERT_TRUE(static_cast<bool>(cert));
  14886. auto common_name = cert.subject_cn();
  14887. EXPECT_EQ("Common Name", common_name);
  14888. });
  14889. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14890. auto se = detail::scope_exit([&] {
  14891. svr.stop();
  14892. t.join();
  14893. ASSERT_FALSE(svr.is_running());
  14894. });
  14895. svr.wait_until_ready();
  14896. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14897. cli.enable_server_certificate_verification(false);
  14898. cli.set_connection_timeout(30);
  14899. auto res = cli.Get("/test");
  14900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14901. ASSERT_EQ(StatusCode::OK_200, res->status);
  14902. }
  14903. // Test verify_hostname on every backend: a host is named by a SAN only
  14904. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14905. using namespace httplib::tls;
  14906. // We need a running server to test against
  14907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14908. ASSERT_TRUE(svr.is_valid());
  14909. svr.Get("/test", [](const Request &, Response &res) {
  14910. res.set_content("ok", "text/plain");
  14911. });
  14912. thread t([&]() { svr.listen(HOST, PORT); });
  14913. auto se = detail::scope_exit([&] {
  14914. svr.stop();
  14915. t.join();
  14916. });
  14917. svr.wait_until_ready();
  14918. bool verify_callback_called = false;
  14919. bool verify_result_wrong = false;
  14920. SSLClient cli(HOST, PORT);
  14921. cli.enable_server_certificate_verification(true);
  14922. cli.set_ca_cert_path(CA_CERT_FILE);
  14923. cli.set_connection_timeout(5);
  14924. // Note: Test certificate has CN="Common Name", not "localhost"
  14925. bool verify_result_cn = false;
  14926. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14927. verify_callback_called = true;
  14928. if (!ctx.cert) return false;
  14929. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14930. verify_result_cn = ctx.check_hostname("Common Name");
  14931. // Test 2: wrong hostname should not match
  14932. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14933. return true; // Accept for the purpose of this test
  14934. });
  14935. auto res = cli.Get("/test");
  14936. // The request may succeed or fail depending on cert configuration
  14937. // but the callback should have been called
  14938. ASSERT_TRUE(verify_callback_called)
  14939. << "Verify callback should have been called";
  14940. EXPECT_FALSE(verify_result_cn)
  14941. << "verify_hostname must not match the certificate CN (no SAN)";
  14942. // Wrong hostname should not match
  14943. EXPECT_FALSE(verify_result_wrong)
  14944. << "verify_hostname should not match 'wronghost.example.com'";
  14945. }
  14946. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14947. // backend verifies it.
  14948. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14949. // Certificate CN is "localhost" and it carries no SAN.
  14950. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14951. ASSERT_TRUE(svr.is_valid());
  14952. svr.Get("/test", [](const Request &, Response &res) {
  14953. res.set_content("ok", "text/plain");
  14954. });
  14955. auto port = svr.bind_to_any_port(HOST);
  14956. thread t([&]() { svr.listen_after_bind(); });
  14957. auto se = detail::scope_exit([&] {
  14958. svr.stop();
  14959. t.join();
  14960. });
  14961. svr.wait_until_ready();
  14962. SSLClient cli("localhost", port);
  14963. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14964. cli.enable_server_certificate_verification(true);
  14965. cli.set_connection_timeout(5);
  14966. auto res = cli.Get("/test");
  14967. ASSERT_FALSE(res);
  14968. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14969. // The same certificate is accepted once host name verification is off, so the
  14970. // failure above is the host name and not the chain.
  14971. cli.enable_server_hostname_verification(false);
  14972. res = cli.Get("/test");
  14973. ASSERT_TRUE(res) << to_string(res.error());
  14974. EXPECT_EQ(StatusCode::OK_200, res->status);
  14975. }
  14976. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14977. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14978. // X509_check_ip behavior and must hold for every backend.
  14979. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14980. using namespace httplib::tls;
  14981. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14982. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14983. ASSERT_TRUE(svr.is_valid());
  14984. svr.Get("/test", [](const Request &, Response &res) {
  14985. res.set_content("ok", "text/plain");
  14986. });
  14987. thread t([&]() { svr.listen(HOST, PORT); });
  14988. auto se = detail::scope_exit([&] {
  14989. svr.stop();
  14990. t.join();
  14991. });
  14992. svr.wait_until_ready();
  14993. bool verify_callback_called = false;
  14994. bool ip_matched_via_cn = true;
  14995. SSLClient cli(HOST, PORT);
  14996. cli.enable_server_certificate_verification(true);
  14997. cli.set_ca_cert_path(CA_CERT_FILE);
  14998. cli.set_connection_timeout(5);
  14999. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15000. verify_callback_called = true;
  15001. if (!ctx.cert) return false;
  15002. // The IP appears only in the CN, so it must NOT be accepted.
  15003. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  15004. return true; // Accept for the purpose of this test
  15005. });
  15006. cli.Get("/test");
  15007. ASSERT_TRUE(verify_callback_called)
  15008. << "Verify callback should have been called";
  15009. EXPECT_FALSE(ip_matched_via_cn)
  15010. << "An IP host must not be authenticated via the certificate CN";
  15011. }
  15012. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15013. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15014. using namespace httplib::tls;
  15015. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15016. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15017. ASSERT_TRUE(svr.is_valid());
  15018. svr.Get("/test", [](const Request &, Response &res) {
  15019. res.set_content("ok", "text/plain");
  15020. });
  15021. thread t([&]() { svr.listen(HOST, PORT); });
  15022. auto se = detail::scope_exit([&] {
  15023. svr.stop();
  15024. t.join();
  15025. });
  15026. svr.wait_until_ready();
  15027. bool verify_callback_called = false;
  15028. bool san_matched = false;
  15029. bool wrong_ipv6_matched = true;
  15030. bool cn_ipv6_matched = true;
  15031. SSLClient cli(HOST, PORT);
  15032. cli.enable_server_certificate_verification(true);
  15033. cli.set_ca_cert_path(CA_CERT_FILE);
  15034. cli.set_connection_timeout(5);
  15035. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15036. verify_callback_called = true;
  15037. if (!ctx.cert) return false;
  15038. // Matches the IPv6 iPAddress SAN.
  15039. san_matched = ctx.check_hostname("2001:db8::1");
  15040. // A different IPv6 address must not match.
  15041. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15042. // "::1" lives only in the CN, so it must not be accepted.
  15043. cn_ipv6_matched = ctx.check_hostname("::1");
  15044. return true; // Accept for the purpose of this test
  15045. });
  15046. cli.Get("/test");
  15047. ASSERT_TRUE(verify_callback_called)
  15048. << "Verify callback should have been called";
  15049. EXPECT_TRUE(san_matched)
  15050. << "verify_hostname should match an IPv6 iPAddress SAN";
  15051. EXPECT_FALSE(wrong_ipv6_matched)
  15052. << "verify_hostname should not match a non-matching IPv6 address";
  15053. EXPECT_FALSE(cn_ipv6_matched)
  15054. << "An IPv6 host must not be authenticated via the certificate CN";
  15055. }
  15056. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15057. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15058. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15059. using namespace httplib::tls;
  15060. // SANs: DNS:a.zz, IP:42.46.122.122
  15061. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15062. ASSERT_TRUE(svr.is_valid());
  15063. svr.Get("/test", [](const Request &, Response &res) {
  15064. res.set_content("ok", "text/plain");
  15065. });
  15066. auto port = svr.bind_to_any_port(HOST);
  15067. thread t([&]() { svr.listen_after_bind(); });
  15068. auto se = detail::scope_exit([&] {
  15069. svr.stop();
  15070. t.join();
  15071. });
  15072. svr.wait_until_ready();
  15073. bool verify_callback_called = false;
  15074. bool dns_san_matched = false;
  15075. bool ip_san_matched = false;
  15076. bool ip_matched_via_dns_san = true;
  15077. bool dns_matched_via_ip_san = true;
  15078. bool cn_matched_next_to_dns_san = true;
  15079. SSLClient cli(HOST, port);
  15080. cli.enable_server_certificate_verification(true);
  15081. cli.set_ca_cert_path(CA_CERT_FILE);
  15082. cli.set_connection_timeout(5);
  15083. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15084. verify_callback_called = true;
  15085. if (!ctx.cert) return false;
  15086. dns_san_matched = ctx.check_hostname("a.zz");
  15087. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15088. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15089. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15090. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15091. return true; // Accept for the purpose of this test
  15092. });
  15093. cli.Get("/test");
  15094. ASSERT_TRUE(verify_callback_called)
  15095. << "Verify callback should have been called";
  15096. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15097. EXPECT_TRUE(ip_san_matched)
  15098. << "verify_hostname should match an iPAddress SAN";
  15099. EXPECT_FALSE(ip_matched_via_dns_san)
  15100. << "An IP host must not be authenticated via a dNSName SAN";
  15101. EXPECT_FALSE(dns_matched_via_ip_san)
  15102. << "A DNS host must not be authenticated via an iPAddress SAN";
  15103. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15104. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15105. }
  15106. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15107. // "www.*.example.test" names one host and not every host under example.test.
  15108. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15109. using namespace httplib::tls;
  15110. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15111. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15112. ASSERT_TRUE(svr.is_valid());
  15113. svr.Get("/test", [](const Request &, Response &res) {
  15114. res.set_content("ok", "text/plain");
  15115. });
  15116. auto port = svr.bind_to_any_port(HOST);
  15117. thread t([&]() { svr.listen_after_bind(); });
  15118. auto se = detail::scope_exit([&] {
  15119. svr.stop();
  15120. t.join();
  15121. });
  15122. svr.wait_until_ready();
  15123. bool verify_callback_called = false;
  15124. bool leftmost_wildcard_matched = false;
  15125. bool wildcard_spanned_labels = true;
  15126. bool inner_wildcard_matched = true;
  15127. SSLClient cli(HOST, port);
  15128. cli.enable_server_certificate_verification(true);
  15129. cli.set_ca_cert_path(CA_CERT_FILE);
  15130. cli.set_connection_timeout(5);
  15131. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15132. verify_callback_called = true;
  15133. if (!ctx.cert) return false;
  15134. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15135. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15136. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15137. return true; // Accept for the purpose of this test
  15138. });
  15139. cli.Get("/test");
  15140. ASSERT_TRUE(verify_callback_called)
  15141. << "Verify callback should have been called";
  15142. EXPECT_TRUE(leftmost_wildcard_matched)
  15143. << "A leftmost wildcard should match a single label";
  15144. EXPECT_FALSE(wildcard_spanned_labels)
  15145. << "A wildcard label must not match more than one label";
  15146. EXPECT_FALSE(inner_wildcard_matched)
  15147. << "A wildcard outside the leftmost label must not be honoured";
  15148. }
  15149. // sans() must report each SAN entry under its own type.
  15150. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15151. using namespace httplib::tls;
  15152. // SANs: DNS:a.zz, IP:42.46.122.122
  15153. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15154. ASSERT_TRUE(svr.is_valid());
  15155. svr.Get("/test", [](const Request &, Response &res) {
  15156. res.set_content("ok", "text/plain");
  15157. });
  15158. auto port = svr.bind_to_any_port(HOST);
  15159. thread t([&]() { svr.listen_after_bind(); });
  15160. auto se = detail::scope_exit([&] {
  15161. svr.stop();
  15162. t.join();
  15163. });
  15164. svr.wait_until_ready();
  15165. bool verify_callback_called = false;
  15166. std::vector<SanEntry> sans;
  15167. SSLClient cli(HOST, port);
  15168. cli.enable_server_certificate_verification(true);
  15169. cli.set_ca_cert_path(CA_CERT_FILE);
  15170. cli.set_connection_timeout(5);
  15171. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15172. verify_callback_called = true;
  15173. if (!ctx.cert) return false;
  15174. sans = ctx.sans();
  15175. return true; // Accept for the purpose of this test
  15176. });
  15177. cli.Get("/test");
  15178. ASSERT_TRUE(verify_callback_called)
  15179. << "Verify callback should have been called";
  15180. auto has_san = [&](SanType type, const std::string &value) {
  15181. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15182. return san.type == type && san.value == value;
  15183. });
  15184. };
  15185. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15186. << "sans() should report the dNSName SAN";
  15187. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15188. << "sans() should report the iPAddress SAN";
  15189. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15190. << "sans() must not report the dNSName SAN as an address";
  15191. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15192. << "sans() must not report the iPAddress SAN as a DNS name";
  15193. }
  15194. #endif
  15195. // mbedTLS-specific callback constructor test
  15196. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15197. #ifdef CPPHTTPLIB_SSL_ENABLED
  15198. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15200. ASSERT_TRUE(svr.is_valid());
  15201. // Set up a handler to verify client certificate is present
  15202. bool client_cert_verified = false;
  15203. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15204. // Verify that client certificate was provided
  15205. client_cert_verified = true;
  15206. res.set_content("success", "text/plain");
  15207. });
  15208. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15209. auto se = detail::scope_exit([&] {
  15210. svr.stop();
  15211. t.join();
  15212. ASSERT_FALSE(svr.is_running());
  15213. });
  15214. svr.wait_until_ready();
  15215. // Client with certificate
  15216. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15217. cli.enable_server_certificate_verification(false);
  15218. cli.set_connection_timeout(30);
  15219. auto res = cli.Get("/test");
  15220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15221. ASSERT_EQ(StatusCode::OK_200, res->status);
  15222. ASSERT_TRUE(client_cert_verified);
  15223. EXPECT_EQ("success", res->body);
  15224. }
  15225. #endif
  15226. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15227. // backends
  15228. #ifdef CPPHTTPLIB_SSL_ENABLED
  15229. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15230. using namespace httplib::tls;
  15231. // Test that when client CA cert file is provided,
  15232. // the server properly requests and validates client certificates
  15233. // Create a server with client authentication
  15234. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15235. ASSERT_TRUE(svr.is_valid());
  15236. bool handler_called = false;
  15237. svr.Get("/test", [&](const Request &req, Response &res) {
  15238. handler_called = true;
  15239. // Verify that a client certificate was provided
  15240. auto cert = req.peer_cert();
  15241. ASSERT_TRUE(static_cast<bool>(cert));
  15242. // Get the issuer name
  15243. std::string issuer_str = cert.issuer_name();
  15244. ASSERT_FALSE(issuer_str.empty());
  15245. // The client certificate should be issued by our test CA
  15246. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15247. res.set_content("authenticated", "text/plain");
  15248. });
  15249. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15250. auto se = detail::scope_exit([&] {
  15251. svr.stop();
  15252. t.join();
  15253. ASSERT_FALSE(svr.is_running());
  15254. });
  15255. svr.wait_until_ready();
  15256. // Connect with a client certificate issued by the CA
  15257. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15258. cli.enable_server_certificate_verification(false);
  15259. cli.set_connection_timeout(30);
  15260. auto res = cli.Get("/test");
  15261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15262. ASSERT_EQ(StatusCode::OK_200, res->status);
  15263. ASSERT_TRUE(handler_called);
  15264. EXPECT_EQ("authenticated", res->body);
  15265. }
  15266. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15267. using namespace httplib::tls;
  15268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15269. ASSERT_TRUE(svr.is_valid());
  15270. svr.Get("/test", [](const Request &, Response &res) {
  15271. res.set_content("ok", "text/plain");
  15272. });
  15273. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15274. auto se = detail::scope_exit([&] {
  15275. svr.stop();
  15276. t.join();
  15277. });
  15278. svr.wait_until_ready();
  15279. SSLClient cli(HOST, PORT);
  15280. cli.enable_server_certificate_verification(false);
  15281. cli.set_connection_timeout(30);
  15282. bool cert_checked = false;
  15283. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15284. if (ctx.cert) {
  15285. auto sans = ctx.sans();
  15286. // Test certificate may or may not have SANs - just verify the API
  15287. // works If SANs exist, verify the types are valid
  15288. for (const auto &san : sans) {
  15289. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15290. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15291. san.type == SanType::OTHER);
  15292. EXPECT_FALSE(san.value.empty());
  15293. }
  15294. cert_checked = true;
  15295. }
  15296. return true;
  15297. });
  15298. auto res = cli.Get("/test");
  15299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15300. EXPECT_TRUE(cert_checked);
  15301. }
  15302. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15303. using namespace httplib::tls;
  15304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15305. ASSERT_TRUE(svr.is_valid());
  15306. svr.Get("/test", [](const Request &, Response &res) {
  15307. res.set_content("ok", "text/plain");
  15308. });
  15309. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15310. auto se = detail::scope_exit([&] {
  15311. svr.stop();
  15312. t.join();
  15313. });
  15314. svr.wait_until_ready();
  15315. SSLClient cli(HOST, PORT);
  15316. cli.enable_server_certificate_verification(false);
  15317. cli.set_connection_timeout(30);
  15318. bool validity_checked = false;
  15319. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15320. if (ctx.cert) {
  15321. time_t not_before = 0, not_after = 0;
  15322. bool result = ctx.validity(not_before, not_after);
  15323. EXPECT_TRUE(result);
  15324. // Verify that not_before < now < not_after for a valid cert
  15325. time_t now = time(nullptr);
  15326. EXPECT_LT(not_before, now);
  15327. EXPECT_GT(not_after, now);
  15328. validity_checked = true;
  15329. }
  15330. return true;
  15331. });
  15332. auto res = cli.Get("/test");
  15333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15334. EXPECT_TRUE(validity_checked);
  15335. }
  15336. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15337. using namespace httplib::tls;
  15338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15339. ASSERT_TRUE(svr.is_valid());
  15340. svr.Get("/test", [](const Request &, Response &res) {
  15341. res.set_content("ok", "text/plain");
  15342. });
  15343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15344. auto se = detail::scope_exit([&] {
  15345. svr.stop();
  15346. t.join();
  15347. });
  15348. svr.wait_until_ready();
  15349. SSLClient cli(HOST, PORT);
  15350. cli.enable_server_certificate_verification(false);
  15351. cli.set_connection_timeout(30);
  15352. bool serial_checked = false;
  15353. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15354. if (ctx.cert) {
  15355. std::string serial = ctx.serial();
  15356. EXPECT_FALSE(serial.empty());
  15357. // Serial should be a hex string
  15358. for (char c : serial) {
  15359. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15360. (c >= 'a' && c <= 'f'));
  15361. }
  15362. serial_checked = true;
  15363. }
  15364. return true;
  15365. });
  15366. auto res = cli.Get("/test");
  15367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15368. EXPECT_TRUE(serial_checked);
  15369. }
  15370. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15371. // Test 1: Valid CA file - no error should be recorded
  15372. {
  15373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15374. CLIENT_CA_CERT_FILE);
  15375. ASSERT_TRUE(svr.is_valid());
  15376. // With valid setup, last_ssl_error should be 0
  15377. EXPECT_EQ(0, svr.ssl_last_error());
  15378. }
  15379. // Test 2: Invalid CA file content
  15380. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15381. {
  15382. // Create a temporary file with completely invalid content
  15383. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15384. {
  15385. std::ofstream ofs(temp_invalid_ca);
  15386. ofs << "This is not a certificate file at all\n";
  15387. ofs << "Just plain text content\n";
  15388. }
  15389. // Create server with invalid CA file
  15390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15391. // Clean up temporary file
  15392. std::remove(temp_invalid_ca);
  15393. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15394. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15395. // Note: SSL_CTX_load_verify_locations typically fails first,
  15396. // but our error handling code path is still exercised
  15397. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15398. }
  15399. }
  15400. TEST(VerifyCallbackTest, VerifyContextFields) {
  15401. using namespace httplib::tls;
  15402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15403. ASSERT_TRUE(svr.is_valid());
  15404. svr.Get("/test", [](const Request &, Response &res) {
  15405. res.set_content("ok", "text/plain");
  15406. });
  15407. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15408. auto se = detail::scope_exit([&] {
  15409. svr.stop();
  15410. t.join();
  15411. });
  15412. svr.wait_until_ready();
  15413. SSLClient cli(HOST, PORT);
  15414. cli.enable_server_certificate_verification(false);
  15415. cli.set_connection_timeout(30);
  15416. int callback_count = 0;
  15417. bool saw_leaf_cert = false;
  15418. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15419. if (ctx.cert) {
  15420. callback_count++;
  15421. // We should see at least one certificate (the leaf)
  15422. std::string cn = ctx.subject_cn();
  15423. if (!cn.empty()) { saw_leaf_cert = true; }
  15424. // Verify context fields are populated
  15425. EXPECT_NE(ctx.session, nullptr);
  15426. EXPECT_GE(ctx.depth, 0);
  15427. }
  15428. return true;
  15429. });
  15430. auto res = cli.Get("/test");
  15431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15432. EXPECT_GT(callback_count, 0);
  15433. EXPECT_TRUE(saw_leaf_cert);
  15434. }
  15435. // A verifier that accepts runs alongside the built-in verification, and is the
  15436. // only check once that is turned off.
  15437. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15438. using namespace httplib::tls;
  15439. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15440. ASSERT_TRUE(svr.is_valid());
  15441. svr.Get("/test", [](const Request &, Response &res) {
  15442. res.set_content("ok", "text/plain");
  15443. });
  15444. auto port = svr.bind_to_any_port(HOST);
  15445. thread t([&]() { svr.listen_after_bind(); });
  15446. auto se = detail::scope_exit([&] {
  15447. svr.stop();
  15448. t.join();
  15449. });
  15450. svr.wait_until_ready();
  15451. SSLClient cli(HOST, port);
  15452. cli.enable_server_hostname_verification(false);
  15453. auto calls = 0;
  15454. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15455. calls++;
  15456. return true;
  15457. });
  15458. // cert.pem is not trusted
  15459. auto res = cli.Get("/test");
  15460. ASSERT_FALSE(res);
  15461. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15462. EXPECT_GT(calls, 0);
  15463. cli.enable_server_certificate_verification(false);
  15464. res = cli.Get("/test");
  15465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15466. EXPECT_EQ("ok", res->body);
  15467. }
  15468. // A verifier belongs to the client that set it, not to the thread that set it.
  15469. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15470. using namespace httplib::tls;
  15471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15472. ASSERT_TRUE(svr.is_valid());
  15473. svr.Get("/test", [](const Request &, Response &res) {
  15474. res.set_content("ok", "text/plain");
  15475. });
  15476. auto port = svr.bind_to_any_port(HOST);
  15477. thread t([&]() { svr.listen_after_bind(); });
  15478. auto se = detail::scope_exit([&] {
  15479. svr.stop();
  15480. t.join();
  15481. });
  15482. svr.wait_until_ready();
  15483. auto rejecting_calls = 0;
  15484. SSLClient rejecting(HOST, port);
  15485. rejecting.enable_server_certificate_verification(false);
  15486. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15487. rejecting_calls++;
  15488. return false;
  15489. });
  15490. auto accepting_calls = 0;
  15491. SSLClient accepting(HOST, port);
  15492. accepting.enable_server_certificate_verification(false);
  15493. // Set on another thread than the requests below.
  15494. thread([&]() {
  15495. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15496. accepting_calls++;
  15497. return true;
  15498. });
  15499. }).join();
  15500. // Requested on another thread than the verifier was set on.
  15501. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15502. EXPECT_GT(rejecting_calls, 0);
  15503. auto res = accepting.Get("/test");
  15504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15505. EXPECT_GT(accepting_calls, 0);
  15506. }
  15507. // A verifier replaced while a handshake runs it lives until it returns.
  15508. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  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. SSLClient cli(HOST, port);
  15523. cli.enable_server_certificate_verification(false);
  15524. std::promise<void> entered;
  15525. std::promise<void> replaced;
  15526. auto replaced_future = replaced.get_future();
  15527. auto first_call = true;
  15528. // Long enough to live on the heap
  15529. std::string expected(64, 'v');
  15530. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15531. if (first_call) {
  15532. first_call = false;
  15533. entered.set_value();
  15534. replaced_future.wait();
  15535. }
  15536. return expected == std::string(64, 'v');
  15537. });
  15538. thread request([&]() {
  15539. auto res = cli.Get("/test");
  15540. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15541. });
  15542. entered.get_future().wait();
  15543. cli.set_server_certificate_verifier(
  15544. [](const VerifyContext &) { return true; });
  15545. replaced.set_value();
  15546. request.join();
  15547. }
  15548. // VerifyContext::session is the same handle the other tls:: functions take.
  15549. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15550. using namespace httplib::tls;
  15551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15552. ASSERT_TRUE(svr.is_valid());
  15553. svr.Get("/test", [](const Request &, Response &res) {
  15554. res.set_content("ok", "text/plain");
  15555. });
  15556. auto port = svr.bind_to_any_port(HOST);
  15557. thread t([&]() { svr.listen_after_bind(); });
  15558. auto se = detail::scope_exit([&] {
  15559. svr.stop();
  15560. t.join();
  15561. });
  15562. svr.wait_until_ready();
  15563. SSLClient cli(HOST, port);
  15564. cli.enable_server_certificate_verification(false);
  15565. session_t verifier_session = nullptr;
  15566. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15567. verifier_session = ctx.session;
  15568. return true;
  15569. });
  15570. session_t session_verifier_session = nullptr;
  15571. cli.set_session_verifier([&](session_t session) {
  15572. session_verifier_session = session;
  15573. return SSLVerifierResponse::NoDecisionMade;
  15574. });
  15575. auto res = cli.Get("/test");
  15576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15577. EXPECT_NE(nullptr, verifier_session);
  15578. EXPECT_EQ(session_verifier_session, verifier_session);
  15579. }
  15580. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15581. using httplib::tls::TlsError;
  15582. // Test that verify_error_to_string returns empty for success
  15583. std::string success_str = TlsError::verify_error_to_string(0);
  15584. EXPECT_TRUE(success_str.empty());
  15585. // Test that verify_error_to_string returns non-empty for error codes
  15586. // Using a common error code (certificate expired)
  15587. std::string error_str =
  15588. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15589. EXPECT_FALSE(error_str.empty());
  15590. }
  15591. TEST(SessionVerifierTest, CertificateAccepted) {
  15592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15593. ASSERT_TRUE(svr.is_valid());
  15594. svr.Get("/test", [](const Request &, Response &res) {
  15595. res.set_content("ok", "text/plain");
  15596. });
  15597. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15598. auto se = detail::scope_exit([&] {
  15599. svr.stop();
  15600. t.join();
  15601. });
  15602. svr.wait_until_ready();
  15603. SSLClient cli(HOST, PORT);
  15604. cli.enable_server_certificate_verification(false);
  15605. cli.set_connection_timeout(30);
  15606. bool callback_called = false;
  15607. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15608. EXPECT_NE(session, nullptr);
  15609. callback_called = true;
  15610. return SSLVerifierResponse::CertificateAccepted;
  15611. });
  15612. auto res = cli.Get("/test");
  15613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15614. EXPECT_EQ(200, res->status);
  15615. EXPECT_TRUE(callback_called);
  15616. }
  15617. TEST(SessionVerifierTest, CertificateRejected) {
  15618. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15619. ASSERT_TRUE(svr.is_valid());
  15620. svr.Get("/test", [](const Request &, Response &res) {
  15621. res.set_content("ok", "text/plain");
  15622. });
  15623. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15624. auto se = detail::scope_exit([&] {
  15625. svr.stop();
  15626. t.join();
  15627. });
  15628. svr.wait_until_ready();
  15629. SSLClient cli(HOST, PORT);
  15630. cli.enable_server_certificate_verification(false);
  15631. cli.set_connection_timeout(30);
  15632. bool callback_called = false;
  15633. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15634. EXPECT_NE(session, nullptr);
  15635. callback_called = true;
  15636. return SSLVerifierResponse::CertificateRejected;
  15637. });
  15638. auto res = cli.Get("/test");
  15639. EXPECT_FALSE(res);
  15640. EXPECT_TRUE(callback_called);
  15641. }
  15642. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15644. ASSERT_TRUE(svr.is_valid());
  15645. svr.Get("/test", [](const Request &, Response &res) {
  15646. res.set_content("ok", "text/plain");
  15647. });
  15648. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15649. auto se = detail::scope_exit([&] {
  15650. svr.stop();
  15651. t.join();
  15652. });
  15653. svr.wait_until_ready();
  15654. // NoDecisionMade with verification disabled should succeed (no default check)
  15655. SSLClient cli(HOST, PORT);
  15656. cli.enable_server_certificate_verification(false);
  15657. cli.set_connection_timeout(30);
  15658. bool callback_called = false;
  15659. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15660. EXPECT_NE(session, nullptr);
  15661. callback_called = true;
  15662. return SSLVerifierResponse::NoDecisionMade;
  15663. });
  15664. auto res = cli.Get("/test");
  15665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15666. EXPECT_EQ(200, res->status);
  15667. EXPECT_TRUE(callback_called);
  15668. }
  15669. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15671. ASSERT_TRUE(svr.is_valid());
  15672. svr.Get("/test", [](const Request &, Response &res) {
  15673. res.set_content("ok", "text/plain");
  15674. });
  15675. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15676. auto se = detail::scope_exit([&] {
  15677. svr.stop();
  15678. t.join();
  15679. });
  15680. svr.wait_until_ready();
  15681. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15682. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15683. // so we only check that the request fails, not whether the callback was
  15684. // called.
  15685. SSLClient cli(HOST, PORT);
  15686. cli.enable_server_certificate_verification(true);
  15687. cli.set_connection_timeout(30);
  15688. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15689. EXPECT_NE(session, nullptr);
  15690. return SSLVerifierResponse::NoDecisionMade;
  15691. });
  15692. auto res = cli.Get("/test");
  15693. EXPECT_FALSE(res);
  15694. }
  15695. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15696. // Test SSL server using PemMemory constructor with client CA certificates
  15697. // Read PEM files
  15698. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15699. read_file(SERVER_CERT_FILE, server_cert_pem);
  15700. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15701. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15702. // Create SSLServer with PemMemory constructor including client CA
  15703. SSLServer::PemMemory server_pem = {
  15704. server_cert_pem.c_str(),
  15705. server_cert_pem.size(),
  15706. server_key_pem.c_str(),
  15707. server_key_pem.size(),
  15708. client_ca_pem.c_str(),
  15709. client_ca_pem.size(),
  15710. nullptr // no password for server key
  15711. };
  15712. SSLServer svr(server_pem);
  15713. ASSERT_TRUE(svr.is_valid());
  15714. // No SSL error should be recorded for valid setup
  15715. EXPECT_EQ(0, svr.ssl_last_error());
  15716. // Set up server endpoints
  15717. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15718. res.set_content("ok", "text/plain");
  15719. });
  15720. // Start server in a thread
  15721. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15722. svr.wait_until_ready();
  15723. // Connect with client certificate (using constructor with paths)
  15724. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15725. cli.enable_server_certificate_verification(false);
  15726. auto res = cli.Get("/test-pem-ca");
  15727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15728. EXPECT_EQ(200, res->status);
  15729. EXPECT_EQ("ok", res->body);
  15730. svr.stop();
  15731. server_thread.join();
  15732. }
  15733. #endif
  15734. #ifdef _WIN32
  15735. TEST(CleanupTest, WSACleanup) {
  15736. int ret = WSACleanup();
  15737. ASSERT_EQ(0, ret);
  15738. }
  15739. #endif
  15740. #ifndef CPPHTTPLIB_SSL_ENABLED
  15741. TEST(NoSSLSupport, SimpleInterface) {
  15742. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15743. }
  15744. #endif
  15745. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15746. TEST(InvalidScheme, SimpleInterface) {
  15747. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15748. }
  15749. #endif
  15750. TEST(NoScheme, SimpleInterface) {
  15751. Client cli("yahoo.com:80");
  15752. ASSERT_TRUE(cli.is_valid());
  15753. }
  15754. TEST(SendAPI, SimpleInterface_Online) {
  15755. Client cli("http://yahoo.com");
  15756. Request req;
  15757. req.method = "GET";
  15758. req.path = "/";
  15759. auto res = cli.send(req);
  15760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15761. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15762. }
  15763. TEST(SendAPI, WithParamsInRequest) {
  15764. Server svr;
  15765. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15766. EXPECT_TRUE(req.has_param("test"));
  15767. EXPECT_EQ("test_value", req.get_param_value("test"));
  15768. });
  15769. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15770. auto se = detail::scope_exit([&] {
  15771. svr.stop();
  15772. t.join();
  15773. ASSERT_FALSE(svr.is_running());
  15774. });
  15775. svr.wait_until_ready();
  15776. Client cli(HOST, PORT);
  15777. {
  15778. Request req;
  15779. req.method = "GET";
  15780. req.path = "/";
  15781. req.params.emplace("test", "test_value");
  15782. auto res = cli.send(req);
  15783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15784. }
  15785. {
  15786. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15788. }
  15789. }
  15790. TEST(ClientImplMethods, GetSocketTest) {
  15791. httplib::Server svr;
  15792. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15793. res.status = StatusCode::OK_200;
  15794. });
  15795. auto port = svr.bind_to_any_port("127.0.0.1");
  15796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15797. auto se = detail::scope_exit([&] {
  15798. svr.stop();
  15799. thread.join();
  15800. ASSERT_FALSE(svr.is_running());
  15801. });
  15802. svr.wait_until_ready();
  15803. {
  15804. httplib::Client cli("127.0.0.1", port);
  15805. cli.set_keep_alive(true);
  15806. // Use the behavior of cpp-httplib of opening the connection
  15807. // only when the first request happens. If that changes,
  15808. // this test would be obsolete.
  15809. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15810. // This also implicitly tests the server. But other tests would fail much
  15811. // earlier than this one to be considered.
  15812. auto res = cli.Get("/");
  15813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15814. EXPECT_EQ(StatusCode::OK_200, res->status);
  15815. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15816. }
  15817. }
  15818. #ifdef CPPHTTPLIB_SSL_ENABLED
  15819. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15820. Client cli("http://yahoo.com");
  15821. auto res = cli.Get("/");
  15822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15823. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15824. cli.set_follow_location(true);
  15825. res = cli.Get("/");
  15826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15827. EXPECT_EQ(StatusCode::OK_200, res->status);
  15828. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15829. }
  15830. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15831. Client cli("https://yahoo.com");
  15832. auto res = cli.Get("/");
  15833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15834. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15835. cli.set_follow_location(true);
  15836. res = cli.Get("/");
  15837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15838. EXPECT_EQ(StatusCode::OK_200, res->status);
  15839. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15840. }
  15841. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15842. Client cli("https://yahoo.com");
  15843. auto res = cli.Get("/");
  15844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15845. ASSERT_FALSE(!res);
  15846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15847. ASSERT_FALSE(res == nullptr);
  15848. ASSERT_TRUE(res != nullptr);
  15849. EXPECT_EQ(Error::Success, res.error());
  15850. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15851. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15852. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15853. cli.set_follow_location(true);
  15854. res = cli.Get("/");
  15855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15856. EXPECT_EQ(Error::Success, res.error());
  15857. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15858. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15859. EXPECT_EQ(StatusCode::OK_200, res->status);
  15860. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15861. }
  15862. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15863. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15864. Client cli("https://cdnjs.cloudflare.com");
  15865. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15866. Headers{{"Accept-Encoding", "br"}});
  15867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15868. EXPECT_EQ(StatusCode::OK_200, res->status);
  15869. EXPECT_EQ(287630U, res->body.size());
  15870. EXPECT_EQ("application/javascript; charset=utf-8",
  15871. res->get_header_value("Content-Type"));
  15872. }
  15873. #endif
  15874. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15875. #undef REDIR_HOST // Silence compiler warning
  15876. #define REDIR_HOST "https://httpbingo.org"
  15877. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15878. Client cli(REDIR_HOST);
  15879. cli.set_follow_location(true);
  15880. auto res = retry_gateway_errors([&] {
  15881. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15882. });
  15883. SKIP_ON_GATEWAY_ERROR(res);
  15884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15885. EXPECT_EQ(StatusCode::OK_200, res->status);
  15886. }
  15887. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15888. Client cli(REDIR_HOST);
  15889. cli.set_follow_location(true);
  15890. Params params;
  15891. params.emplace("url", "http://example.com");
  15892. params.emplace("status_code", "302");
  15893. auto res = retry_gateway_errors(
  15894. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  15895. SKIP_ON_GATEWAY_ERROR(res);
  15896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15897. EXPECT_EQ(StatusCode::OK_200, res->status);
  15898. }
  15899. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15900. Client cli(REDIR_HOST);
  15901. cli.set_follow_location(true);
  15902. Params params;
  15903. params.emplace("url", "http://example.com");
  15904. auto res = retry_gateway_errors([&] {
  15905. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15906. });
  15907. SKIP_ON_GATEWAY_ERROR(res);
  15908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15909. EXPECT_EQ(StatusCode::OK_200, res->status);
  15910. }
  15911. TEST(HttpToHttpsRedirectTest, CertFile) {
  15912. auto ssl_port = PORT + 1;
  15913. Server svr;
  15914. ASSERT_TRUE(svr.is_valid());
  15915. svr.Get("/index", [&](const Request &, Response &res) {
  15916. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15917. "/index");
  15918. svr.stop();
  15919. });
  15920. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15921. ASSERT_TRUE(ssl_svr.is_valid());
  15922. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15923. res.set_content("test", "text/plain");
  15924. ssl_svr.stop();
  15925. });
  15926. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15927. thread t2 =
  15928. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15929. auto se = detail::scope_exit([&] {
  15930. t2.join();
  15931. t.join();
  15932. ASSERT_FALSE(svr.is_running());
  15933. });
  15934. svr.wait_until_ready();
  15935. ssl_svr.wait_until_ready();
  15936. Client cli("127.0.0.1", PORT);
  15937. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15938. cli.enable_server_certificate_verification(true);
  15939. cli.set_follow_location(true);
  15940. cli.set_connection_timeout(30);
  15941. auto res = cli.Get("/index");
  15942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15943. ASSERT_EQ(StatusCode::OK_200, res->status);
  15944. }
  15945. TEST(UppercaseSchemeTest, UsesTLS) {
  15946. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15947. ASSERT_TRUE(ssl_svr.is_valid());
  15948. ssl_svr.Get("/index", [](const Request &, Response &res) {
  15949. res.set_content("test", "text/plain");
  15950. });
  15951. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  15952. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  15953. Server svr;
  15954. svr.Get("/index", [&](const Request &, Response &res) {
  15955. res.set_redirect(https_url + "/index");
  15956. });
  15957. auto port = svr.bind_to_any_port("127.0.0.1");
  15958. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  15959. auto t2 = thread([&] { svr.listen_after_bind(); });
  15960. auto se = detail::scope_exit([&] {
  15961. svr.stop();
  15962. ssl_svr.stop();
  15963. t2.join();
  15964. t.join();
  15965. });
  15966. ssl_svr.wait_until_ready();
  15967. svr.wait_until_ready();
  15968. {
  15969. Client cli(https_url);
  15970. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15971. auto res = cli.Get("/index");
  15972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15973. EXPECT_EQ("test", res->body);
  15974. }
  15975. {
  15976. Client cli("127.0.0.1", port);
  15977. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15978. cli.set_follow_location(true);
  15979. auto res = cli.Get("/index");
  15980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15981. EXPECT_EQ("test", res->body);
  15982. }
  15983. }
  15984. TEST(SSLClientRedirectTest, CertFile) {
  15985. auto ssl_port = PORT + 1;
  15986. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15987. ASSERT_TRUE(ssl_svr1.is_valid());
  15988. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15989. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15990. "/index");
  15991. ssl_svr1.stop();
  15992. });
  15993. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15994. ASSERT_TRUE(ssl_svr2.is_valid());
  15995. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15996. res.set_content("test", "text/plain");
  15997. ssl_svr2.stop();
  15998. });
  15999. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16000. thread t2 =
  16001. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16002. auto se = detail::scope_exit([&] {
  16003. t2.join();
  16004. t.join();
  16005. ASSERT_FALSE(ssl_svr1.is_running());
  16006. });
  16007. ssl_svr1.wait_until_ready();
  16008. ssl_svr2.wait_until_ready();
  16009. SSLClient cli("127.0.0.1", PORT);
  16010. std::string cert;
  16011. read_file(SERVER_CERT2_FILE, cert);
  16012. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16013. cli.enable_server_certificate_verification(true);
  16014. cli.set_follow_location(true);
  16015. cli.set_connection_timeout(30);
  16016. auto res = cli.Get("/index");
  16017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16018. ASSERT_EQ(StatusCode::OK_200, res->status);
  16019. }
  16020. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16021. // another port, so the client follows it with a new client.
  16022. static Result GetThroughTlsRedirectToDifferentPort(
  16023. const std::function<void(SSLClient &)> &setup,
  16024. const char *target_cert = SERVER_CERT2_FILE,
  16025. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16026. auto ssl_port = PORT + 1;
  16027. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16028. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16029. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16030. "/index");
  16031. });
  16032. SSLServer ssl_svr2(target_cert, target_key);
  16033. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16034. res.set_content("test", "text/plain");
  16035. });
  16036. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16037. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16038. auto se = detail::scope_exit([&] {
  16039. ssl_svr2.stop();
  16040. ssl_svr1.stop();
  16041. t2.join();
  16042. t.join();
  16043. });
  16044. ssl_svr1.wait_until_ready();
  16045. ssl_svr2.wait_until_ready();
  16046. SSLClient cli("127.0.0.1", PORT);
  16047. cli.set_follow_location(true);
  16048. cli.set_connection_timeout(30);
  16049. setup(cli);
  16050. return cli.Get("/index");
  16051. }
  16052. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16053. auto calls = 0;
  16054. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16055. cli.enable_server_certificate_verification(false);
  16056. // Accept the first server only.
  16057. cli.set_session_verifier([&](tls::session_t) {
  16058. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16059. : SSLVerifierResponse::CertificateRejected;
  16060. });
  16061. });
  16062. ASSERT_FALSE(res);
  16063. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16064. EXPECT_EQ(2, calls);
  16065. }
  16066. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16067. std::string pinned;
  16068. auto res = GetThroughTlsRedirectToDifferentPort(
  16069. [&](SSLClient &cli) {
  16070. cli.enable_server_certificate_verification(false);
  16071. // Pin the first certificate seen.
  16072. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16073. if (pinned.empty()) { pinned = ctx.serial(); }
  16074. return ctx.serial() == pinned;
  16075. });
  16076. },
  16077. // A certificate other than the first server's.
  16078. SERVER_CERT_FILE);
  16079. EXPECT_FALSE(res);
  16080. EXPECT_FALSE(pinned.empty());
  16081. }
  16082. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16083. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16084. std::string cert;
  16085. read_file(SERVER_CERT2_FILE, cert);
  16086. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16087. });
  16088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16089. EXPECT_EQ(StatusCode::OK_200, res->status);
  16090. }
  16091. // The target's certificate is signed by the root CA, which the first server's
  16092. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16093. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16094. auto res = GetThroughTlsRedirectToDifferentPort(
  16095. [](SSLClient &cli) {
  16096. std::string root_ca, cert;
  16097. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16098. read_file(SERVER_CERT2_FILE, cert);
  16099. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16100. cli.load_ca_cert_store(cert.data(), cert.size());
  16101. cli.enable_server_hostname_verification(false);
  16102. },
  16103. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16105. EXPECT_EQ(StatusCode::OK_200, res->status);
  16106. }
  16107. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16108. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16109. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16110. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16111. auto res = GetThroughTlsRedirectToDifferentPort(
  16112. [](SSLClient &cli) {
  16113. std::string root_ca, cert;
  16114. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16115. read_file(SERVER_CERT2_FILE, cert);
  16116. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16117. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16118. cli.enable_server_hostname_verification(false);
  16119. },
  16120. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16121. ASSERT_FALSE(res);
  16122. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16123. }
  16124. #endif
  16125. #endif
  16126. #ifdef CPPHTTPLIB_SSL_ENABLED
  16127. // Test that set_ca_cert_store() skips system certs (consistent with
  16128. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16129. // should be trusted - system certs should NOT be loaded.
  16130. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16131. // Load a specific cert that is NOT a system CA cert
  16132. std::string cert;
  16133. read_file(SERVER_CERT2_FILE, cert);
  16134. SSLClient cli("google.com");
  16135. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16136. cli.enable_server_certificate_verification(true);
  16137. // This should FAIL because:
  16138. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16139. // 2. System certs should NOT be loaded when custom store is set
  16140. // If system certs WERE loaded, this would succeed
  16141. auto res = cli.Get("/");
  16142. ASSERT_FALSE(res);
  16143. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16144. }
  16145. // Same as above, but through the native store handle path. Regression test:
  16146. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16147. // merged system certs into the user-provided store.
  16148. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16149. std::string cert;
  16150. read_file(SERVER_CERT2_FILE, cert);
  16151. SSLClient cli("google.com");
  16152. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16153. cli.enable_server_certificate_verification(true);
  16154. auto res = cli.Get("/");
  16155. ASSERT_FALSE(res);
  16156. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16157. }
  16158. // A custom store set via the native handle must still verify a server whose
  16159. // cert it does contain.
  16160. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16161. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16162. ASSERT_TRUE(svr.is_valid());
  16163. svr.Get("/test", [&](const Request &, Response &res) {
  16164. res.set_content("test", "text/plain");
  16165. });
  16166. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16167. auto se = detail::scope_exit([&] {
  16168. svr.stop();
  16169. t.join();
  16170. ASSERT_FALSE(svr.is_running());
  16171. });
  16172. svr.wait_until_ready();
  16173. SSLClient cli("127.0.0.1", PORT);
  16174. std::string cert;
  16175. read_file(SERVER_CERT2_FILE, cert);
  16176. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16177. cli.enable_server_certificate_verification(true);
  16178. cli.set_connection_timeout(30);
  16179. auto res = cli.Get("/test");
  16180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16181. ASSERT_EQ(StatusCode::OK_200, res->status);
  16182. }
  16183. // CA certs loaded through the universal Client must be transferred to the
  16184. // client created internally for following an HTTPS redirect. Regression test:
  16185. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16186. // the CA data for redirect transfer.
  16187. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16188. auto ssl_port = PORT + 1;
  16189. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16190. ASSERT_TRUE(ssl_svr1.is_valid());
  16191. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16192. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16193. "/index");
  16194. });
  16195. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16196. ASSERT_TRUE(ssl_svr2.is_valid());
  16197. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16198. res.set_content("test", "text/plain");
  16199. });
  16200. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16201. thread t2 =
  16202. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16203. auto se = detail::scope_exit([&] {
  16204. ssl_svr2.stop();
  16205. ssl_svr1.stop();
  16206. t2.join();
  16207. t.join();
  16208. ASSERT_FALSE(ssl_svr1.is_running());
  16209. });
  16210. ssl_svr1.wait_until_ready();
  16211. ssl_svr2.wait_until_ready();
  16212. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16213. std::string cert;
  16214. read_file(SERVER_CERT2_FILE, cert);
  16215. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16216. cli.enable_server_certificate_verification(true);
  16217. cli.set_follow_location(true);
  16218. cli.set_connection_timeout(30);
  16219. auto res = cli.Get("/index");
  16220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16221. ASSERT_EQ(StatusCode::OK_200, res->status);
  16222. }
  16223. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16224. // so a host signed by a system CA verifies even though a custom CA is set
  16225. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16226. std::string cert;
  16227. read_file(SERVER_CERT2_FILE, cert);
  16228. SSLClient cli("google.com");
  16229. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16230. cli.enable_system_ca(true);
  16231. cli.enable_server_certificate_verification(true);
  16232. auto res = cli.Get("/");
  16233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16234. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16235. }
  16236. // The custom CA remains effective when combined with the system CA
  16237. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16238. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16239. ASSERT_TRUE(svr.is_valid());
  16240. svr.Get("/test", [&](const Request &, Response &res) {
  16241. res.set_content("test", "text/plain");
  16242. });
  16243. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16244. auto se = detail::scope_exit([&] {
  16245. svr.stop();
  16246. t.join();
  16247. ASSERT_FALSE(svr.is_running());
  16248. });
  16249. svr.wait_until_ready();
  16250. SSLClient cli("127.0.0.1", PORT);
  16251. std::string cert;
  16252. read_file(SERVER_CERT2_FILE, cert);
  16253. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16254. cli.enable_system_ca(true);
  16255. cli.enable_server_certificate_verification(true);
  16256. cli.set_connection_timeout(30);
  16257. auto res = cli.Get("/test");
  16258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16259. ASSERT_EQ(StatusCode::OK_200, res->status);
  16260. }
  16261. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16262. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16263. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16264. static CFDictionaryRef
  16265. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16266. const SecTrustSettingsResult *result) {
  16267. auto constraint =
  16268. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16269. &kCFTypeDictionaryValueCallBacks);
  16270. if (policy) {
  16271. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16272. }
  16273. if (policy_string) {
  16274. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16275. kCFStringEncodingUTF8);
  16276. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16277. CFRelease(str);
  16278. }
  16279. if (result) {
  16280. auto number_value = static_cast<SInt32>(*result);
  16281. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16282. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16283. CFRelease(number);
  16284. }
  16285. return constraint;
  16286. }
  16287. static SecTrustSettingsResult
  16288. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16289. auto trust_settings =
  16290. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16291. for (auto constraint : constraints) {
  16292. CFArrayAppendValue(trust_settings, constraint);
  16293. CFRelease(constraint);
  16294. }
  16295. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16296. CFRelease(trust_settings);
  16297. return result;
  16298. }
  16299. // The system CA loader takes a Keychain certificate as a trusted root only
  16300. // when its Trust Settings say so for SSL, not merely because it has some.
  16301. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16302. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16303. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16304. const auto deny = kSecTrustSettingsResultDeny;
  16305. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16306. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16307. auto x509_policy = SecPolicyCreateBasicX509();
  16308. // "Always Trust", which stores no constraint at all
  16309. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16310. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16311. ssl_trust_settings_result(
  16312. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16313. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16314. ssl_trust_settings_result(
  16315. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16316. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16317. ssl_trust_settings_result(
  16318. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16319. // "Never Trust", for everything or for SSL
  16320. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16321. ssl_trust_settings_result(
  16322. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16323. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16324. ssl_trust_settings_result(
  16325. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16326. // Trusted for another policy, for one host, or not at all
  16327. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16328. ssl_trust_settings_result(
  16329. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16330. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16331. ssl_trust_settings_result({make_usage_constraint(
  16332. ssl_policy, "www.example.com", &trust_root)}));
  16333. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16334. ssl_trust_settings_result(
  16335. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16336. // The first constraint that applies to SSL decides
  16337. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16338. ssl_trust_settings_result(
  16339. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16340. make_usage_constraint(nullptr, nullptr, &deny)}));
  16341. CFRelease(x509_policy);
  16342. CFRelease(ssl_policy);
  16343. }
  16344. #endif
  16345. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16346. // skip chain verification entirely (only the certificate identity was
  16347. // checked), so a server presenting an untrusted certificate with a matching
  16348. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16349. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16350. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16351. ASSERT_TRUE(svr.is_valid());
  16352. svr.Get("/test", [&](const Request &, Response &res) {
  16353. res.set_content("test", "text/plain");
  16354. });
  16355. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16356. auto se = detail::scope_exit([&] {
  16357. svr.stop();
  16358. t.join();
  16359. ASSERT_FALSE(svr.is_running());
  16360. });
  16361. svr.wait_until_ready();
  16362. SSLClient cli("127.0.0.1", PORT);
  16363. std::string cert;
  16364. // A trusted CA that did not sign the server certificate. The server cert
  16365. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16366. // this connection.
  16367. read_file(CLIENT_CA_CERT_FILE, cert);
  16368. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16369. cli.enable_server_certificate_verification(true);
  16370. cli.set_connection_timeout(30);
  16371. auto res = cli.Get("/test");
  16372. ASSERT_FALSE(res);
  16373. }
  16374. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16375. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16376. // CA that failed to come through fails verification instead of trusting them.
  16377. // (wolfSSL does not list the system CAs it loaded.)
  16378. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16379. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16380. ASSERT_TRUE(svr.is_valid());
  16381. auto port = svr.bind_to_any_port("127.0.0.1");
  16382. ASSERT_LT(0, port);
  16383. thread t = thread([&] { svr.listen_after_bind(); });
  16384. auto se = detail::scope_exit([&] {
  16385. svr.stop();
  16386. t.join();
  16387. ASSERT_FALSE(svr.is_running());
  16388. });
  16389. svr.wait_until_ready();
  16390. // The CAs a client trusts once its first request has loaded them
  16391. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16392. Client cli("https://127.0.0.1:" + std::to_string(port));
  16393. setup(cli);
  16394. cli.Get("/");
  16395. return tls::get_ca_names(cli.tls_context()).size();
  16396. };
  16397. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16398. EXPECT_EQ(0u,
  16399. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16400. }
  16401. #endif
  16402. // A TLS setting changed between requests applies to the next one, not just to
  16403. // the next connection
  16404. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16405. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16406. ASSERT_TRUE(svr.is_valid());
  16407. svr.Get("/", [](const Request &req, Response &res) {
  16408. res.set_content(std::to_string(req.remote_port), "text/plain");
  16409. });
  16410. auto port = svr.bind_to_any_port("127.0.0.1");
  16411. ASSERT_LT(0, port);
  16412. thread t = thread([&] { svr.listen_after_bind(); });
  16413. auto se = detail::scope_exit([&] {
  16414. svr.stop();
  16415. t.join();
  16416. ASSERT_FALSE(svr.is_running());
  16417. });
  16418. svr.wait_until_ready();
  16419. SSLClient cli("127.0.0.1", port);
  16420. cli.set_keep_alive(true);
  16421. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16422. cli.enable_server_certificate_verification(false);
  16423. // The port the request went out from, so a new one means a new connection
  16424. auto client_port = [&] {
  16425. auto res = cli.Get("/");
  16426. return res ? res->body : std::string();
  16427. };
  16428. auto last = client_port();
  16429. ASSERT_FALSE(last.empty());
  16430. // Setting a value it already has keeps the connection
  16431. cli.enable_server_certificate_verification(false);
  16432. cli.enable_server_hostname_verification(true);
  16433. EXPECT_EQ(last, client_port());
  16434. cli.enable_server_certificate_verification(true);
  16435. auto res = cli.Get("/");
  16436. EXPECT_FALSE(res);
  16437. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16438. std::string ca;
  16439. read_file(SERVER_CERT2_FILE, ca);
  16440. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16441. last = client_port();
  16442. ASSERT_FALSE(last.empty());
  16443. std::vector<std::function<void()>> setters = {
  16444. [&] { cli.enable_server_hostname_verification(false); },
  16445. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16446. [&] {
  16447. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16448. },
  16449. [&] {
  16450. cli.set_server_certificate_verifier(
  16451. [](const tls::VerifyContext &) { return true; });
  16452. },
  16453. [&] {
  16454. cli.set_session_verifier(
  16455. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16456. },
  16457. };
  16458. for (const auto &setter : setters) {
  16459. setter();
  16460. auto next = client_port();
  16461. ASSERT_FALSE(next.empty());
  16462. EXPECT_NE(last, next);
  16463. last = next;
  16464. }
  16465. cli.set_session_verifier(
  16466. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16467. auto handle = cli.open_stream("GET", "/");
  16468. EXPECT_FALSE(handle.is_valid());
  16469. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16470. }
  16471. // A PEM given to create_ca_store() needs no NUL after it
  16472. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16473. std::string pem;
  16474. read_file(SERVER_CERT2_FILE, pem);
  16475. auto buf = pem + "X";
  16476. auto store = tls::create_ca_store(buf.data(), pem.size());
  16477. EXPECT_TRUE(store != nullptr);
  16478. SSLClient cli("localhost");
  16479. cli.set_ca_cert_store(store);
  16480. }
  16481. // enable_system_ca(false) prevents system CA loading entirely
  16482. TEST(SSLClientTest, DisableSystemCa_Online) {
  16483. SSLClient cli("google.com");
  16484. cli.enable_system_ca(false);
  16485. cli.enable_server_certificate_verification(true);
  16486. auto res = cli.Get("/");
  16487. ASSERT_FALSE(res);
  16488. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16489. // itself when the CA chain is empty
  16490. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16491. res.error() == Error::SSLConnection);
  16492. }
  16493. // The universal Client forwards enable_system_ca()
  16494. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16495. std::string cert;
  16496. read_file(SERVER_CERT2_FILE, cert);
  16497. Client cli("https://google.com");
  16498. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16499. cli.enable_system_ca(true);
  16500. cli.enable_server_certificate_verification(true);
  16501. auto res = cli.Get("/");
  16502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16503. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16504. }
  16505. // The system CA policy must carry over to the client created internally for
  16506. // following a cross-host HTTPS redirect
  16507. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16508. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16509. ASSERT_TRUE(svr.is_valid());
  16510. svr.Get("/index", [&](const Request &, Response &res) {
  16511. res.set_redirect("https://www.google.com/");
  16512. });
  16513. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16514. auto se = detail::scope_exit([&] {
  16515. svr.stop();
  16516. t.join();
  16517. ASSERT_FALSE(svr.is_running());
  16518. });
  16519. svr.wait_until_ready();
  16520. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16521. std::string cert;
  16522. read_file(SERVER_CERT2_FILE, cert);
  16523. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16524. cli.enable_system_ca(true);
  16525. cli.enable_server_certificate_verification(true);
  16526. cli.set_follow_location(true);
  16527. cli.set_connection_timeout(30);
  16528. // Receiving any response proves the redirect client completed the TLS
  16529. // handshake with a system-CA-signed host
  16530. auto res = cli.Get("/index");
  16531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16532. }
  16533. TEST(MultipartFormDataTest, LargeData) {
  16534. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16535. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16536. const ContentReader &content_reader) {
  16537. if (req.is_multipart_form_data()) {
  16538. std::vector<FormData> items;
  16539. content_reader(
  16540. [&](const FormData &file) {
  16541. items.push_back(file);
  16542. return true;
  16543. },
  16544. [&](const char *data, size_t data_length) {
  16545. items.back().content.append(data, data_length);
  16546. return true;
  16547. });
  16548. EXPECT_TRUE(std::string(items[0].name) == "document");
  16549. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16550. EXPECT_TRUE(items[0].filename == "2MB_data");
  16551. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16552. EXPECT_TRUE(items[1].name == "hello");
  16553. EXPECT_TRUE(items[1].content == "world");
  16554. EXPECT_TRUE(items[1].filename == "");
  16555. EXPECT_TRUE(items[1].content_type == "");
  16556. } else {
  16557. std::string body;
  16558. content_reader([&](const char *data, size_t data_length) {
  16559. body.append(data, data_length);
  16560. return true;
  16561. });
  16562. }
  16563. });
  16564. auto port = svr.bind_to_any_port(HOST);
  16565. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16566. auto se = detail::scope_exit([&] {
  16567. svr.stop();
  16568. t.join();
  16569. ASSERT_FALSE(svr.is_running());
  16570. });
  16571. svr.wait_until_ready();
  16572. {
  16573. std::string data(1024 * 1024 * 2, '.');
  16574. std::stringstream buffer;
  16575. buffer << data;
  16576. SSLClient cli(HOST, port);
  16577. cli.enable_server_certificate_verification(false);
  16578. UploadFormDataItems items{
  16579. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16580. {"hello", "world", "", ""},
  16581. };
  16582. auto res = cli.Post("/post", items);
  16583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16584. ASSERT_EQ(StatusCode::OK_200, res->status);
  16585. }
  16586. }
  16587. TEST(MultipartFormDataTest, DataProviderItems) {
  16588. std::random_device seed_gen;
  16589. std::mt19937 random(seed_gen());
  16590. std::string rand1;
  16591. rand1.resize(1000);
  16592. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16593. std::string rand2;
  16594. rand2.resize(3000);
  16595. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16597. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16598. const ContentReader &content_reader) {
  16599. ASSERT_FALSE(req.is_multipart_form_data());
  16600. std::string body;
  16601. content_reader([&](const char *data, size_t data_length) {
  16602. body.append(data, data_length);
  16603. return true;
  16604. });
  16605. EXPECT_EQ(body, "");
  16606. });
  16607. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16608. const ContentReader &content_reader) {
  16609. ASSERT_TRUE(req.is_multipart_form_data());
  16610. std::vector<FormData> items;
  16611. content_reader(
  16612. [&](const FormData &file) {
  16613. items.push_back(file);
  16614. return true;
  16615. },
  16616. [&](const char *data, size_t data_length) {
  16617. items.back().content.append(data, data_length);
  16618. return true;
  16619. });
  16620. ASSERT_TRUE(items.size() == 2);
  16621. EXPECT_EQ(std::string(items[0].name), "name1");
  16622. EXPECT_EQ(items[0].content, "Testing123");
  16623. EXPECT_EQ(items[0].filename, "filename1");
  16624. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16625. EXPECT_EQ(items[1].name, "name2");
  16626. EXPECT_EQ(items[1].content, "Testing456");
  16627. EXPECT_EQ(items[1].filename, "");
  16628. EXPECT_EQ(items[1].content_type, "");
  16629. });
  16630. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16631. const ContentReader &content_reader) {
  16632. ASSERT_TRUE(req.is_multipart_form_data());
  16633. std::vector<FormData> items;
  16634. content_reader(
  16635. [&](const FormData &file) {
  16636. items.push_back(file);
  16637. return true;
  16638. },
  16639. [&](const char *data, size_t data_length) {
  16640. items.back().content.append(data, data_length);
  16641. return true;
  16642. });
  16643. ASSERT_TRUE(items.size() == 2);
  16644. EXPECT_EQ(items[0].name, "name3");
  16645. EXPECT_EQ(items[0].content, rand1);
  16646. EXPECT_EQ(items[0].filename, "filename3");
  16647. EXPECT_EQ(items[0].content_type, "");
  16648. EXPECT_EQ(items[1].name, "name4");
  16649. EXPECT_EQ(items[1].content, rand2);
  16650. EXPECT_EQ(items[1].filename, "filename4");
  16651. EXPECT_EQ(items[1].content_type, "");
  16652. });
  16653. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16654. const ContentReader &content_reader) {
  16655. ASSERT_TRUE(req.is_multipart_form_data());
  16656. std::vector<FormData> items;
  16657. content_reader(
  16658. [&](const FormData &file) {
  16659. items.push_back(file);
  16660. return true;
  16661. },
  16662. [&](const char *data, size_t data_length) {
  16663. items.back().content.append(data, data_length);
  16664. return true;
  16665. });
  16666. ASSERT_TRUE(items.size() == 4);
  16667. EXPECT_EQ(std::string(items[0].name), "name1");
  16668. EXPECT_EQ(items[0].content, "Testing123");
  16669. EXPECT_EQ(items[0].filename, "filename1");
  16670. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16671. EXPECT_EQ(items[1].name, "name2");
  16672. EXPECT_EQ(items[1].content, "Testing456");
  16673. EXPECT_EQ(items[1].filename, "");
  16674. EXPECT_EQ(items[1].content_type, "");
  16675. EXPECT_EQ(items[2].name, "name3");
  16676. EXPECT_EQ(items[2].content, rand1);
  16677. EXPECT_EQ(items[2].filename, "filename3");
  16678. EXPECT_EQ(items[2].content_type, "");
  16679. EXPECT_EQ(items[3].name, "name4");
  16680. EXPECT_EQ(items[3].content, rand2);
  16681. EXPECT_EQ(items[3].filename, "filename4");
  16682. EXPECT_EQ(items[3].content_type, "");
  16683. });
  16684. auto port = svr.bind_to_any_port("localhost");
  16685. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16686. auto se = detail::scope_exit([&] {
  16687. svr.stop();
  16688. t.join();
  16689. ASSERT_FALSE(svr.is_running());
  16690. });
  16691. svr.wait_until_ready();
  16692. {
  16693. SSLClient cli("localhost", port);
  16694. cli.enable_server_certificate_verification(false);
  16695. UploadFormDataItems items{
  16696. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16697. {"name2", "Testing456", "", ""}, // not a file
  16698. };
  16699. {
  16700. auto res = cli.Post("/post-none", {}, {}, {});
  16701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16702. ASSERT_EQ(StatusCode::OK_200, res->status);
  16703. }
  16704. FormDataProviderItems providers;
  16705. {
  16706. auto res =
  16707. cli.Post("/post-items", {}, items, providers); // empty providers
  16708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16709. ASSERT_EQ(StatusCode::OK_200, res->status);
  16710. }
  16711. providers.push_back({"name3",
  16712. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16713. // test the offset is given correctly at each step
  16714. if (!offset)
  16715. sink.os.write(rand1.data(), 30);
  16716. else if (offset == 30)
  16717. sink.os.write(rand1.data() + 30, 300);
  16718. else if (offset == 330)
  16719. sink.os.write(rand1.data() + 330, 670);
  16720. else if (offset == rand1.size())
  16721. sink.done();
  16722. return true;
  16723. },
  16724. "filename3",
  16725. {}});
  16726. providers.push_back({"name4",
  16727. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16728. // test the offset is given correctly at each step
  16729. if (!offset)
  16730. sink.os.write(rand2.data(), 2000);
  16731. else if (offset == 2000)
  16732. sink.os.write(rand2.data() + 2000, 1);
  16733. else if (offset == 2001)
  16734. sink.os.write(rand2.data() + 2001, 999);
  16735. else if (offset == rand2.size())
  16736. sink.done();
  16737. return true;
  16738. },
  16739. "filename4",
  16740. {}});
  16741. {
  16742. auto res = cli.Post("/post-providers", {}, {}, providers);
  16743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16744. ASSERT_EQ(StatusCode::OK_200, res->status);
  16745. }
  16746. {
  16747. auto res = cli.Post("/post-both", {}, items, providers);
  16748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16749. ASSERT_EQ(StatusCode::OK_200, res->status);
  16750. }
  16751. }
  16752. }
  16753. TEST(MultipartFormDataTest, BadHeader) {
  16754. Server svr;
  16755. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16756. res.set_content("ok", "text/plain");
  16757. });
  16758. thread t = thread([&] { svr.listen(HOST, PORT); });
  16759. auto se = detail::scope_exit([&] {
  16760. svr.stop();
  16761. t.join();
  16762. ASSERT_FALSE(svr.is_running());
  16763. });
  16764. svr.wait_until_ready();
  16765. const std::string body =
  16766. "This is the preamble. It is to be ignored, though it\r\n"
  16767. "is a handy place for composition agents to include an\r\n"
  16768. "explanatory note to non-MIME conformant readers.\r\n"
  16769. "\r\n"
  16770. "\r\n"
  16771. "--simple boundary\r\n"
  16772. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16773. ": BAD...\r\n"
  16774. "\r\n"
  16775. "value1\r\n"
  16776. "--simple boundary\r\n"
  16777. "Content-Disposition: form-data; name=\"field2\"; "
  16778. "filename=\"example.txt\"\r\n"
  16779. "\r\n"
  16780. "value2\r\n"
  16781. "--simple boundary--\r\n"
  16782. "This is the epilogue. It is also to be ignored.\r\n";
  16783. std::string content_type =
  16784. R"(multipart/form-data; boundary="simple boundary")";
  16785. Client cli(HOST, PORT);
  16786. auto res = cli.Post("/post", body, content_type.c_str());
  16787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16788. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16789. }
  16790. TEST(MultipartFormDataTest, WithPreamble) {
  16791. Server svr;
  16792. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16793. res.set_content("ok", "text/plain");
  16794. });
  16795. thread t = thread([&] { svr.listen(HOST, PORT); });
  16796. auto se = detail::scope_exit([&] {
  16797. svr.stop();
  16798. t.join();
  16799. ASSERT_FALSE(svr.is_running());
  16800. });
  16801. svr.wait_until_ready();
  16802. const std::string body =
  16803. "This is the preamble. It is to be ignored, though it\r\n"
  16804. "is a handy place for composition agents to include an\r\n"
  16805. "explanatory note to non-MIME conformant readers.\r\n"
  16806. "\r\n"
  16807. "\r\n"
  16808. "--simple boundary\r\n"
  16809. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16810. "\r\n"
  16811. "value1\r\n"
  16812. "--simple boundary\r\n"
  16813. "Content-Disposition: form-data; name=\"field2\"; "
  16814. "filename=\"example.txt\"\r\n"
  16815. "\r\n"
  16816. "value2\r\n"
  16817. "--simple boundary--\r\n"
  16818. "This is the epilogue. It is also to be ignored.\r\n";
  16819. std::string content_type =
  16820. R"(multipart/form-data; boundary="simple boundary")";
  16821. Client cli(HOST, PORT);
  16822. auto res = cli.Post("/post", body, content_type.c_str());
  16823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16824. EXPECT_EQ(StatusCode::OK_200, res->status);
  16825. }
  16826. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16828. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16829. const ContentReader &content_reader) {
  16830. if (req.is_multipart_form_data()) {
  16831. std::vector<FormData> items;
  16832. content_reader(
  16833. [&](const FormData &file) {
  16834. items.push_back(file);
  16835. return true;
  16836. },
  16837. [&](const char *data, size_t data_length) {
  16838. items.back().content.append(data, data_length);
  16839. return true;
  16840. });
  16841. EXPECT_TRUE(std::string(items[0].name) == "document");
  16842. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16843. EXPECT_TRUE(items[0].filename == "2MB_data");
  16844. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16845. EXPECT_TRUE(items[1].name == "hello");
  16846. EXPECT_TRUE(items[1].content == "world");
  16847. EXPECT_TRUE(items[1].filename == "");
  16848. EXPECT_TRUE(items[1].content_type == "");
  16849. } else {
  16850. std::string body;
  16851. content_reader([&](const char *data, size_t data_length) {
  16852. body.append(data, data_length);
  16853. return true;
  16854. });
  16855. }
  16856. });
  16857. auto port = svr.bind_to_any_port("localhost");
  16858. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16859. auto se = detail::scope_exit([&] {
  16860. svr.stop();
  16861. t.join();
  16862. ASSERT_FALSE(svr.is_running());
  16863. });
  16864. svr.wait_until_ready();
  16865. {
  16866. std::string data(1024 * 1024 * 2, '.');
  16867. std::stringstream buffer;
  16868. buffer << data;
  16869. SSLClient cli("localhost", port);
  16870. cli.enable_server_certificate_verification(false);
  16871. UploadFormDataItems items{
  16872. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16873. {"hello", "world", "", ""},
  16874. };
  16875. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16877. ASSERT_EQ(StatusCode::OK_200, res->status);
  16878. }
  16879. }
  16880. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16881. std::string data(1024 * 1024 * 2, '&');
  16882. std::stringstream buffer;
  16883. buffer << data;
  16884. Client cli("https://localhost:8080");
  16885. UploadFormDataItems items{
  16886. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16887. {"hello", "world", "", ""},
  16888. };
  16889. for (const char &c : " \t\r\n") {
  16890. auto res =
  16891. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16892. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16893. ASSERT_FALSE(res);
  16894. }
  16895. }
  16896. TEST(MultipartFormDataTest, PutFormData) {
  16897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16898. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16899. const ContentReader &content_reader) {
  16900. if (req.is_multipart_form_data()) {
  16901. std::vector<FormData> items;
  16902. content_reader(
  16903. [&](const FormData &file) {
  16904. items.push_back(file);
  16905. return true;
  16906. },
  16907. [&](const char *data, size_t data_length) {
  16908. items.back().content.append(data, data_length);
  16909. return true;
  16910. });
  16911. EXPECT_TRUE(std::string(items[0].name) == "document");
  16912. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16913. EXPECT_TRUE(items[0].filename == "2MB_data");
  16914. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16915. EXPECT_TRUE(items[1].name == "hello");
  16916. EXPECT_TRUE(items[1].content == "world");
  16917. EXPECT_TRUE(items[1].filename == "");
  16918. EXPECT_TRUE(items[1].content_type == "");
  16919. } else {
  16920. std::string body;
  16921. content_reader([&](const char *data, size_t data_length) {
  16922. body.append(data, data_length);
  16923. return true;
  16924. });
  16925. }
  16926. });
  16927. auto port = svr.bind_to_any_port("localhost");
  16928. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16929. auto se = detail::scope_exit([&] {
  16930. svr.stop();
  16931. t.join();
  16932. ASSERT_FALSE(svr.is_running());
  16933. });
  16934. svr.wait_until_ready();
  16935. {
  16936. std::string data(1024 * 1024 * 2, '&');
  16937. std::stringstream buffer;
  16938. buffer << data;
  16939. SSLClient cli("localhost", port);
  16940. cli.enable_server_certificate_verification(false);
  16941. UploadFormDataItems items{
  16942. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16943. {"hello", "world", "", ""},
  16944. };
  16945. auto res = cli.Put("/put", items);
  16946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16947. ASSERT_EQ(StatusCode::OK_200, res->status);
  16948. }
  16949. }
  16950. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16952. svr.Put("/put_customboundary",
  16953. [&](const Request &req, const Response & /*res*/,
  16954. const ContentReader &content_reader) {
  16955. if (req.is_multipart_form_data()) {
  16956. std::vector<FormData> items;
  16957. content_reader(
  16958. [&](const FormData &file) {
  16959. items.push_back(file);
  16960. return true;
  16961. },
  16962. [&](const char *data, size_t data_length) {
  16963. items.back().content.append(data, data_length);
  16964. return true;
  16965. });
  16966. EXPECT_TRUE(std::string(items[0].name) == "document");
  16967. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16968. EXPECT_TRUE(items[0].filename == "2MB_data");
  16969. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16970. EXPECT_TRUE(items[1].name == "hello");
  16971. EXPECT_TRUE(items[1].content == "world");
  16972. EXPECT_TRUE(items[1].filename == "");
  16973. EXPECT_TRUE(items[1].content_type == "");
  16974. } else {
  16975. std::string body;
  16976. content_reader([&](const char *data, size_t data_length) {
  16977. body.append(data, data_length);
  16978. return true;
  16979. });
  16980. }
  16981. });
  16982. auto port = svr.bind_to_any_port("localhost");
  16983. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16984. auto se = detail::scope_exit([&] {
  16985. svr.stop();
  16986. t.join();
  16987. ASSERT_FALSE(svr.is_running());
  16988. });
  16989. svr.wait_until_ready();
  16990. {
  16991. std::string data(1024 * 1024 * 2, '&');
  16992. std::stringstream buffer;
  16993. buffer << data;
  16994. SSLClient cli("localhost", port);
  16995. cli.enable_server_certificate_verification(false);
  16996. UploadFormDataItems items{
  16997. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16998. {"hello", "world", "", ""},
  16999. };
  17000. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17002. ASSERT_EQ(StatusCode::OK_200, res->status);
  17003. }
  17004. }
  17005. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17006. std::string data(1024 * 1024 * 2, '&');
  17007. std::stringstream buffer;
  17008. buffer << data;
  17009. Client cli("https://localhost:8080");
  17010. cli.enable_server_certificate_verification(false);
  17011. UploadFormDataItems items{
  17012. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17013. {"hello", "world", "", ""},
  17014. };
  17015. for (const char &c : " \t\r\n") {
  17016. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17017. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17018. ASSERT_FALSE(res);
  17019. }
  17020. }
  17021. TEST(MultipartFormDataTest, AlternateFilename) {
  17022. auto handled = false;
  17023. Server svr;
  17024. svr.Post("/test", [&](const Request &req, Response &res) {
  17025. ASSERT_EQ(2u, req.form.files.size());
  17026. ASSERT_EQ(1u, req.form.fields.size());
  17027. // Test files
  17028. const auto &file1 = req.form.get_file("file1");
  17029. ASSERT_EQ("file1", file1.name);
  17030. ASSERT_EQ("A.txt", file1.filename);
  17031. ASSERT_EQ("text/plain", file1.content_type);
  17032. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17033. const auto &file2 = req.form.get_file("file2");
  17034. ASSERT_EQ("file2", file2.name);
  17035. ASSERT_EQ("a.html", file2.filename);
  17036. ASSERT_EQ("text/html", file2.content_type);
  17037. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17038. file2.content);
  17039. // Test text field
  17040. const auto &text = req.form.get_field("text");
  17041. ASSERT_EQ("text default", text);
  17042. res.set_content("ok", "text/plain");
  17043. handled = true;
  17044. });
  17045. thread t = thread([&] { svr.listen(HOST, PORT); });
  17046. auto se = detail::scope_exit([&] {
  17047. svr.stop();
  17048. t.join();
  17049. ASSERT_FALSE(svr.is_running());
  17050. ASSERT_TRUE(handled);
  17051. });
  17052. svr.wait_until_ready();
  17053. auto req = "POST /test HTTP/1.1\r\n"
  17054. "Host: localhost\r\n"
  17055. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17056. "Content-Length: 399\r\n"
  17057. "\r\n"
  17058. "----------\r\n"
  17059. "Content-Disposition: form-data; name=\"text\"\r\n"
  17060. "\r\n"
  17061. "text default\r\n"
  17062. "----------\r\n"
  17063. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17064. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17065. "Content-Type: text/plain\r\n"
  17066. "\r\n"
  17067. "Content of a.txt.\r\n"
  17068. "\r\n"
  17069. "----------\r\n"
  17070. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17071. "\"a.html\"\r\n"
  17072. "Content-Type: text/html\r\n"
  17073. "\r\n"
  17074. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17075. "\r\n"
  17076. "------------\r\n";
  17077. ASSERT_TRUE(send_request(1, req));
  17078. }
  17079. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17080. auto handled = false;
  17081. Server svr;
  17082. svr.Post("/test", [&](const Request &req, Response &res) {
  17083. // Case-insensitive "utf-8''" prefix with a long value
  17084. const auto &file = req.form.get_file("file1");
  17085. ASSERT_EQ("file1", file.name);
  17086. // 8000 chars exercises both the Content-Disposition parser and the
  17087. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17088. // Prior to the fix, std::regex_match on this header would cause O(N)
  17089. // stack recursion in libstdc++, leading to SIGSEGV.
  17090. std::string expected_filename(8000, 'A');
  17091. ASSERT_EQ(expected_filename, file.filename);
  17092. res.set_content("ok", "text/plain");
  17093. handled = true;
  17094. });
  17095. thread t = thread([&] { svr.listen(HOST, PORT); });
  17096. auto se = detail::scope_exit([&] {
  17097. svr.stop();
  17098. t.join();
  17099. ASSERT_FALSE(svr.is_running());
  17100. ASSERT_TRUE(handled);
  17101. });
  17102. svr.wait_until_ready();
  17103. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17104. // Regression test for GHSA-qq6v-r583-3h69
  17105. std::string long_filename(8000, 'A');
  17106. std::string body = "----------\r\n"
  17107. "Content-Disposition: form-data; name=\"file1\"; "
  17108. "filename*=\"Utf-8''" +
  17109. long_filename +
  17110. "\"\r\n"
  17111. "\r\n"
  17112. "hello\r\n"
  17113. "------------\r\n";
  17114. auto req = "POST /test HTTP/1.1\r\n"
  17115. "Host: localhost\r\n"
  17116. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17117. "Content-Length: " +
  17118. std::to_string(body.size()) + "\r\n\r\n" + body;
  17119. ASSERT_TRUE(send_request(1, req));
  17120. }
  17121. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17122. auto handled = false;
  17123. Server svr;
  17124. svr.Post("/test", [&](const Request &req, Response &) {
  17125. ASSERT_EQ(2u, req.form.fields.size());
  17126. const auto &text1 = req.form.get_field("text1");
  17127. ASSERT_EQ("text1", text1);
  17128. const auto &text2 = req.form.get_field("text2");
  17129. ASSERT_EQ("text2", text2);
  17130. handled = true;
  17131. });
  17132. thread t = thread([&] { svr.listen(HOST, PORT); });
  17133. auto se = detail::scope_exit([&] {
  17134. svr.stop();
  17135. t.join();
  17136. ASSERT_FALSE(svr.is_running());
  17137. ASSERT_TRUE(handled);
  17138. });
  17139. svr.wait_until_ready();
  17140. auto req = "POST /test HTTP/1.1\r\n"
  17141. "Host: localhost\r\n"
  17142. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17143. "Content-Length: 146\r\n"
  17144. "\r\n----------\r\n"
  17145. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17146. "\r\n"
  17147. "text1"
  17148. "\r\n----------\r\n"
  17149. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17150. "\r\n"
  17151. "text2"
  17152. "\r\n------------";
  17153. std::string response;
  17154. ASSERT_TRUE(send_request(1, req, &response));
  17155. ASSERT_EQ("200", response.substr(9, 3));
  17156. }
  17157. TEST(MultipartFormDataTest, ContentLength) {
  17158. auto handled = false;
  17159. Server svr;
  17160. svr.Post("/test", [&](const Request &req, Response &) {
  17161. ASSERT_EQ(2u, req.form.fields.size());
  17162. const auto &text1 = req.form.get_field("text1");
  17163. ASSERT_EQ("text1", text1);
  17164. const auto &text2 = req.form.get_field("text2");
  17165. ASSERT_EQ("text2", text2);
  17166. handled = true;
  17167. });
  17168. thread t = thread([&] { svr.listen(HOST, PORT); });
  17169. auto se = detail::scope_exit([&] {
  17170. svr.stop();
  17171. t.join();
  17172. ASSERT_FALSE(svr.is_running());
  17173. ASSERT_TRUE(handled);
  17174. });
  17175. svr.wait_until_ready();
  17176. auto req = "POST /test HTTP/1.1\r\n"
  17177. "Host: localhost\r\n"
  17178. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17179. "Content-Length: 167\r\n"
  17180. "\r\n----------\r\n"
  17181. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17182. "Content-Length: 5\r\n"
  17183. "\r\n"
  17184. "text1"
  17185. "\r\n----------\r\n"
  17186. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17187. "\r\n"
  17188. "text2"
  17189. "\r\n------------\r\n";
  17190. std::string response;
  17191. ASSERT_TRUE(send_request(1, req, &response));
  17192. ASSERT_EQ("200", response.substr(9, 3));
  17193. }
  17194. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17195. auto handled = false;
  17196. Server svr;
  17197. svr.Post("/test", [&](const Request &req, Response &) {
  17198. ASSERT_EQ(2u, req.form.fields.size());
  17199. const auto &text1 = req.form.get_field("text1");
  17200. ASSERT_EQ("text1", text1);
  17201. // TODO: Add header access for text fields if needed
  17202. const auto &text2 = req.form.get_field("text2");
  17203. ASSERT_EQ("text2", text2);
  17204. // TODO: Header access for text fields needs to be implemented
  17205. // auto &headers = it->second.headers;
  17206. // ASSERT_EQ(3U, headers.size());
  17207. // auto custom_header = headers.find("x-whatever");
  17208. // ASSERT_TRUE(custom_header != headers.end());
  17209. // ASSERT_NE("customvalue", custom_header->second);
  17210. // ASSERT_EQ("CustomValue", custom_header->second);
  17211. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17212. handled = true;
  17213. });
  17214. thread t = thread([&] { svr.listen(HOST, PORT); });
  17215. auto se = detail::scope_exit([&] {
  17216. svr.stop();
  17217. t.join();
  17218. ASSERT_FALSE(svr.is_running());
  17219. ASSERT_TRUE(handled);
  17220. });
  17221. svr.wait_until_ready();
  17222. auto req = "POST /test HTTP/1.1\r\n"
  17223. "Host: localhost\r\n"
  17224. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17225. "Content-Length: 232\r\n"
  17226. "\r\n----------\r\n"
  17227. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17228. "Content-Length: 5\r\n"
  17229. "X-Test: 1\r\n"
  17230. "\r\n"
  17231. "text1"
  17232. "\r\n----------\r\n"
  17233. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17234. "Content-Type: text/plain\r\n"
  17235. "X-Whatever: CustomValue\r\n"
  17236. "\r\n"
  17237. "text2"
  17238. "\r\n------------\r\n"
  17239. "That should be disregarded. Not even read";
  17240. std::string response;
  17241. ASSERT_TRUE(send_request(1, req, &response));
  17242. ASSERT_EQ("200", response.substr(9, 3));
  17243. }
  17244. TEST(MultipartFormDataTest, LargeHeader) {
  17245. auto handled = false;
  17246. Server svr;
  17247. svr.Post("/test", [&](const Request &req, Response &) {
  17248. ASSERT_EQ(1u, req.form.fields.size());
  17249. const auto &text = req.form.get_field("name1");
  17250. ASSERT_EQ("text1", text);
  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 boundary = std::string("cpp-httplib-multipart-data");
  17262. std::string content = "--" + boundary +
  17263. "\r\n"
  17264. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17265. "\r\n"
  17266. "text1\r\n"
  17267. "--" +
  17268. boundary + "--\r\n";
  17269. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17270. "Host: localhost\r\n"
  17271. "Content-Type: multipart/form-data;boundary=" +
  17272. boundary +
  17273. "\r\n"
  17274. "Content-Length: " +
  17275. std::to_string(content.size()) +
  17276. "\r\n"
  17277. "Dummy-Header: ";
  17278. std::string header_suffix = "\r\n"
  17279. "\r\n";
  17280. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17281. size_t header_dummy_size =
  17282. read_buff_size -
  17283. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17284. auto header_dummy = std::string(header_dummy_size, '@');
  17285. auto req = header_prefix + header_dummy + header_suffix + content;
  17286. std::string response;
  17287. ASSERT_TRUE(send_request(1, req, &response));
  17288. ASSERT_EQ("200", response.substr(9, 3));
  17289. }
  17290. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17291. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17292. // (not chunked Transfer-Encoding) after the streaming refactor.
  17293. auto handled = false;
  17294. Server svr;
  17295. svr.Post("/upload", [&](const Request &req, Response &res) {
  17296. auto cl_it = req.headers.find("Content-Length");
  17297. EXPECT_TRUE(cl_it != req.headers.end());
  17298. auto te_it = req.headers.find("Transfer-Encoding");
  17299. EXPECT_TRUE(te_it == req.headers.end());
  17300. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17301. res.set_content("ok", "text/plain");
  17302. handled = true;
  17303. });
  17304. auto port = svr.bind_to_any_port(HOST);
  17305. auto t = thread([&] { svr.listen_after_bind(); });
  17306. auto se = detail::scope_exit([&] {
  17307. svr.stop();
  17308. t.join();
  17309. ASSERT_FALSE(svr.is_running());
  17310. ASSERT_TRUE(handled);
  17311. });
  17312. svr.wait_until_ready();
  17313. UploadFormDataItems items = {
  17314. {"field1", "hello", "", "text/plain"},
  17315. {"file1", "world", "test.txt", "application/octet-stream"},
  17316. };
  17317. Client cli(HOST, port);
  17318. auto res = cli.Post("/upload", {}, items);
  17319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17320. EXPECT_EQ(StatusCode::OK_200, res->status);
  17321. }
  17322. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17323. // Verify that make_multipart_content_provider coalesces many small segments
  17324. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17325. constexpr size_t kItemCount = 1000;
  17326. UploadFormDataItems items;
  17327. items.reserve(kItemCount);
  17328. for (size_t i = 0; i < kItemCount; i++) {
  17329. items.push_back(
  17330. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17331. }
  17332. const std::string boundary = "----test-boundary";
  17333. auto content_length = detail::get_multipart_content_length(items, boundary);
  17334. auto provider = detail::make_multipart_content_provider(items, boundary);
  17335. // Drive the provider the same way write_content_with_progress does
  17336. size_t write_count = 0;
  17337. size_t total_bytes = 0;
  17338. DataSink sink;
  17339. size_t offset = 0;
  17340. sink.write = [&](const char *d, size_t l) -> bool {
  17341. (void)d;
  17342. write_count++;
  17343. total_bytes += l;
  17344. offset += l;
  17345. return true;
  17346. };
  17347. sink.is_writable = []() -> bool { return true; };
  17348. while (offset < content_length) {
  17349. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17350. }
  17351. EXPECT_EQ(content_length, total_bytes);
  17352. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17353. // With buffering into 64KB blocks, write_count should be much smaller.
  17354. auto segment_count = 3 * kItemCount + 1;
  17355. EXPECT_LT(write_count, segment_count / 10);
  17356. }
  17357. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17358. // Integration test: send many UploadFormDataItems and verify the server
  17359. // receives all of them correctly (#2410).
  17360. constexpr size_t kItemCount = 500;
  17361. auto handled = false;
  17362. Server svr;
  17363. svr.Post("/upload", [&](const Request &req, Response &res) {
  17364. EXPECT_EQ(kItemCount, req.form.fields.size());
  17365. for (size_t i = 0; i < kItemCount; i++) {
  17366. auto key = "field" + std::to_string(i);
  17367. auto val = "value" + std::to_string(i);
  17368. auto it = req.form.fields.find(key);
  17369. if (it != req.form.fields.end()) {
  17370. EXPECT_EQ(val, it->second.content);
  17371. } else {
  17372. ADD_FAILURE() << "Missing field: " << key;
  17373. }
  17374. }
  17375. res.set_content("ok", "text/plain");
  17376. handled = true;
  17377. });
  17378. auto port = svr.bind_to_any_port(HOST);
  17379. auto t = thread([&] { svr.listen_after_bind(); });
  17380. auto se = detail::scope_exit([&] {
  17381. svr.stop();
  17382. t.join();
  17383. ASSERT_FALSE(svr.is_running());
  17384. ASSERT_TRUE(handled);
  17385. });
  17386. svr.wait_until_ready();
  17387. UploadFormDataItems items;
  17388. items.reserve(kItemCount);
  17389. for (size_t i = 0; i < kItemCount; i++) {
  17390. items.push_back(
  17391. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17392. }
  17393. Client cli(HOST, port);
  17394. auto res = cli.Post("/upload", items);
  17395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17396. EXPECT_EQ(StatusCode::OK_200, res->status);
  17397. }
  17398. TEST(MultipartFormDataTest, MakeFileProvider) {
  17399. // Verify make_file_provider sends a file's contents correctly.
  17400. const std::string file_content(4096, 'Z');
  17401. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17402. {
  17403. std::ofstream ofs(tmp_path, std::ios::binary);
  17404. ofs.write(file_content.data(),
  17405. static_cast<std::streamsize>(file_content.size()));
  17406. }
  17407. auto handled = false;
  17408. Server svr;
  17409. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17410. const ContentReader &content_reader) {
  17411. ASSERT_TRUE(req.is_multipart_form_data());
  17412. std::vector<FormData> items;
  17413. content_reader(
  17414. [&](const FormData &file) {
  17415. items.push_back(file);
  17416. return true;
  17417. },
  17418. [&](const char *data, size_t data_length) {
  17419. items.back().content.append(data, data_length);
  17420. return true;
  17421. });
  17422. ASSERT_EQ(1u, items.size());
  17423. EXPECT_EQ("myfile", items[0].name);
  17424. EXPECT_EQ("data.bin", items[0].filename);
  17425. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17426. EXPECT_EQ(file_content, items[0].content);
  17427. handled = true;
  17428. });
  17429. auto port = svr.bind_to_any_port(HOST);
  17430. auto t = thread([&] { svr.listen_after_bind(); });
  17431. auto se = detail::scope_exit([&] {
  17432. svr.stop();
  17433. t.join();
  17434. ASSERT_FALSE(svr.is_running());
  17435. ASSERT_TRUE(handled);
  17436. std::remove(tmp_path.c_str());
  17437. });
  17438. svr.wait_until_ready();
  17439. FormDataProviderItems providers;
  17440. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17441. "application/octet-stream"));
  17442. Client cli(HOST, port);
  17443. auto res = cli.Post("/upload", {}, {}, providers);
  17444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17445. EXPECT_EQ(StatusCode::OK_200, res->status);
  17446. }
  17447. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17448. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17449. // (100) headers is rejected with a 400 Bad Request response.
  17450. Server svr;
  17451. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17452. res.set_content("ok", "text/plain");
  17453. });
  17454. thread t = thread([&] { svr.listen(HOST, PORT); });
  17455. auto se = detail::scope_exit([&] {
  17456. svr.stop();
  17457. t.join();
  17458. ASSERT_FALSE(svr.is_running());
  17459. });
  17460. svr.wait_until_ready();
  17461. // Build a multipart part with 101 custom headers (exceeding
  17462. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17463. std::stringstream body;
  17464. body << "--simpleboundary\r\n"
  17465. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17466. for (int i = 0; i < 101; i++) {
  17467. body << "X-Custom-Header-" << i << ": value\r\n";
  17468. }
  17469. body << "\r\n"
  17470. << "value1\r\n"
  17471. << "--simpleboundary--\r\n";
  17472. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17473. Client cli(HOST, PORT);
  17474. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17476. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17477. }
  17478. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17479. // A body that never contains the declared boundary must not be accumulated
  17480. // while the parser waits for it. Buffering it would also make every read
  17481. // rescan everything seen so far, which is quadratic in the body size.
  17482. Server svr;
  17483. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17484. res.set_content("ok", "text/plain");
  17485. });
  17486. auto port = svr.bind_to_any_port(HOST);
  17487. thread t = thread([&] { svr.listen_after_bind(); });
  17488. auto se = detail::scope_exit([&] {
  17489. svr.stop();
  17490. t.join();
  17491. ASSERT_FALSE(svr.is_running());
  17492. });
  17493. svr.wait_until_ready();
  17494. Client cli(HOST, port);
  17495. cli.set_read_timeout(60, 0);
  17496. cli.set_write_timeout(60, 0);
  17497. // '-' is the worst case: it matches the first character of the boundary, so
  17498. // every position has to be checked against it.
  17499. auto post_dashes = [&](size_t size) {
  17500. const std::string body(size, '-');
  17501. auto start = std::chrono::steady_clock::now();
  17502. auto res =
  17503. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17504. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17505. std::chrono::steady_clock::now() - start)
  17506. .count();
  17507. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17508. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17509. return ms;
  17510. };
  17511. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17512. // Windows.
  17513. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17514. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17515. // Comparing the two sizes rather than checking an absolute duration keeps
  17516. // this meaningful across build types and CI load, both of which move the
  17517. // absolute numbers by more than an order of magnitude. Four times the bytes
  17518. // costs about four times the time when parsing is linear, and about sixteen
  17519. // times when the body is buffered and rescanned.
  17520. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17521. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17522. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17523. << "ms, which suggests the body is being buffered and rescanned";
  17524. }
  17525. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17526. // A boundary can only be followed by CRLF or by "--", so anything else is
  17527. // malformed no matter what comes next. The parser must say so right away
  17528. // instead of buffering the rest of the declared body.
  17529. Server svr;
  17530. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17531. res.set_content("ok", "text/plain");
  17532. });
  17533. auto port = svr.bind_to_any_port(HOST);
  17534. thread t = thread([&] { svr.listen_after_bind(); });
  17535. auto se = detail::scope_exit([&] {
  17536. svr.stop();
  17537. t.join();
  17538. ASSERT_FALSE(svr.is_running());
  17539. });
  17540. svr.wait_until_ready();
  17541. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17542. // buffers instead of failing would still be waiting for the remaining bytes.
  17543. const std::string body = "--zzzz\r\n"
  17544. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17545. "\r\n"
  17546. "text1"
  17547. "\r\n--zzzzXX";
  17548. const std::string req = "POST /post HTTP/1.1\r\n"
  17549. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17550. "Content-Length: 1048576\r\n"
  17551. "\r\n" +
  17552. body;
  17553. std::string response;
  17554. ASSERT_TRUE(send_request(3, req, &response, port));
  17555. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17556. EXPECT_EQ("400", response.substr(9, 3));
  17557. }
  17558. // Posts a multipart body split into two writes, so that the server sees the
  17559. // split at whatever offset the caller chose, and expects the single "text1"
  17560. // field to come through.
  17561. static void expect_split_multipart_ok(const std::string &body1,
  17562. const std::string &body2) {
  17563. auto handled = false;
  17564. Server svr;
  17565. svr.Post("/post", [&](const Request &req, Response &) {
  17566. EXPECT_EQ(1u, req.form.fields.size());
  17567. EXPECT_EQ("text1", req.form.get_field("text1"));
  17568. handled = true;
  17569. });
  17570. auto port = svr.bind_to_any_port(HOST);
  17571. thread t = thread([&] { svr.listen_after_bind(); });
  17572. auto se = detail::scope_exit([&] {
  17573. svr.stop();
  17574. t.join();
  17575. ASSERT_FALSE(svr.is_running());
  17576. ASSERT_TRUE(handled);
  17577. });
  17578. svr.wait_until_ready();
  17579. // "Connection: close" makes the server close once it has answered, so the
  17580. // response drain ends immediately instead of idling until the read timeout.
  17581. const std::string head =
  17582. "POST /post HTTP/1.1\r\n"
  17583. "Host: localhost\r\n"
  17584. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17585. "Connection: close\r\n"
  17586. "Content-Length: " +
  17587. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17588. std::string response;
  17589. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17590. ASSERT_GE(response.size(), 12u) << "no response";
  17591. EXPECT_EQ("200", response.substr(9, 3));
  17592. }
  17593. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17594. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17595. // ignored, including when it does not arrive in the same read as the
  17596. // close-delimiter itself.
  17597. expect_split_multipart_ok("--zzzz\r\n"
  17598. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17599. "\r\n"
  17600. "text1"
  17601. "\r\n--zzzz--",
  17602. "\r\nthis epilogue must be ignored\r\n");
  17603. }
  17604. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17605. // The initial boundary may be preceded by a preamble of any length and may
  17606. // straddle a read boundary. Discarding data while waiting for it must not
  17607. // throw away a partial boundary sitting at the end of the buffer.
  17608. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17609. "zz\r\n"
  17610. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17611. "\r\n"
  17612. "text1"
  17613. "\r\n--zzzz--\r\n");
  17614. }
  17615. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17616. // The received boundary was only checked for being non-empty, so it could be
  17617. // as long as a header is allowed to be. The parser scans the body for
  17618. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17619. // costs a nearly full comparison at nearly every position, making the
  17620. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17621. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17622. Server svr;
  17623. svr.Post("/post", [](const Request &req, Response &res) {
  17624. EXPECT_EQ(1u, req.form.fields.size());
  17625. EXPECT_EQ("text1", req.form.get_field("text1"));
  17626. res.set_content("ok", "text/plain");
  17627. });
  17628. auto port = svr.bind_to_any_port(HOST);
  17629. thread t = thread([&] { svr.listen_after_bind(); });
  17630. auto se = detail::scope_exit([&] {
  17631. svr.stop();
  17632. t.join();
  17633. ASSERT_FALSE(svr.is_running());
  17634. });
  17635. svr.wait_until_ready();
  17636. Client cli(HOST, port);
  17637. auto post_with_boundary_of_length = [&](size_t len) {
  17638. const std::string boundary(len, 'a');
  17639. const std::string body =
  17640. "--" + boundary +
  17641. "\r\n"
  17642. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17643. "\r\n"
  17644. "text1"
  17645. "\r\n--" +
  17646. boundary + "--\r\n";
  17647. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17648. };
  17649. auto res = post_with_boundary_of_length(70);
  17650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17651. EXPECT_EQ(StatusCode::OK_200, res->status);
  17652. res = post_with_boundary_of_length(71);
  17653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17654. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17655. }
  17656. TEST(MakeFileBodyTest, Basic) {
  17657. const std::string file_content(4096, 'Z');
  17658. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17659. {
  17660. std::ofstream ofs(tmp_path, std::ios::binary);
  17661. ofs.write(file_content.data(),
  17662. static_cast<std::streamsize>(file_content.size()));
  17663. }
  17664. auto handled = false;
  17665. Server svr;
  17666. svr.Post("/upload", [&](const Request &req, Response &res) {
  17667. EXPECT_EQ(file_content, req.body);
  17668. handled = true;
  17669. res.status = StatusCode::OK_200;
  17670. });
  17671. auto port = svr.bind_to_any_port(HOST);
  17672. auto t = thread([&] { svr.listen_after_bind(); });
  17673. auto se = detail::scope_exit([&] {
  17674. svr.stop();
  17675. t.join();
  17676. ASSERT_FALSE(svr.is_running());
  17677. ASSERT_TRUE(handled);
  17678. std::remove(tmp_path.c_str());
  17679. });
  17680. svr.wait_until_ready();
  17681. auto fb = make_file_body(tmp_path);
  17682. ASSERT_GT(fb.first, 0u);
  17683. Client cli(HOST, port);
  17684. auto res =
  17685. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17687. EXPECT_EQ(StatusCode::OK_200, res->status);
  17688. }
  17689. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17690. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17691. {
  17692. std::ofstream ofs(path, std::ios::binary);
  17693. const std::string content(100, 'A');
  17694. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17695. }
  17696. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17697. auto body = make_file_body(path);
  17698. ASSERT_EQ(100u, body.first);
  17699. ASSERT_TRUE(static_cast<bool>(body.second));
  17700. // Rewritten shorter after its length was measured - and, on a server, after
  17701. // that length has already gone out as Content-Length.
  17702. {
  17703. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17704. const std::string content(10, 'A');
  17705. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17706. }
  17707. std::string written;
  17708. DataSink sink;
  17709. sink.write = [&](const char *d, size_t l) {
  17710. written.append(d, l);
  17711. return true;
  17712. };
  17713. // The provider has to report failure. write_content_with_progress() advances
  17714. // its offset only by what was written, so a provider that returns true
  17715. // without completing the length it promised is called again straight away,
  17716. // and again.
  17717. EXPECT_FALSE(body.second(0, body.first, sink));
  17718. EXPECT_EQ(std::string(10, 'A'), written);
  17719. }
  17720. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17721. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17722. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17723. {
  17724. std::ofstream ofs(path, std::ios::binary);
  17725. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17726. }
  17727. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17728. auto body = make_file_body(path);
  17729. ASSERT_EQ(content.size(), body.first);
  17730. ASSERT_TRUE(static_cast<bool>(body.second));
  17731. std::string written;
  17732. DataSink sink;
  17733. sink.write = [&](const char *d, size_t l) {
  17734. written.append(d, l);
  17735. return true;
  17736. };
  17737. EXPECT_TRUE(body.second(0, body.first, sink));
  17738. EXPECT_EQ(content, written);
  17739. }
  17740. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17741. static constexpr unsigned int number_of_tasks{1000000};
  17742. std::atomic_uint count{0};
  17743. std::unique_ptr<TaskQueue> task_queue{
  17744. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17745. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17746. auto queued = task_queue->enqueue(
  17747. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17748. EXPECT_TRUE(queued);
  17749. }
  17750. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17751. task_queue->shutdown();
  17752. #else
  17753. EXPECT_NO_THROW(task_queue->shutdown());
  17754. #endif
  17755. EXPECT_EQ(number_of_tasks, count.load());
  17756. }
  17757. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17758. static constexpr unsigned int number_of_tasks{1000000};
  17759. static constexpr unsigned int qlimit{2};
  17760. unsigned int queued_count{0};
  17761. std::atomic_uint count{0};
  17762. std::unique_ptr<TaskQueue> task_queue{
  17763. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17764. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17765. if (task_queue->enqueue(
  17766. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17767. queued_count++;
  17768. }
  17769. }
  17770. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17771. task_queue->shutdown();
  17772. #else
  17773. EXPECT_NO_THROW(task_queue->shutdown());
  17774. #endif
  17775. EXPECT_EQ(queued_count, count.load());
  17776. EXPECT_TRUE(queued_count <= number_of_tasks);
  17777. EXPECT_TRUE(queued_count >= qlimit);
  17778. }
  17779. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17780. // Use a short idle timeout so a dynamic thread spawns, times out and
  17781. // exits during the test, and the pool keeps working afterwards.
  17782. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17783. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17784. /*idle_timeout_sec=*/1}};
  17785. std::atomic_uint count{0};
  17786. std::condition_variable cv;
  17787. std::mutex mtx;
  17788. bool release = false;
  17789. // Block the base thread so the second task spawns a dynamic thread.
  17790. EXPECT_TRUE(task_queue->enqueue([&] {
  17791. std::unique_lock<std::mutex> lock(mtx);
  17792. while (!release) {
  17793. cv.wait(lock);
  17794. }
  17795. count++;
  17796. }));
  17797. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17798. // Let the dynamic thread finish its task and exceed the idle timeout.
  17799. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17800. {
  17801. std::unique_lock<std::mutex> lock(mtx);
  17802. release = true;
  17803. }
  17804. cv.notify_all();
  17805. // The pool must still accept and run tasks after the dynamic thread exited.
  17806. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17807. task_queue->shutdown();
  17808. EXPECT_EQ(3u, count.load());
  17809. }
  17810. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17811. static constexpr size_t number_of_tasks{32};
  17812. std::unique_ptr<TaskQueue> task_queue{
  17813. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17814. // Let the base threads go idle so the burst below finds them waiting.
  17815. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17816. std::mutex mtx;
  17817. std::condition_variable cv;
  17818. size_t running = 0;
  17819. bool release = false;
  17820. for (size_t i = 0; i < number_of_tasks; i++) {
  17821. EXPECT_TRUE(task_queue->enqueue([&] {
  17822. std::unique_lock<std::mutex> lock(mtx);
  17823. running++;
  17824. cv.notify_all();
  17825. cv.wait(lock, [&] { return release; });
  17826. }));
  17827. }
  17828. {
  17829. std::unique_lock<std::mutex> lock(mtx);
  17830. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17831. [&] { return running == number_of_tasks; }));
  17832. release = true;
  17833. }
  17834. cv.notify_all();
  17835. task_queue->shutdown();
  17836. }
  17837. TEST(TaskQueueTest, MaxQueuedRequests) {
  17838. static constexpr unsigned int qlimit{3};
  17839. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17840. std::condition_variable sem_cv;
  17841. std::mutex sem_mtx;
  17842. int credits = 0;
  17843. bool queued;
  17844. /* Fill up the queue with tasks that will block until we give them credits to
  17845. * complete. */
  17846. for (unsigned int n = 0; n <= qlimit;) {
  17847. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17848. std::unique_lock<std::mutex> lock(sem_mtx);
  17849. while (credits <= 0) {
  17850. sem_cv.wait(lock);
  17851. }
  17852. /* Consume the credit and signal the test code if they are all gone. */
  17853. if (--credits == 0) { sem_cv.notify_one(); }
  17854. });
  17855. if (n < qlimit) {
  17856. /* The first qlimit enqueues must succeed. */
  17857. EXPECT_TRUE(queued);
  17858. } else {
  17859. /* The last one will succeed only when the worker thread
  17860. * starts and dequeues the first blocking task. Although
  17861. * not necessary for the correctness of this test, we sleep for
  17862. * a short while to avoid busy waiting. */
  17863. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17864. }
  17865. if (queued) { n++; }
  17866. }
  17867. /* Further enqueues must fail since the queue is full. */
  17868. for (auto i = 0; i < 4; i++) {
  17869. queued = task_queue->enqueue([] {});
  17870. EXPECT_FALSE(queued);
  17871. }
  17872. /* Give the credits to allow the previous tasks to complete. */
  17873. {
  17874. std::unique_lock<std::mutex> lock(sem_mtx);
  17875. credits += qlimit + 1;
  17876. }
  17877. sem_cv.notify_all();
  17878. /* Wait for all the credits to be consumed. */
  17879. {
  17880. std::unique_lock<std::mutex> lock(sem_mtx);
  17881. while (credits > 0) {
  17882. sem_cv.wait(lock);
  17883. }
  17884. }
  17885. /* Check that we are able again to enqueue at least qlimit tasks. */
  17886. for (unsigned int i = 0; i < qlimit; i++) {
  17887. queued = task_queue->enqueue([] {});
  17888. EXPECT_TRUE(queued);
  17889. }
  17890. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17891. task_queue->shutdown();
  17892. #else
  17893. EXPECT_NO_THROW(task_queue->shutdown());
  17894. #endif
  17895. }
  17896. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17897. Server svr;
  17898. std::string method;
  17899. std::string body;
  17900. auto has_content_length = false;
  17901. auto has_transfer_encoding = false;
  17902. std::atomic<int> bad_requests{0};
  17903. // Leftover body bytes get parsed as a malformed request and answered with
  17904. // 400
  17905. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17906. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17907. });
  17908. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17909. res.set_redirect("/down", StatusCode::SeeOther_303);
  17910. });
  17911. svr.Get("/down", [&](const Request &req, Response &res) {
  17912. method = req.method;
  17913. body = req.body;
  17914. has_content_length = req.has_header("Content-Length");
  17915. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17916. res.set_content("ok", "text/plain");
  17917. });
  17918. auto port = svr.bind_to_any_port(HOST);
  17919. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17920. auto se = detail::scope_exit([&] {
  17921. svr.stop();
  17922. thread.join();
  17923. ASSERT_FALSE(svr.is_running());
  17924. });
  17925. svr.wait_until_ready();
  17926. const std::string payload = "SECRET-BODY";
  17927. auto check = [&](Client &cli, const Result &res) {
  17928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17929. EXPECT_EQ(StatusCode::OK_200, res->status);
  17930. EXPECT_EQ("ok", res->body);
  17931. EXPECT_EQ("GET", method);
  17932. EXPECT_TRUE(body.empty());
  17933. EXPECT_FALSE(has_content_length);
  17934. EXPECT_FALSE(has_transfer_encoding);
  17935. // Nothing of the original body may be left on the connection
  17936. auto res2 = cli.Get("/down");
  17937. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17938. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17939. EXPECT_EQ("ok", res2->body);
  17940. EXPECT_EQ(0, bad_requests);
  17941. };
  17942. // With content length
  17943. {
  17944. Client cli(HOST, port);
  17945. cli.set_keep_alive(true);
  17946. cli.set_follow_location(true);
  17947. auto res = cli.Post(
  17948. "/up", payload.size(),
  17949. [&](size_t offset, size_t length, DataSink &sink) {
  17950. return sink.write(payload.data() + offset, length);
  17951. },
  17952. "text/plain");
  17953. check(cli, res);
  17954. }
  17955. // Without content length (chunked)
  17956. {
  17957. Client cli(HOST, port);
  17958. cli.set_keep_alive(true);
  17959. cli.set_follow_location(true);
  17960. auto res = cli.Post(
  17961. "/up",
  17962. [&](size_t /*offset*/, DataSink &sink) {
  17963. sink.write(payload.data(), payload.size());
  17964. sink.done();
  17965. return true;
  17966. },
  17967. "text/plain");
  17968. check(cli, res);
  17969. }
  17970. }
  17971. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17972. Server svr;
  17973. std::string target;
  17974. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17975. // Echo the still-encoded name back in the Location
  17976. const std::string prefix = "/start/";
  17977. res.status = StatusCode::Found_302;
  17978. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17979. });
  17980. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17981. target = req.target;
  17982. res.set_content("ok", "text/plain");
  17983. });
  17984. auto port = svr.bind_to_any_port(HOST);
  17985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17986. auto se = detail::scope_exit([&] {
  17987. svr.stop();
  17988. thread.join();
  17989. ASSERT_FALSE(svr.is_running());
  17990. });
  17991. svr.wait_until_ready();
  17992. // Decoding the Location path would turn the first four into a path
  17993. // separator, a query delimiter, a fragment delimiter and a different
  17994. // percent-encoded octet. The rest must keep reaching the server as they are.
  17995. const std::vector<std::string> names = {
  17996. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17997. };
  17998. for (auto path_encode : {true, false}) {
  17999. Client cli(HOST, port);
  18000. cli.set_follow_location(true);
  18001. cli.set_path_encode(path_encode);
  18002. for (const auto &name : names) {
  18003. target.clear();
  18004. auto res = cli.Get("/start/" + name);
  18005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18006. EXPECT_EQ(StatusCode::OK_200, res->status);
  18007. EXPECT_EQ("/dest/" + name, target);
  18008. }
  18009. }
  18010. }
  18011. TEST(RedirectTest, NotModifiedIsReturned) {
  18012. Server svr;
  18013. svr.Get("/cached", [](const Request &, Response &res) {
  18014. res.status = StatusCode::NotModified_304;
  18015. });
  18016. auto port = svr.bind_to_any_port(HOST);
  18017. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18018. auto se = detail::scope_exit([&] {
  18019. svr.stop();
  18020. thread.join();
  18021. ASSERT_FALSE(svr.is_running());
  18022. });
  18023. svr.wait_until_ready();
  18024. Client cli(HOST, port);
  18025. cli.set_follow_location(true);
  18026. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18028. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18029. }
  18030. TEST(RedirectTest, NoLocationIsReturned) {
  18031. Server svr;
  18032. svr.Get("/no-location", [](const Request &, Response &res) {
  18033. res.status = StatusCode::Found_302;
  18034. res.set_content("no location", "text/plain");
  18035. });
  18036. auto port = svr.bind_to_any_port(HOST);
  18037. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18038. auto se = detail::scope_exit([&] {
  18039. svr.stop();
  18040. thread.join();
  18041. ASSERT_FALSE(svr.is_running());
  18042. });
  18043. svr.wait_until_ready();
  18044. Client cli(HOST, port);
  18045. cli.set_follow_location(true);
  18046. auto res = cli.Get("/no-location");
  18047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18048. EXPECT_EQ(StatusCode::Found_302, res->status);
  18049. EXPECT_EQ("no location", res->body);
  18050. // The callbacks see the body of the response that is returned
  18051. auto handler_called = false;
  18052. auto progress_called = false;
  18053. std::string body;
  18054. auto res2 = cli.Get(
  18055. "/no-location",
  18056. [&](const Response &) {
  18057. handler_called = true;
  18058. return true;
  18059. },
  18060. [&](const char *data, size_t data_length) {
  18061. body.append(data, data_length);
  18062. return true;
  18063. },
  18064. [&](size_t, size_t) {
  18065. progress_called = true;
  18066. return true;
  18067. });
  18068. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18069. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18070. EXPECT_TRUE(handler_called);
  18071. EXPECT_TRUE(progress_called);
  18072. EXPECT_EQ("no location", body);
  18073. }
  18074. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18075. Server svr;
  18076. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18077. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18078. });
  18079. svr.Get("/hello", [](const Request &req, Response &res) {
  18080. res.set_content(req.get_param_value("key"), "text/plain");
  18081. });
  18082. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18083. auto se = detail::scope_exit([&] {
  18084. svr.stop();
  18085. thread.join();
  18086. ASSERT_FALSE(svr.is_running());
  18087. });
  18088. svr.wait_until_ready();
  18089. {
  18090. Client cli(HOST, PORT);
  18091. cli.set_follow_location(true);
  18092. auto res = cli.Get("/");
  18093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18094. EXPECT_EQ(StatusCode::OK_200, res->status);
  18095. EXPECT_EQ("val&key2=val2", res->body);
  18096. }
  18097. }
  18098. #endif
  18099. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18100. Server svr;
  18101. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18102. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18103. });
  18104. svr.Get("/hello", [](const Request &req, Response &res) {
  18105. res.set_content(req.get_param_value("key"), "text/plain");
  18106. });
  18107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18108. auto se = detail::scope_exit([&] {
  18109. svr.stop();
  18110. thread.join();
  18111. ASSERT_FALSE(svr.is_running());
  18112. });
  18113. svr.wait_until_ready();
  18114. {
  18115. Client cli(HOST, PORT);
  18116. cli.set_follow_location(true);
  18117. auto res = cli.Get("/");
  18118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18119. EXPECT_EQ(StatusCode::OK_200, res->status);
  18120. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18121. }
  18122. }
  18123. TEST(RedirectTest, RedirectWithPlusInPath) {
  18124. Server svr;
  18125. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18126. res.set_redirect("/a+b");
  18127. });
  18128. // Route pattern uses regex; escape + as \\+
  18129. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18130. res.set_content(req.path, "text/plain");
  18131. });
  18132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18133. auto se = detail::scope_exit([&] {
  18134. svr.stop();
  18135. thread.join();
  18136. ASSERT_FALSE(svr.is_running());
  18137. });
  18138. svr.wait_until_ready();
  18139. {
  18140. Client cli(HOST, PORT);
  18141. cli.set_follow_location(true);
  18142. auto res = cli.Get("/");
  18143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18144. EXPECT_EQ(StatusCode::OK_200, res->status);
  18145. EXPECT_EQ("/a+b", res->body);
  18146. }
  18147. }
  18148. TEST(RedirectTest, ResolveRelativeLocation) {
  18149. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18150. const std::vector<std::pair<std::string, std::string>> cases = {
  18151. {"g", "/b/c/g"},
  18152. {"./g", "/b/c/g"},
  18153. {"g/", "/b/c/g/"},
  18154. {"?y", "/b/c/d;p?y"},
  18155. {"g?y", "/b/c/g?y"},
  18156. {"#s", "/b/c/d;p?q#s"},
  18157. {"g#s", "/b/c/g#s"},
  18158. {"g?y#s", "/b/c/g?y#s"},
  18159. {";x", "/b/c/;x"},
  18160. {"g;x", "/b/c/g;x"},
  18161. {".", "/b/c/"},
  18162. {"./", "/b/c/"},
  18163. {"..", "/b/"},
  18164. {"../", "/b/"},
  18165. {"../g", "/b/g"},
  18166. {"../..", "/"},
  18167. {"../../", "/"},
  18168. {"../../g", "/g"},
  18169. {"../../../g", "/g"},
  18170. {"g.", "/b/c/g."},
  18171. {".g", "/b/c/.g"},
  18172. {"g..", "/b/c/g.."},
  18173. {"..g", "/b/c/..g"},
  18174. {"./../g", "/b/g"},
  18175. {"./g/.", "/b/c/g/"},
  18176. {"g/./h", "/b/c/g/h"},
  18177. {"g/../h", "/b/c/h"},
  18178. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18179. {"g;x=1/../y", "/b/c/y"},
  18180. {"g?y/./x", "/b/c/g?y/./x"},
  18181. {"g#s/../x", "/b/c/g#s/../x"},
  18182. // Not relative-path references, so left for parse_url.
  18183. {"/g", "/g"},
  18184. {"//g", "//g"},
  18185. {"http://g/x", "http://g/x"},
  18186. {"g:h", "g:h"},
  18187. };
  18188. for (const auto &c : cases) {
  18189. EXPECT_EQ(c.second,
  18190. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18191. << c.first;
  18192. }
  18193. // A result starting with "//" is still a path, not a network-path reference
  18194. EXPECT_EQ("/.//g",
  18195. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18196. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18197. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18198. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18199. }
  18200. TEST(RedirectTest, RemoveDotSegments) {
  18201. // RFC 3986 section 5.2.4
  18202. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18203. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18204. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18205. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18206. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18207. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18208. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18209. }
  18210. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18211. Server svr;
  18212. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18213. res.set_redirect("/dir/../target?x=1");
  18214. });
  18215. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18216. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18217. "/dir/./../target");
  18218. });
  18219. svr.Get("/target", [](const Request &req, Response &res) {
  18220. res.set_content(req.path, "text/plain");
  18221. });
  18222. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18223. auto se = detail::scope_exit([&] {
  18224. svr.stop();
  18225. th.join();
  18226. ASSERT_FALSE(svr.is_running());
  18227. });
  18228. svr.wait_until_ready();
  18229. Client cli("localhost", PORT);
  18230. cli.set_follow_location(true);
  18231. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18232. auto res = cli.Get(path);
  18233. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18234. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18235. EXPECT_EQ("/target", res->body) << path;
  18236. }
  18237. }
  18238. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18239. Server svr;
  18240. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18241. res.set_redirect(req.get_param_value("to"));
  18242. });
  18243. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18244. res.set_content(req.target, "text/plain");
  18245. });
  18246. svr.Get("/other", [](const Request &req, Response &res) {
  18247. res.set_content(req.target, "text/plain");
  18248. });
  18249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18250. auto se = detail::scope_exit([&] {
  18251. svr.stop();
  18252. thread.join();
  18253. ASSERT_FALSE(svr.is_running());
  18254. });
  18255. svr.wait_until_ready();
  18256. const std::vector<std::pair<std::string, std::string>> cases = {
  18257. {"next", "/dir/next"},
  18258. {"./next?x=1", "/dir/next?x=1"},
  18259. {"../other", "/other"},
  18260. };
  18261. for (const auto &c : cases) {
  18262. Client cli(HOST, PORT);
  18263. cli.set_follow_location(true);
  18264. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18265. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18266. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18267. EXPECT_EQ(c.second, res->body) << c.first;
  18268. }
  18269. }
  18270. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18271. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18272. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18273. Server other;
  18274. std::atomic<int> other_hits{0};
  18275. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18276. other_hits++;
  18277. res.set_content("other", "text/plain");
  18278. });
  18279. auto other_port = other.bind_to_any_port("127.0.0.1");
  18280. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18281. Server svr;
  18282. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18283. res.set_redirect(req.get_param_value("to"));
  18284. });
  18285. svr.Get(".*", [](const Request &req, Response &res) {
  18286. res.set_content(req.path, "text/plain");
  18287. });
  18288. auto port = svr.bind_to_any_port(HOST);
  18289. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18290. auto se = detail::scope_exit([&] {
  18291. svr.stop();
  18292. thread.join();
  18293. other.stop();
  18294. other_thread.join();
  18295. ASSERT_FALSE(svr.is_running());
  18296. ASSERT_FALSE(other.is_running());
  18297. });
  18298. svr.wait_until_ready();
  18299. other.wait_until_ready();
  18300. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18301. for (const auto &to :
  18302. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18303. Client cli(HOST, port);
  18304. cli.set_follow_location(true);
  18305. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18306. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18307. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18308. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18309. }
  18310. EXPECT_EQ(0, other_hits.load());
  18311. }
  18312. #ifdef CPPHTTPLIB_SSL_ENABLED
  18313. TEST(RedirectTest, Issue2185_Online) {
  18314. SSLClient client("github.com");
  18315. client.set_follow_location(true);
  18316. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18317. "Coollab-Windows.zip");
  18318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18319. EXPECT_EQ(StatusCode::OK_200, res->status);
  18320. EXPECT_EQ(9920427U, res->body.size());
  18321. }
  18322. #endif
  18323. TEST(VulnerabilityTest, CRLFInjection) {
  18324. Server svr;
  18325. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18326. res.set_content("Hello 1", "text/plain");
  18327. });
  18328. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18329. res.set_content("Hello 2", "text/plain");
  18330. });
  18331. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18332. res.set_content("Hello 3", "text/plain");
  18333. });
  18334. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18335. res.set_content("Hello 4", "text/plain");
  18336. });
  18337. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18338. for (const auto &x : req.headers) {
  18339. auto key = x.first;
  18340. EXPECT_STRNE("evil", key.c_str());
  18341. }
  18342. });
  18343. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18344. auto se = detail::scope_exit([&] {
  18345. svr.stop();
  18346. thread.join();
  18347. ASSERT_FALSE(svr.is_running());
  18348. });
  18349. svr.wait_until_ready();
  18350. {
  18351. Client cli(HOST, PORT);
  18352. cli.Post("/test1", "A=B",
  18353. "application/x-www-form-urlencoded\r\nevil: hello1");
  18354. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18355. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18356. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18357. }
  18358. }
  18359. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18360. auto server_thread = std::thread([] {
  18361. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18362. default_socket_options(srv);
  18363. sockaddr_in addr{};
  18364. addr.sin_family = AF_INET;
  18365. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18366. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18367. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18368. ::listen(srv, 1);
  18369. sockaddr_in cli_addr{};
  18370. socklen_t cli_len = sizeof(cli_addr);
  18371. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18372. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18373. std::string buf_all;
  18374. char buf[2048];
  18375. ssize_t n;
  18376. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18377. buf_all.append(buf, static_cast<size_t>(n));
  18378. size_t pos;
  18379. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18380. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18381. auto e = request_block.find("\r\n");
  18382. if (e != std::string::npos) {
  18383. auto request_line = request_block.substr(0, e);
  18384. std::string msg =
  18385. "CRLF injection detected in request line: '" + request_line + "'";
  18386. EXPECT_FALSE(true) << msg;
  18387. }
  18388. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18389. ::send(cli,
  18390. #ifdef _WIN32
  18391. static_cast<const char *>(resp.c_str()),
  18392. static_cast<int>(resp.size()),
  18393. #else
  18394. resp.c_str(), resp.size(),
  18395. #endif
  18396. 0);
  18397. buf_all.erase(0, pos + 4);
  18398. }
  18399. }
  18400. detail::close_socket(cli);
  18401. detail::close_socket(srv);
  18402. });
  18403. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18404. auto cli = Client("127.0.0.1", PORT + 1);
  18405. auto headers = Headers{
  18406. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18407. {"Connection", "keep-alive"}};
  18408. auto res = cli.Get("/hi", headers);
  18409. EXPECT_FALSE(res);
  18410. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18411. server_thread.join();
  18412. }
  18413. // A request rejected before any byte reaches the socket must fail right away
  18414. // instead of waiting for a response the server will never send.
  18415. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18416. // The kernel completes the TCP handshake from the listen backlog, so the
  18417. // client connects, but nothing ever reads, responds or closes.
  18418. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18419. default_socket_options(srv);
  18420. sockaddr_in addr{};
  18421. addr.sin_family = AF_INET;
  18422. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18423. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18424. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18425. ASSERT_EQ(0, ::listen(srv, 8));
  18426. auto cli = Client("127.0.0.1", PORT + 1);
  18427. cli.set_read_timeout(10, 0);
  18428. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18429. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18430. std::chrono::steady_clock::now() - start)
  18431. .count();
  18432. };
  18433. {
  18434. Request req;
  18435. req.method = "GE T";
  18436. req.path = "/";
  18437. auto start = std::chrono::steady_clock::now();
  18438. auto res = cli.send(req);
  18439. EXPECT_FALSE(res);
  18440. EXPECT_EQ(Error::Write, res.error());
  18441. EXPECT_LT(elapsed_ms(start), 1000);
  18442. }
  18443. {
  18444. auto start = std::chrono::steady_clock::now();
  18445. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18446. EXPECT_FALSE(res);
  18447. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18448. EXPECT_LT(elapsed_ms(start), 1000);
  18449. }
  18450. EXPECT_FALSE(cli.is_socket_open());
  18451. detail::close_socket(srv);
  18452. }
  18453. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18454. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18455. default_socket_options(srv);
  18456. sockaddr_in addr{};
  18457. addr.sin_family = AF_INET;
  18458. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18459. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18460. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18461. ASSERT_EQ(0, ::listen(srv, 1));
  18462. std::string received;
  18463. auto server_thread = std::thread([&] {
  18464. auto sock = ::accept(srv, nullptr, nullptr);
  18465. if (sock == INVALID_SOCKET) { return; }
  18466. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18467. char buf[2048];
  18468. ssize_t n;
  18469. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18470. received.append(buf, static_cast<size_t>(n));
  18471. }
  18472. detail::close_socket(sock);
  18473. });
  18474. {
  18475. auto cli = Client("127.0.0.1", PORT + 1);
  18476. // "Z" sorts after the default headers, so writing straight to the socket
  18477. // would have sent the request line and those headers before the rejection.
  18478. auto handle =
  18479. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18480. EXPECT_FALSE(handle.is_valid());
  18481. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18482. }
  18483. server_thread.join();
  18484. detail::close_socket(srv);
  18485. EXPECT_TRUE(received.empty()) << received;
  18486. }
  18487. TEST(PathParamsTest, StaticMatch) {
  18488. const auto pattern = "/users/all";
  18489. detail::PathParamsMatcher matcher(pattern);
  18490. Request request;
  18491. request.path = "/users/all";
  18492. ASSERT_TRUE(matcher.match(request));
  18493. std::unordered_map<std::string, std::string> expected_params = {};
  18494. EXPECT_EQ(request.path_params, expected_params);
  18495. }
  18496. TEST(PathParamsTest, StaticMismatch) {
  18497. const auto pattern = "/users/all";
  18498. detail::PathParamsMatcher matcher(pattern);
  18499. Request request;
  18500. request.path = "/users/1";
  18501. ASSERT_FALSE(matcher.match(request));
  18502. }
  18503. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18504. const auto pattern = "/users/:id/subscriptions";
  18505. detail::PathParamsMatcher matcher(pattern);
  18506. Request request;
  18507. request.path = "/users/42/subscriptions";
  18508. ASSERT_TRUE(matcher.match(request));
  18509. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18510. EXPECT_EQ(request.path_params, expected_params);
  18511. }
  18512. TEST(PathParamsTest, SingleParamInTheEnd) {
  18513. const auto pattern = "/users/:id";
  18514. detail::PathParamsMatcher matcher(pattern);
  18515. Request request;
  18516. request.path = "/users/24";
  18517. ASSERT_TRUE(matcher.match(request));
  18518. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18519. EXPECT_EQ(request.path_params, expected_params);
  18520. }
  18521. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18522. const auto pattern = "/users/:id/";
  18523. detail::PathParamsMatcher matcher(pattern);
  18524. Request request;
  18525. request.path = "/users/42/";
  18526. ASSERT_TRUE(matcher.match(request));
  18527. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18528. EXPECT_EQ(request.path_params, expected_params);
  18529. }
  18530. TEST(PathParamsTest, EmptyParam) {
  18531. const auto pattern = "/users/:id/";
  18532. detail::PathParamsMatcher matcher(pattern);
  18533. Request request;
  18534. request.path = "/users//";
  18535. ASSERT_TRUE(matcher.match(request));
  18536. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18537. EXPECT_EQ(request.path_params, expected_params);
  18538. }
  18539. TEST(PathParamsTest, FragmentMismatch) {
  18540. const auto pattern = "/users/:id/";
  18541. detail::PathParamsMatcher matcher(pattern);
  18542. Request request;
  18543. request.path = "/admins/24/";
  18544. ASSERT_FALSE(matcher.match(request));
  18545. }
  18546. TEST(PathParamsTest, ExtraFragments) {
  18547. const auto pattern = "/users/:id";
  18548. detail::PathParamsMatcher matcher(pattern);
  18549. Request request;
  18550. request.path = "/users/42/subscriptions";
  18551. ASSERT_FALSE(matcher.match(request));
  18552. }
  18553. TEST(PathParamsTest, MissingTrailingParam) {
  18554. const auto pattern = "/users/:id";
  18555. detail::PathParamsMatcher matcher(pattern);
  18556. Request request;
  18557. request.path = "/users";
  18558. ASSERT_FALSE(matcher.match(request));
  18559. }
  18560. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18561. const auto pattern = "/users/:id/subscriptions";
  18562. detail::PathParamsMatcher matcher(pattern);
  18563. Request request;
  18564. request.path = "/users/subscriptions";
  18565. ASSERT_FALSE(matcher.match(request));
  18566. }
  18567. TEST(PathParamsTest, MultipleParams) {
  18568. const auto pattern = "/users/:userid/subscriptions/:subid";
  18569. detail::PathParamsMatcher matcher(pattern);
  18570. Request request;
  18571. request.path = "/users/42/subscriptions/2";
  18572. ASSERT_TRUE(matcher.match(request));
  18573. std::unordered_map<std::string, std::string> expected_params = {
  18574. {"userid", "42"}, {"subid", "2"}};
  18575. EXPECT_EQ(request.path_params, expected_params);
  18576. }
  18577. TEST(PathParamsTest, SequenceOfParams) {
  18578. const auto pattern = "/values/:x/:y/:z";
  18579. detail::PathParamsMatcher matcher(pattern);
  18580. Request request;
  18581. request.path = "/values/1/2/3";
  18582. ASSERT_TRUE(matcher.match(request));
  18583. std::unordered_map<std::string, std::string> expected_params = {
  18584. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18585. EXPECT_EQ(request.path_params, expected_params);
  18586. }
  18587. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18588. const auto pattern = "/prefix:suffix";
  18589. detail::PathParamsMatcher matcher(pattern);
  18590. Request request;
  18591. request.path = "/prefix:suffix";
  18592. ASSERT_TRUE(matcher.match(request));
  18593. const std::unordered_map<std::string, std::string> expected_params = {};
  18594. EXPECT_EQ(request.path_params, expected_params);
  18595. }
  18596. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18597. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18598. // calling thread's stack on a long enough path for a quantified pattern;
  18599. // RegexMatcher must refuse to run regex matching on paths beyond
  18600. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18601. detail::RegexMatcher matcher("/files/(.*)");
  18602. Request within_limit;
  18603. within_limit.path = "/files/" + std::string(10, 'A');
  18604. EXPECT_TRUE(matcher.match(within_limit));
  18605. Request over_limit;
  18606. over_limit.path =
  18607. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18608. EXPECT_FALSE(matcher.match(over_limit));
  18609. }
  18610. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18611. Server svr;
  18612. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18613. res.set_content("ok", "text/plain");
  18614. });
  18615. auto port = svr.bind_to_any_port(HOST);
  18616. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18617. auto se = detail::scope_exit([&] {
  18618. svr.stop();
  18619. thread.join();
  18620. ASSERT_FALSE(svr.is_running());
  18621. });
  18622. svr.wait_until_ready();
  18623. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18624. // request URI limit; this used to be able to crash the process.
  18625. std::string path =
  18626. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18627. std::string req = "GET " + path +
  18628. " HTTP/1.1\r\n"
  18629. "Host: " +
  18630. std::string(HOST) + ":" + std::to_string(port) +
  18631. "\r\n"
  18632. "Connection: close\r\n"
  18633. "\r\n";
  18634. std::string response;
  18635. ASSERT_TRUE(send_request(5, req, &response, port));
  18636. EXPECT_NE(std::string::npos, response.find("404"));
  18637. }
  18638. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18639. Server svr;
  18640. auto handler = [](const Request & /*req*/, Response &res) {
  18641. res.set_content("hit", "text/plain");
  18642. };
  18643. // No regex metacharacter, so this one is compared literally
  18644. svr.Get("/literal/route", handler);
  18645. // '.' is a regex metacharacter, so this one must keep regex semantics
  18646. svr.Get("/a.c", handler);
  18647. auto port = svr.bind_to_any_port(HOST);
  18648. std::thread t([&]() { svr.listen_after_bind(); });
  18649. auto se = detail::scope_exit([&] {
  18650. svr.stop();
  18651. t.join();
  18652. ASSERT_FALSE(svr.is_running());
  18653. });
  18654. svr.wait_until_ready();
  18655. Client cli(HOST, port);
  18656. struct {
  18657. const char *path;
  18658. int status;
  18659. } cases[] = {
  18660. {"/literal/route", StatusCode::OK_200},
  18661. {"/literal/routes", StatusCode::NotFound_404},
  18662. {"/literal/rout", StatusCode::NotFound_404},
  18663. {"/abc", StatusCode::OK_200},
  18664. {"/a.c", StatusCode::OK_200},
  18665. };
  18666. for (const auto &x : cases) {
  18667. auto res = cli.Get(x.path);
  18668. ASSERT_TRUE(res) << x.path;
  18669. EXPECT_EQ(x.status, res->status) << x.path;
  18670. }
  18671. }
  18672. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18673. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18674. // from exhausting the stack, so it must only constrain routes that actually
  18675. // run a regular expression. A literal route is matched by comparison and
  18676. // stays usable at any length.
  18677. Server svr;
  18678. const std::string pattern =
  18679. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18680. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18681. res.set_content("hit", "text/plain");
  18682. });
  18683. auto port = svr.bind_to_any_port(HOST);
  18684. std::thread t([&]() { svr.listen_after_bind(); });
  18685. auto se = detail::scope_exit([&] {
  18686. svr.stop();
  18687. t.join();
  18688. ASSERT_FALSE(svr.is_running());
  18689. });
  18690. svr.wait_until_ready();
  18691. Client cli(HOST, port);
  18692. auto res = cli.Get(pattern);
  18693. ASSERT_TRUE(res);
  18694. EXPECT_EQ(StatusCode::OK_200, res->status);
  18695. }
  18696. TEST(ParseUrlTest, VariousPatterns) {
  18697. {
  18698. detail::UrlComponents uc;
  18699. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18700. EXPECT_EQ("http", uc.scheme);
  18701. EXPECT_EQ("example.com", uc.host);
  18702. EXPECT_EQ("8080", uc.port);
  18703. EXPECT_EQ("/path", uc.path);
  18704. EXPECT_EQ("?q=1", uc.query);
  18705. }
  18706. {
  18707. detail::UrlComponents uc;
  18708. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18709. EXPECT_EQ("https", uc.scheme);
  18710. EXPECT_EQ("example.com", uc.host);
  18711. EXPECT_TRUE(uc.port.empty());
  18712. EXPECT_EQ("/path", uc.path);
  18713. }
  18714. {
  18715. detail::UrlComponents uc;
  18716. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18717. EXPECT_EQ("::1", uc.host);
  18718. EXPECT_EQ("8080", uc.port);
  18719. EXPECT_EQ("/path", uc.path);
  18720. }
  18721. {
  18722. detail::UrlComponents uc;
  18723. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18724. }
  18725. {
  18726. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18727. // the path while the connection still targets the bracketed host.
  18728. detail::UrlComponents uc;
  18729. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18730. }
  18731. {
  18732. detail::UrlComponents uc;
  18733. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18734. }
  18735. {
  18736. detail::UrlComponents uc;
  18737. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18738. EXPECT_EQ("::1", uc.host);
  18739. EXPECT_TRUE(uc.port.empty());
  18740. EXPECT_EQ("/path", uc.path);
  18741. }
  18742. {
  18743. detail::UrlComponents uc;
  18744. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18745. EXPECT_TRUE(uc.scheme.empty());
  18746. EXPECT_EQ("example.com", uc.host);
  18747. EXPECT_EQ("/path", uc.path);
  18748. EXPECT_EQ("?q=1", uc.query);
  18749. }
  18750. {
  18751. detail::UrlComponents uc;
  18752. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18753. EXPECT_TRUE(uc.host.empty());
  18754. EXPECT_EQ("/path", uc.path);
  18755. EXPECT_EQ("?q=1", uc.query);
  18756. }
  18757. {
  18758. detail::UrlComponents uc;
  18759. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18760. EXPECT_EQ("example.com", uc.host);
  18761. EXPECT_EQ("8080", uc.port);
  18762. }
  18763. {
  18764. // Unix socket path — must not be parsed as host
  18765. detail::UrlComponents uc;
  18766. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18767. EXPECT_TRUE(uc.host.empty());
  18768. }
  18769. {
  18770. detail::UrlComponents uc;
  18771. ASSERT_TRUE(detail::parse_url("", uc));
  18772. EXPECT_TRUE(uc.host.empty());
  18773. EXPECT_TRUE(uc.path.empty());
  18774. }
  18775. {
  18776. detail::UrlComponents uc;
  18777. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18778. EXPECT_EQ("http", uc.scheme);
  18779. }
  18780. {
  18781. detail::UrlComponents uc;
  18782. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18783. }
  18784. {
  18785. // Accepted by parse_url; callers restrict to http/https
  18786. detail::UrlComponents uc;
  18787. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18788. EXPECT_EQ("ftp", uc.scheme);
  18789. }
  18790. {
  18791. detail::UrlComponents uc;
  18792. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18793. }
  18794. {
  18795. detail::UrlComponents uc;
  18796. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18797. }
  18798. }
  18799. TEST(ParseUrlTest, FragmentHandling) {
  18800. {
  18801. detail::UrlComponents uc;
  18802. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18803. EXPECT_EQ("/path", uc.path);
  18804. EXPECT_TRUE(uc.query.empty());
  18805. }
  18806. {
  18807. detail::UrlComponents uc;
  18808. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18809. EXPECT_TRUE(uc.path.empty());
  18810. EXPECT_TRUE(uc.query.empty());
  18811. }
  18812. }
  18813. TEST(ParseUrlTest, UserinfoHandling) {
  18814. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18815. // parsers would see evil.com as the host.
  18816. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18817. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18818. for (auto url : urls) {
  18819. detail::UrlComponents uc;
  18820. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18821. }
  18822. }
  18823. TEST(ParseUrlTest, IPv6EdgeCases) {
  18824. {
  18825. detail::UrlComponents uc;
  18826. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18827. EXPECT_TRUE(uc.scheme.empty());
  18828. EXPECT_EQ("::1", uc.host);
  18829. EXPECT_EQ("8080", uc.port);
  18830. }
  18831. {
  18832. // Zone ID '%25' is not in [a-fA-F0-9:]
  18833. detail::UrlComponents uc;
  18834. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18835. }
  18836. }
  18837. TEST(ParseUrlTest, SchemeEdgeCases) {
  18838. {
  18839. detail::UrlComponents uc;
  18840. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18841. }
  18842. {
  18843. detail::UrlComponents uc;
  18844. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18845. }
  18846. {
  18847. detail::UrlComponents uc;
  18848. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18849. }
  18850. {
  18851. detail::UrlComponents uc;
  18852. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18853. EXPECT_EQ("https", uc.scheme);
  18854. }
  18855. }
  18856. TEST(ParseUrlTest, PortEdgeCases) {
  18857. {
  18858. detail::UrlComponents uc;
  18859. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18860. EXPECT_TRUE(uc.port.empty());
  18861. EXPECT_EQ("/path", uc.path);
  18862. }
  18863. {
  18864. // parse_url accepts any port string; validation is done by parse_port
  18865. detail::UrlComponents uc;
  18866. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18867. EXPECT_EQ("abc", uc.port);
  18868. }
  18869. }
  18870. TEST(ParseUrlTest, WebSocketPatterns) {
  18871. {
  18872. detail::UrlComponents uc;
  18873. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18874. EXPECT_EQ("ws", uc.scheme);
  18875. EXPECT_EQ("echo.example.com", uc.host);
  18876. EXPECT_EQ("8080", uc.port);
  18877. EXPECT_EQ("/ws", uc.path);
  18878. }
  18879. {
  18880. detail::UrlComponents uc;
  18881. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18882. EXPECT_EQ("wss", uc.scheme);
  18883. EXPECT_EQ("echo.example.com", uc.host);
  18884. EXPECT_TRUE(uc.port.empty());
  18885. EXPECT_EQ("/ws", uc.path);
  18886. }
  18887. }
  18888. TEST(ParseUrlTest, QueryOnly) {
  18889. detail::UrlComponents uc;
  18890. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18891. EXPECT_TRUE(uc.host.empty());
  18892. EXPECT_TRUE(uc.path.empty());
  18893. EXPECT_EQ("?q=1&r=2", uc.query);
  18894. }
  18895. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18896. detail::UrlComponents uc;
  18897. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18898. EXPECT_TRUE(uc.scheme.empty());
  18899. EXPECT_EQ("example.com", uc.host);
  18900. EXPECT_EQ("443", uc.port);
  18901. EXPECT_EQ("/path", uc.path);
  18902. }
  18903. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18904. // If ipv6 regex working, regex match codepath is taken.
  18905. // else port will default to 80 in Client impl
  18906. int clientImplMagicPort = 80;
  18907. int port = 4321;
  18908. // above ports must be different to avoid false negative
  18909. EXPECT_NE(clientImplMagicPort, port);
  18910. std::string ipV6TestURL = "http://[ff06::c3]";
  18911. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18912. CLIENT_PRIVATE_KEY_FILE);
  18913. EXPECT_EQ(cli.port(), port);
  18914. }
  18915. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18916. auto file_path = "./www/dir/index.html";
  18917. auto dir_path = "./www/dir";
  18918. detail::FileStat stat_file(file_path);
  18919. EXPECT_TRUE(stat_file.is_file());
  18920. EXPECT_FALSE(stat_file.is_dir());
  18921. detail::FileStat stat_dir(dir_path);
  18922. EXPECT_FALSE(stat_dir.is_file());
  18923. EXPECT_TRUE(stat_dir.is_dir());
  18924. }
  18925. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18926. // IPv4 with default HTTP port (80)
  18927. EXPECT_EQ("example.com",
  18928. detail::make_host_and_port_string("example.com", 80, false));
  18929. // IPv4 with default HTTPS port (443)
  18930. EXPECT_EQ("example.com",
  18931. detail::make_host_and_port_string("example.com", 443, true));
  18932. // IPv4 with non-default HTTP port
  18933. EXPECT_EQ("example.com:8080",
  18934. detail::make_host_and_port_string("example.com", 8080, false));
  18935. // IPv4 with non-default HTTPS port
  18936. EXPECT_EQ("example.com:8443",
  18937. detail::make_host_and_port_string("example.com", 8443, true));
  18938. // IPv6 with default HTTP port (80)
  18939. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18940. // IPv6 with default HTTPS port (443)
  18941. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18942. // IPv6 with non-default HTTP port
  18943. EXPECT_EQ("[::1]:8080",
  18944. detail::make_host_and_port_string("::1", 8080, false));
  18945. // IPv6 with non-default HTTPS port
  18946. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18947. // IPv6 full address with default port
  18948. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18949. detail::make_host_and_port_string(
  18950. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18951. // IPv6 full address with non-default port
  18952. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18953. detail::make_host_and_port_string(
  18954. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18955. // IPv6 localhost with non-default port
  18956. EXPECT_EQ("[::1]:3000",
  18957. detail::make_host_and_port_string("::1", 3000, false));
  18958. // IPv6 with zone ID (link-local address) with default port
  18959. EXPECT_EQ("[fe80::1%eth0]",
  18960. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18961. // IPv6 with zone ID (link-local address) with non-default port
  18962. EXPECT_EQ("[fe80::1%eth0]:8080",
  18963. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18964. // Edge case: Port 443 with is_ssl=false (should add port)
  18965. EXPECT_EQ("example.com:443",
  18966. detail::make_host_and_port_string("example.com", 443, false));
  18967. // Edge case: Port 80 with is_ssl=true (should add port)
  18968. EXPECT_EQ("example.com:80",
  18969. detail::make_host_and_port_string("example.com", 80, true));
  18970. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18971. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18972. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18973. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18974. // Security fix: Already bracketed IPv6 should not get double brackets
  18975. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18976. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18977. EXPECT_EQ("[::1]:8080",
  18978. detail::make_host_and_port_string("[::1]", 8080, false));
  18979. EXPECT_EQ("[2001:db8::1]:8080",
  18980. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18981. EXPECT_EQ("[fe80::1%eth0]",
  18982. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18983. EXPECT_EQ("[fe80::1%eth0]:8080",
  18984. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18985. // Edge case: Empty host (should return as-is)
  18986. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18987. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18988. // This is a known limitation but shouldn't crash
  18989. EXPECT_EQ("[host:name]",
  18990. detail::make_host_and_port_string("host:name", 80, false));
  18991. // Port number edge cases (no validation, but should not crash)
  18992. EXPECT_EQ("example.com:0",
  18993. detail::make_host_and_port_string("example.com", 0, false));
  18994. EXPECT_EQ("example.com:-1",
  18995. detail::make_host_and_port_string("example.com", -1, false));
  18996. EXPECT_EQ("example.com:65535",
  18997. detail::make_host_and_port_string("example.com", 65535, false));
  18998. EXPECT_EQ("example.com:65536",
  18999. detail::make_host_and_port_string("example.com", 65536, false));
  19000. }
  19001. namespace httplib {
  19002. namespace detail {
  19003. std::string
  19004. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19005. const std::string &host, int port);
  19006. } // namespace detail
  19007. } // namespace httplib
  19008. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19009. std::map<std::string, std::string> addr_map = {
  19010. {"ipv4.example", "192.0.2.10"},
  19011. {"ipv6.example", "2001:db8::1"},
  19012. {"name.example", "internal.example.lan"},
  19013. {"empty.example", ""}};
  19014. EXPECT_EQ("192.0.2.10:443",
  19015. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19016. EXPECT_EQ("[2001:db8::1]:443",
  19017. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19018. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19019. addr_map, "name.example", 8443));
  19020. // An empty or absent mapping keeps the hostname as the target
  19021. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19022. addr_map, "empty.example", 443));
  19023. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19024. addr_map, "other.example", 443));
  19025. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19026. }
  19027. #ifdef CPPHTTPLIB_SSL_ENABLED
  19028. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19029. httplib::SSLClient cli("roblox.com", 443);
  19030. cli.set_follow_location(true);
  19031. auto res = cli.Get("/");
  19032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19033. EXPECT_EQ(StatusCode::OK_200, res->status);
  19034. }
  19035. #endif
  19036. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19037. Server svr;
  19038. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19039. EXPECT_EQ(res.status, 400);
  19040. });
  19041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19042. auto se = detail::scope_exit([&] {
  19043. svr.stop();
  19044. thread.join();
  19045. ASSERT_FALSE(svr.is_running());
  19046. });
  19047. svr.wait_until_ready();
  19048. Client cli(HOST, PORT);
  19049. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19050. }
  19051. TEST(InvalidHeaderCharsTest, is_field_name) {
  19052. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19053. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19054. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19055. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19056. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19057. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19058. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19059. EXPECT_FALSE(detail::fields::is_field_name(""));
  19060. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19061. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19062. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19063. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19064. }
  19065. TEST(InvalidHeaderCharsTest, is_field_value) {
  19066. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19067. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19068. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19069. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19070. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19071. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19072. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19073. EXPECT_TRUE(detail::fields::is_field_value(""));
  19074. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19075. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19076. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19077. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19078. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19079. }
  19080. TEST(InvalidHeaderCharsTest, OnServer) {
  19081. Server svr;
  19082. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19083. std::string header = "Not Set";
  19084. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19085. res.set_header(header, "value");
  19086. res.set_content("Page Content Page Content", "text/plain");
  19087. });
  19088. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19089. std::string header = "Not Set";
  19090. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19091. res.set_header("X-Test", header);
  19092. res.set_content("Page Content Page Content", "text/plain");
  19093. });
  19094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19095. auto se = detail::scope_exit([&] {
  19096. svr.stop();
  19097. thread.join();
  19098. ASSERT_FALSE(svr.is_running());
  19099. });
  19100. svr.wait_until_ready();
  19101. Client cli(HOST, PORT);
  19102. {
  19103. auto res = cli.Get(
  19104. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19106. EXPECT_EQ("Page Content Page Content", res->body);
  19107. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19108. }
  19109. {
  19110. auto res = cli.Get(
  19111. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19113. EXPECT_EQ("Page Content Page Content", res->body);
  19114. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19115. }
  19116. }
  19117. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19118. auto handled = false;
  19119. Server svr;
  19120. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19121. thread t = thread([&] { svr.listen(HOST, PORT); });
  19122. auto se = detail::scope_exit([&] {
  19123. svr.stop();
  19124. t.join();
  19125. ASSERT_FALSE(svr.is_running());
  19126. ASSERT_FALSE(handled);
  19127. });
  19128. svr.wait_until_ready();
  19129. auto req = "POST /test HTTP/1.1\r\n"
  19130. "Content-Length: x\r\n"
  19131. "\r\n";
  19132. std::string response;
  19133. ASSERT_TRUE(send_request(1, req, &response));
  19134. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19135. response.substr(0, response.find("\r\n")));
  19136. }
  19137. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19138. // case-insensitive, and a server that receives a 100-continue expectation in
  19139. // an HTTP/1.0 request MUST ignore it.
  19140. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19141. std::string response;
  19142. ASSERT_TRUE(send_request(1, req, &response, port));
  19143. *got_100 = response.find("100 Continue") != std::string::npos;
  19144. }
  19145. class ExpectTokenTest : public ::testing::Test {
  19146. protected:
  19147. void SetUp() override {
  19148. svr_.Post("/p", [](const Request &, Response &res) {
  19149. res.set_content("ok", "text/plain");
  19150. });
  19151. port_ = svr_.bind_to_any_port(HOST);
  19152. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19153. svr_.wait_until_ready();
  19154. }
  19155. void TearDown() override {
  19156. svr_.stop();
  19157. if (thread_.joinable()) { thread_.join(); }
  19158. }
  19159. std::string request(const char *version, const char *expect_value) const {
  19160. return std::string("POST /p ") + version +
  19161. "\r\n"
  19162. "Host: localhost\r\n"
  19163. "Content-Length: 2\r\n"
  19164. "Connection: close\r\n"
  19165. "Expect: " +
  19166. expect_value +
  19167. "\r\n"
  19168. "\r\n"
  19169. "hi";
  19170. }
  19171. Server svr_;
  19172. int port_ = 0;
  19173. thread thread_;
  19174. };
  19175. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19176. bool got_100 = false;
  19177. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19178. EXPECT_TRUE(got_100);
  19179. }
  19180. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19181. bool got_100 = true;
  19182. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19183. EXPECT_FALSE(got_100);
  19184. }
  19185. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19186. bool got_100 = false;
  19187. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19188. EXPECT_TRUE(got_100);
  19189. }
  19190. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19191. bool got_100 = false;
  19192. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19193. EXPECT_TRUE(got_100);
  19194. }
  19195. // `100 Continue` is sent only when the server starts reading the body, so a
  19196. // request rejected before that never invites the client to send it. The
  19197. // requests below carry the expectation but withhold the body, as a client
  19198. // waiting for `100 Continue` would.
  19199. // A POST that expects `100 Continue` and withholds its two-byte body.
  19200. static std::string expect_headers_only(const std::string &path) {
  19201. return "POST " + path +
  19202. " HTTP/1.1\r\n"
  19203. "Host: localhost\r\n"
  19204. "Content-Length: 2\r\n"
  19205. "Expect: 100-continue\r\n"
  19206. "\r\n";
  19207. }
  19208. class ExpectLazyContinueTest : public ::testing::Test {
  19209. protected:
  19210. void SetUp() override {
  19211. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19212. if (req.path == "/pre-routing") {
  19213. res.status = StatusCode::Unauthorized_401;
  19214. return Server::HandlerResponse::Handled;
  19215. }
  19216. return Server::HandlerResponse::Unhandled;
  19217. });
  19218. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19219. if (req.matched_route == "/pre-request") {
  19220. res.status = StatusCode::Forbidden_403;
  19221. return Server::HandlerResponse::Handled;
  19222. }
  19223. return Server::HandlerResponse::Unhandled;
  19224. });
  19225. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19226. res.set_content("ok", "text/plain");
  19227. });
  19228. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19229. res.set_content("ok", "text/plain");
  19230. });
  19231. svr_.Post("/reader-used", [](const Request &, Response &res,
  19232. const ContentReader &content_reader) {
  19233. std::string body;
  19234. content_reader([&](const char *data, size_t len) {
  19235. body.append(data, len);
  19236. return true;
  19237. });
  19238. res.set_content(body, "text/plain");
  19239. });
  19240. svr_.Post("/reader-unused",
  19241. [](const Request &, Response &res, const ContentReader &) {
  19242. res.set_content("ignored", "text/plain");
  19243. });
  19244. port_ = svr_.bind_to_any_port(HOST);
  19245. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19246. svr_.wait_until_ready();
  19247. }
  19248. void TearDown() override {
  19249. svr_.stop();
  19250. if (thread_.joinable()) { thread_.join(); }
  19251. }
  19252. // Sends `req` and reads until the server closes the connection. Returns
  19253. // false if the read had to wait for the client-side timeout instead.
  19254. bool send_until_closed(const std::string &req, std::string *resp) const {
  19255. auto start = std::chrono::steady_clock::now();
  19256. if (!send_request(3, req, resp, port_)) { return false; }
  19257. auto elapsed = std::chrono::steady_clock::now() - start;
  19258. return elapsed < std::chrono::seconds(2);
  19259. }
  19260. // The final response comes without `100 Continue`, and the server closes
  19261. // the connection since the body may or may not follow.
  19262. void expect_final_without_interim(const std::string &path,
  19263. const char *status_line) const {
  19264. std::string resp;
  19265. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19266. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19267. EXPECT_EQ(0u, resp.find(status_line));
  19268. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19269. }
  19270. Server svr_;
  19271. int port_ = 0;
  19272. thread thread_;
  19273. };
  19274. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19275. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19276. }
  19277. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19278. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19279. }
  19280. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19281. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19282. }
  19283. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19284. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19285. }
  19286. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19287. // The body follows once `100 Continue` has had time to arrive.
  19288. auto req = expect_headers_only("/reader-used");
  19289. req.insert(req.size() - 2, "Connection: close\r\n");
  19290. std::string resp;
  19291. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19292. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19293. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19294. EXPECT_NE(std::string::npos, resp.find("hi"));
  19295. }
  19296. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19297. // Large enough for the client to add `Expect: 100-continue` itself.
  19298. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19299. std::atomic<bool> body_sent{false};
  19300. Client cli(HOST, port_);
  19301. auto res = cli.Post(
  19302. "/pre-request", length,
  19303. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19304. body_sent = true;
  19305. std::string chunk(len, 'x');
  19306. sink.write(chunk.data(), chunk.size());
  19307. return true;
  19308. },
  19309. "application/octet-stream");
  19310. ASSERT_TRUE(res);
  19311. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19312. EXPECT_FALSE(body_sent);
  19313. }
  19314. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19315. Server svr;
  19316. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19317. return StatusCode::ExpectationFailed_417;
  19318. });
  19319. svr.Post("/p", [](const Request &, Response &res) {
  19320. res.set_content("ok", "text/plain");
  19321. });
  19322. auto port = svr.bind_to_any_port(HOST);
  19323. thread t = thread([&] { svr.listen_after_bind(); });
  19324. auto se = detail::scope_exit([&] {
  19325. svr.stop();
  19326. t.join();
  19327. });
  19328. svr.wait_until_ready();
  19329. std::string resp;
  19330. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19331. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19332. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19333. // Exactly one response: the route handler must not run after the 417.
  19334. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19335. }
  19336. #ifndef _WIN32
  19337. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19338. static constexpr char reject[] = "Unauthorized";
  19339. static constexpr char accept[] = "Upload accepted";
  19340. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19341. Server svr;
  19342. svr.set_expect_100_continue_handler(
  19343. [](const Request & /*req*/, Response &res) {
  19344. res.status = StatusCode::Unauthorized_401;
  19345. res.set_content(reject, "text/plain");
  19346. return res.status;
  19347. });
  19348. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19349. res.set_content(accept, "text/plain");
  19350. });
  19351. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19352. auto se = detail::scope_exit([&] {
  19353. svr.stop();
  19354. thread.join();
  19355. ASSERT_FALSE(svr.is_running());
  19356. });
  19357. svr.wait_until_ready();
  19358. {
  19359. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19360. curl_easy_init(), &curl_easy_cleanup};
  19361. ASSERT_NE(curl, nullptr);
  19362. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19363. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19364. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19365. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19366. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19367. &curl_slist_free_all};
  19368. ASSERT_NE(list, nullptr);
  19369. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19370. struct read_data {
  19371. uint64_t read_size;
  19372. uint64_t total_size;
  19373. } data = {0, total_size};
  19374. using read_callback_t =
  19375. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19376. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19377. void *userdata) -> size_t {
  19378. read_data *d = (read_data *)userdata;
  19379. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19380. std::fill_n(ptr, size * nmemb, 'A');
  19381. d->read_size += size * nmemb;
  19382. return size * nmemb;
  19383. };
  19384. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19385. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19386. std::vector<char> buffer;
  19387. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19388. using write_callback_t =
  19389. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19390. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19391. void *userdata) -> size_t {
  19392. std::vector<char> *buf = (std::vector<char> *)userdata;
  19393. buf->reserve(buf->size() + size * nmemb + 1);
  19394. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19395. return size * nmemb;
  19396. };
  19397. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19398. {
  19399. const auto res = curl_easy_perform(curl.get());
  19400. ASSERT_EQ(res, CURLE_OK);
  19401. }
  19402. {
  19403. auto response_code = long{};
  19404. const auto res =
  19405. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19406. ASSERT_EQ(res, CURLE_OK);
  19407. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19408. }
  19409. {
  19410. auto dl = curl_off_t{};
  19411. const auto res =
  19412. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19413. ASSERT_EQ(res, CURLE_OK);
  19414. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19415. }
  19416. {
  19417. buffer.push_back('\0');
  19418. ASSERT_STRCASEEQ(buffer.data(), reject);
  19419. }
  19420. }
  19421. }
  19422. #endif
  19423. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19424. // Regression test for #2458.
  19425. //
  19426. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19427. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19428. // ticket can make the client socket spuriously readable during the
  19429. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19430. // the client withholds the body and then blocks reading a response that never
  19431. // comes, failing with `Failed to read connection`.
  19432. //
  19433. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19434. // within the timeout. This raw OpenSSL server deliberately never sends
  19435. // `100 Continue`; the client must still deliver the body and receive 200.
  19436. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19437. signal(SIGPIPE, SIG_IGN);
  19438. const auto port = PORT + 4;
  19439. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19440. ASSERT_NE(srv, INVALID_SOCKET);
  19441. int opt = 1;
  19442. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19443. sockaddr_in addr{};
  19444. addr.sin_family = AF_INET;
  19445. addr.sin_port = htons(static_cast<uint16_t>(port));
  19446. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19447. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19448. ASSERT_EQ(0, ::listen(srv, 1));
  19449. std::atomic<size_t> server_body_bytes{0};
  19450. auto server_thread = std::thread([&] {
  19451. sockaddr_in cli_addr{};
  19452. socklen_t cli_len = sizeof(cli_addr);
  19453. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19454. if (cli == INVALID_SOCKET) { return; }
  19455. // Bound the lifetime of the server side so a buggy client (which never
  19456. // sends the body) cannot make this thread block forever on join.
  19457. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19458. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19459. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19460. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19461. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19462. SSL *ssl = SSL_new(ctx);
  19463. SSL_set_fd(ssl, static_cast<int>(cli));
  19464. if (SSL_accept(ssl) > 0) {
  19465. // Read the request headers. Reading here also flushes the TLS 1.3
  19466. // session tickets to the client. Deliberately do NOT send
  19467. // `100 Continue`.
  19468. std::string buf;
  19469. char tmp[1024];
  19470. while (buf.find("\r\n\r\n") == std::string::npos) {
  19471. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19472. if (n <= 0) { break; }
  19473. buf.append(tmp, static_cast<size_t>(n));
  19474. }
  19475. // A correct client sends the body now; count what arrives.
  19476. auto pos = buf.find("\r\n\r\n");
  19477. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19478. while (body < 4096) {
  19479. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19480. if (n <= 0) { break; }
  19481. body += static_cast<size_t>(n);
  19482. }
  19483. server_body_bytes = body;
  19484. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19485. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19486. SSL_shutdown(ssl);
  19487. }
  19488. SSL_free(ssl);
  19489. detail::close_socket(cli);
  19490. SSL_CTX_free(ctx);
  19491. });
  19492. auto se = detail::scope_exit([&] {
  19493. server_thread.join();
  19494. detail::close_socket(srv);
  19495. });
  19496. SSLClient cli("127.0.0.1", port);
  19497. cli.enable_server_certificate_verification(false);
  19498. cli.set_connection_timeout(5, 0);
  19499. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19500. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19501. std::string body(4096, 'A');
  19502. auto res = cli.Put("/api/test", body, "application/json");
  19503. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19504. EXPECT_EQ(StatusCode::OK_200, res->status);
  19505. EXPECT_EQ(body.size(), server_body_bytes.load());
  19506. }
  19507. #endif
  19508. template <typename S, typename C>
  19509. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19510. svr.Get("/stream", [&](const Request &, Response &res) {
  19511. auto data = new std::string("01234567890123456789");
  19512. res.set_content_provider(
  19513. data->size(), "text/plain",
  19514. [&, data](size_t offset, size_t length, DataSink &sink) {
  19515. const size_t DATA_CHUNK_SIZE = 4;
  19516. const auto &d = *data;
  19517. std::this_thread::sleep_for(std::chrono::seconds(1));
  19518. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19519. return true;
  19520. },
  19521. [data](bool success) {
  19522. EXPECT_FALSE(success);
  19523. delete data;
  19524. });
  19525. });
  19526. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19527. auto i = new size_t(0);
  19528. res.set_content_provider(
  19529. "text/plain",
  19530. [i](size_t, DataSink &sink) {
  19531. if (*i < 5) {
  19532. std::this_thread::sleep_for(std::chrono::seconds(1));
  19533. sink.write("abcd", 4);
  19534. (*i)++;
  19535. } else {
  19536. sink.done();
  19537. }
  19538. return true;
  19539. },
  19540. [i](bool success) {
  19541. EXPECT_FALSE(success);
  19542. delete i;
  19543. });
  19544. });
  19545. svr.Get("/chunked", [&](const Request &, Response &res) {
  19546. auto i = new size_t(0);
  19547. res.set_chunked_content_provider(
  19548. "text/plain",
  19549. [i](size_t, DataSink &sink) {
  19550. if (*i < 5) {
  19551. std::this_thread::sleep_for(std::chrono::seconds(1));
  19552. sink.os << "abcd";
  19553. (*i)++;
  19554. } else {
  19555. sink.done();
  19556. }
  19557. return true;
  19558. },
  19559. [i](bool success) {
  19560. EXPECT_FALSE(success);
  19561. delete i;
  19562. });
  19563. });
  19564. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19565. auto se = detail::scope_exit([&] {
  19566. svr.stop();
  19567. listen_thread.join();
  19568. ASSERT_FALSE(svr.is_running());
  19569. });
  19570. svr.wait_until_ready();
  19571. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19572. {
  19573. auto start = std::chrono::steady_clock::now();
  19574. auto res = cli.Get("/stream");
  19575. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19576. std::chrono::steady_clock::now() - start)
  19577. .count();
  19578. ASSERT_FALSE(res);
  19579. EXPECT_EQ(Error::Read, res.error());
  19580. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19581. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19582. }
  19583. {
  19584. auto start = std::chrono::steady_clock::now();
  19585. auto res = cli.Get("/stream_without_length");
  19586. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19587. std::chrono::steady_clock::now() - start)
  19588. .count();
  19589. ASSERT_FALSE(res);
  19590. EXPECT_EQ(Error::Read, res.error());
  19591. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19592. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19593. }
  19594. {
  19595. auto start = std::chrono::steady_clock::now();
  19596. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19597. EXPECT_EQ("abcd", string(data, data_length));
  19598. return true;
  19599. });
  19600. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19601. std::chrono::steady_clock::now() - start)
  19602. .count();
  19603. ASSERT_FALSE(res);
  19604. EXPECT_EQ(Error::Read, res.error());
  19605. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19606. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19607. }
  19608. }
  19609. TEST(MaxTimeoutTest, ContentStream) {
  19610. time_t timeout = 2000;
  19611. time_t threshold = 200;
  19612. Server svr;
  19613. Client cli("localhost", PORT);
  19614. max_timeout_test(svr, cli, timeout, threshold);
  19615. }
  19616. #ifdef CPPHTTPLIB_SSL_ENABLED
  19617. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19618. time_t timeout = 2000;
  19619. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19621. SSLClient cli("localhost", PORT);
  19622. cli.enable_server_certificate_verification(false);
  19623. max_timeout_test(svr, cli, timeout, threshold);
  19624. }
  19625. #endif
  19626. class EventDispatcher {
  19627. public:
  19628. EventDispatcher() {}
  19629. bool wait_event(DataSink *sink) {
  19630. unique_lock<mutex> lk(m_);
  19631. int id = id_;
  19632. // Wait with timeout to prevent hanging if client disconnects
  19633. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19634. [&] { return cid_ == id; })) {
  19635. return false; // Timeout occurred
  19636. }
  19637. sink->write(message_.data(), message_.size());
  19638. return true;
  19639. }
  19640. void send_event(const string &message) {
  19641. lock_guard<mutex> lk(m_);
  19642. cid_ = id_++;
  19643. message_ = message;
  19644. cv_.notify_all();
  19645. }
  19646. private:
  19647. mutex m_;
  19648. condition_variable cv_;
  19649. atomic_int id_{0};
  19650. atomic_int cid_{-1};
  19651. string message_;
  19652. };
  19653. TEST(ClientInThreadTest, Issue2068) {
  19654. EventDispatcher ed;
  19655. Server svr;
  19656. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19657. res.set_chunked_content_provider("text/event-stream",
  19658. [&](size_t /*offset*/, DataSink &sink) {
  19659. return ed.wait_event(&sink);
  19660. });
  19661. });
  19662. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19663. svr.wait_until_ready();
  19664. thread event_thread([&] {
  19665. int id = 0;
  19666. while (svr.is_running()) {
  19667. this_thread::sleep_for(chrono::milliseconds(500));
  19668. std::stringstream ss;
  19669. ss << "data: " << id << "\n\n";
  19670. ed.send_event(ss.str());
  19671. id++;
  19672. }
  19673. });
  19674. auto se = detail::scope_exit([&] {
  19675. svr.stop();
  19676. listen_thread.join();
  19677. event_thread.join();
  19678. ASSERT_FALSE(svr.is_running());
  19679. });
  19680. {
  19681. auto client = detail::make_unique<Client>(HOST, PORT);
  19682. client->set_read_timeout(std::chrono::minutes(10));
  19683. std::atomic<bool> stop{false};
  19684. std::thread t([&] {
  19685. client->Get("/event1",
  19686. [&](const char *, size_t) -> bool { return !stop; });
  19687. });
  19688. std::this_thread::sleep_for(std::chrono::seconds(2));
  19689. stop = true;
  19690. client->stop();
  19691. t.join();
  19692. // Reset client after thread has finished
  19693. client.reset();
  19694. }
  19695. }
  19696. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19697. auto handled = false;
  19698. Server svr;
  19699. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19700. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19701. auto se = detail::scope_exit([&] {
  19702. svr.stop();
  19703. t.join();
  19704. ASSERT_FALSE(svr.is_running());
  19705. ASSERT_FALSE(handled);
  19706. });
  19707. svr.wait_until_ready();
  19708. // Two Content-Length headers with different values — must be rejected
  19709. auto req = "POST /test HTTP/1.1\r\n"
  19710. "Content-Length: 5\r\n"
  19711. "Content-Length: 10\r\n"
  19712. "\r\n"
  19713. "hello";
  19714. std::string response;
  19715. ASSERT_TRUE(send_request(1, req, &response));
  19716. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19717. response.substr(0, response.find("\r\n")));
  19718. }
  19719. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19720. auto handled = false;
  19721. Server svr;
  19722. svr.Post("/test", [&](const Request &, Response &res) {
  19723. handled = true;
  19724. res.set_content("ok", "text/plain");
  19725. });
  19726. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19727. auto se = detail::scope_exit([&] {
  19728. svr.stop();
  19729. t.join();
  19730. ASSERT_FALSE(svr.is_running());
  19731. ASSERT_TRUE(handled);
  19732. });
  19733. svr.wait_until_ready();
  19734. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19735. auto req = "POST /test HTTP/1.1\r\n"
  19736. "Host: localhost\r\n"
  19737. "Content-Length: 5\r\n"
  19738. "Content-Length: 5\r\n"
  19739. "\r\n"
  19740. "hello";
  19741. std::string response;
  19742. ASSERT_TRUE(send_request(1, req, &response));
  19743. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19744. }
  19745. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19746. Server svr;
  19747. svr.Get("/test", [](const Request &, Response &res) {
  19748. res.set_content("ok", "text/plain");
  19749. });
  19750. auto port = svr.bind_to_any_port(HOST);
  19751. thread t = thread([&] { svr.listen_after_bind(); });
  19752. auto se = detail::scope_exit([&] {
  19753. svr.stop();
  19754. t.join();
  19755. ASSERT_FALSE(svr.is_running());
  19756. });
  19757. svr.wait_until_ready();
  19758. auto status_line = [&](const std::string &host_lines) {
  19759. std::string res;
  19760. send_request(
  19761. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19762. &res, port);
  19763. return res.substr(0, res.find("\r\n"));
  19764. };
  19765. const char *accepted[] = {
  19766. "Host: localhost\r\n",
  19767. "Host: a.example:8080\r\n",
  19768. "Host: my_service\r\n",
  19769. "Host: [::1]:8080\r\n",
  19770. "Host: [fe80::1%25eth0]\r\n",
  19771. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19772. };
  19773. for (auto host_lines : accepted) {
  19774. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19775. }
  19776. const char *rejected[] = {
  19777. "Host: a.example\r\nHost: b.example\r\n",
  19778. "Host: a.example\r\nHost: a.example\r\n",
  19779. "Host: a@b.example\r\n",
  19780. "Host: a.example/b\r\n",
  19781. "Host: a.example\\b\r\n",
  19782. "Host: a.example?b\r\n",
  19783. "Host: a.example#b\r\n",
  19784. "Host: a.example b.example\r\n",
  19785. };
  19786. for (auto host_lines : rejected) {
  19787. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19788. << host_lines;
  19789. }
  19790. }
  19791. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19792. Server svr;
  19793. svr.Get("/", [](const Request &req, Response &res) {
  19794. EXPECT_EQ(2U, req.trailers.size());
  19795. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19796. // Denied
  19797. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19798. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19799. // Accepted
  19800. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19801. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19802. EXPECT_TRUE(req.has_trailer("X-World"));
  19803. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19804. res.set_content("ok", "text/plain");
  19805. });
  19806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19807. auto se = detail::scope_exit([&] {
  19808. svr.stop();
  19809. t.join();
  19810. ASSERT_FALSE(svr.is_running());
  19811. });
  19812. svr.wait_until_ready();
  19813. const std::string req = "GET / HTTP/1.1\r\n"
  19814. "Transfer-Encoding: chunked\r\n"
  19815. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19816. "\r\n"
  19817. "0\r\n"
  19818. "Content-Length: 10\r\n"
  19819. "Host: internal.local\r\n"
  19820. "Content-Type: malicious/content\r\n"
  19821. "Cookie: any\r\n"
  19822. "Set-Cookie: any\r\n"
  19823. "X-Forwarded-For: attacker.com\r\n"
  19824. "X-Real-Ip: 1.1.1.1\r\n"
  19825. "X-Hello: hello\r\n"
  19826. "X-World: world\r\n"
  19827. "\r\n";
  19828. std::string res;
  19829. ASSERT_TRUE(send_request(1, req, &res));
  19830. }
  19831. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19832. // several field lines, and the combined value is what has to be parsed. A
  19833. // Trailer field split across lines therefore declares every name it lists;
  19834. // reading only the first line silently drops the trailers the later lines
  19835. // declare. The prohibited-trailer filter still applies to every line.
  19836. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19837. Server svr;
  19838. size_t observed_trailer_count = 0;
  19839. std::string observed_hello;
  19840. std::string observed_world;
  19841. bool observed_content_length = true;
  19842. svr.Get("/", [&](const Request &req, Response &res) {
  19843. observed_trailer_count = req.trailers.size();
  19844. observed_hello = req.get_trailer_value("X-Hello");
  19845. observed_world = req.get_trailer_value("X-World");
  19846. observed_content_length = req.has_trailer("Content-Length");
  19847. res.set_content("ok", "text/plain");
  19848. });
  19849. auto port = svr.bind_to_any_port(HOST);
  19850. thread t = thread([&]() { svr.listen_after_bind(); });
  19851. auto se = detail::scope_exit([&] {
  19852. svr.stop();
  19853. t.join();
  19854. ASSERT_FALSE(svr.is_running());
  19855. });
  19856. svr.wait_until_ready();
  19857. const std::string req = "GET / HTTP/1.1\r\n"
  19858. "Host: localhost\r\n"
  19859. "Transfer-Encoding: chunked\r\n"
  19860. "Trailer: X-Hello\r\n"
  19861. "Trailer: X-World, Content-Length\r\n"
  19862. "\r\n"
  19863. "0\r\n"
  19864. "X-Hello: hello\r\n"
  19865. "X-World: world\r\n"
  19866. "Content-Length: 10\r\n"
  19867. "\r\n";
  19868. std::string res;
  19869. ASSERT_TRUE(send_request(1, req, &res, port));
  19870. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19871. // Accepted: both field lines contribute to the declared set
  19872. EXPECT_EQ(2U, observed_trailer_count);
  19873. EXPECT_EQ(observed_hello, "hello");
  19874. EXPECT_EQ(observed_world, "world");
  19875. // Denied: a prohibited name stays prohibited on a later field line
  19876. EXPECT_FALSE(observed_content_length);
  19877. }
  19878. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19879. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19880. // unbounded run of fields that are never declared, because the counter would
  19881. // only advance for declared fields.
  19882. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19883. Server svr;
  19884. bool handler_called = false;
  19885. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19886. handler_called = true;
  19887. res.set_content("ok", "text/plain");
  19888. });
  19889. auto port = svr.bind_to_any_port(HOST);
  19890. thread t = thread([&]() { svr.listen_after_bind(); });
  19891. auto se = detail::scope_exit([&] {
  19892. svr.stop();
  19893. t.join();
  19894. ASSERT_FALSE(svr.is_running());
  19895. });
  19896. svr.wait_until_ready();
  19897. // Declare nothing, then send far more undeclared trailer fields than the
  19898. // header-count limit. Parsing must stop and reject the request rather than
  19899. // read every line.
  19900. std::string req = "GET / HTTP/1.1\r\n"
  19901. "Transfer-Encoding: chunked\r\n"
  19902. "\r\n"
  19903. "0\r\n";
  19904. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19905. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19906. }
  19907. req += "\r\n";
  19908. std::string res;
  19909. ASSERT_TRUE(send_request(1, req, &res, port));
  19910. // The request is rejected before the handler runs.
  19911. EXPECT_FALSE(handler_called);
  19912. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19913. }
  19914. // The set of declared trailer names is capped so a peer cannot grow it without
  19915. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19916. // declared past the cap is not honored, even if the field is actually sent.
  19917. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19918. Server svr;
  19919. // One name inside the cap and one past it, so the test tracks the cap rather
  19920. // than a fixed count.
  19921. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19922. const std::string within_cap_name = "X-T-0";
  19923. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19924. bool observed_within_cap = false;
  19925. bool observed_past_cap = false;
  19926. svr.Get("/", [&](const Request &req, Response &res) {
  19927. observed_within_cap = req.has_trailer(within_cap_name);
  19928. observed_past_cap = req.has_trailer(past_cap_name);
  19929. res.set_content("ok", "text/plain");
  19930. });
  19931. auto port = svr.bind_to_any_port(HOST);
  19932. thread t = thread([&]() { svr.listen_after_bind(); });
  19933. auto se = detail::scope_exit([&] {
  19934. svr.stop();
  19935. t.join();
  19936. ASSERT_FALSE(svr.is_running());
  19937. });
  19938. svr.wait_until_ready();
  19939. // Declare more trailer names than the cap in a single Trailer field, then
  19940. // actually send the first (within the cap) and the last (past it).
  19941. std::string trailer_decl = "Trailer: ";
  19942. for (int i = 0; i < declared_count; i++) {
  19943. if (i != 0) { trailer_decl += ", "; }
  19944. trailer_decl += "X-T-" + std::to_string(i);
  19945. }
  19946. trailer_decl += "\r\n";
  19947. const std::string req = "GET / HTTP/1.1\r\n"
  19948. "Host: localhost\r\n"
  19949. "Transfer-Encoding: chunked\r\n" +
  19950. trailer_decl +
  19951. "\r\n"
  19952. "0\r\n" +
  19953. within_cap_name + ": a\r\n" + past_cap_name +
  19954. ": b\r\n"
  19955. "\r\n";
  19956. std::string res;
  19957. ASSERT_TRUE(send_request(1, req, &res, port));
  19958. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19959. // A name within the cap is honored; one declared past the cap is dropped.
  19960. EXPECT_TRUE(observed_within_cap);
  19961. EXPECT_FALSE(observed_past_cap);
  19962. }
  19963. // A direct client that is not listed in trusted_proxies must not be able to
  19964. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19965. // the peer address on the actual TCP connection determines whether the
  19966. // header is honored.
  19967. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19968. Server svr;
  19969. // Deliberately does NOT include the loopback address the test client
  19970. // actually connects from, so the direct connection is not a trusted proxy.
  19971. svr.set_trusted_proxies({"203.0.113.66"});
  19972. std::string observed_remote_addr;
  19973. svr.Get("/ip", [&](const Request &req, Response &res) {
  19974. observed_remote_addr = req.remote_addr;
  19975. res.set_content("ok", "text/plain");
  19976. });
  19977. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19978. auto se = detail::scope_exit([&] {
  19979. svr.stop();
  19980. t.join();
  19981. ASSERT_FALSE(svr.is_running());
  19982. });
  19983. svr.wait_until_ready();
  19984. Client cli(HOST, PORT);
  19985. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19987. EXPECT_EQ(StatusCode::OK_200, res->status);
  19988. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19989. // ignored entirely and the real connection-level address retained.
  19990. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19991. observed_remote_addr == "127.0.0.1");
  19992. }
  19993. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19994. Server svr;
  19995. std::string observed_remote_addr;
  19996. std::string observed_xff;
  19997. svr.Get("/ip", [&](const Request &req, Response &res) {
  19998. observed_remote_addr = req.remote_addr;
  19999. observed_xff = req.get_header_value("X-Forwarded-For");
  20000. res.set_content("ok", "text/plain");
  20001. });
  20002. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20003. auto se = detail::scope_exit([&] {
  20004. svr.stop();
  20005. t.join();
  20006. ASSERT_FALSE(svr.is_running());
  20007. });
  20008. svr.wait_until_ready();
  20009. Client cli(HOST, PORT);
  20010. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20012. EXPECT_EQ(StatusCode::OK_200, res->status);
  20013. EXPECT_EQ(observed_xff, "203.0.113.66");
  20014. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20015. observed_remote_addr == "127.0.0.1");
  20016. }
  20017. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20018. Server svr;
  20019. svr.set_trusted_proxies({"203.0.113.66"});
  20020. std::string observed_remote_addr;
  20021. std::string observed_xff;
  20022. svr.Get("/ip", [&](const Request &req, Response &res) {
  20023. observed_remote_addr = req.remote_addr;
  20024. observed_xff = req.get_header_value("X-Forwarded-For");
  20025. res.set_content("ok", "text/plain");
  20026. });
  20027. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20028. auto se = detail::scope_exit([&] {
  20029. svr.stop();
  20030. t.join();
  20031. ASSERT_FALSE(svr.is_running());
  20032. });
  20033. svr.wait_until_ready();
  20034. Client cli(HOST, PORT);
  20035. auto res = cli.Get("/ip");
  20036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20037. EXPECT_EQ(StatusCode::OK_200, res->status);
  20038. EXPECT_EQ(observed_xff, "");
  20039. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20040. observed_remote_addr == "127.0.0.1");
  20041. }
  20042. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20043. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20044. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20045. Server svr;
  20046. svr.set_trusted_proxies({"127.0.0.1"});
  20047. svr.Get("/ip", [](const Request &req, Response &res) {
  20048. res.set_content(req.remote_addr, "text/plain");
  20049. });
  20050. auto port = svr.bind_to_any_port("::");
  20051. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20052. thread t = thread([&] { svr.listen_after_bind(); });
  20053. auto se = detail::scope_exit([&] {
  20054. svr.stop();
  20055. t.join();
  20056. ASSERT_FALSE(svr.is_running());
  20057. });
  20058. svr.wait_until_ready();
  20059. Client cli("127.0.0.1", port);
  20060. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20062. EXPECT_EQ("198.51.100.23", res->body);
  20063. }
  20064. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20065. Server svr;
  20066. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20067. svr.Get("/ip", [](const Request &req, Response &res) {
  20068. res.set_content(req.remote_addr, "text/plain");
  20069. });
  20070. auto port = svr.bind_to_any_port(HOST);
  20071. ASSERT_GT(port, 0);
  20072. thread t = thread([&] { svr.listen_after_bind(); });
  20073. auto se = detail::scope_exit([&] {
  20074. svr.stop();
  20075. t.join();
  20076. ASSERT_FALSE(svr.is_running());
  20077. });
  20078. svr.wait_until_ready();
  20079. Client cli(HOST, port);
  20080. auto res = cli.Get(
  20081. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20083. EXPECT_EQ("198.51.100.23", res->body);
  20084. }
  20085. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20086. Server svr;
  20087. // Include the loopback address the test client actually connects from, so
  20088. // the direct connection itself is recognized as the trusted proxy hop.
  20089. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20090. std::string observed_remote_addr;
  20091. std::string observed_xff;
  20092. svr.Get("/ip", [&](const Request &req, Response &res) {
  20093. observed_remote_addr = req.remote_addr;
  20094. observed_xff = req.get_header_value("X-Forwarded-For");
  20095. res.set_content("ok", "text/plain");
  20096. });
  20097. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20098. auto se = detail::scope_exit([&] {
  20099. svr.stop();
  20100. t.join();
  20101. ASSERT_FALSE(svr.is_running());
  20102. });
  20103. svr.wait_until_ready();
  20104. Client cli(HOST, PORT);
  20105. auto res = cli.Get(
  20106. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20108. EXPECT_EQ(StatusCode::OK_200, res->status);
  20109. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20110. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20111. }
  20112. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20113. Server svr;
  20114. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20115. std::string observed_remote_addr;
  20116. std::string observed_xff;
  20117. svr.Get("/ip", [&](const Request &req, Response &res) {
  20118. observed_remote_addr = req.remote_addr;
  20119. observed_xff = req.get_header_value("X-Forwarded-For");
  20120. res.set_content("ok", "text/plain");
  20121. });
  20122. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20123. auto se = detail::scope_exit([&] {
  20124. svr.stop();
  20125. t.join();
  20126. ASSERT_FALSE(svr.is_running());
  20127. });
  20128. svr.wait_until_ready();
  20129. Client cli(HOST, PORT);
  20130. auto res = cli.Get(
  20131. "/ip",
  20132. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20134. EXPECT_EQ(StatusCode::OK_200, res->status);
  20135. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20136. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20137. }
  20138. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20139. Server svr;
  20140. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20141. std::string observed_remote_addr;
  20142. std::string observed_xff;
  20143. svr.Get("/ip", [&](const Request &req, Response &res) {
  20144. observed_remote_addr = req.remote_addr;
  20145. observed_xff = req.get_header_value("X-Forwarded-For");
  20146. res.set_content("ok", "text/plain");
  20147. });
  20148. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20149. auto se = detail::scope_exit([&] {
  20150. svr.stop();
  20151. t.join();
  20152. ASSERT_FALSE(svr.is_running());
  20153. });
  20154. svr.wait_until_ready();
  20155. Client cli(HOST, PORT);
  20156. auto res = cli.Get(
  20157. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20159. EXPECT_EQ(StatusCode::OK_200, res->status);
  20160. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20161. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20162. // and must not be selected.
  20163. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20164. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20165. }
  20166. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20167. Server svr;
  20168. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20169. std::string observed_remote_addr;
  20170. svr.Get("/ip", [&](const Request &req, Response &res) {
  20171. observed_remote_addr = req.remote_addr;
  20172. res.set_content("ok", "text/plain");
  20173. });
  20174. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20175. auto se = detail::scope_exit([&] {
  20176. svr.stop();
  20177. t.join();
  20178. ASSERT_FALSE(svr.is_running());
  20179. });
  20180. svr.wait_until_ready();
  20181. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20182. // a forged address and the trusted proxy's own address; the forged value must
  20183. // not win over the address the trusted proxy actually recorded.
  20184. Client cli(HOST, PORT);
  20185. auto res = cli.Get(
  20186. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20188. EXPECT_EQ(StatusCode::OK_200, res->status);
  20189. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20190. }
  20191. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20192. Server svr;
  20193. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20194. std::string observed_remote_addr;
  20195. std::string observed_xff;
  20196. svr.Get("/ip", [&](const Request &req, Response &res) {
  20197. observed_remote_addr = req.remote_addr;
  20198. observed_xff = req.get_header_value("X-Forwarded-For");
  20199. res.set_content("ok", "text/plain");
  20200. });
  20201. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20202. auto se = detail::scope_exit([&] {
  20203. svr.stop();
  20204. t.join();
  20205. ASSERT_FALSE(svr.is_running());
  20206. });
  20207. svr.wait_until_ready();
  20208. Client cli(HOST, PORT);
  20209. auto res = cli.Get(
  20210. "/ip",
  20211. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20213. EXPECT_EQ(StatusCode::OK_200, res->status);
  20214. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20215. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20216. }
  20217. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20218. Server svr;
  20219. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20220. std::string observed_remote_addr;
  20221. std::string observed_xff;
  20222. svr.Get("/ip", [&](const Request &req, Response &res) {
  20223. observed_remote_addr = req.remote_addr;
  20224. observed_xff = req.get_header_value("X-Forwarded-For");
  20225. res.set_content("ok", "text/plain");
  20226. });
  20227. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20228. auto se = detail::scope_exit([&] {
  20229. svr.stop();
  20230. t.join();
  20231. ASSERT_FALSE(svr.is_running());
  20232. });
  20233. svr.wait_until_ready();
  20234. std::string raw_req =
  20235. "GET /ip HTTP/1.1\r\n"
  20236. "Host: localhost\r\n"
  20237. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20238. "Connection: close\r\n"
  20239. "\r\n";
  20240. std::string out;
  20241. ASSERT_TRUE(send_request(5, raw_req, &out));
  20242. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20243. // Header parser trims surrounding whitespace of the header value
  20244. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20245. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20246. }
  20247. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20248. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20249. // their own X-Forwarded-For as a separate field line rather than extending the
  20250. // one the client sent, so every occurrence has to be taken into account.
  20251. // Reading only the first one hands back the address the client chose.
  20252. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20253. Server svr;
  20254. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20255. std::string observed_remote_addr;
  20256. size_t observed_xff_count = 0;
  20257. svr.Get("/ip", [&](const Request &req, Response &res) {
  20258. observed_remote_addr = req.remote_addr;
  20259. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20260. res.set_content("ok", "text/plain");
  20261. });
  20262. auto port = svr.bind_to_any_port(HOST);
  20263. thread t = thread([&]() { svr.listen_after_bind(); });
  20264. auto se = detail::scope_exit([&] {
  20265. svr.stop();
  20266. t.join();
  20267. ASSERT_FALSE(svr.is_running());
  20268. });
  20269. svr.wait_until_ready();
  20270. // The client supplies the first field line; the trusted proxy appends the
  20271. // address it observed as a second one.
  20272. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20273. "Host: localhost\r\n"
  20274. "X-Forwarded-For: 1.2.3.4\r\n"
  20275. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20276. "Connection: close\r\n"
  20277. "\r\n";
  20278. std::string out;
  20279. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20280. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20281. EXPECT_EQ(observed_xff_count, 2U);
  20282. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20283. // The same chain spread over one field line per hop derives the same client
  20284. // address, i.e. the split and the comma-joined representations agree.
  20285. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20286. "Host: localhost\r\n"
  20287. "X-Forwarded-For: 1.2.3.4\r\n"
  20288. "X-Forwarded-For: 198.51.100.23\r\n"
  20289. "X-Forwarded-For: 192.0.2.45\r\n"
  20290. "Connection: close\r\n"
  20291. "\r\n";
  20292. out.clear();
  20293. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20294. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20295. EXPECT_EQ(observed_xff_count, 3U);
  20296. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20297. }
  20298. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20299. // crash the server (it used to call front() on an empty vector inside
  20300. // get_client_ip). The connection-level remote address must be retained instead.
  20301. static void run_malformed_xff_test(const std::string &xff_value) {
  20302. Server svr;
  20303. svr.set_trusted_proxies({"192.0.2.45"});
  20304. std::string observed_remote_addr;
  20305. svr.Get("/ip", [&](const Request &req, Response &res) {
  20306. observed_remote_addr = req.remote_addr;
  20307. res.set_content("ok", "text/plain");
  20308. });
  20309. int port = 0;
  20310. thread t = thread([&]() {
  20311. port = svr.bind_to_any_port(HOST);
  20312. svr.listen_after_bind();
  20313. });
  20314. auto se = detail::scope_exit([&] {
  20315. svr.stop();
  20316. t.join();
  20317. ASSERT_FALSE(svr.is_running());
  20318. });
  20319. svr.wait_until_ready();
  20320. Client cli(HOST, port);
  20321. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20323. EXPECT_EQ(StatusCode::OK_200, res->status);
  20324. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20325. observed_remote_addr == "127.0.0.1");
  20326. }
  20327. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20328. run_malformed_xff_test("");
  20329. }
  20330. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20331. run_malformed_xff_test(",");
  20332. }
  20333. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20334. run_malformed_xff_test(", , ,");
  20335. }
  20336. // The same rule applies to Accept: a request whose acceptable types are spread
  20337. // over several field lines must be negotiated against all of them.
  20338. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20339. // case-insensitive connection options. Comparing the whole field value against
  20340. // one option misses a client that sends several of them, and misses every
  20341. // casing but the one written in the comparison.
  20342. //
  20343. // Sends req, reads the response, then reuses the same socket for a second
  20344. // request to find out whether the server kept the connection.
  20345. static void probe_connection_reuse(int port, const std::string &req,
  20346. bool *announced_close, bool *reusable) {
  20347. auto error = Error::Success;
  20348. auto sock = detail::create_client_socket(
  20349. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20350. /*connection_timeout_sec=*/5, 0,
  20351. /*read_timeout_sec=*/1, 0,
  20352. /*write_timeout_sec=*/5, 0, std::string(), error);
  20353. ASSERT_NE(sock, INVALID_SOCKET);
  20354. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20355. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20356. "Host: localhost\r\n"
  20357. "Connection: close\r\n"
  20358. "\r\n";
  20359. std::string first_response;
  20360. std::string second_response;
  20361. detail::process_client_socket(
  20362. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20363. [&](Stream &strm) {
  20364. if (strm.write(req.data(), req.size()) !=
  20365. static_cast<ssize_t>(req.size())) {
  20366. return false;
  20367. }
  20368. char buf[512];
  20369. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20370. // Headers plus the two-byte body of the handler below
  20371. while (reader.getline()) {
  20372. first_response += reader.ptr();
  20373. if (first_response.find("ok") != std::string::npos) { break; }
  20374. }
  20375. if (strm.write(second.data(), second.size()) !=
  20376. static_cast<ssize_t>(second.size())) {
  20377. return true;
  20378. }
  20379. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20380. while (reader2.getline()) {
  20381. second_response += reader2.ptr();
  20382. if (second_response.find("ok") != std::string::npos) { break; }
  20383. }
  20384. return true;
  20385. });
  20386. *announced_close =
  20387. first_response.find("Connection: close") != std::string::npos;
  20388. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20389. }
  20390. class ConnectionTokenTest : public ::testing::Test {
  20391. protected:
  20392. void SetUp() override {
  20393. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20394. res.set_content("ok", "text/plain");
  20395. });
  20396. port_ = svr_.bind_to_any_port(HOST);
  20397. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20398. svr_.wait_until_ready();
  20399. }
  20400. void TearDown() override {
  20401. svr_.stop();
  20402. if (thread_.joinable()) { thread_.join(); }
  20403. }
  20404. Server svr_;
  20405. int port_ = 0;
  20406. thread thread_;
  20407. };
  20408. // "close" alongside another option still closes the connection, and the
  20409. // response says so rather than leaving the peer to discover it.
  20410. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20411. bool announced_close = false;
  20412. bool reusable = true;
  20413. probe_connection_reuse(port_,
  20414. "GET /keepalive HTTP/1.1\r\n"
  20415. "Host: localhost\r\n"
  20416. "Connection: keep-alive, close\r\n"
  20417. "\r\n",
  20418. &announced_close, &reusable);
  20419. EXPECT_TRUE(announced_close);
  20420. EXPECT_FALSE(reusable);
  20421. }
  20422. // "close" split over two field lines is the same list, so it is honored too.
  20423. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20424. bool announced_close = false;
  20425. bool reusable = true;
  20426. probe_connection_reuse(port_,
  20427. "GET /keepalive HTTP/1.1\r\n"
  20428. "Host: localhost\r\n"
  20429. "Connection: keep-alive\r\n"
  20430. "Connection: close\r\n"
  20431. "\r\n",
  20432. &announced_close, &reusable);
  20433. EXPECT_TRUE(announced_close);
  20434. EXPECT_FALSE(reusable);
  20435. }
  20436. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20437. // keep-alive in the spelling everyone actually sends keeps its connection.
  20438. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20439. bool announced_close = false;
  20440. bool reusable = false;
  20441. probe_connection_reuse(port_,
  20442. "GET /keepalive HTTP/1.0\r\n"
  20443. "Host: localhost\r\n"
  20444. "Connection: keep-alive\r\n"
  20445. "\r\n",
  20446. &announced_close, &reusable);
  20447. EXPECT_FALSE(announced_close);
  20448. EXPECT_TRUE(reusable);
  20449. }
  20450. // A token the value merely contains is not the token itself.
  20451. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20452. bool announced_close = false;
  20453. bool reusable = false;
  20454. probe_connection_reuse(port_,
  20455. "GET /keepalive HTTP/1.1\r\n"
  20456. "Host: localhost\r\n"
  20457. "Connection: notclose\r\n"
  20458. "\r\n",
  20459. &announced_close, &reusable);
  20460. EXPECT_FALSE(announced_close);
  20461. EXPECT_TRUE(reusable);
  20462. }
  20463. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20464. Server svr;
  20465. std::vector<std::string> observed_types;
  20466. svr.Get("/", [&](const Request &req, Response &res) {
  20467. observed_types = req.accept_content_types;
  20468. res.set_content("ok", "text/plain");
  20469. });
  20470. auto port = svr.bind_to_any_port(HOST);
  20471. thread t = thread([&]() { svr.listen_after_bind(); });
  20472. auto se = detail::scope_exit([&] {
  20473. svr.stop();
  20474. t.join();
  20475. ASSERT_FALSE(svr.is_running());
  20476. });
  20477. svr.wait_until_ready();
  20478. Client cli(HOST, port);
  20479. Headers headers;
  20480. headers.emplace("Accept", "text/plain;q=0.5");
  20481. headers.emplace("Accept", "application/json");
  20482. auto res = cli.Get("/", headers);
  20483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20484. EXPECT_EQ(StatusCode::OK_200, res->status);
  20485. // Sorted by q-value, so the second field line's type comes first
  20486. ASSERT_EQ(2U, observed_types.size());
  20487. EXPECT_EQ("application/json", observed_types[0]);
  20488. EXPECT_EQ("text/plain", observed_types[1]);
  20489. }
  20490. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20491. // empty field line must not contribute a bare comma to the combined value.
  20492. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20493. Server svr;
  20494. std::vector<std::string> observed_types;
  20495. svr.Get("/", [&](const Request &req, Response &res) {
  20496. observed_types = req.accept_content_types;
  20497. res.set_content("ok", "text/plain");
  20498. });
  20499. auto port = svr.bind_to_any_port(HOST);
  20500. thread t = thread([&]() { svr.listen_after_bind(); });
  20501. auto se = detail::scope_exit([&] {
  20502. svr.stop();
  20503. t.join();
  20504. ASSERT_FALSE(svr.is_running());
  20505. });
  20506. svr.wait_until_ready();
  20507. // Empty first field line, then a real one
  20508. std::string raw_req = "GET / HTTP/1.1\r\n"
  20509. "Host: localhost\r\n"
  20510. "Accept:\r\n"
  20511. "Accept: application/json\r\n"
  20512. "Connection: close\r\n"
  20513. "\r\n";
  20514. std::string out;
  20515. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20516. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20517. ASSERT_EQ(1U, observed_types.size());
  20518. EXPECT_EQ("application/json", observed_types[0]);
  20519. }
  20520. // The skip in get_combined_header_value() is what keeps an empty field line
  20521. // from contributing a bare comma. Only a trailing empty field line exercises
  20522. // it: a leading one is already covered by the "combined is still empty" check,
  20523. // and parse_accept_header() now ignores the empty element either way, so the
  20524. // request-level test above can no longer tell the two apart.
  20525. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20526. Headers headers;
  20527. headers.emplace("Accept", "text/html");
  20528. headers.emplace("Accept", "");
  20529. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20530. headers.clear();
  20531. headers.emplace("Accept", "");
  20532. headers.emplace("Accept", "application/json");
  20533. EXPECT_EQ("application/json",
  20534. detail::get_combined_header_value(headers, "Accept"));
  20535. }
  20536. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20537. // An encoding offered on a later Accept-Encoding field line is still offered.
  20538. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20539. Server svr;
  20540. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20541. res.set_content(std::string(1024, 'x'), "text/plain");
  20542. });
  20543. auto port = svr.bind_to_any_port(HOST);
  20544. thread t = thread([&]() { svr.listen_after_bind(); });
  20545. auto se = detail::scope_exit([&] {
  20546. svr.stop();
  20547. t.join();
  20548. ASSERT_FALSE(svr.is_running());
  20549. });
  20550. svr.wait_until_ready();
  20551. Client cli(HOST, port);
  20552. cli.set_decompress(false);
  20553. Headers headers;
  20554. headers.emplace("Accept-Encoding", "identity");
  20555. headers.emplace("Accept-Encoding", "gzip");
  20556. auto res = cli.Get("/", headers);
  20557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20558. EXPECT_EQ(StatusCode::OK_200, res->status);
  20559. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20560. }
  20561. #endif
  20562. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20563. // Transfer-Encoding is not its body.
  20564. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20565. Server svr;
  20566. svr.set_payload_max_length(8);
  20567. svr.Post("/test", [](const Request &, Response &res) {
  20568. res.set_content("ok", "text/plain");
  20569. });
  20570. auto port = svr.bind_to_any_port(HOST);
  20571. ASSERT_GT(port, 0);
  20572. thread t = thread([&] { svr.listen_after_bind(); });
  20573. auto se = detail::scope_exit([&] {
  20574. svr.stop();
  20575. t.join();
  20576. ASSERT_FALSE(svr.is_running());
  20577. });
  20578. svr.wait_until_ready();
  20579. std::string resp;
  20580. ASSERT_TRUE(send_request(1,
  20581. "POST /test HTTP/1.1\r\n"
  20582. "Host: localhost\r\n"
  20583. "Connection: close\r\n"
  20584. "\r\n" +
  20585. std::string(16, 'X'),
  20586. &resp, port));
  20587. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20588. }
  20589. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20590. Server svr;
  20591. svr.Post("/post", [&](const Request &req, Response &res) {
  20592. res.set_content(req.body, "text/plain");
  20593. });
  20594. svr.Put("/put", [&](const Request &req, Response &res) {
  20595. res.set_content(req.body, "text/plain");
  20596. });
  20597. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20598. res.set_content(req.body, "text/plain");
  20599. });
  20600. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20601. res.set_content(req.body, "text/plain");
  20602. });
  20603. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20604. auto se = detail::scope_exit([&] {
  20605. svr.stop();
  20606. t.join();
  20607. ASSERT_FALSE(svr.is_running());
  20608. });
  20609. svr.wait_until_ready();
  20610. std::string resp;
  20611. // POST without Content-Length
  20612. ASSERT_TRUE(send_request(5,
  20613. "POST /post HTTP/1.1\r\n"
  20614. "Host: localhost\r\n"
  20615. "Connection: close\r\n"
  20616. "\r\n",
  20617. &resp));
  20618. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20619. // PUT without Content-Length
  20620. resp.clear();
  20621. ASSERT_TRUE(send_request(5,
  20622. "PUT /put HTTP/1.1\r\n"
  20623. "Host: localhost\r\n"
  20624. "Connection: close\r\n"
  20625. "\r\n",
  20626. &resp));
  20627. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20628. // PATCH without Content-Length
  20629. resp.clear();
  20630. ASSERT_TRUE(send_request(5,
  20631. "PATCH /patch HTTP/1.1\r\n"
  20632. "Host: localhost\r\n"
  20633. "Connection: close\r\n"
  20634. "\r\n",
  20635. &resp));
  20636. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20637. // DELETE without Content-Length
  20638. resp.clear();
  20639. ASSERT_TRUE(send_request(5,
  20640. "DELETE /delete HTTP/1.1\r\n"
  20641. "Host: localhost\r\n"
  20642. "Connection: close\r\n"
  20643. "\r\n",
  20644. &resp));
  20645. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20646. }
  20647. //==============================================================================
  20648. // open_stream() Tests
  20649. //==============================================================================
  20650. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20651. std::string result;
  20652. char buf[8192];
  20653. ssize_t n;
  20654. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20655. result.append(buf, static_cast<size_t>(n));
  20656. }
  20657. return result;
  20658. }
  20659. // Mock stream for unit tests
  20660. class MockStream : public Stream {
  20661. public:
  20662. std::string data;
  20663. size_t pos = 0;
  20664. ssize_t error_after = -1; // -1 = no error
  20665. explicit MockStream(const std::string &d, ssize_t err = -1)
  20666. : data(d), error_after(err) {}
  20667. bool is_readable() const override { return true; }
  20668. bool wait_readable() const override { return true; }
  20669. bool wait_writable() const override { return true; }
  20670. ssize_t read(char *ptr, size_t size) override {
  20671. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20672. if (pos >= data.size()) return 0;
  20673. size_t limit =
  20674. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20675. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20676. std::memcpy(ptr, data.data() + pos, to_read);
  20677. pos += to_read;
  20678. return static_cast<ssize_t>(to_read);
  20679. }
  20680. ssize_t write(const char *, size_t) override { return -1; }
  20681. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20682. ip = "127.0.0.1";
  20683. port = 0;
  20684. }
  20685. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20686. ip = "127.0.0.1";
  20687. port = 0;
  20688. }
  20689. socket_t socket() const override { return INVALID_SOCKET; }
  20690. time_t duration() const override { return 0; }
  20691. };
  20692. TEST(StreamHandleTest, Basic) {
  20693. ClientImpl::StreamHandle handle;
  20694. EXPECT_FALSE(handle.is_valid());
  20695. handle.response = detail::make_unique<Response>();
  20696. handle.error = Error::Connection;
  20697. EXPECT_FALSE(handle.is_valid());
  20698. handle.error = Error::Success;
  20699. EXPECT_TRUE(handle.is_valid());
  20700. }
  20701. TEST(BodyReaderTest, Basic) {
  20702. MockStream stream("Hello, World!");
  20703. detail::BodyReader reader;
  20704. reader.stream = &stream;
  20705. reader.content_length = 13;
  20706. char buf[32];
  20707. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20708. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20709. EXPECT_TRUE(reader.eof);
  20710. }
  20711. TEST(BodyReaderTest, NoStream) {
  20712. detail::BodyReader reader;
  20713. char buf[32];
  20714. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20715. EXPECT_EQ(Error::Connection, reader.last_error);
  20716. }
  20717. TEST(BodyReaderTest, Error) {
  20718. MockStream stream("Hello, World!", 5);
  20719. detail::BodyReader reader;
  20720. reader.stream = &stream;
  20721. reader.content_length = 13;
  20722. char buf[32];
  20723. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20724. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20725. EXPECT_EQ(Error::Read, reader.last_error);
  20726. }
  20727. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20728. // Mock-based StreamHandle tests relying on private internals are removed.
  20729. class OpenStreamTest : public ::testing::Test {
  20730. protected:
  20731. void SetUp() override {
  20732. svr_.Get("/hello", [](const Request &, Response &res) {
  20733. res.set_content("Hello World!", "text/plain");
  20734. });
  20735. svr_.Get("/large", [](const Request &, Response &res) {
  20736. res.set_content(std::string(10000, 'X'), "text/plain");
  20737. });
  20738. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20739. res.set_content("Hello World!", "image/jpeg");
  20740. res.set_header("Content-Encoding", "UTF-8");
  20741. });
  20742. svr_.Get("/chunked", [](const Request &, Response &res) {
  20743. res.set_chunked_content_provider("text/plain",
  20744. [](size_t offset, DataSink &sink) {
  20745. if (offset < 15) {
  20746. sink.write("chunk", 5);
  20747. return true;
  20748. }
  20749. sink.done();
  20750. return true;
  20751. });
  20752. });
  20753. svr_.Get("/compressible", [](const Request &, Response &res) {
  20754. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20755. DataSink &sink) {
  20756. if (offset < 100 * 1024) {
  20757. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20758. sink.write(chunk.data(), chunk.size());
  20759. return true;
  20760. }
  20761. sink.done();
  20762. return true;
  20763. });
  20764. });
  20765. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20766. [](const Request & /*req*/, Response &res) {
  20767. auto i = new int(0);
  20768. res.set_header("Trailer", "Content-Length, X-Allowed");
  20769. res.set_chunked_content_provider(
  20770. "text/plain",
  20771. [i](size_t /*offset*/, DataSink &sink) {
  20772. switch (*i) {
  20773. case 0: sink.os << "123"; break;
  20774. case 1: sink.os << "456"; break;
  20775. case 2: sink.os << "789"; break;
  20776. case 3: {
  20777. sink.done_with_trailer(
  20778. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20779. } break;
  20780. }
  20781. (*i)++;
  20782. return true;
  20783. },
  20784. [i](bool success) {
  20785. EXPECT_TRUE(success);
  20786. delete i;
  20787. });
  20788. });
  20789. // Echo headers endpoint for header-related tests
  20790. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20791. std::string body;
  20792. for (const auto &h : req.headers) {
  20793. body.append(h.first);
  20794. body.push_back(':');
  20795. body.append(h.second);
  20796. body.push_back('\n');
  20797. }
  20798. res.set_content(body, "text/plain");
  20799. });
  20800. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20801. std::string body;
  20802. for (const auto &h : req.headers) {
  20803. body.append(h.first);
  20804. body.push_back(':');
  20805. body.append(h.second);
  20806. body.push_back('\n');
  20807. }
  20808. res.set_content(body, "text/plain");
  20809. });
  20810. port_ = svr_.bind_to_any_port("127.0.0.1");
  20811. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20812. svr_.wait_until_ready();
  20813. }
  20814. void TearDown() override {
  20815. svr_.stop();
  20816. if (thread_.joinable()) thread_.join();
  20817. }
  20818. Server svr_;
  20819. std::thread thread_;
  20820. int port_ = 0;
  20821. };
  20822. TEST_F(OpenStreamTest, Basic) {
  20823. Client cli("127.0.0.1", port_);
  20824. auto handle = cli.open_stream("GET", "/hello");
  20825. EXPECT_TRUE(handle.is_valid());
  20826. EXPECT_EQ("Hello World!", read_all(handle));
  20827. }
  20828. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20829. Client cli("127.0.0.1", port_);
  20830. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20831. ASSERT_TRUE(handle.is_valid());
  20832. EXPECT_EQ("Hello World!", read_all(handle));
  20833. }
  20834. TEST_F(OpenStreamTest, SmallBuffer) {
  20835. Client cli("127.0.0.1", port_);
  20836. auto handle = cli.open_stream("GET", "/hello");
  20837. std::string result;
  20838. char buf[4];
  20839. ssize_t n;
  20840. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20841. result.append(buf, static_cast<size_t>(n));
  20842. EXPECT_EQ("Hello World!", result);
  20843. }
  20844. TEST_F(OpenStreamTest, DefaultHeaders) {
  20845. Client cli("127.0.0.1", port_);
  20846. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20847. {
  20848. auto handle = cli.open_stream("GET", "/echo-headers");
  20849. ASSERT_TRUE(handle.is_valid());
  20850. auto body = read_all(handle);
  20851. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20852. std::string::npos);
  20853. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20854. std::string::npos);
  20855. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20856. }
  20857. // open_stream POST with body and no explicit content_type should NOT add
  20858. // text/plain Content-Type (behavior differs from non-streaming path), but
  20859. // should include Content-Length
  20860. {
  20861. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20862. ASSERT_TRUE(handle.is_valid());
  20863. auto body = read_all(handle);
  20864. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20865. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20866. }
  20867. // open_stream POST with explicit Content-Type should preserve it
  20868. {
  20869. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20870. {{"Content-Type", "application/custom"}},
  20871. "{}", "application/custom");
  20872. ASSERT_TRUE(handle.is_valid());
  20873. auto body = read_all(handle);
  20874. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20875. }
  20876. // User-specified User-Agent must not be overwritten for stream API
  20877. {
  20878. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20879. {{"User-Agent", "MyAgent/1.2"}});
  20880. ASSERT_TRUE(handle.is_valid());
  20881. auto body = read_all(handle);
  20882. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20883. }
  20884. }
  20885. TEST_F(OpenStreamTest, Large) {
  20886. Client cli("127.0.0.1", port_);
  20887. auto handle = cli.open_stream("GET", "/large");
  20888. EXPECT_EQ(10000u, read_all(handle).size());
  20889. }
  20890. TEST_F(OpenStreamTest, ConnectionError) {
  20891. Client cli("127.0.0.1", 9999);
  20892. auto handle = cli.open_stream("GET", "/hello");
  20893. EXPECT_FALSE(handle.is_valid());
  20894. }
  20895. TEST_F(OpenStreamTest, Chunked) {
  20896. Client cli("127.0.0.1", port_);
  20897. auto handle = cli.open_stream("GET", "/chunked");
  20898. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20899. "Transfer-Encoding") == "chunked");
  20900. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20901. }
  20902. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20903. Client cli("127.0.0.1", port_);
  20904. auto handle =
  20905. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20906. ASSERT_TRUE(handle.is_valid());
  20907. // Consume body to allow trailers to be received/parsed
  20908. auto body = read_all(handle);
  20909. // Explicitly parse trailers (ensure trailers are available for assertion)
  20910. handle.parse_trailers_if_needed();
  20911. EXPECT_EQ(std::string("123456789"), body);
  20912. // The response should include a Trailer header declaring both names
  20913. ASSERT_TRUE(handle.response);
  20914. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20915. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20916. handle.response->get_header_value("Trailer"));
  20917. // Prohibited trailer must not be present
  20918. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20919. // Allowed trailer should be present
  20920. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20921. EXPECT_EQ(std::string("yes"),
  20922. handle.response->get_trailer_value("X-Allowed"));
  20923. // Verify trailers are NOT present as regular headers
  20924. EXPECT_EQ(std::string(""),
  20925. handle.response->get_header_value("Content-Length"));
  20926. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20927. }
  20928. // Accepts one connection on an OS-assigned port, which it hands over through
  20929. // port_promise, reads the request head and sends back response. after_send,
  20930. // if given, runs on the connection before it is closed.
  20931. static std::thread
  20932. serve_single_response(std::promise<int> &port_promise,
  20933. const std::string &response,
  20934. std::function<void(socket_t)> after_send = nullptr) {
  20935. return std::thread([&port_promise, response, after_send] {
  20936. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20937. default_socket_options(srv);
  20938. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20939. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20940. sockaddr_in addr{};
  20941. addr.sin_family = AF_INET;
  20942. addr.sin_port = htons(0); // Let OS assign a free port
  20943. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20944. int opt = 1;
  20945. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20946. #ifdef _WIN32
  20947. reinterpret_cast<const char *>(&opt),
  20948. #else
  20949. &opt,
  20950. #endif
  20951. sizeof(opt));
  20952. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20953. ::listen(srv, 1) != 0) {
  20954. port_promise.set_value(-1);
  20955. detail::close_socket(srv);
  20956. return;
  20957. }
  20958. socklen_t addr_len = sizeof(addr);
  20959. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20960. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20961. sockaddr_in cli_addr{};
  20962. socklen_t cli_len = sizeof(cli_addr);
  20963. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20964. if (cli != INVALID_SOCKET) {
  20965. // Read the complete HTTP request (until the blank line that terminates
  20966. // headers) before sending the response. If the server closes the socket
  20967. // while the client's request data is still unread in the kernel receive
  20968. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20969. // connection on both sides: it discards the client's receive buffer
  20970. // (which already holds our response) and causes any in-progress write on
  20971. // the client to fail with ECONNRESET. Reading all request data first
  20972. // ensures close() emits a graceful FIN.
  20973. {
  20974. char rbuf[256];
  20975. std::string req;
  20976. while (req.find("\r\n\r\n") == std::string::npos) {
  20977. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20978. if (n <= 0) { break; }
  20979. req.append(rbuf, static_cast<size_t>(n));
  20980. }
  20981. }
  20982. ::send(cli,
  20983. #ifdef _WIN32
  20984. static_cast<const char *>(response.c_str()),
  20985. static_cast<int>(response.size()),
  20986. #else
  20987. response.c_str(), response.size(),
  20988. #endif
  20989. 0);
  20990. if (after_send) { after_send(cli); }
  20991. detail::close_socket(cli);
  20992. }
  20993. detail::close_socket(srv);
  20994. });
  20995. }
  20996. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20997. #ifndef _WIN32
  20998. signal(SIGPIPE, SIG_IGN);
  20999. #endif
  21000. std::promise<int> port_promise;
  21001. auto port_future = port_promise.get_future();
  21002. auto server_thread =
  21003. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21004. "Content-Type: text/plain\r\n"
  21005. "Content-Length: not-a-number\r\n"
  21006. "Connection: close\r\n"
  21007. "\r\n"
  21008. "hello");
  21009. auto port = port_future.get();
  21010. ASSERT_GT(port, 0);
  21011. Client cli("127.0.0.1", port);
  21012. auto handle = cli.open_stream("GET", "/");
  21013. EXPECT_FALSE(handle.is_valid());
  21014. server_thread.join();
  21015. }
  21016. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21017. #ifndef _WIN32
  21018. signal(SIGPIPE, SIG_IGN);
  21019. #endif
  21020. std::promise<int> port_promise;
  21021. auto port_future = port_promise.get_future();
  21022. auto server_thread = serve_single_response(
  21023. port_promise, "HTTP/1.1 200 OK\r\n"
  21024. "Content-Type: text/plain\r\n"
  21025. "Content-Length: 99999999999999999999999999\r\n"
  21026. "Connection: close\r\n"
  21027. "\r\n"
  21028. "hello");
  21029. auto port = port_future.get();
  21030. ASSERT_GT(port, 0);
  21031. // Historically std::stoull would throw std::out_of_range here and crash
  21032. // the process, then parsing silently clamped to a bogus framing length and
  21033. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21034. // so the stream fails to open, matching the not-a-number case above. The
  21035. // process still must NOT terminate.
  21036. Client cli("127.0.0.1", port);
  21037. auto handle = cli.open_stream("GET", "/");
  21038. EXPECT_FALSE(handle.is_valid());
  21039. server_thread.join();
  21040. }
  21041. #ifndef _WIN32
  21042. // As above for the body of a streamed request: a send() cut short by the write
  21043. // timeout must not leave the rest of the body unsent.
  21044. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21045. signal(SIGPIPE, SIG_IGN);
  21046. Server svr;
  21047. svr.set_socket_options([](socket_t sock) {
  21048. int size = 8192;
  21049. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21050. reinterpret_cast<const char *>(&size), sizeof(size));
  21051. });
  21052. svr.Post("/size", [](const Request &, Response &res,
  21053. const ContentReader &content_reader) {
  21054. // Outlast the client's write timeout before reading the body.
  21055. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21056. size_t received = 0;
  21057. content_reader([&](const char *, size_t len) {
  21058. received += len;
  21059. return true;
  21060. });
  21061. res.set_content(std::to_string(received), "text/plain");
  21062. });
  21063. auto port = svr.bind_to_any_port(HOST);
  21064. std::thread t([&]() { svr.listen_after_bind(); });
  21065. auto se = detail::scope_exit([&] {
  21066. svr.stop();
  21067. t.join();
  21068. });
  21069. svr.wait_until_ready();
  21070. Client cli(HOST, port);
  21071. cli.set_write_timeout(0, 500000);
  21072. cli.set_socket_options([](socket_t sock) {
  21073. int size = 8192;
  21074. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21075. reinterpret_cast<const char *>(&size), sizeof(size));
  21076. });
  21077. const std::string body(4 * 1024 * 1024, 'A');
  21078. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21079. "application/octet-stream");
  21080. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21081. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21082. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21083. }
  21084. #endif
  21085. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21086. std::promise<void> slow_started;
  21087. auto slow_started_future = slow_started.get_future();
  21088. Server svr;
  21089. svr.Get("/slow", [&](const Request &, Response &res) {
  21090. slow_started.set_value();
  21091. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21092. res.set_content("slow", "text/plain");
  21093. });
  21094. svr.Get("/fast", [](const Request &, Response &res) {
  21095. res.set_content("fast", "text/plain");
  21096. });
  21097. auto port = svr.bind_to_any_port(HOST);
  21098. std::thread t([&]() { svr.listen_after_bind(); });
  21099. auto se = detail::scope_exit([&] {
  21100. svr.stop();
  21101. t.join();
  21102. });
  21103. svr.wait_until_ready();
  21104. Client cli(HOST, port);
  21105. std::string slow_body;
  21106. std::thread slow_thread([&] {
  21107. auto res = cli.Get("/slow");
  21108. if (res) { slow_body = res->body; }
  21109. });
  21110. slow_started_future.wait();
  21111. auto result = stream::Get(cli, "/fast");
  21112. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21113. slow_thread.join();
  21114. EXPECT_EQ("slow", slow_body);
  21115. EXPECT_EQ("fast", fast_body);
  21116. }
  21117. // Serves `response` to the single request `fn` makes with a fresh client.
  21118. template <typename Fn>
  21119. static void with_single_response(const std::string &response, Fn fn) {
  21120. #ifndef _WIN32
  21121. signal(SIGPIPE, SIG_IGN);
  21122. #endif
  21123. std::promise<int> port_promise;
  21124. auto port_future = port_promise.get_future();
  21125. auto server_thread = serve_single_response(port_promise, response);
  21126. auto se = detail::scope_exit([&] { server_thread.join(); });
  21127. auto port = port_future.get();
  21128. ASSERT_GT(port, 0);
  21129. Client cli("127.0.0.1", port);
  21130. fn(cli);
  21131. }
  21132. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21133. // too, also in a build without the decoder for the advertised coding.
  21134. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21135. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21136. const auto response = "HTTP/1.1 200 OK\r\n"
  21137. "Content-Encoding: gzip\r\n"
  21138. "Content-Length: " +
  21139. std::to_string(gzipped.size()) +
  21140. "\r\n"
  21141. "Connection: close\r\n\r\n" +
  21142. gzipped;
  21143. with_single_response(response, [&](Client &cli) {
  21144. cli.set_decompress(false);
  21145. auto handle = cli.open_stream("GET", "/");
  21146. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21147. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21148. EXPECT_EQ(gzipped, read_all(handle));
  21149. EXPECT_FALSE(handle.has_read_error());
  21150. });
  21151. with_single_response(response, [&](Client &cli) {
  21152. cli.set_decompress(false);
  21153. auto res = stream::Get(cli, "/", 7);
  21154. ASSERT_TRUE(res) << to_string(res.error());
  21155. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21156. EXPECT_EQ(gzipped, res.read_all());
  21157. EXPECT_FALSE(res.has_read_error());
  21158. });
  21159. }
  21160. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21161. // Neither Content-Length nor chunked: the body ends at the close
  21162. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21163. "Connection: close\r\n"
  21164. "\r\n"
  21165. "hello";
  21166. with_single_response(close_delimited, [](Client &cli) {
  21167. auto handle = cli.open_stream("GET", "/");
  21168. ASSERT_TRUE(handle.is_valid());
  21169. EXPECT_EQ("hello", read_all(handle));
  21170. EXPECT_FALSE(handle.has_read_error());
  21171. });
  21172. // A close before the end of the Content-Length is still an error
  21173. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21174. "Content-Length: 10\r\n"
  21175. "\r\n"
  21176. "hello";
  21177. with_single_response(short_content_length, [](Client &cli) {
  21178. auto handle = cli.open_stream("GET", "/");
  21179. ASSERT_TRUE(handle.is_valid());
  21180. read_all(handle);
  21181. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21182. });
  21183. // So is a close before the last chunk
  21184. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21185. "Transfer-Encoding: chunked\r\n"
  21186. "\r\n"
  21187. "5\r\nhello\r\n";
  21188. with_single_response(short_chunked, [](Client &cli) {
  21189. auto handle = cli.open_stream("GET", "/");
  21190. ASSERT_TRUE(handle.is_valid());
  21191. read_all(handle);
  21192. EXPECT_TRUE(handle.has_read_error());
  21193. });
  21194. }
  21195. #ifdef CPPHTTPLIB_SSL_ENABLED
  21196. // Serves `response` to one request, then closes with or without a close_notify
  21197. template <typename Fn>
  21198. static void with_single_tls_response(const std::string &response,
  21199. bool close_notify, Fn fn) {
  21200. #ifndef _WIN32
  21201. signal(SIGPIPE, SIG_IGN);
  21202. #endif
  21203. std::promise<int> port_promise;
  21204. auto port_future = port_promise.get_future();
  21205. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21206. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21207. default_socket_options(srv);
  21208. sockaddr_in addr{};
  21209. addr.sin_family = AF_INET;
  21210. addr.sin_port = htons(0);
  21211. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21212. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21213. ::listen(srv, 1) != 0) {
  21214. port_promise.set_value(-1);
  21215. detail::close_socket(srv);
  21216. return;
  21217. }
  21218. socklen_t addr_len = sizeof(addr);
  21219. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21220. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21221. auto cli = ::accept(srv, nullptr, nullptr);
  21222. if (cli != INVALID_SOCKET) {
  21223. auto ctx = tls::create_server_context();
  21224. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21225. nullptr);
  21226. auto session = tls::create_session(ctx, cli);
  21227. tls::TlsError err;
  21228. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  21229. // The request head first, so that closing the socket sends a FIN
  21230. // rather than an RST for the unread bytes.
  21231. std::string req;
  21232. char buf[256];
  21233. while (req.find("\r\n\r\n") == std::string::npos) {
  21234. auto n = tls::read(session, buf, sizeof(buf), err);
  21235. if (n <= 0) { break; }
  21236. req.append(buf, static_cast<size_t>(n));
  21237. }
  21238. size_t sent = 0;
  21239. while (sent < response.size()) {
  21240. auto n = tls::write(session, response.data() + sent,
  21241. response.size() - sent, err);
  21242. if (n <= 0) { break; }
  21243. sent += static_cast<size_t>(n);
  21244. }
  21245. if (close_notify) { tls::shutdown(session, true); }
  21246. }
  21247. tls::free_session(session);
  21248. detail::close_socket(cli);
  21249. tls::free_context(ctx);
  21250. }
  21251. detail::close_socket(srv);
  21252. });
  21253. auto se = detail::scope_exit([&] { server_thread.join(); });
  21254. auto port = port_future.get();
  21255. ASSERT_GT(port, 0);
  21256. SSLClient cli("127.0.0.1", port);
  21257. cli.enable_server_certificate_verification(false);
  21258. fn(cli);
  21259. }
  21260. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21261. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21262. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21263. "Connection: close\r\n"
  21264. "\r\n"
  21265. "hello";
  21266. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21267. auto res = cli.Get("/");
  21268. ASSERT_TRUE(res) << to_string(res.error());
  21269. EXPECT_EQ("hello", res->body);
  21270. });
  21271. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21272. auto res = cli.Get("/");
  21273. ASSERT_FALSE(res);
  21274. EXPECT_EQ(Error::Read, res.error());
  21275. });
  21276. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21277. auto handle = cli.open_stream("GET", "/");
  21278. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21279. read_all(handle);
  21280. EXPECT_TRUE(handle.has_read_error());
  21281. });
  21282. // A framed body ends where its framing says, with or without the alert
  21283. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21284. "Content-Length: 5\r\n"
  21285. "Connection: close\r\n"
  21286. "\r\n"
  21287. "hello";
  21288. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21289. auto res = cli.Get("/");
  21290. ASSERT_TRUE(res) << to_string(res.error());
  21291. EXPECT_EQ("hello", res->body);
  21292. });
  21293. }
  21294. #endif
  21295. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21296. const char *responses[] = {
  21297. "HTTP/1.1 103 Early Hints\r\n"
  21298. "Link: </style.css>; rel=preload\r\n"
  21299. "\r\n"
  21300. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21301. "HTTP/1.1 100 Continue\r\n"
  21302. "X-Note: interim\r\n"
  21303. "\r\n"
  21304. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21305. };
  21306. for (auto response : responses) {
  21307. with_single_response(response, [](Client &cli) {
  21308. auto res = cli.Get("/");
  21309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21310. EXPECT_EQ(StatusCode::OK_200, res->status);
  21311. EXPECT_EQ("ok", res->body);
  21312. });
  21313. }
  21314. }
  21315. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21316. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21317. const std::string final_response =
  21318. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21319. std::string interims;
  21320. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21321. interims += interim;
  21322. }
  21323. with_single_response(interims + final_response, [](Client &cli) {
  21324. auto res = cli.Get("/");
  21325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21326. EXPECT_EQ("ok", res->body);
  21327. });
  21328. with_single_response(interims + interim + final_response, [](Client &cli) {
  21329. auto res = cli.Get("/");
  21330. ASSERT_FALSE(res);
  21331. EXPECT_EQ(Error::Read, res.error());
  21332. });
  21333. }
  21334. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21335. #ifndef _WIN32
  21336. signal(SIGPIPE, SIG_IGN);
  21337. #endif
  21338. // The server answers the head without asking for the body. Bytes it then
  21339. // reads on the connection would be taken for the body the request declared.
  21340. auto closed_by_client = false;
  21341. std::promise<int> port_promise;
  21342. auto server_thread = serve_single_response(
  21343. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21344. [&](socket_t sock) {
  21345. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21346. char buf[256];
  21347. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21348. });
  21349. Client cli("127.0.0.1", port_promise.get_future().get());
  21350. cli.set_keep_alive(true);
  21351. cli.set_read_timeout(1, 0);
  21352. // Long enough for the client to send Expect: 100-continue.
  21353. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21355. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21356. cli.Get("/second");
  21357. server_thread.join();
  21358. EXPECT_TRUE(closed_by_client);
  21359. }
  21360. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21361. // Long enough for the client to send Expect: 100-continue
  21362. with_single_response(
  21363. "HTTP/1.1 103 Early Hints\r\n"
  21364. "Link: </style.css>; rel=preload\r\n"
  21365. "\r\n"
  21366. "HTTP/1.1 401 Unauthorized\r\n"
  21367. "Content-Length: 0\r\n\r\n",
  21368. [](Client &cli) {
  21369. cli.set_read_timeout(2, 0);
  21370. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21372. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21373. });
  21374. }
  21375. #ifdef CPPHTTPLIB_SSL_ENABLED
  21376. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21377. #ifndef _WIN32
  21378. signal(SIGPIPE, SIG_IGN);
  21379. #endif
  21380. auto reused = false;
  21381. std::promise<int> port_promise;
  21382. auto server_thread = serve_single_response(
  21383. port_promise,
  21384. "HTTP/1.1 401 Unauthorized\r\n"
  21385. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21386. "Content-Length: 0\r\n\r\n",
  21387. [&](socket_t sock) {
  21388. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21389. char buf[256];
  21390. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21391. });
  21392. Client cli("127.0.0.1", port_promise.get_future().get());
  21393. cli.set_keep_alive(true);
  21394. cli.set_digest_auth("user", "pass");
  21395. cli.set_read_timeout(1, 0);
  21396. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21397. server_thread.join();
  21398. EXPECT_FALSE(reused);
  21399. }
  21400. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21401. // Any other answer to CONNECT would read as the origin's response.
  21402. struct {
  21403. const char *response;
  21404. bool passed_on;
  21405. } cases[] = {
  21406. {"HTTP/1.1 201 Created\r\n"
  21407. "Set-Cookie: session=from-proxy\r\n"
  21408. "Content-Length: 0\r\n\r\n",
  21409. false},
  21410. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21411. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21412. "Content-Length: 0\r\n\r\n",
  21413. true},
  21414. };
  21415. for (const auto &c : cases) {
  21416. std::promise<int> port_promise;
  21417. auto server_thread = serve_single_response(port_promise, c.response);
  21418. SSLClient cli("example.com", 443);
  21419. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21420. auto res = cli.Get("/");
  21421. server_thread.join();
  21422. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21423. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21424. if (res) {
  21425. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21426. }
  21427. }
  21428. }
  21429. #endif
  21430. // Records the client's error logger calls as "error METHOD path", or
  21431. // "error null" for a call without a request
  21432. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21433. return [&log](const Error &err, const Request *req) {
  21434. log.push_back(to_string(err) + " " +
  21435. (req ? req->method + " " + req->path : "null"));
  21436. };
  21437. }
  21438. // A failed request is reported once, with the request the caller made
  21439. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21440. Server svr;
  21441. svr.Get("/big", [](const Request &, Response &res) {
  21442. res.set_content(std::string(100000, 'b'), "text/plain");
  21443. });
  21444. auto port = svr.bind_to_any_port(HOST);
  21445. std::thread t([&]() { svr.listen_after_bind(); });
  21446. auto se = detail::scope_exit([&] {
  21447. svr.stop();
  21448. t.join();
  21449. });
  21450. svr.wait_until_ready();
  21451. Client cli(HOST, port);
  21452. std::vector<std::string> log;
  21453. cli.set_error_logger(record_errors(log));
  21454. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21455. cli.Get("/big", [](const char *, size_t) { return false; });
  21456. EXPECT_EQ(expected, log);
  21457. log.clear();
  21458. cli.Get("/big", [](size_t, size_t) { return false; });
  21459. EXPECT_EQ(expected, log);
  21460. }
  21461. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21462. // Fails while the body is read
  21463. auto broken = [](const Request &, Response &res) {
  21464. res.set_content_provider(10, "text/plain",
  21465. [](size_t, size_t, DataSink &) { return false; });
  21466. };
  21467. Server other;
  21468. other.Get("/broken", broken);
  21469. auto other_port = other.bind_to_any_port(HOST);
  21470. std::thread other_t([&]() { other.listen_after_bind(); });
  21471. auto other_se = detail::scope_exit([&] {
  21472. other.stop();
  21473. other_t.join();
  21474. });
  21475. other.wait_until_ready();
  21476. Server svr;
  21477. svr.Get("/broken", broken);
  21478. svr.Get("/same-origin",
  21479. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21480. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21481. res.set_redirect("http://" + std::string(HOST) + ":" +
  21482. std::to_string(other_port) + "/broken");
  21483. });
  21484. auto port = svr.bind_to_any_port(HOST);
  21485. std::thread t([&]() { svr.listen_after_bind(); });
  21486. auto se = detail::scope_exit([&] {
  21487. svr.stop();
  21488. t.join();
  21489. });
  21490. svr.wait_until_ready();
  21491. Client cli(HOST, port);
  21492. cli.set_follow_location(true);
  21493. std::vector<std::string> log;
  21494. cli.set_error_logger(record_errors(log));
  21495. for (auto path : {"/same-origin", "/cross-origin"}) {
  21496. log.clear();
  21497. auto res = cli.Get(path);
  21498. ASSERT_FALSE(res);
  21499. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21500. log);
  21501. }
  21502. }
  21503. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21504. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21505. std::vector<std::string> log;
  21506. cli.set_error_logger(record_errors(log));
  21507. auto handle = cli.open_stream("GET", "/x");
  21508. EXPECT_FALSE(handle.is_valid());
  21509. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21510. log);
  21511. });
  21512. }
  21513. #ifdef CPPHTTPLIB_SSL_ENABLED
  21514. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21515. // Not a TLS server, so the handshake fails. It waits for a request line in
  21516. // the handshake bytes, so a short read timeout lets it close quickly.
  21517. Server svr;
  21518. svr.set_read_timeout(0, 100000);
  21519. svr.Get("/x", [](const Request &, Response &res) {
  21520. res.set_content("x", "text/plain");
  21521. });
  21522. auto port = svr.bind_to_any_port(HOST);
  21523. std::thread t([&]() { svr.listen_after_bind(); });
  21524. auto se = detail::scope_exit([&] {
  21525. svr.stop();
  21526. t.join();
  21527. });
  21528. svr.wait_until_ready();
  21529. std::vector<std::string> log;
  21530. SSLClient cli(HOST, port);
  21531. cli.enable_server_certificate_verification(false);
  21532. cli.set_error_logger(record_errors(log));
  21533. auto res = cli.Get("/x");
  21534. ASSERT_FALSE(res);
  21535. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21536. log.clear();
  21537. auto handle = cli.open_stream("GET", "/x");
  21538. EXPECT_FALSE(handle.is_valid());
  21539. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21540. log.clear();
  21541. SSLClient no_ca(HOST, port);
  21542. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21543. no_ca.set_error_logger(record_errors(log));
  21544. res = no_ca.Get("/x");
  21545. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21546. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21547. }
  21548. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21549. #ifndef _WIN32
  21550. signal(SIGPIPE, SIG_IGN);
  21551. #endif
  21552. // Refused, answered with a challenge, or closed without an answer
  21553. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21554. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21555. "Content-Length: 0\r\n\r\n",
  21556. ""}) {
  21557. std::promise<int> port_promise;
  21558. auto server_thread = serve_single_response(port_promise, response);
  21559. SSLClient cli("example.com", 443);
  21560. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21561. std::vector<std::string> log;
  21562. cli.set_error_logger(record_errors(log));
  21563. auto res = cli.Get("/");
  21564. server_thread.join();
  21565. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21566. << response;
  21567. }
  21568. }
  21569. #endif
  21570. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21571. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21572. // the chunked coding and drop Content-Length, so a front-end that trusts
  21573. // Content-Length would disagree about where the body ends (response
  21574. // smuggling). The client must reject such a response.
  21575. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21576. for (const char *te : {"chunked", "gzip, chunked"}) {
  21577. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21578. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21579. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21580. "5\r\nhello\r\n0\r\n\r\n";
  21581. with_single_response(response, [&](Client &cli) {
  21582. auto res = cli.Get("/");
  21583. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21584. EXPECT_EQ(Error::Read, res.error()) << te;
  21585. });
  21586. with_single_response(response, [&](Client &cli) {
  21587. auto handle = cli.open_stream("GET", "/");
  21588. EXPECT_FALSE(handle.is_valid()) << te;
  21589. EXPECT_EQ(Error::Read, handle.error) << te;
  21590. });
  21591. }
  21592. }
  21593. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21594. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21595. // closing the connection (unlike a request, which must be rejected).
  21596. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21597. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21598. "Transfer-Encoding: chunked\r\n"
  21599. "Connection: close\r\n"
  21600. "\r\n"
  21601. "5\r\nhello\r\n0\r\n\r\n",
  21602. "HTTP/1.1 200 OK\r\n"
  21603. "Transfer-Encoding: gzip\r\n"
  21604. "Connection: close\r\n"
  21605. "\r\n"
  21606. "hello"}) {
  21607. with_single_response(response, [&](Client &cli) {
  21608. auto res = cli.Get("/");
  21609. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21610. EXPECT_EQ("hello", res->body);
  21611. });
  21612. with_single_response(response, [&](Client &cli) {
  21613. auto handle = cli.open_stream("GET", "/");
  21614. ASSERT_TRUE(handle.is_valid()) << response;
  21615. EXPECT_EQ("hello", read_all(handle));
  21616. });
  21617. }
  21618. }
  21619. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21620. // framing headers describe nothing to read and must not be rejected.
  21621. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21622. const std::string framing = "Content-Length: 5\r\n"
  21623. "Transfer-Encoding: chunked\r\n"
  21624. "Connection: close\r\n"
  21625. "\r\n";
  21626. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21627. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21628. });
  21629. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21630. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21631. });
  21632. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21633. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21634. with_single_response(response, [&](Client &cli) {
  21635. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21636. });
  21637. with_single_response(response, [&](Client &cli) {
  21638. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21639. });
  21640. }
  21641. }
  21642. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21643. // header section, so a stream opened on one has nothing to read, whatever
  21644. // framing or coding headers it carries.
  21645. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21646. struct Case {
  21647. const char *method;
  21648. const char *status;
  21649. };
  21650. // A reader of the declared body reports an early close when nothing
  21651. // follows, and hands back what does.
  21652. struct Framing {
  21653. const char *headers;
  21654. const char *after;
  21655. };
  21656. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21657. Case{"GET", "304 Not Modified"}}) {
  21658. for (const auto &f :
  21659. {Framing{"Content-Length: 5\r\n", ""},
  21660. Framing{"Content-Length: 5\r\n", "hello"},
  21661. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21662. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21663. // Not decoded, so a build without Brotli opens it too
  21664. Framing{"Content-Encoding: br\r\n", ""}}) {
  21665. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21666. "Connection: close\r\n"
  21667. "\r\n" +
  21668. f.after;
  21669. with_single_response(response, [&](Client &cli) {
  21670. auto handle = cli.open_stream(c.method, "/");
  21671. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21672. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21673. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21674. });
  21675. }
  21676. }
  21677. }
  21678. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21679. // response, is faulty framing, so the connection is not reused after it.
  21680. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21681. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21682. "Content-Length: 0\r\n"
  21683. "Transfer-Encoding: chunked\r\n"
  21684. "\r\n"
  21685. "5\r\nhello\r\n0\r\n\r\n",
  21686. "HTTP/1.0 200 Connection established\r\n"
  21687. "Connection: keep-alive\r\n"
  21688. "Transfer-Encoding: chunked\r\n"
  21689. "\r\n"
  21690. "5\r\nhello\r\n0\r\n\r\n"}) {
  21691. with_single_response(response, [&](Client &cli) {
  21692. cli.set_keep_alive(true);
  21693. auto res = cli.Get("/");
  21694. ASSERT_TRUE(res) << response;
  21695. EXPECT_EQ("hello", res->body);
  21696. EXPECT_FALSE(cli.is_socket_open()) << response;
  21697. });
  21698. }
  21699. }
  21700. // A payload max length of 0 means no limit, however the body is framed.
  21701. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21702. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21703. "Transfer-Encoding: chunked\r\n"
  21704. "\r\n"
  21705. "5\r\nhello\r\n0\r\n\r\n",
  21706. "HTTP/1.1 200 OK\r\n"
  21707. "Connection: close\r\n"
  21708. "\r\n"
  21709. "hello"}) {
  21710. with_single_response(response, [&](Client &cli) {
  21711. cli.set_payload_max_length(0);
  21712. auto res = cli.Get("/");
  21713. ASSERT_TRUE(res) << response;
  21714. EXPECT_EQ("hello", res->body) << response;
  21715. });
  21716. }
  21717. }
  21718. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21719. Server svr;
  21720. svr.set_payload_max_length(0);
  21721. svr.Post("/echo", [](const Request &req, Response &res) {
  21722. res.set_content(req.body, "text/plain");
  21723. });
  21724. auto port = svr.bind_to_any_port(HOST);
  21725. thread t = thread([&] { svr.listen_after_bind(); });
  21726. auto se = detail::scope_exit([&] {
  21727. svr.stop();
  21728. t.join();
  21729. ASSERT_FALSE(svr.is_running());
  21730. });
  21731. svr.wait_until_ready();
  21732. Client cli(HOST, port);
  21733. auto res = cli.Post(
  21734. "/echo",
  21735. [](size_t /*offset*/, DataSink &sink) {
  21736. sink.write("hello", 5);
  21737. sink.done();
  21738. return true;
  21739. },
  21740. "text/plain");
  21741. ASSERT_TRUE(res);
  21742. EXPECT_EQ(StatusCode::OK_200, res->status);
  21743. EXPECT_EQ("hello", res->body);
  21744. }
  21745. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21746. TEST_F(OpenStreamTest, Gzip) {
  21747. Client cli("127.0.0.1", port_);
  21748. auto handle = cli.open_stream("GET", "/compressible", {},
  21749. {{"Accept-Encoding", "gzip"}});
  21750. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21751. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21752. }
  21753. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21754. Client cli("127.0.0.1", port_);
  21755. auto handle =
  21756. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21757. {{"Accept-Encoding", "gzip"}});
  21758. ASSERT_TRUE(handle.is_valid());
  21759. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21760. EXPECT_EQ("123456789", read_all(handle));
  21761. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21762. }
  21763. #endif
  21764. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21765. TEST_F(OpenStreamTest, Brotli) {
  21766. Client cli("127.0.0.1", port_);
  21767. auto handle =
  21768. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21769. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21770. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21771. }
  21772. #endif
  21773. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21774. TEST_F(OpenStreamTest, Zstd) {
  21775. Client cli("127.0.0.1", port_);
  21776. auto handle = cli.open_stream("GET", "/compressible", {},
  21777. {{"Accept-Encoding", "zstd"}});
  21778. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21779. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21780. }
  21781. #endif
  21782. #ifdef CPPHTTPLIB_SSL_ENABLED
  21783. class SSLOpenStreamTest : public ::testing::Test {
  21784. protected:
  21785. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21786. void SetUp() override {
  21787. svr_.Get("/hello", [](const Request &, Response &res) {
  21788. res.set_content("Hello SSL World!", "text/plain");
  21789. });
  21790. svr_.Get("/chunked", [](const Request &, Response &res) {
  21791. res.set_chunked_content_provider("text/plain",
  21792. [](size_t offset, DataSink &sink) {
  21793. if (offset < 15) {
  21794. sink.write("chunk", 5);
  21795. return true;
  21796. }
  21797. sink.done();
  21798. return true;
  21799. });
  21800. });
  21801. svr_.Post("/echo", [](const Request &req, Response &res) {
  21802. res.set_content(req.body, req.get_header_value("Content-Type"));
  21803. });
  21804. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21805. std::string body = req.body;
  21806. res.set_chunked_content_provider(
  21807. "text/plain", [body](size_t offset, DataSink &sink) {
  21808. if (offset < body.size()) {
  21809. sink.write(body.data() + offset, body.size() - offset);
  21810. }
  21811. sink.done();
  21812. return true;
  21813. });
  21814. });
  21815. port_ = svr_.bind_to_any_port("127.0.0.1");
  21816. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21817. svr_.wait_until_ready();
  21818. }
  21819. void TearDown() override {
  21820. svr_.stop();
  21821. if (thread_.joinable()) thread_.join();
  21822. }
  21823. SSLServer svr_;
  21824. std::thread thread_;
  21825. int port_ = 0;
  21826. };
  21827. TEST_F(SSLOpenStreamTest, Basic) {
  21828. SSLClient cli("127.0.0.1", port_);
  21829. cli.enable_server_certificate_verification(false);
  21830. auto handle = cli.open_stream("GET", "/hello");
  21831. ASSERT_TRUE(handle.is_valid());
  21832. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21833. }
  21834. TEST_F(SSLOpenStreamTest, Chunked) {
  21835. SSLClient cli("127.0.0.1", port_);
  21836. cli.enable_server_certificate_verification(false);
  21837. auto handle = cli.open_stream("GET", "/chunked");
  21838. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21839. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21840. "Transfer-Encoding") == "chunked");
  21841. auto body = read_all(handle);
  21842. EXPECT_EQ("chunkchunkchunk", body);
  21843. }
  21844. TEST_F(SSLOpenStreamTest, Post) {
  21845. SSLClient cli("127.0.0.1", port_);
  21846. cli.enable_server_certificate_verification(false);
  21847. auto handle =
  21848. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21849. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21850. EXPECT_EQ(200, handle.response->status);
  21851. auto body = read_all(handle);
  21852. EXPECT_EQ("Hello SSL POST", body);
  21853. }
  21854. TEST_F(SSLOpenStreamTest, PostChunked) {
  21855. SSLClient cli("127.0.0.1", port_);
  21856. cli.enable_server_certificate_verification(false);
  21857. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21858. "Chunked SSL Data", "text/plain");
  21859. ASSERT_TRUE(handle.is_valid());
  21860. EXPECT_EQ(200, handle.response->status);
  21861. auto body = read_all(handle);
  21862. EXPECT_EQ("Chunked SSL Data", body);
  21863. }
  21864. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21865. // Content-Length is terminated by the server closing the connection. When the
  21866. // SSL peer sends a close_notify after the body, the client must treat it as a
  21867. // clean EOF and return a successful response rather than an error.
  21868. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21870. ASSERT_TRUE(svr.is_valid());
  21871. svr.set_keep_alive_max_count(1);
  21872. const std::string expected_body = "Hello from connection-close response!";
  21873. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21874. res.set_content_provider("text/plain",
  21875. [&](size_t offset, DataSink &sink) -> bool {
  21876. if (offset < expected_body.size()) {
  21877. sink.write(expected_body.data() + offset,
  21878. expected_body.size() - offset);
  21879. }
  21880. sink.done();
  21881. return true;
  21882. });
  21883. });
  21884. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21885. auto se = detail::scope_exit([&] {
  21886. svr.stop();
  21887. listen_thread.join();
  21888. ASSERT_FALSE(svr.is_running());
  21889. });
  21890. svr.wait_until_ready();
  21891. SSLClient cli(HOST, PORT);
  21892. cli.enable_server_certificate_verification(false);
  21893. auto res = cli.Get("/no-content-length");
  21894. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21895. EXPECT_EQ(StatusCode::OK_200, res->status);
  21896. EXPECT_EQ(expected_body, res->body);
  21897. }
  21898. // Without Content-Length, the full buffer size reaches tls::read().
  21899. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21900. if (sizeof(size_t) <= sizeof(int)) {
  21901. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21902. }
  21903. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21904. ASSERT_TRUE(svr.is_valid());
  21905. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21906. res.set_content_provider("text/plain",
  21907. [&](size_t offset, DataSink &sink) -> bool {
  21908. if (offset == 0) { sink.write("Hello", 5); }
  21909. sink.done();
  21910. return true;
  21911. });
  21912. });
  21913. auto port = svr.bind_to_any_port(HOST);
  21914. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21915. auto se = detail::scope_exit([&] {
  21916. svr.stop();
  21917. listen_thread.join();
  21918. });
  21919. svr.wait_until_ready();
  21920. SSLClient cli(HOST, port);
  21921. cli.enable_server_certificate_verification(false);
  21922. auto handle = cli.open_stream("GET", "/no-content-length");
  21923. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21924. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21925. std::unique_ptr<char[]> buf(new char[len]);
  21926. std::string body;
  21927. ssize_t n;
  21928. while ((n = handle.read(buf.get(), len)) > 0) {
  21929. body.append(buf.get(), static_cast<size_t>(n));
  21930. }
  21931. EXPECT_EQ(0, n);
  21932. EXPECT_EQ("Hello", body);
  21933. }
  21934. #endif // CPPHTTPLIB_SSL_ENABLED
  21935. //==============================================================================
  21936. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21937. // results for various scenarios.
  21938. //==============================================================================
  21939. TEST(ParityTest, GetVsOpenStream) {
  21940. Server svr;
  21941. const std::string path = "/parity";
  21942. const std::string content = "Parity test content: hello world";
  21943. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21944. res.set_content(content, "text/plain");
  21945. });
  21946. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21947. auto se = detail::scope_exit([&] {
  21948. svr.stop();
  21949. t.join();
  21950. ASSERT_FALSE(svr.is_running());
  21951. });
  21952. svr.wait_until_ready();
  21953. Client cli(HOST, PORT);
  21954. // Non-stream path
  21955. auto r1 = cli.Get(path);
  21956. ASSERT_TRUE(r1);
  21957. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21958. // Stream path
  21959. auto h = cli.open_stream("GET", path);
  21960. ASSERT_TRUE(h.is_valid());
  21961. EXPECT_EQ(r1->body, read_all(h));
  21962. }
  21963. // Helper to compress data with provided compressor type T
  21964. template <typename Compressor>
  21965. static std::string compress_payload_for_parity(const std::string &in) {
  21966. std::string out;
  21967. Compressor compressor;
  21968. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21969. [&](const char *data, size_t n) {
  21970. out.append(data, n);
  21971. return true;
  21972. });
  21973. EXPECT_TRUE(ok);
  21974. return out;
  21975. }
  21976. // Helper function for compression parity tests
  21977. template <typename Compressor>
  21978. static void test_compression_parity(const std::string &original,
  21979. const std::string &path,
  21980. const std::string &encoding) {
  21981. const std::string compressed =
  21982. compress_payload_for_parity<Compressor>(original);
  21983. Server svr;
  21984. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21985. res.set_content(compressed, "application/octet-stream");
  21986. res.set_header("Content-Encoding", encoding);
  21987. });
  21988. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21989. auto se = detail::scope_exit([&] {
  21990. svr.stop();
  21991. t.join();
  21992. ASSERT_FALSE(svr.is_running());
  21993. });
  21994. svr.wait_until_ready();
  21995. Client cli(HOST, PORT);
  21996. // Non-streaming
  21997. {
  21998. auto res = cli.Get(path);
  21999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22000. EXPECT_EQ(StatusCode::OK_200, res->status);
  22001. EXPECT_EQ(original, res->body);
  22002. }
  22003. // Streaming
  22004. {
  22005. auto h = cli.open_stream("GET", path);
  22006. ASSERT_TRUE(h.is_valid());
  22007. EXPECT_EQ(original, read_all(h));
  22008. }
  22009. }
  22010. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22011. TEST(ParityTest, Gzip) {
  22012. test_compression_parity<detail::gzip_compressor>(
  22013. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22014. }
  22015. #endif
  22016. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22017. TEST(ParityTest, Brotli) {
  22018. test_compression_parity<detail::brotli_compressor>(
  22019. "Hello, brotli parity test payload", "/parity-br", "br");
  22020. }
  22021. #endif
  22022. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22023. TEST(ParityTest, Zstd) {
  22024. test_compression_parity<detail::zstd_compressor>(
  22025. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22026. }
  22027. #endif
  22028. //==============================================================================
  22029. // New Stream API Tests
  22030. //==============================================================================
  22031. inline std::string read_body(httplib::stream::Result &result) {
  22032. std::string body;
  22033. while (result.next()) {
  22034. body.append(result.data(), result.size());
  22035. }
  22036. return body;
  22037. }
  22038. TEST(ClientConnectionTest, Basic) {
  22039. httplib::ClientConnection conn;
  22040. EXPECT_FALSE(conn.is_open());
  22041. conn.sock = 1;
  22042. EXPECT_TRUE(conn.is_open());
  22043. httplib::ClientConnection conn2(std::move(conn));
  22044. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22045. conn2.sock = INVALID_SOCKET;
  22046. }
  22047. // Unified test server for all stream::* tests
  22048. class StreamApiTest : public ::testing::Test {
  22049. protected:
  22050. void SetUp() override {
  22051. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22052. res.set_content("Hello World!", "text/plain");
  22053. });
  22054. svr_.Get("/echo-params",
  22055. [](const httplib::Request &req, httplib::Response &res) {
  22056. std::string r;
  22057. for (const auto &p : req.params) {
  22058. if (!r.empty()) r += "&";
  22059. r += p.first + "=" + p.second;
  22060. }
  22061. res.set_content(r, "text/plain");
  22062. });
  22063. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22064. res.set_content(req.body, req.get_header_value("Content-Type"));
  22065. });
  22066. svr_.Post("/echo-headers",
  22067. [](const httplib::Request &req, httplib::Response &res) {
  22068. std::string r;
  22069. for (const auto &h : req.headers)
  22070. r += h.first + ": " + h.second + "\n";
  22071. res.set_content(r, "text/plain");
  22072. });
  22073. svr_.Post("/echo-params",
  22074. [](const httplib::Request &req, httplib::Response &res) {
  22075. std::string r = "params:";
  22076. for (const auto &p : req.params)
  22077. r += p.first + "=" + p.second + ";";
  22078. res.set_content(r + " body:" + req.body, "text/plain");
  22079. });
  22080. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22081. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22082. });
  22083. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22084. res.set_content("PUT:" + req.body, "text/plain");
  22085. });
  22086. svr_.Patch("/echo",
  22087. [](const httplib::Request &req, httplib::Response &res) {
  22088. res.set_content("PATCH:" + req.body, "text/plain");
  22089. });
  22090. svr_.Delete(
  22091. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22092. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22093. "text/plain");
  22094. });
  22095. svr_.Get("/head-test",
  22096. [](const httplib::Request &, httplib::Response &res) {
  22097. res.set_content("body for HEAD", "text/plain");
  22098. });
  22099. svr_.Options("/options",
  22100. [](const httplib::Request &, httplib::Response &res) {
  22101. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22102. });
  22103. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22104. svr_.wait_until_ready();
  22105. }
  22106. void TearDown() override {
  22107. svr_.stop();
  22108. if (thread_.joinable()) thread_.join();
  22109. }
  22110. httplib::Server svr_;
  22111. std::thread thread_;
  22112. };
  22113. // stream::Get tests
  22114. TEST_F(StreamApiTest, GetBasic) {
  22115. httplib::Client cli(HOST, PORT);
  22116. auto result = httplib::stream::Get(cli, "/hello");
  22117. ASSERT_TRUE(result.is_valid());
  22118. EXPECT_EQ(200, result.status());
  22119. EXPECT_EQ("Hello World!", read_body(result));
  22120. }
  22121. TEST_F(StreamApiTest, GetWithParams) {
  22122. httplib::Client cli(HOST, PORT);
  22123. httplib::Params params{{"foo", "bar"}};
  22124. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22125. ASSERT_TRUE(result.is_valid());
  22126. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22127. }
  22128. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22129. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22130. httplib::Client cli(HOST, PORT);
  22131. cli.set_payload_max_length(0);
  22132. auto result = httplib::stream::Get(cli, "/hello");
  22133. ASSERT_TRUE(result.is_valid());
  22134. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22135. EXPECT_EQ("Hello World!", read_body(result));
  22136. }
  22137. #endif
  22138. TEST_F(StreamApiTest, GetConnectionError) {
  22139. httplib::Client cli(HOST, 9999);
  22140. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22141. }
  22142. TEST_F(StreamApiTest, Get404) {
  22143. httplib::Client cli(HOST, PORT);
  22144. auto result = httplib::stream::Get(cli, "/nonexistent");
  22145. EXPECT_TRUE(result.is_valid());
  22146. EXPECT_EQ(404, result.status());
  22147. }
  22148. // stream::Post tests
  22149. TEST_F(StreamApiTest, PostBasic) {
  22150. httplib::Client cli(HOST, PORT);
  22151. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22152. "application/json");
  22153. ASSERT_TRUE(result.is_valid());
  22154. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22155. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22156. }
  22157. TEST_F(StreamApiTest, PostWithHeaders) {
  22158. httplib::Client cli(HOST, PORT);
  22159. httplib::Headers headers{{"X-Custom", "value"}};
  22160. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22161. "text/plain");
  22162. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22163. }
  22164. TEST_F(StreamApiTest, PostWithParams) {
  22165. httplib::Client cli(HOST, PORT);
  22166. httplib::Params params{{"k", "v"}};
  22167. auto result =
  22168. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22169. auto body = read_body(result);
  22170. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22171. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22172. }
  22173. TEST_F(StreamApiTest, PostLarge) {
  22174. httplib::Client cli(HOST, PORT);
  22175. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22176. size_t total = 0;
  22177. while (result.next()) {
  22178. total += result.size();
  22179. }
  22180. EXPECT_EQ(100u * 1024u, total);
  22181. }
  22182. // stream::Put/Patch tests
  22183. TEST_F(StreamApiTest, PutAndPatch) {
  22184. httplib::Client cli(HOST, PORT);
  22185. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22186. EXPECT_EQ("PUT:test", read_body(put));
  22187. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22188. EXPECT_EQ("PATCH:test", read_body(patch));
  22189. }
  22190. // stream::Delete tests
  22191. TEST_F(StreamApiTest, Delete) {
  22192. httplib::Client cli(HOST, PORT);
  22193. auto del1 = httplib::stream::Delete(cli, "/resource");
  22194. EXPECT_EQ("Deleted", read_body(del1));
  22195. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22196. EXPECT_EQ("Deleted:data", read_body(del2));
  22197. }
  22198. // stream::Head/Options tests
  22199. TEST_F(StreamApiTest, HeadAndOptions) {
  22200. httplib::Client cli(HOST, PORT);
  22201. auto head = httplib::stream::Head(cli, "/head-test");
  22202. EXPECT_TRUE(head.is_valid());
  22203. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22204. auto opts = httplib::stream::Options(cli, "/options");
  22205. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22206. }
  22207. // SSL stream::* tests
  22208. #ifdef CPPHTTPLIB_SSL_ENABLED
  22209. class SSLStreamApiTest : public ::testing::Test {
  22210. protected:
  22211. void SetUp() override {
  22212. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22213. res.set_content("Hello SSL!", "text/plain");
  22214. });
  22215. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22216. res.set_content(req.body, "text/plain");
  22217. });
  22218. port_ = svr_.bind_to_any_port("127.0.0.1");
  22219. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22220. svr_.wait_until_ready();
  22221. }
  22222. void TearDown() override {
  22223. svr_.stop();
  22224. if (thread_.joinable()) thread_.join();
  22225. }
  22226. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22227. std::thread thread_;
  22228. int port_ = 0;
  22229. };
  22230. TEST_F(SSLStreamApiTest, GetAndPost) {
  22231. httplib::SSLClient cli("127.0.0.1", port_);
  22232. cli.enable_server_certificate_verification(false);
  22233. auto get = httplib::stream::Get(cli, "/hello");
  22234. EXPECT_EQ("Hello SSL!", read_body(get));
  22235. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22236. EXPECT_EQ("test", read_body(post));
  22237. }
  22238. #endif
  22239. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22240. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22241. // BodyReader
  22242. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22243. // Test that read timeout during streaming is detected
  22244. // Use a large content-length response where server delays mid-stream
  22245. Server svr;
  22246. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22247. // Send a large response with delay in the middle
  22248. res.set_content_provider(
  22249. 1000, // content_length
  22250. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22251. if (offset < 100) {
  22252. // Send first 100 bytes immediately
  22253. std::string data(100, 'A');
  22254. sink.write(data.c_str(), data.size());
  22255. return true;
  22256. }
  22257. // Then delay longer than client timeout
  22258. std::this_thread::sleep_for(std::chrono::seconds(3));
  22259. std::string data(900, 'B');
  22260. sink.write(data.c_str(), data.size());
  22261. return true;
  22262. });
  22263. });
  22264. auto port = 8091;
  22265. std::thread t([&]() { svr.listen("localhost", port); });
  22266. svr.wait_until_ready();
  22267. Client cli("localhost", port);
  22268. cli.set_read_timeout(1, 0); // 1 second timeout
  22269. auto handle = cli.open_stream("GET", "/slow-stream");
  22270. ASSERT_TRUE(handle.is_valid());
  22271. char buf[256];
  22272. ssize_t total = 0;
  22273. ssize_t n;
  22274. bool got_error = false;
  22275. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22276. total += n;
  22277. }
  22278. if (n < 0) {
  22279. got_error = true;
  22280. // Should be timeout or read error
  22281. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22282. handle.get_read_error() == Error::Read)
  22283. << "Actual error: " << to_string(handle.get_read_error());
  22284. }
  22285. // Either we got an error, or we got less data than expected
  22286. EXPECT_TRUE(got_error || total < 1000)
  22287. << "Expected timeout but got all " << total << " bytes";
  22288. svr.stop();
  22289. t.join();
  22290. }
  22291. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22292. // Test connection closed detection via BodyReader
  22293. Server svr;
  22294. std::atomic<bool> close_now{false};
  22295. svr.Get("/will-close", [&](const Request &, Response &res) {
  22296. res.set_content_provider(
  22297. 10000, // Large content_length that we won't fully send
  22298. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22299. if (offset < 100) {
  22300. std::string data(100, 'X');
  22301. sink.write(data.c_str(), data.size());
  22302. return true;
  22303. }
  22304. // Wait for signal then abort
  22305. while (!close_now) {
  22306. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22307. }
  22308. return false; // Abort - server will close connection
  22309. });
  22310. });
  22311. auto port = 8092;
  22312. std::thread t([&]() { svr.listen("localhost", port); });
  22313. svr.wait_until_ready();
  22314. Client cli("localhost", port);
  22315. auto handle = cli.open_stream("GET", "/will-close");
  22316. ASSERT_TRUE(handle.is_valid());
  22317. char buf[256];
  22318. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22319. EXPECT_GT(n, 0) << "First read should succeed";
  22320. // Signal server to close
  22321. close_now = true;
  22322. // Keep reading until error or EOF
  22323. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22324. // Keep reading
  22325. }
  22326. // Should get an error since content_length wasn't satisfied
  22327. if (n < 0) {
  22328. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22329. handle.get_read_error() == Error::Read)
  22330. << "Actual error: " << to_string(handle.get_read_error());
  22331. }
  22332. svr.stop();
  22333. t.join();
  22334. }
  22335. #ifdef CPPHTTPLIB_SSL_ENABLED
  22336. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22337. // Test that read timeout during SSL streaming is detected
  22338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22339. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22340. res.set_content_provider(
  22341. 1000, "text/plain",
  22342. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22343. if (offset < 100) {
  22344. std::string data(100, 'A');
  22345. sink.write(data.c_str(), data.size());
  22346. return true;
  22347. }
  22348. std::this_thread::sleep_for(std::chrono::seconds(3));
  22349. std::string data(900, 'B');
  22350. sink.write(data.c_str(), data.size());
  22351. return true;
  22352. });
  22353. });
  22354. auto port = 8093;
  22355. std::thread t([&]() { svr.listen("localhost", port); });
  22356. svr.wait_until_ready();
  22357. SSLClient cli("localhost", port);
  22358. cli.enable_server_certificate_verification(false);
  22359. cli.set_read_timeout(1, 0); // 1 second timeout
  22360. auto handle = cli.open_stream("GET", "/slow-stream");
  22361. ASSERT_TRUE(handle.is_valid());
  22362. char buf[256];
  22363. ssize_t total = 0;
  22364. ssize_t n;
  22365. bool got_error = false;
  22366. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22367. total += n;
  22368. }
  22369. if (n < 0) {
  22370. got_error = true;
  22371. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22372. handle.get_read_error() == Error::Read)
  22373. << "Actual error: " << to_string(handle.get_read_error());
  22374. }
  22375. EXPECT_TRUE(got_error || total < 1000)
  22376. << "Expected timeout but got all " << total << " bytes";
  22377. svr.stop();
  22378. t.join();
  22379. }
  22380. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22381. // Test SSL connection closed detection
  22382. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22383. std::atomic<bool> close_now{false};
  22384. svr.Get("/will-close", [&](const Request &, Response &res) {
  22385. res.set_content_provider(
  22386. 10000, "text/plain",
  22387. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22388. if (offset < 100) {
  22389. std::string data(100, 'X');
  22390. sink.write(data.c_str(), data.size());
  22391. return true;
  22392. }
  22393. while (!close_now) {
  22394. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22395. }
  22396. return false;
  22397. });
  22398. });
  22399. auto port = 8094;
  22400. std::thread t([&]() { svr.listen("localhost", port); });
  22401. svr.wait_until_ready();
  22402. SSLClient cli("localhost", port);
  22403. cli.enable_server_certificate_verification(false);
  22404. auto handle = cli.open_stream("GET", "/will-close");
  22405. ASSERT_TRUE(handle.is_valid());
  22406. char buf[256];
  22407. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22408. EXPECT_GT(n, 0);
  22409. // Signal server to close
  22410. close_now = true;
  22411. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22412. // Keep reading
  22413. }
  22414. if (n < 0) {
  22415. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22416. handle.get_read_error() == Error::Read)
  22417. << "Actual error: " << to_string(handle.get_read_error());
  22418. }
  22419. svr.stop();
  22420. t.join();
  22421. }
  22422. #endif
  22423. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22424. using namespace httplib;
  22425. // Create a test file
  22426. const char *fname = "etag_testfile.txt";
  22427. const char *content = "etag-content";
  22428. {
  22429. std::ofstream ofs(fname);
  22430. ofs << content;
  22431. ASSERT_TRUE(ofs.good());
  22432. }
  22433. Server svr;
  22434. svr.set_mount_point("/static", ".");
  22435. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22436. svr.wait_until_ready();
  22437. Client cli(HOST, PORT);
  22438. // First request: should get 200 with ETag header
  22439. auto res1 = cli.Get("/static/etag_testfile.txt");
  22440. ASSERT_TRUE(res1);
  22441. ASSERT_EQ(200, res1->status);
  22442. ASSERT_TRUE(res1->has_header("ETag"));
  22443. std::string etag = res1->get_header_value("ETag");
  22444. EXPECT_FALSE(etag.empty());
  22445. // Verify ETag format: W/"hex-hex"
  22446. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22447. EXPECT_EQ('W', etag[0]);
  22448. EXPECT_EQ('/', etag[1]);
  22449. EXPECT_EQ('"', etag[2]);
  22450. EXPECT_EQ('"', etag.back());
  22451. // Exact match: expect 304 Not Modified
  22452. Headers h2 = {{"If-None-Match", etag}};
  22453. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22454. ASSERT_TRUE(res2);
  22455. EXPECT_EQ(304, res2->status);
  22456. // Wildcard match: expect 304 Not Modified
  22457. Headers h3 = {{"If-None-Match", "*"}};
  22458. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22459. ASSERT_TRUE(res3);
  22460. EXPECT_EQ(304, res3->status);
  22461. // Non-matching ETag: expect 200
  22462. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22463. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22464. ASSERT_TRUE(res4);
  22465. EXPECT_EQ(200, res4->status);
  22466. // Multiple ETags with one matching: expect 304
  22467. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22468. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22469. ASSERT_TRUE(res5);
  22470. EXPECT_EQ(304, res5->status);
  22471. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22472. // that equivalent to the single comma-separated list above, so the match on
  22473. // the second line must still be found.
  22474. Headers h6;
  22475. h6.emplace("If-None-Match", "W/\"other\"");
  22476. h6.emplace("If-None-Match", etag);
  22477. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22478. ASSERT_TRUE(res6);
  22479. EXPECT_EQ(304, res6->status);
  22480. svr.stop();
  22481. t.join();
  22482. std::remove(fname);
  22483. }
  22484. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22485. using namespace httplib;
  22486. Server svr;
  22487. svr.set_mount_point("/static", ".");
  22488. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22489. svr.wait_until_ready();
  22490. Client cli(HOST, PORT);
  22491. // Send If-None-Match: * to a non-existent file
  22492. Headers h = {{"If-None-Match", "*"}};
  22493. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22495. EXPECT_EQ(404, res->status);
  22496. svr.stop();
  22497. t.join();
  22498. }
  22499. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22500. using namespace httplib;
  22501. // Create a test file
  22502. const char *fname = "etag_boundary_testfile.txt";
  22503. const char *content = "boundary-test";
  22504. {
  22505. std::ofstream ofs(fname);
  22506. ofs << content;
  22507. ASSERT_TRUE(ofs.good());
  22508. }
  22509. Server svr;
  22510. svr.set_mount_point("/static", ".");
  22511. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22512. svr.wait_until_ready();
  22513. Client cli(HOST, PORT);
  22514. // Get the actual ETag
  22515. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22516. ASSERT_TRUE(res1);
  22517. ASSERT_EQ(200, res1->status);
  22518. ASSERT_TRUE(res1->has_header("ETag"));
  22519. std::string etag = res1->get_header_value("ETag");
  22520. // Test 1: Very long ETag value (longer than actual ETag)
  22521. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22522. Headers h1 = {{"If-None-Match", "W/"
  22523. "\"very-long-etag-value-that-is-much-longer-"
  22524. "than-the-actual-etag-value\""}};
  22525. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22526. ASSERT_TRUE(res2);
  22527. EXPECT_EQ(200, res2->status); // Should not match
  22528. // Test 2: Long string followed by wildcard
  22529. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22530. // string)
  22531. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22532. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22533. ASSERT_TRUE(res3);
  22534. EXPECT_EQ(304, res3->status); // Should match on "*"
  22535. // Test 3: Wildcard followed by long string
  22536. // Should match on "*" immediately and return 304
  22537. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22538. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22539. ASSERT_TRUE(res4);
  22540. EXPECT_EQ(304, res4->status); // Should match on "*"
  22541. // Test 4: Multiple long non-matching values
  22542. // Should NOT match and return 200 (test that all comparisons are safe)
  22543. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22544. "W/\"second-long-non-matching-value\", "
  22545. "W/\"third-long-non-matching-value\""}};
  22546. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22547. ASSERT_TRUE(res5);
  22548. EXPECT_EQ(200, res5->status); // Should not match
  22549. // Test 5: Single character that is not "*" (edge case)
  22550. Headers h5 = {{"If-None-Match", "X"}};
  22551. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22552. ASSERT_TRUE(res6);
  22553. EXPECT_EQ(200, res6->status); // Should not match
  22554. svr.stop();
  22555. t.join();
  22556. std::remove(fname);
  22557. }
  22558. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22559. using namespace httplib;
  22560. // Create a test file
  22561. const char *fname = "ims_testfile.txt";
  22562. const char *content = "if-modified-since-test";
  22563. {
  22564. std::ofstream ofs(fname);
  22565. ofs << content;
  22566. ASSERT_TRUE(ofs.good());
  22567. }
  22568. Server svr;
  22569. svr.set_mount_point("/static", ".");
  22570. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22571. svr.wait_until_ready();
  22572. Client cli(HOST, PORT);
  22573. // First request: should get 200 with Last-Modified header
  22574. auto res1 = cli.Get("/static/ims_testfile.txt");
  22575. ASSERT_TRUE(res1);
  22576. ASSERT_EQ(200, res1->status);
  22577. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22578. std::string last_modified = res1->get_header_value("Last-Modified");
  22579. EXPECT_FALSE(last_modified.empty());
  22580. // If-Modified-Since with same time: expect 304
  22581. Headers h2 = {{"If-Modified-Since", last_modified}};
  22582. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22583. ASSERT_TRUE(res2);
  22584. EXPECT_EQ(304, res2->status);
  22585. // If-Modified-Since with future time: expect 304
  22586. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22587. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22588. ASSERT_TRUE(res3);
  22589. EXPECT_EQ(304, res3->status);
  22590. // If-Modified-Since with past time: expect 200
  22591. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22592. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22593. ASSERT_TRUE(res4);
  22594. EXPECT_EQ(200, res4->status);
  22595. // If-None-Match takes precedence over If-Modified-Since
  22596. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22597. ASSERT_TRUE(res1->has_header("ETag"));
  22598. std::string etag = res1->get_header_value("ETag");
  22599. Headers h5 = {{"If-None-Match", etag},
  22600. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22601. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22602. ASSERT_TRUE(res5);
  22603. EXPECT_EQ(304, res5->status);
  22604. svr.stop();
  22605. t.join();
  22606. std::remove(fname);
  22607. }
  22608. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22609. using namespace httplib;
  22610. Server svr;
  22611. // Endpoint that returns compressible content
  22612. svr.Get("/compressible", [](const Request &, Response &res) {
  22613. // Return a large enough body to trigger compression
  22614. std::string body(1000, 'a');
  22615. res.set_content(body, "text/plain");
  22616. });
  22617. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22618. svr.wait_until_ready();
  22619. Client cli(HOST, PORT);
  22620. // Request with gzip support: should get Vary header when compressed
  22621. cli.set_compress(true);
  22622. auto res1 = cli.Get("/compressible");
  22623. ASSERT_TRUE(res1);
  22624. EXPECT_EQ(200, res1->status);
  22625. // If Content-Encoding is set, Vary should also be set
  22626. if (res1->has_header("Content-Encoding")) {
  22627. EXPECT_TRUE(res1->has_header("Vary"));
  22628. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22629. }
  22630. // Request without Accept-Encoding header: should not have compression
  22631. Headers h_no_compress;
  22632. auto res2 = cli.Get("/compressible", h_no_compress);
  22633. ASSERT_TRUE(res2);
  22634. EXPECT_EQ(200, res2->status);
  22635. // Verify Vary header is present when compression is applied
  22636. // (the exact behavior depends on server configuration)
  22637. svr.stop();
  22638. t.join();
  22639. }
  22640. TEST(ETagTest, IfRangeWithETag) {
  22641. using namespace httplib;
  22642. // Create a test file with known content
  22643. const char *fname = "if_range_testfile.txt";
  22644. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22645. {
  22646. std::ofstream ofs(fname);
  22647. ofs << content;
  22648. ASSERT_TRUE(ofs.good());
  22649. }
  22650. Server svr;
  22651. svr.set_mount_point("/static", ".");
  22652. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22653. svr.wait_until_ready();
  22654. Client cli(HOST, PORT);
  22655. // First request: get ETag
  22656. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22657. ASSERT_TRUE(res1);
  22658. ASSERT_EQ(200, res1->status);
  22659. ASSERT_TRUE(res1->has_header("ETag"));
  22660. std::string etag = res1->get_header_value("ETag");
  22661. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22662. // Since our server generates weak ETags (W/"..."), If-Range with our
  22663. // ETag should NOT result in partial content - it should return full content.
  22664. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22665. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22666. ASSERT_TRUE(res2);
  22667. // Weak ETag in If-Range -> full content (200), not partial (206)
  22668. EXPECT_EQ(200, res2->status);
  22669. EXPECT_EQ(content, res2->body);
  22670. EXPECT_FALSE(res2->has_header("Content-Range"));
  22671. // Range request with non-matching If-Range (ETag): should get 200 (full
  22672. // content)
  22673. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22674. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22675. ASSERT_TRUE(res3);
  22676. EXPECT_EQ(200, res3->status);
  22677. EXPECT_EQ(content, res3->body);
  22678. EXPECT_FALSE(res3->has_header("Content-Range"));
  22679. // Range request with strong ETag (hypothetical - our server doesn't generate
  22680. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22681. // should return full content)
  22682. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22683. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22684. ASSERT_TRUE(res4);
  22685. EXPECT_EQ(200, res4->status);
  22686. EXPECT_EQ(content, res4->body);
  22687. EXPECT_FALSE(res4->has_header("Content-Range"));
  22688. svr.stop();
  22689. t.join();
  22690. std::remove(fname);
  22691. }
  22692. TEST(ETagTest, IfRangeWithDate) {
  22693. using namespace httplib;
  22694. // Create a test file
  22695. const char *fname = "if_range_date_testfile.txt";
  22696. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22697. {
  22698. std::ofstream ofs(fname);
  22699. ofs << content;
  22700. ASSERT_TRUE(ofs.good());
  22701. }
  22702. Server svr;
  22703. svr.set_mount_point("/static", ".");
  22704. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22705. svr.wait_until_ready();
  22706. Client cli(HOST, PORT);
  22707. // First request: get Last-Modified
  22708. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22709. ASSERT_TRUE(res1);
  22710. ASSERT_EQ(200, res1->status);
  22711. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22712. std::string last_modified = res1->get_header_value("Last-Modified");
  22713. // Range request with matching If-Range (date): should get 206
  22714. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22715. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22716. ASSERT_TRUE(res2);
  22717. EXPECT_EQ(206, res2->status);
  22718. EXPECT_EQ("FGHIJ", res2->body);
  22719. // Range request with old If-Range date: should get 200 (full content)
  22720. Headers h3 = {{"Range", "bytes=5-9"},
  22721. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22722. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22723. ASSERT_TRUE(res3);
  22724. EXPECT_EQ(200, res3->status);
  22725. EXPECT_EQ(content, res3->body);
  22726. // Range request with future If-Range date: should get 206
  22727. Headers h4 = {{"Range", "bytes=0-4"},
  22728. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22729. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22730. ASSERT_TRUE(res4);
  22731. EXPECT_EQ(206, res4->status);
  22732. EXPECT_EQ("ABCDE", res4->body);
  22733. svr.stop();
  22734. t.join();
  22735. std::remove(fname);
  22736. }
  22737. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22738. using namespace httplib;
  22739. const char *fname = "etag_malformed.txt";
  22740. const char *content = "malformed-etag";
  22741. {
  22742. std::ofstream ofs(fname);
  22743. ofs << content;
  22744. ASSERT_TRUE(ofs.good());
  22745. }
  22746. Server svr;
  22747. svr.set_mount_point("/static", ".");
  22748. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22749. svr.wait_until_ready();
  22750. Client cli(HOST, PORT);
  22751. // baseline: should get 200 and an ETag
  22752. auto res1 = cli.Get("/static/etag_malformed.txt");
  22753. ASSERT_TRUE(res1);
  22754. ASSERT_EQ(200, res1->status);
  22755. ASSERT_TRUE(res1->has_header("ETag"));
  22756. // Malformed ETag value (missing quotes) should be treated as non-matching
  22757. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22758. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22759. ASSERT_TRUE(res_bad);
  22760. EXPECT_EQ(200, res_bad->status);
  22761. // Whitespace-only header value should be considered invalid / non-matching
  22762. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22763. "Host: localhost\r\n"
  22764. "If-None-Match: \r\n"
  22765. "Connection: close\r\n"
  22766. "\r\n";
  22767. std::string out;
  22768. ASSERT_TRUE(send_request(5, raw_req, &out));
  22769. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22770. svr.stop();
  22771. t.join();
  22772. std::remove(fname);
  22773. }
  22774. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22775. using namespace httplib;
  22776. const char *fname = "ims_invalid_format.txt";
  22777. const char *content = "ims-bad-format";
  22778. {
  22779. std::ofstream ofs(fname);
  22780. ofs << content;
  22781. ASSERT_TRUE(ofs.good());
  22782. }
  22783. Server svr;
  22784. svr.set_mount_point("/static", ".");
  22785. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22786. svr.wait_until_ready();
  22787. Client cli(HOST, PORT);
  22788. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22789. ASSERT_TRUE(res1);
  22790. ASSERT_EQ(200, res1->status);
  22791. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22792. // If-Modified-Since with invalid format should not result in 304
  22793. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22794. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22795. ASSERT_TRUE(res_bad);
  22796. EXPECT_EQ(200, res_bad->status);
  22797. // If-Range with invalid date format should be treated as mismatch -> full
  22798. // content (200)
  22799. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22800. {"If-Range", "invalid-date"}};
  22801. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22802. ASSERT_TRUE(res_ifrange);
  22803. EXPECT_EQ(200, res_ifrange->status);
  22804. svr.stop();
  22805. t.join();
  22806. std::remove(fname);
  22807. }
  22808. TEST(ETagTest, IfRangeWithMalformedETag) {
  22809. using namespace httplib;
  22810. const char *fname = "ifrange_malformed.txt";
  22811. const std::string content = "0123456789";
  22812. {
  22813. std::ofstream ofs(fname);
  22814. ofs << content;
  22815. ASSERT_TRUE(ofs.good());
  22816. }
  22817. Server svr;
  22818. svr.set_mount_point("/static", ".");
  22819. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22820. svr.wait_until_ready();
  22821. Client cli(HOST, PORT);
  22822. // First request: get ETag
  22823. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22824. ASSERT_TRUE(res1);
  22825. ASSERT_EQ(200, res1->status);
  22826. ASSERT_TRUE(res1->has_header("ETag"));
  22827. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22828. // full content (200)
  22829. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22830. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22831. ASSERT_TRUE(res2);
  22832. EXPECT_EQ(200, res2->status);
  22833. EXPECT_EQ(content, res2->body);
  22834. svr.stop();
  22835. t.join();
  22836. std::remove(fname);
  22837. }
  22838. TEST(ETagTest, ExtremeLargeDateValues) {
  22839. using namespace httplib;
  22840. const char *fname = "ims_extreme_date.txt";
  22841. const char *content = "ims-extreme-date";
  22842. {
  22843. std::ofstream ofs(fname);
  22844. ofs << content;
  22845. ASSERT_TRUE(ofs.good());
  22846. }
  22847. Server svr;
  22848. svr.set_mount_point("/static", ".");
  22849. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22850. svr.wait_until_ready();
  22851. Client cli(HOST, PORT);
  22852. auto res1 = cli.Get(std::string("/static/") + fname);
  22853. ASSERT_TRUE(res1);
  22854. ASSERT_EQ(200, res1->status);
  22855. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22856. // Extremely large year that may overflow date parsing routines.
  22857. Headers h_large_date = {
  22858. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22859. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22860. ASSERT_TRUE(res_bad);
  22861. // Expect server to treat this as invalid/mismatch and return full content
  22862. EXPECT_EQ(200, res_bad->status);
  22863. // If-Range with extremely large date should be treated as mismatch -> full
  22864. // content (200)
  22865. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22866. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22867. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22868. ASSERT_TRUE(res_ifrange);
  22869. EXPECT_EQ(200, res_ifrange->status);
  22870. svr.stop();
  22871. t.join();
  22872. std::remove(fname);
  22873. }
  22874. TEST(ETagTest, NegativeFileModificationTime) {
  22875. using namespace httplib;
  22876. const char *fname = "ims_negative_mtime.txt";
  22877. const std::string content = "negative-mtime";
  22878. {
  22879. std::ofstream ofs(fname);
  22880. ofs << content;
  22881. ASSERT_TRUE(ofs.good());
  22882. }
  22883. // Try to set file mtime to a negative value. This may fail on some
  22884. // platforms/filesystems; if it fails, the test will still verify server
  22885. // behaves safely by performing a regular conditional request.
  22886. #if defined(__APPLE__) || defined(__linux__)
  22887. bool set_negative = false;
  22888. do {
  22889. struct timeval times[2];
  22890. // access time: now
  22891. times[0].tv_sec = time(nullptr);
  22892. times[0].tv_usec = 0;
  22893. // modification time: negative (e.g., -1)
  22894. times[1].tv_sec = -1;
  22895. times[1].tv_usec = 0;
  22896. if (utimes(fname, times) == 0) { set_negative = true; }
  22897. } while (0);
  22898. #else
  22899. bool set_negative = false;
  22900. #endif
  22901. Server svr;
  22902. svr.set_mount_point("/static", ".");
  22903. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22904. svr.wait_until_ready();
  22905. Client cli(HOST, PORT);
  22906. auto res1 = cli.Get(std::string("/static/") + fname);
  22907. ASSERT_TRUE(res1);
  22908. ASSERT_EQ(200, res1->status);
  22909. bool has_last_modified = res1->has_header("Last-Modified");
  22910. std::string last_modified;
  22911. if (has_last_modified) {
  22912. last_modified = res1->get_header_value("Last-Modified");
  22913. }
  22914. if (set_negative) {
  22915. // If we successfully set a negative mtime, ensure server returns a
  22916. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22917. // with an old date and ensure server handles it without crash.
  22918. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22919. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22920. ASSERT_TRUE(res2);
  22921. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22922. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22923. } else {
  22924. // Could not set negative mtime on this platform; fall back to verifying
  22925. // that normal invalid/malformed dates are treated safely (non-304).
  22926. Headers h_bad_date = {
  22927. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22928. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22929. ASSERT_TRUE(res_bad);
  22930. EXPECT_EQ(200, res_bad->status);
  22931. }
  22932. svr.stop();
  22933. t.join();
  22934. std::remove(fname);
  22935. }
  22936. //==============================================================================
  22937. // Integration Tests with Server
  22938. //==============================================================================
  22939. class SSEIntegrationTest : public ::testing::Test {
  22940. protected:
  22941. void SetUp() override {
  22942. stop_server_.store(false);
  22943. events_.clear();
  22944. server_ = httplib::detail::make_unique<Server>();
  22945. setup_server();
  22946. start_server();
  22947. }
  22948. void TearDown() override {
  22949. stop_server_.store(true);
  22950. event_cv_.notify_all();
  22951. server_->stop();
  22952. if (server_thread_.joinable()) { server_thread_.join(); }
  22953. }
  22954. void setup_server() {
  22955. // Simple SSE endpoint
  22956. server_->Get("/events", [this](const Request &req, Response &res) {
  22957. auto last_id = req.get_header_value("Last-Event-ID");
  22958. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22959. res.set_chunked_content_provider(
  22960. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22961. std::unique_lock<std::mutex> lock(event_mutex_);
  22962. if (event_cv_.wait_for(
  22963. lock, std::chrono::milliseconds(200), [this] {
  22964. return !events_.empty() || stop_server_.load();
  22965. })) {
  22966. if (stop_server_.load()) { return false; }
  22967. if (!events_.empty()) {
  22968. std::string event = events_.front();
  22969. events_.erase(events_.begin());
  22970. sink.write(event.data(), event.size());
  22971. return true;
  22972. }
  22973. }
  22974. return !stop_server_.load();
  22975. });
  22976. });
  22977. // Endpoint that returns error
  22978. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22979. res.status = 500;
  22980. res.set_content("Internal Server Error", "text/plain");
  22981. });
  22982. // Endpoint for custom event types
  22983. server_->Get("/custom-events", [](const Request &, Response &res) {
  22984. res.set_chunked_content_provider(
  22985. "text/event-stream", [](size_t offset, DataSink &sink) {
  22986. if (offset == 0) {
  22987. std::string event = "event: update\ndata: updated\n\n"
  22988. "event: delete\ndata: deleted\n\n";
  22989. sink.write(event.data(), event.size());
  22990. }
  22991. return false; // End stream after sending
  22992. });
  22993. });
  22994. }
  22995. void start_server() {
  22996. port_ = server_->bind_to_any_port(HOST);
  22997. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22998. // Wait for server to start
  22999. while (!server_->is_running()) {
  23000. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23001. }
  23002. }
  23003. int get_port() const { return port_; }
  23004. void send_event(const std::string &event) {
  23005. std::lock_guard<std::mutex> lock(event_mutex_);
  23006. events_.push_back(event);
  23007. event_cv_.notify_all();
  23008. }
  23009. std::unique_ptr<Server> server_;
  23010. std::thread server_thread_;
  23011. std::mutex event_mutex_;
  23012. std::condition_variable event_cv_;
  23013. std::vector<std::string> events_;
  23014. std::atomic<bool> stop_server_{false};
  23015. std::string last_received_event_id_;
  23016. int port_ = 0;
  23017. };
  23018. //==============================================================================
  23019. // SSE Parser Tests
  23020. //==============================================================================
  23021. struct SSEParseResult {
  23022. std::vector<sse::SSEMessage> events;
  23023. std::vector<std::string> ids;
  23024. std::vector<int> retries;
  23025. bool ok = true;
  23026. std::string trace; // Every handler call in order
  23027. };
  23028. static SSEParseResult
  23029. sse_parse(const std::vector<std::string> &chunks,
  23030. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23031. SSEParseResult r;
  23032. detail::SSEParser parser(
  23033. [&](const sse::SSEMessage &msg) {
  23034. r.events.push_back(msg);
  23035. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23036. },
  23037. [&](const std::string &id) {
  23038. r.ids.push_back(id);
  23039. r.trace += "id[" + id + "]";
  23040. },
  23041. [&](int retry_ms) {
  23042. r.retries.push_back(retry_ms);
  23043. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23044. },
  23045. max_event_length);
  23046. for (const auto &chunk : chunks) {
  23047. if (!parser.parse(chunk.data(), chunk.size())) {
  23048. r.ok = false;
  23049. break;
  23050. }
  23051. }
  23052. return r;
  23053. }
  23054. static SSEParseResult sse_parse(const std::string &stream) {
  23055. return sse_parse(std::vector<std::string>{stream});
  23056. }
  23057. TEST(SSEParserTest, SingleLineData) {
  23058. auto r = sse_parse("data: hello\n\n");
  23059. ASSERT_EQ(r.events.size(), 1u);
  23060. EXPECT_EQ(r.events[0].data, "hello");
  23061. EXPECT_EQ(r.events[0].event, "message");
  23062. }
  23063. TEST(SSEParserTest, MultiLineData) {
  23064. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23065. ASSERT_EQ(r.events.size(), 1u);
  23066. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23067. }
  23068. TEST(SSEParserTest, CustomEventType) {
  23069. auto r = sse_parse("event: update\ndata: payload\n\n");
  23070. ASSERT_EQ(r.events.size(), 1u);
  23071. EXPECT_EQ(r.events[0].event, "update");
  23072. EXPECT_EQ(r.events[0].data, "payload");
  23073. }
  23074. TEST(SSEParserTest, EventIdHandling) {
  23075. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23076. ASSERT_EQ(r.events.size(), 1u);
  23077. EXPECT_EQ(r.events[0].id, "12345");
  23078. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23079. }
  23080. TEST(SSEParserTest, EmptyEventId) {
  23081. auto r = sse_parse("id:\ndata: test\n\n");
  23082. ASSERT_EQ(r.events.size(), 1u);
  23083. EXPECT_EQ(r.events[0].id, "");
  23084. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23085. }
  23086. TEST(SSEParserTest, CommentsIgnored) {
  23087. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23088. ASSERT_EQ(r.events.size(), 1u);
  23089. EXPECT_EQ(r.events[0].data, "hello");
  23090. EXPECT_EQ(r.events[0].event, "message");
  23091. }
  23092. TEST(SSEParserTest, ColonInValue) {
  23093. auto r = sse_parse("data: hello:world:test\n\n");
  23094. ASSERT_EQ(r.events.size(), 1u);
  23095. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23096. }
  23097. TEST(SSEParserTest, FieldNameOnly) {
  23098. // A line without a colon is a field name with an empty value
  23099. auto r = sse_parse("data\n\n");
  23100. ASSERT_EQ(r.events.size(), 1u);
  23101. EXPECT_EQ(r.events[0].data, "");
  23102. }
  23103. TEST(SSEParserTest, TrailingCarriageReturn) {
  23104. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23105. ASSERT_EQ(r.events.size(), 1u);
  23106. EXPECT_EQ(r.events[0].event, "update");
  23107. EXPECT_EQ(r.events[0].data, "hello");
  23108. }
  23109. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23110. auto r = sse_parse("data\r\n\r\n");
  23111. ASSERT_EQ(r.events.size(), 1u);
  23112. EXPECT_EQ(r.events[0].data, "");
  23113. }
  23114. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23115. auto r = sse_parse("event: update\rdata: hello\r\r");
  23116. ASSERT_EQ(r.events.size(), 1u);
  23117. EXPECT_EQ(r.events[0].event, "update");
  23118. EXPECT_EQ(r.events[0].data, "hello");
  23119. }
  23120. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23121. // Chunk boundaries fall inside every \r\n and right before the first one
  23122. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23123. "\ndata: hello\r", "\n\r", "\n"});
  23124. ASSERT_EQ(r.events.size(), 1u);
  23125. EXPECT_EQ(r.events[0].event, "update");
  23126. EXPECT_EQ(r.events[0].data, "hello");
  23127. }
  23128. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23129. // Only a BOM at the start of the stream is ignored
  23130. auto r = sse_parse("\xEF\xBB\xBF"
  23131. "data: first\n\n"
  23132. "\xEF\xBB\xBF"
  23133. "data: second\n\n");
  23134. ASSERT_EQ(r.events.size(), 1u);
  23135. EXPECT_EQ(r.events[0].data, "first");
  23136. }
  23137. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23138. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23139. ASSERT_EQ(r.events.size(), 1u);
  23140. EXPECT_EQ(r.events[0].data, "hello");
  23141. EXPECT_EQ(r.events[0].event, "message");
  23142. }
  23143. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23144. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23145. ASSERT_EQ(r.events.size(), 2u);
  23146. EXPECT_EQ(r.events[0].data, "hello");
  23147. EXPECT_EQ(r.events[1].data, "hello");
  23148. }
  23149. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23150. // An event without data is not dispatched, and its type must not leak
  23151. // into the next event
  23152. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23153. ASSERT_EQ(r.events.size(), 1u);
  23154. EXPECT_EQ(r.events[0].event, "message");
  23155. EXPECT_EQ(r.events[0].data, "hello");
  23156. }
  23157. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23158. // Also when the empty field replaces an earlier type
  23159. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23160. ASSERT_EQ(r.events.size(), 2u);
  23161. EXPECT_EQ(r.events[0].event, "message");
  23162. EXPECT_EQ(r.events[1].event, "message");
  23163. }
  23164. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23165. auto r = sse_parse("id: 42\n\n");
  23166. EXPECT_TRUE(r.events.empty());
  23167. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23168. }
  23169. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23170. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23171. ASSERT_EQ(r.events.size(), 2u);
  23172. EXPECT_EQ(r.events[0].id, "1");
  23173. EXPECT_EQ(r.events[1].id, "");
  23174. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23175. }
  23176. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23177. // Ids that cannot be carried in a Last-Event-ID header
  23178. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23179. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23180. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23181. }
  23182. TEST(SSEParserTest, RetryDigitsOnly) {
  23183. auto r = sse_parse("retry: 1000\n");
  23184. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23185. // A value that is not all ASCII digits, or does not fit, is ignored
  23186. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23187. EXPECT_TRUE(r.retries.empty());
  23188. }
  23189. TEST(SSEParserTest, CompleteEventParsing) {
  23190. auto r = sse_parse("event: notification\nid: evt-42\n"
  23191. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23192. ASSERT_EQ(r.events.size(), 1u);
  23193. EXPECT_EQ(r.events[0].event, "notification");
  23194. EXPECT_EQ(r.events[0].id, "evt-42");
  23195. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23196. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23197. }
  23198. TEST(SSEParserTest, IncompleteEventNotReported) {
  23199. // An event still waiting for its blank line when the stream ends is
  23200. // discarded per the SSE spec
  23201. auto r = sse_parse("id: 1\ndata: x\n");
  23202. EXPECT_TRUE(r.events.empty());
  23203. EXPECT_TRUE(r.ids.empty());
  23204. }
  23205. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23206. const std::vector<std::string> streams = {
  23207. "\xEF\xBB\xBF"
  23208. "data: bom\r\n\r\n",
  23209. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23210. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23211. };
  23212. for (const auto &stream : streams) {
  23213. auto expected = sse_parse(stream).trace;
  23214. ASSERT_FALSE(expected.empty());
  23215. for (size_t i = 0; i <= stream.size(); i++) {
  23216. auto r = sse_parse(
  23217. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23218. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23219. }
  23220. std::vector<std::string> bytes;
  23221. for (auto c : stream) {
  23222. bytes.emplace_back(1, c);
  23223. }
  23224. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23225. }
  23226. }
  23227. TEST(SSEParserTest, MaxEventLength) {
  23228. // A line still waiting for its end
  23229. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23230. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23231. // Data accumulated over the lines of one event
  23232. EXPECT_TRUE(
  23233. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23234. EXPECT_FALSE(
  23235. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23236. // 0 means no limit
  23237. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23238. // Events completed in the same chunk are still reported
  23239. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23240. EXPECT_FALSE(r.ok);
  23241. ASSERT_EQ(r.events.size(), 1u);
  23242. EXPECT_EQ(r.events[0].data, "a");
  23243. }
  23244. TEST(SSEMessageTest, Clear) {
  23245. sse::SSEMessage msg;
  23246. msg.event = "custom";
  23247. msg.data = "some data";
  23248. msg.id = "123";
  23249. msg.clear();
  23250. EXPECT_EQ(msg.event, "message");
  23251. EXPECT_EQ(msg.data, "");
  23252. EXPECT_EQ(msg.id, "");
  23253. }
  23254. //==============================================================================
  23255. // SSE Integration Tests
  23256. //==============================================================================
  23257. // Test: Successful connection and on_open callback
  23258. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23259. // Add a simple endpoint that sends one event and closes
  23260. server_->Get("/simple-event", [](const Request &, Response &res) {
  23261. res.set_chunked_content_provider(
  23262. "text/event-stream", [](size_t offset, DataSink &sink) {
  23263. if (offset == 0) {
  23264. std::string event = "data: hello\n\n";
  23265. sink.write(event.data(), event.size());
  23266. }
  23267. return false; // Close stream after sending
  23268. });
  23269. });
  23270. Client client("localhost", get_port());
  23271. sse::SSEClient sse(client, "/simple-event");
  23272. std::atomic<bool> open_called{false};
  23273. std::atomic<bool> message_received{false};
  23274. sse.on_open([&open_called]() { open_called.store(true); });
  23275. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23276. if (msg.data == "hello") { message_received.store(true); }
  23277. });
  23278. sse.set_reconnect_interval(100);
  23279. sse.set_max_reconnect_attempts(1);
  23280. // Start async
  23281. sse.start_async();
  23282. // Wait for message to be processed
  23283. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23284. sse.stop();
  23285. EXPECT_TRUE(open_called.load());
  23286. EXPECT_TRUE(message_received.load());
  23287. }
  23288. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23289. // A data line that never ends.
  23290. server_->Get("/endless-line", [](const Request &, Response &res) {
  23291. res.set_chunked_content_provider(
  23292. "text/event-stream", [](size_t offset, DataSink &sink) {
  23293. if (offset == 0) { sink.write("data: ", 6); }
  23294. std::string chunk(64 * 1024, 'A');
  23295. return sink.write(chunk.data(), chunk.size());
  23296. });
  23297. });
  23298. Client client("localhost", get_port());
  23299. sse::SSEClient sse(client, "/endless-line");
  23300. std::atomic<bool> too_long{false};
  23301. sse.on_error([&](Error err) {
  23302. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23303. });
  23304. sse.set_max_reconnect_attempts(1);
  23305. sse.start_async();
  23306. for (int i = 0; i < 500 && !too_long; i++) {
  23307. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23308. }
  23309. sse.stop();
  23310. EXPECT_TRUE(too_long);
  23311. }
  23312. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23313. // Far more in all than the client's payload limit below.
  23314. server_->Get("/many-events", [](const Request &, Response &res) {
  23315. res.set_chunked_content_provider(
  23316. "text/event-stream", [](size_t offset, DataSink &sink) {
  23317. if (offset == 0) {
  23318. std::string events;
  23319. for (int i = 0; i < 1000; i++) {
  23320. events += "data: message\n\n";
  23321. }
  23322. sink.write(events.data(), events.size());
  23323. }
  23324. return false;
  23325. });
  23326. });
  23327. Client client("localhost", get_port());
  23328. client.set_payload_max_length(1024);
  23329. sse::SSEClient sse(client, "/many-events");
  23330. std::atomic<int> messages{0};
  23331. std::atomic<bool> too_large{false};
  23332. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23333. sse.on_error([&](Error err) {
  23334. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23335. });
  23336. sse.set_max_reconnect_attempts(1);
  23337. sse.start_async();
  23338. for (int i = 0; i < 500 && messages < 1000; i++) {
  23339. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23340. }
  23341. sse.stop();
  23342. EXPECT_GE(messages.load(), 1000);
  23343. EXPECT_FALSE(too_large);
  23344. }
  23345. // Test: on_message callback
  23346. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23347. // Endpoint that sends multiple events then closes
  23348. server_->Get("/multi-event", [](const Request &, Response &res) {
  23349. res.set_chunked_content_provider(
  23350. "text/event-stream", [](size_t offset, DataSink &sink) {
  23351. if (offset == 0) {
  23352. std::string events = "data: message1\n\ndata: message2\n\n";
  23353. sink.write(events.data(), events.size());
  23354. }
  23355. return false;
  23356. });
  23357. });
  23358. Client client("localhost", get_port());
  23359. sse::SSEClient sse(client, "/multi-event");
  23360. std::vector<std::string> received_messages;
  23361. std::mutex messages_mutex;
  23362. sse.on_message([&](const sse::SSEMessage &msg) {
  23363. std::lock_guard<std::mutex> lock(messages_mutex);
  23364. received_messages.push_back(msg.data);
  23365. });
  23366. sse.set_reconnect_interval(100);
  23367. sse.set_max_reconnect_attempts(1);
  23368. sse.start_async();
  23369. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23370. sse.stop();
  23371. std::lock_guard<std::mutex> lock(messages_mutex);
  23372. EXPECT_GE(received_messages.size(), 2u);
  23373. if (received_messages.size() >= 2) {
  23374. EXPECT_EQ(received_messages[0], "message1");
  23375. EXPECT_EQ(received_messages[1], "message2");
  23376. }
  23377. }
  23378. // Test: on_event for specific types
  23379. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23380. Client client("localhost", get_port());
  23381. sse::SSEClient sse(client, "/custom-events");
  23382. std::atomic<bool> update_received{false};
  23383. std::atomic<bool> delete_received{false};
  23384. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23385. if (msg.data == "updated") { update_received.store(true); }
  23386. });
  23387. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23388. if (msg.data == "deleted") { delete_received.store(true); }
  23389. });
  23390. sse.set_max_reconnect_attempts(1);
  23391. sse.start_async();
  23392. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23393. sse.stop();
  23394. EXPECT_TRUE(update_received.load());
  23395. EXPECT_TRUE(delete_received.load());
  23396. }
  23397. // Test: on_error callback on connection failure
  23398. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23399. // Connect to a non-existent port
  23400. Client client("localhost", 59999);
  23401. sse::SSEClient sse(client, "/events");
  23402. std::atomic<bool> error_called{false};
  23403. Error received_error = Error::Success;
  23404. sse.on_error([&](Error err) {
  23405. error_called.store(true);
  23406. received_error = err;
  23407. });
  23408. sse.set_reconnect_interval(50);
  23409. sse.set_max_reconnect_attempts(1);
  23410. sse.start_async();
  23411. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23412. sse.stop();
  23413. EXPECT_TRUE(error_called.load());
  23414. EXPECT_NE(received_error, Error::Success);
  23415. }
  23416. // Test: Last-Event-ID header sent on reconnect
  23417. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23418. // Endpoint that sends event with ID
  23419. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23420. res.set_chunked_content_provider(
  23421. "text/event-stream", [](size_t offset, DataSink &sink) {
  23422. if (offset == 0) {
  23423. std::string event = "id: evt-123\ndata: test\n\n";
  23424. sink.write(event.data(), event.size());
  23425. }
  23426. return false;
  23427. });
  23428. });
  23429. Client client("localhost", get_port());
  23430. sse::SSEClient sse(client, "/event-with-id");
  23431. std::atomic<bool> id_received{false};
  23432. sse.on_message([&](const sse::SSEMessage &msg) {
  23433. if (!msg.id.empty()) { id_received.store(true); }
  23434. });
  23435. sse.set_reconnect_interval(100);
  23436. sse.set_max_reconnect_attempts(1);
  23437. sse.start_async();
  23438. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23439. sse.stop();
  23440. EXPECT_TRUE(id_received.load());
  23441. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23442. }
  23443. // Test: last_event_id() read from another thread while start_async() runs
  23444. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23445. // Ids of every length up to 200, so the stored id keeps changing size
  23446. server_->Get("/many-ids", [](const Request &, Response &res) {
  23447. res.set_chunked_content_provider(
  23448. "text/event-stream", [](size_t offset, DataSink &sink) {
  23449. if (offset == 0) {
  23450. std::string events;
  23451. for (size_t i = 0; i < 2000; i++) {
  23452. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23453. events += "data: x\n\n";
  23454. }
  23455. events += "id: end\ndata: x\n\n";
  23456. sink.write(events.data(), events.size());
  23457. }
  23458. return false;
  23459. });
  23460. });
  23461. Client client("localhost", get_port());
  23462. sse::SSEClient sse(client, "/many-ids");
  23463. // Wait out the rest of the test rather than replay the stream
  23464. sse.set_reconnect_interval(10000);
  23465. sse.set_max_reconnect_attempts(1);
  23466. sse.start_async();
  23467. auto well_formed = true;
  23468. std::string id;
  23469. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23470. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23471. id = sse.last_event_id();
  23472. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23473. well_formed = false;
  23474. }
  23475. }
  23476. sse.stop();
  23477. EXPECT_TRUE(well_formed);
  23478. EXPECT_EQ(sse.last_event_id(), "end");
  23479. }
  23480. // Test: Manual stop
  23481. TEST_F(SSEIntegrationTest, ManualStop) {
  23482. // Endpoint that sends one event and stays open briefly. The server outlives
  23483. // this test body, so the provider uses the fixture's flag, not a local.
  23484. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23485. res.set_chunked_content_provider(
  23486. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23487. if (offset == 0) {
  23488. std::string event = "data: connected\n\n";
  23489. sink.write(event.data(), event.size());
  23490. }
  23491. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23492. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23493. }
  23494. return false;
  23495. });
  23496. });
  23497. Client client("localhost", get_port());
  23498. sse::SSEClient sse(client, "/stay-open");
  23499. std::atomic<bool> connected{false};
  23500. sse.on_open([&connected]() { connected.store(true); });
  23501. sse.set_reconnect_interval(100);
  23502. sse.set_max_reconnect_attempts(1);
  23503. sse.start_async();
  23504. // Wait for connection to establish
  23505. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23506. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23507. }
  23508. EXPECT_TRUE(connected.load());
  23509. EXPECT_TRUE(sse.is_connected());
  23510. // Signal handler to stop
  23511. stop_server_.store(true);
  23512. // Stop SSE client
  23513. sse.stop();
  23514. EXPECT_FALSE(sse.is_connected());
  23515. }
  23516. // Sends one event, then nothing until stop is set
  23517. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23518. return [&stop](const Request &, Response &res) {
  23519. res.set_chunked_content_provider(
  23520. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23521. if (offset == 0) {
  23522. std::string event = "data: hello\n\n";
  23523. sink.write(event.data(), event.size());
  23524. }
  23525. while (!stop.load()) {
  23526. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23527. }
  23528. return false;
  23529. });
  23530. };
  23531. }
  23532. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23533. static void check_stop_interrupts_blocked_read(Client &client) {
  23534. client.set_read_timeout(30, 0);
  23535. for (auto by_destructor : {false, true}) {
  23536. std::atomic<bool> received{false};
  23537. std::chrono::steady_clock::time_point start;
  23538. {
  23539. sse::SSEClient sse(client, "/idle-stream");
  23540. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23541. sse.start_async();
  23542. for (int i = 0; i < 500 && !received.load(); ++i) {
  23543. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23544. }
  23545. ASSERT_TRUE(received.load());
  23546. // Let the client block in the next read
  23547. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23548. start = std::chrono::steady_clock::now();
  23549. if (!by_destructor) { sse.stop(); }
  23550. }
  23551. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23552. std::chrono::seconds(2));
  23553. }
  23554. }
  23555. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23556. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23557. Client client("localhost", get_port());
  23558. check_stop_interrupts_blocked_read(client);
  23559. }
  23560. #ifdef CPPHTTPLIB_SSL_ENABLED
  23561. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23563. std::atomic<bool> done{false};
  23564. svr.Get("/idle-stream", idle_event_stream(done));
  23565. auto port = svr.bind_to_any_port(HOST);
  23566. std::thread t([&] { svr.listen_after_bind(); });
  23567. auto se = detail::scope_exit([&] {
  23568. done.store(true);
  23569. svr.stop();
  23570. t.join();
  23571. });
  23572. svr.wait_until_ready();
  23573. Client client("https://localhost:" + std::to_string(port));
  23574. client.enable_server_certificate_verification(false);
  23575. check_stop_interrupts_blocked_read(client);
  23576. }
  23577. #endif
  23578. // Test: SSEClient with custom headers
  23579. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23580. // Setup a server endpoint that checks for custom header
  23581. std::atomic<bool> header_received{false};
  23582. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23583. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23584. header_received.store(true);
  23585. }
  23586. res.set_chunked_content_provider("text/event-stream",
  23587. [](size_t, DataSink &) { return false; });
  23588. });
  23589. Client client("localhost", get_port());
  23590. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23591. sse::SSEClient sse(client, "/header-check", headers);
  23592. sse.set_max_reconnect_attempts(1);
  23593. sse.start_async();
  23594. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23595. sse.stop();
  23596. EXPECT_TRUE(header_received.load());
  23597. }
  23598. // Test: Reconnect interval configuration
  23599. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23600. Client client("localhost", get_port());
  23601. sse::SSEClient sse(client, "/events");
  23602. auto &result = sse.set_reconnect_interval(500);
  23603. // Builder pattern should return reference to self
  23604. EXPECT_EQ(&result, &sse);
  23605. }
  23606. // Test: Max reconnect attempts
  23607. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23608. // Connect to non-existent port to force reconnects
  23609. Client client("localhost", 59998);
  23610. sse::SSEClient sse(client, "/events");
  23611. std::atomic<int> error_count{0};
  23612. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23613. sse.set_reconnect_interval(50);
  23614. sse.set_max_reconnect_attempts(2);
  23615. auto start = std::chrono::steady_clock::now();
  23616. sse.start(); // Blocking call
  23617. auto end = std::chrono::steady_clock::now();
  23618. // Should have stopped after 2 failed attempts
  23619. EXPECT_GE(error_count.load(), 2);
  23620. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23621. auto duration =
  23622. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23623. #ifdef _WIN32
  23624. // Windows is much slower for socket connection failures
  23625. EXPECT_LT(duration.count(), 7000);
  23626. #else
  23627. EXPECT_LT(duration.count(), 1000);
  23628. #endif
  23629. }
  23630. // Test: Multi-line data in integration
  23631. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23632. // Endpoint with multi-line data
  23633. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23634. res.set_chunked_content_provider(
  23635. "text/event-stream", [](size_t offset, DataSink &sink) {
  23636. if (offset == 0) {
  23637. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23638. sink.write(event.data(), event.size());
  23639. }
  23640. return false;
  23641. });
  23642. });
  23643. Client client("localhost", get_port());
  23644. sse::SSEClient sse(client, "/multiline-data");
  23645. std::string received_data;
  23646. std::mutex data_mutex;
  23647. sse.on_message([&](const sse::SSEMessage &msg) {
  23648. std::lock_guard<std::mutex> lock(data_mutex);
  23649. received_data = msg.data;
  23650. });
  23651. sse.set_reconnect_interval(100);
  23652. sse.set_max_reconnect_attempts(1);
  23653. sse.start_async();
  23654. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23655. sse.stop();
  23656. std::lock_guard<std::mutex> lock(data_mutex);
  23657. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23658. }
  23659. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23660. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23661. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23662. DataSink &sink) {
  23663. if (offset == 0) {
  23664. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23665. sink.write(events.data(), events.size());
  23666. }
  23667. return false;
  23668. });
  23669. });
  23670. Client client("localhost", get_port());
  23671. sse::SSEClient sse(client, "/empty-data-lines");
  23672. std::mutex mutex;
  23673. std::condition_variable cv;
  23674. std::vector<std::string> received;
  23675. sse.on_message([&](const sse::SSEMessage &msg) {
  23676. std::lock_guard<std::mutex> lock(mutex);
  23677. received.push_back(msg.data);
  23678. cv.notify_all();
  23679. });
  23680. sse.set_max_reconnect_attempts(1);
  23681. sse.start_async();
  23682. {
  23683. std::unique_lock<std::mutex> lock(mutex);
  23684. cv.wait_for(lock, std::chrono::seconds(2),
  23685. [&] { return received.size() >= 3; });
  23686. }
  23687. sse.stop();
  23688. ASSERT_GE(received.size(), 3u);
  23689. EXPECT_EQ(received[0], "");
  23690. EXPECT_EQ(received[1], "\nhello");
  23691. EXPECT_EQ(received[2], "");
  23692. }
  23693. // Test: Auto-reconnect after server disconnection
  23694. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23695. std::atomic<int> connection_count{0};
  23696. std::atomic<int> message_count{0};
  23697. // Endpoint that sends one event and closes, forcing reconnect
  23698. server_->Get("/reconnect-test",
  23699. [&connection_count](const Request &, Response &res) {
  23700. connection_count.fetch_add(1);
  23701. res.set_chunked_content_provider(
  23702. "text/event-stream", [](size_t offset, DataSink &sink) {
  23703. if (offset == 0) {
  23704. std::string event = "data: hello\n\n";
  23705. sink.write(event.data(), event.size());
  23706. }
  23707. return false; // Close connection after sending
  23708. });
  23709. });
  23710. Client client("localhost", get_port());
  23711. sse::SSEClient sse(client, "/reconnect-test");
  23712. sse.on_message([&message_count](const sse::SSEMessage &) {
  23713. message_count.fetch_add(1);
  23714. });
  23715. sse.set_reconnect_interval(100);
  23716. sse.set_max_reconnect_attempts(3);
  23717. sse.start_async();
  23718. // Wait long enough for multiple reconnects
  23719. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23720. sse.stop();
  23721. // Should have connected multiple times (initial + reconnects)
  23722. EXPECT_GE(connection_count.load(), 2);
  23723. // Should have received messages from multiple connections
  23724. EXPECT_GE(message_count.load(), 2);
  23725. }
  23726. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23727. std::atomic<int> connection_count{0};
  23728. // Neither Content-Length nor chunked: the close ends the stream
  23729. server_->Get("/close-delimited",
  23730. [&connection_count](const Request &, Response &res) {
  23731. connection_count.fetch_add(1);
  23732. res.set_content_provider(
  23733. "text/event-stream", [](size_t offset, DataSink &sink) {
  23734. if (offset == 0) {
  23735. std::string event = "data: hello\n\n";
  23736. sink.write(event.data(), event.size());
  23737. } else {
  23738. sink.done();
  23739. }
  23740. return true;
  23741. });
  23742. });
  23743. Client client("localhost", get_port());
  23744. sse::SSEClient sse(client, "/close-delimited");
  23745. std::atomic<int> error_count{0};
  23746. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23747. sse.set_reconnect_interval(100);
  23748. sse.start_async();
  23749. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23750. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23751. }
  23752. sse.stop();
  23753. // Reconnects as after any end of the stream, but reports no error
  23754. EXPECT_GE(connection_count.load(), 2);
  23755. EXPECT_EQ(0, error_count.load());
  23756. }
  23757. // Test: A retry field of all ASCII digits sets the reconnection time
  23758. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23759. std::mutex mutex;
  23760. std::condition_variable cv;
  23761. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23762. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23763. {
  23764. std::lock_guard<std::mutex> lock(mutex);
  23765. connected_at.push_back(std::chrono::steady_clock::now());
  23766. cv.notify_all();
  23767. }
  23768. res.set_chunked_content_provider(
  23769. "text/event-stream", [](size_t offset, DataSink &sink) {
  23770. if (offset == 0) {
  23771. std::string event = "retry: 0\ndata: hello\n\n";
  23772. sink.write(event.data(), event.size());
  23773. }
  23774. return false;
  23775. });
  23776. });
  23777. Client client("localhost", get_port());
  23778. sse::SSEClient sse(client, "/zero-retry");
  23779. sse.set_reconnect_interval(10000);
  23780. sse.start_async();
  23781. {
  23782. std::unique_lock<std::mutex> lock(mutex);
  23783. cv.wait_for(lock, std::chrono::seconds(5),
  23784. [&] { return connected_at.size() >= 2; });
  23785. }
  23786. sse.stop();
  23787. // The server-supplied interval is applied, but never below 100ms, so
  23788. // "retry: 0" does not cause a busy reconnect loop
  23789. std::lock_guard<std::mutex> lock(mutex);
  23790. ASSERT_GE(connected_at.size(), 2u);
  23791. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23792. connected_at[1] - connected_at[0])
  23793. .count();
  23794. EXPECT_GE(interval_ms, 100);
  23795. }
  23796. // Test: Last-Event-ID sent on reconnect
  23797. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23798. std::atomic<int> connection_count{0};
  23799. std::vector<std::string> received_last_event_ids;
  23800. std::mutex id_mutex;
  23801. // Endpoint that checks Last-Event-ID header and sends event with ID
  23802. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23803. int conn = connection_count.fetch_add(1);
  23804. // Capture the Last-Event-ID header from each connection
  23805. {
  23806. std::lock_guard<std::mutex> lock(id_mutex);
  23807. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23808. }
  23809. res.set_chunked_content_provider(
  23810. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23811. if (offset == 0) {
  23812. std::string event =
  23813. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23814. sink.write(event.data(), event.size());
  23815. }
  23816. return false;
  23817. });
  23818. });
  23819. Client client("localhost", get_port());
  23820. sse::SSEClient sse(client, "/reconnect-with-id");
  23821. sse.set_reconnect_interval(100);
  23822. sse.set_max_reconnect_attempts(3);
  23823. sse.start_async();
  23824. // Wait for at least 2 connections
  23825. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23826. sse.stop();
  23827. // Verify behavior
  23828. std::lock_guard<std::mutex> lock(id_mutex);
  23829. EXPECT_GE(received_last_event_ids.size(), 2u);
  23830. // First connection should have no Last-Event-ID
  23831. if (!received_last_event_ids.empty()) {
  23832. EXPECT_EQ(received_last_event_ids[0], "");
  23833. }
  23834. // Second connection should have Last-Event-ID from first connection
  23835. if (received_last_event_ids.size() >= 2) {
  23836. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23837. }
  23838. }
  23839. // Test: set_headers updates headers used on reconnect
  23840. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23841. std::vector<std::string> received_tokens;
  23842. std::mutex token_mutex;
  23843. // Endpoint that captures Authorization header
  23844. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23845. {
  23846. std::lock_guard<std::mutex> lock(token_mutex);
  23847. received_tokens.push_back(req.get_header_value("Authorization"));
  23848. }
  23849. res.set_chunked_content_provider(
  23850. "text/event-stream", [](size_t offset, DataSink &sink) {
  23851. if (offset == 0) {
  23852. std::string event = "data: hello\n\n";
  23853. sink.write(event.data(), event.size());
  23854. }
  23855. return false; // Close connection to trigger reconnect
  23856. });
  23857. });
  23858. Client client("localhost", get_port());
  23859. Headers headers = {{"Authorization", "Bearer old-token"}};
  23860. sse::SSEClient sse(client, "/auth-check", headers);
  23861. // Update headers on each successful connection
  23862. sse.on_open(
  23863. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23864. sse.set_reconnect_interval(100);
  23865. sse.set_max_reconnect_attempts(3);
  23866. sse.start_async();
  23867. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23868. sse.stop();
  23869. std::lock_guard<std::mutex> lock(token_mutex);
  23870. ASSERT_GE(received_tokens.size(), 2u);
  23871. // First connection uses original header
  23872. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23873. // Second connection uses updated header from set_headers
  23874. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23875. }
  23876. // Test: 401 allows reconnection (so on_error can refresh headers)
  23877. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23878. std::atomic<int> connection_count{0};
  23879. // Endpoint: returns 401 on first attempt, 200 on second
  23880. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23881. int conn = connection_count.fetch_add(1);
  23882. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23883. res.status = StatusCode::Unauthorized_401;
  23884. res.set_content("Unauthorized", "text/plain");
  23885. return;
  23886. }
  23887. res.set_chunked_content_provider(
  23888. "text/event-stream", [](size_t offset, DataSink &sink) {
  23889. if (offset == 0) {
  23890. std::string event = "data: authenticated\n\n";
  23891. sink.write(event.data(), event.size());
  23892. }
  23893. return false;
  23894. });
  23895. });
  23896. Client client("localhost", get_port());
  23897. Headers headers = {{"Authorization", "Bearer expired"}};
  23898. sse::SSEClient sse(client, "/auth-retry", headers);
  23899. std::atomic<bool> message_received{false};
  23900. // Refresh token on error
  23901. sse.on_error(
  23902. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23903. sse.on_message([&](const sse::SSEMessage &msg) {
  23904. if (msg.data == "authenticated") { message_received.store(true); }
  23905. });
  23906. sse.set_reconnect_interval(100);
  23907. sse.set_max_reconnect_attempts(3);
  23908. sse.start_async();
  23909. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23910. sse.stop();
  23911. // Should have reconnected after 401 and succeeded with new token
  23912. EXPECT_GE(connection_count.load(), 2);
  23913. EXPECT_TRUE(message_received.load());
  23914. }
  23915. TEST(Issue2318Test, EmptyHostString) {
  23916. {
  23917. httplib::Client cli_empty("", PORT);
  23918. auto res = cli_empty.Get("/");
  23919. ASSERT_FALSE(res);
  23920. EXPECT_EQ(httplib::Error::Connection, res.error());
  23921. }
  23922. {
  23923. httplib::Client cli(" ", PORT);
  23924. auto res = cli.Get("/");
  23925. ASSERT_FALSE(res);
  23926. EXPECT_EQ(httplib::Error::Connection, res.error());
  23927. }
  23928. }
  23929. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23930. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23931. Server svr;
  23932. // Set a small payload limit (1KB)
  23933. svr.set_payload_max_length(1024);
  23934. svr.Post("/test", [&](const Request &req, Response &res) {
  23935. res.set_content("Body size: " + std::to_string(req.body.size()),
  23936. "text/plain");
  23937. });
  23938. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23939. auto se = detail::scope_exit([&] {
  23940. svr.stop();
  23941. listen_thread.join();
  23942. });
  23943. svr.wait_until_ready();
  23944. // Create data that compresses well but exceeds limit when decompressed
  23945. // 8KB of repeated null bytes compresses to a very small size
  23946. std::string original_data(8 * 1024, '\0');
  23947. // Compress the data using gzip
  23948. std::string compressed_data;
  23949. detail::gzip_compressor compressor;
  23950. compressor.compress(original_data.data(), original_data.size(), true,
  23951. [&](const char *data, size_t size) {
  23952. compressed_data.append(data, size);
  23953. return true;
  23954. });
  23955. // Verify compression worked (compressed should be much smaller)
  23956. ASSERT_LT(compressed_data.size(), original_data.size());
  23957. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23958. // Send compressed data with Content-Encoding: gzip
  23959. Client cli(HOST, PORT);
  23960. Headers headers = {{"Content-Encoding", "gzip"}};
  23961. auto res =
  23962. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23963. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23965. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23966. }
  23967. #endif
  23968. // ============================================================================
  23969. // OpenSSL-Specific Tests
  23970. // ============================================================================
  23971. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23972. X509 *readCertificate(const std::string &strFileName) {
  23973. std::ifstream inStream(strFileName);
  23974. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23975. std::istreambuf_iterator<char>());
  23976. if (strCertPEM.empty()) return (nullptr);
  23977. BIO *pbCert = BIO_new(BIO_s_mem());
  23978. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23979. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23980. BIO_free(pbCert);
  23981. return (pCert);
  23982. }
  23983. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23984. std::ifstream inStream(strFileName);
  23985. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23986. std::istreambuf_iterator<char>());
  23987. if (strPrivateKeyPEM.empty()) return (nullptr);
  23988. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23989. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23990. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23991. BIO_free(pbPrivKey);
  23992. return (pPrivateKey);
  23993. }
  23994. TEST(BindServerTest, UpdateCerts) {
  23995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23996. int port = svr.bind_to_any_port("0.0.0.0");
  23997. ASSERT_TRUE(svr.is_valid());
  23998. ASSERT_TRUE(port > 0);
  23999. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24000. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24001. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24002. ASSERT_TRUE(cert != nullptr);
  24003. ASSERT_TRUE(ca_cert != nullptr);
  24004. ASSERT_TRUE(key != nullptr);
  24005. X509_STORE *cert_store = X509_STORE_new();
  24006. X509_STORE_add_cert(cert_store, ca_cert);
  24007. // svr.update_certs(cert, key, cert_store); // deprecated
  24008. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24009. CLIENT_CA_CERT_FILE);
  24010. ASSERT_TRUE(svr.is_valid());
  24011. svr.stop();
  24012. X509_STORE_free(cert_store);
  24013. X509_free(cert);
  24014. X509_free(ca_cert);
  24015. EVP_PKEY_free(key);
  24016. }
  24017. // Test that update_certs() updates client CA list correctly
  24018. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24019. // Start with file-based constructor
  24020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24021. ASSERT_TRUE(svr.is_valid());
  24022. // Initially no client CA list should be set
  24023. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24024. ASSERT_TRUE(ssl_ctx != nullptr);
  24025. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24026. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24027. // Now update with client CA (PEM string)
  24028. std::string cert_pem, key_pem, ca_pem;
  24029. read_file(SERVER_CERT_FILE, cert_pem);
  24030. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24031. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24032. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24033. ASSERT_TRUE(svr.is_valid());
  24034. // Now client CA list should be set
  24035. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24036. ASSERT_TRUE(ca_list_after != nullptr);
  24037. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24038. }
  24039. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24040. // Test that the file-path SSLServer constructor properly sets the client CA
  24041. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24043. ASSERT_TRUE(svr.is_valid());
  24044. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24045. ASSERT_TRUE(ssl_ctx != nullptr);
  24046. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24047. ASSERT_TRUE(ca_list != nullptr);
  24048. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24049. }
  24050. #endif
  24051. // ============================================================================
  24052. // MbedTLS-Specific Tests
  24053. // ============================================================================
  24054. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24055. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24056. using namespace httplib::tls;
  24057. // Track if callback was invoked
  24058. bool callback_invoked = false;
  24059. // The callback receives void* ctx which is actually MbedTlsContext*
  24060. // We can access the mbedtls_ssl_config via the context
  24061. auto setup_callback = [&callback_invoked](void *ctx) {
  24062. callback_invoked = true;
  24063. // Cast to MbedTlsContext* to access the ssl config
  24064. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24065. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24066. // Use static variables to hold certificate data (simplified for test)
  24067. static mbedtls_x509_crt own_cert;
  24068. static mbedtls_pk_context own_key;
  24069. static mbedtls_x509_crt ca_chain;
  24070. static bool initialized = false;
  24071. if (!initialized) {
  24072. mbedtls_x509_crt_init(&own_cert);
  24073. mbedtls_pk_init(&own_key);
  24074. mbedtls_x509_crt_init(&ca_chain);
  24075. // Load server certificate
  24076. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24077. return false;
  24078. }
  24079. // Load server private key.
  24080. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24081. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24082. #if MBEDTLS_VERSION_MAJOR == 3
  24083. ,
  24084. mbedtls_ctr_drbg_random, nullptr
  24085. #endif
  24086. ) != 0) {
  24087. return false;
  24088. }
  24089. // Load CA chain for client verification
  24090. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24091. return false;
  24092. }
  24093. initialized = true;
  24094. }
  24095. // Configure the SSL config
  24096. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24097. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24098. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24099. // Set minimum TLS version using mbedTLS native API
  24100. #if MBEDTLS_VERSION_MAJOR >= 3
  24101. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24102. #else
  24103. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24104. MBEDTLS_SSL_MINOR_VERSION_3);
  24105. #endif
  24106. return true;
  24107. };
  24108. SSLServer svr(setup_callback);
  24109. ASSERT_TRUE(svr.is_valid());
  24110. ASSERT_TRUE(callback_invoked);
  24111. svr.Get("/test", [&](const Request &req, Response &res) {
  24112. res.set_content("test", "text/plain");
  24113. auto cert = req.peer_cert();
  24114. ASSERT_TRUE(static_cast<bool>(cert));
  24115. auto common_name = cert.subject_cn();
  24116. EXPECT_EQ("Common Name", common_name);
  24117. });
  24118. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24119. auto se = detail::scope_exit([&] {
  24120. svr.stop();
  24121. t.join();
  24122. ASSERT_FALSE(svr.is_running());
  24123. });
  24124. svr.wait_until_ready();
  24125. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24126. cli.enable_server_certificate_verification(false);
  24127. cli.set_connection_timeout(30);
  24128. auto res = cli.Get("/test");
  24129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24130. ASSERT_EQ(StatusCode::OK_200, res->status);
  24131. }
  24132. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24133. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24134. // keep-alive SSL session, which reads through that config in
  24135. // mbedtls_ssl_close_notify.
  24136. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24137. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24138. ASSERT_TRUE(svr.is_valid());
  24139. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24140. res.set_content("test", "text/plain");
  24141. });
  24142. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24143. auto se = detail::scope_exit([&] {
  24144. svr.stop();
  24145. t.join();
  24146. ASSERT_FALSE(svr.is_running());
  24147. });
  24148. svr.wait_until_ready();
  24149. {
  24150. SSLClient cli(HOST, PORT);
  24151. cli.enable_server_certificate_verification(false);
  24152. cli.set_keep_alive(true);
  24153. auto res = cli.Get("/test");
  24154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24155. ASSERT_EQ(StatusCode::OK_200, res->status);
  24156. // cli is destructed here with the keep-alive SSL session still open.
  24157. }
  24158. }
  24159. #endif
  24160. // WebSocket Tests
  24161. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24162. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24163. // defining the meaning of these bits has been negotiated.
  24164. auto make_frame = [](uint8_t first_byte) {
  24165. std::string frame;
  24166. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24167. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24168. frame += "Hello";
  24169. return frame;
  24170. };
  24171. // RSV1 set (0x40)
  24172. {
  24173. detail::BufferStream strm;
  24174. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24175. ws::Opcode opcode;
  24176. std::string payload;
  24177. bool fin;
  24178. EXPECT_EQ(
  24179. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24180. ws::impl::FrameRead::Fail);
  24181. }
  24182. // RSV2 set (0x20)
  24183. {
  24184. detail::BufferStream strm;
  24185. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24186. ws::Opcode opcode;
  24187. std::string payload;
  24188. bool fin;
  24189. EXPECT_EQ(
  24190. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24191. ws::impl::FrameRead::Fail);
  24192. }
  24193. // RSV3 set (0x10)
  24194. {
  24195. detail::BufferStream strm;
  24196. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24197. ws::Opcode opcode;
  24198. std::string payload;
  24199. bool fin;
  24200. EXPECT_EQ(
  24201. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24202. ws::impl::FrameRead::Fail);
  24203. }
  24204. // No RSV bits set - should succeed
  24205. {
  24206. detail::BufferStream strm;
  24207. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24208. ws::Opcode opcode;
  24209. std::string payload;
  24210. bool fin;
  24211. EXPECT_EQ(
  24212. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24213. ws::impl::FrameRead::Ok);
  24214. EXPECT_EQ(ws::Opcode::Text, opcode);
  24215. EXPECT_EQ("Hello", payload);
  24216. EXPECT_TRUE(fin);
  24217. }
  24218. }
  24219. TEST(WebSocketTest, ControlFrameValidation) {
  24220. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24221. // payload length <= 125.
  24222. // Ping with FIN=0 - must be rejected
  24223. {
  24224. detail::BufferStream strm;
  24225. std::string frame;
  24226. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24227. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24228. strm.write(frame.data(), frame.size());
  24229. ws::Opcode opcode;
  24230. std::string payload;
  24231. bool fin;
  24232. EXPECT_EQ(
  24233. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24234. ws::impl::FrameRead::Fail);
  24235. }
  24236. // Close with FIN=0 - must be rejected
  24237. {
  24238. detail::BufferStream strm;
  24239. std::string frame;
  24240. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24241. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24242. strm.write(frame.data(), frame.size());
  24243. ws::Opcode opcode;
  24244. std::string payload;
  24245. bool fin;
  24246. EXPECT_EQ(
  24247. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24248. ws::impl::FrameRead::Fail);
  24249. }
  24250. // Ping with payload_len=126 (extended length) - must be rejected
  24251. {
  24252. detail::BufferStream strm;
  24253. std::string frame;
  24254. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24255. frame += static_cast<char>(126); // payload_len=126 (>125)
  24256. frame += static_cast<char>(0x00); // extended length high byte
  24257. frame += static_cast<char>(126); // extended length low byte
  24258. frame += std::string(126, 'x');
  24259. strm.write(frame.data(), frame.size());
  24260. ws::Opcode opcode;
  24261. std::string payload;
  24262. bool fin;
  24263. EXPECT_EQ(
  24264. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24265. ws::impl::FrameRead::Fail);
  24266. }
  24267. // Ping with FIN=1 and payload_len=125 - should succeed
  24268. {
  24269. detail::BufferStream strm;
  24270. std::string frame;
  24271. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24272. frame += static_cast<char>(125); // payload_len=125
  24273. frame += std::string(125, 'x');
  24274. strm.write(frame.data(), frame.size());
  24275. ws::Opcode opcode;
  24276. std::string payload;
  24277. bool fin;
  24278. EXPECT_EQ(
  24279. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24280. ws::impl::FrameRead::Ok);
  24281. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24282. EXPECT_EQ(125u, payload.size());
  24283. EXPECT_TRUE(fin);
  24284. }
  24285. }
  24286. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24287. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24288. // length MUST be 0.
  24289. // MSB set - must be rejected
  24290. {
  24291. detail::BufferStream strm;
  24292. std::string frame;
  24293. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24294. frame += static_cast<char>(127); // 64-bit extended length
  24295. frame += static_cast<char>(0x80); // MSB set (invalid)
  24296. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24297. strm.write(frame.data(), frame.size());
  24298. ws::Opcode opcode;
  24299. std::string payload;
  24300. bool fin;
  24301. EXPECT_EQ(
  24302. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24303. ws::impl::FrameRead::Fail);
  24304. }
  24305. // MSB clear - should pass length parsing (will be rejected by max_len,
  24306. // but that's a different check; use a small length to verify)
  24307. {
  24308. detail::BufferStream strm;
  24309. std::string frame;
  24310. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24311. frame += static_cast<char>(127); // 64-bit extended length
  24312. frame += std::string(7, '\0'); // high bytes = 0
  24313. frame += static_cast<char>(0x03); // length = 3
  24314. frame += "abc";
  24315. strm.write(frame.data(), frame.size());
  24316. ws::Opcode opcode;
  24317. std::string payload;
  24318. bool fin;
  24319. EXPECT_EQ(
  24320. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24321. ws::impl::FrameRead::Ok);
  24322. EXPECT_EQ(ws::Opcode::Text, opcode);
  24323. EXPECT_EQ("abc", payload);
  24324. }
  24325. }
  24326. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24327. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24328. // Valid UTF-8
  24329. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24330. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24331. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24332. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24333. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24334. // Invalid UTF-8
  24335. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24336. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24337. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24338. EXPECT_FALSE(
  24339. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24340. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24341. }
  24342. TEST(WebSocketTest, ConnectAndDisconnect) {
  24343. Server svr;
  24344. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24345. std::string msg;
  24346. while (ws.read(msg)) {}
  24347. });
  24348. auto port = svr.bind_to_any_port(HOST);
  24349. std::thread t([&]() { svr.listen_after_bind(); });
  24350. svr.wait_until_ready();
  24351. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24352. auto res = client.connect();
  24353. ASSERT_TRUE(res);
  24354. EXPECT_EQ(Error::Success, res.error());
  24355. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24356. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24357. EXPECT_TRUE(client.is_open());
  24358. client.close();
  24359. EXPECT_FALSE(client.is_open());
  24360. svr.stop();
  24361. t.join();
  24362. }
  24363. TEST(WebSocketTest, ValidURL) {
  24364. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24365. EXPECT_TRUE(ws1.is_valid());
  24366. ws::WebSocketClient ws2("ws://example.com/path");
  24367. EXPECT_TRUE(ws2.is_valid());
  24368. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24369. EXPECT_TRUE(ws3.is_valid());
  24370. #ifdef CPPHTTPLIB_SSL_ENABLED
  24371. ws::WebSocketClient wss1("wss://example.com/path");
  24372. EXPECT_TRUE(wss1.is_valid());
  24373. ws::WebSocketClient wss2("wss://example.com:443/path");
  24374. EXPECT_TRUE(wss2.is_valid());
  24375. #endif
  24376. }
  24377. TEST(WebSocketTest, InvalidURL) {
  24378. // No scheme
  24379. ws::WebSocketClient ws1("localhost:8080/path");
  24380. EXPECT_FALSE(ws1.is_valid());
  24381. // No path
  24382. ws::WebSocketClient ws2("ws://localhost:8080");
  24383. EXPECT_FALSE(ws2.is_valid());
  24384. // Empty string
  24385. ws::WebSocketClient ws3("");
  24386. EXPECT_FALSE(ws3.is_valid());
  24387. // Missing host
  24388. ws::WebSocketClient ws4("ws://:8080/path");
  24389. EXPECT_FALSE(ws4.is_valid());
  24390. // Port number overflow — should not crash
  24391. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24392. EXPECT_FALSE(ws5.is_valid());
  24393. // Port out of range
  24394. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24395. EXPECT_FALSE(ws6.is_valid());
  24396. }
  24397. TEST(WebSocketTest, UnsupportedScheme) {
  24398. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24399. ws::WebSocketClient ws1("http://localhost:8080/path");
  24400. EXPECT_FALSE(ws1.is_valid());
  24401. ws::WebSocketClient ws2("https://localhost:8080/path");
  24402. EXPECT_FALSE(ws2.is_valid());
  24403. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24404. EXPECT_FALSE(ws3.is_valid());
  24405. #else
  24406. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24407. std::invalid_argument);
  24408. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24409. std::invalid_argument);
  24410. #endif
  24411. }
  24412. TEST(WebSocketTest, ConnectWhenInvalid) {
  24413. ws::WebSocketClient ws("not a valid url");
  24414. EXPECT_FALSE(ws.is_valid());
  24415. auto res = ws.connect();
  24416. EXPECT_FALSE(res);
  24417. EXPECT_EQ(Error::Connection, res.error());
  24418. EXPECT_EQ(-1, res.status());
  24419. }
  24420. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24421. // Grab a port that is free, then close it again so nothing listens there
  24422. Server svr;
  24423. auto port = svr.bind_to_any_port(HOST);
  24424. svr.stop();
  24425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24426. auto res = client.connect();
  24427. ASSERT_FALSE(res);
  24428. EXPECT_EQ(Error::Connection, res.error());
  24429. EXPECT_EQ(-1, res.status());
  24430. }
  24431. TEST(WebSocketTest, DefaultPort) {
  24432. ws::WebSocketClient ws1("ws://example.com/path");
  24433. EXPECT_TRUE(ws1.is_valid());
  24434. // ws:// defaults to port 80 (verified by successful parse)
  24435. #ifdef CPPHTTPLIB_SSL_ENABLED
  24436. ws::WebSocketClient ws2("wss://example.com/path");
  24437. EXPECT_TRUE(ws2.is_valid());
  24438. // wss:// defaults to port 443 (verified by successful parse)
  24439. #endif
  24440. }
  24441. TEST(WebSocketTest, IPv6LiteralAddress) {
  24442. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24443. EXPECT_TRUE(ws1.is_valid());
  24444. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24445. EXPECT_TRUE(ws2.is_valid());
  24446. }
  24447. TEST(WebSocketTest, ComplexPath) {
  24448. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24449. EXPECT_TRUE(ws1.is_valid());
  24450. ws::WebSocketClient ws2("ws://localhost:8080/");
  24451. EXPECT_TRUE(ws2.is_valid());
  24452. }
  24453. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24454. Server svr;
  24455. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24456. std::string msg;
  24457. while (ws.read(msg)) {}
  24458. });
  24459. auto port = svr.bind_to_any_port(HOST);
  24460. std::thread t([&]() { svr.listen_after_bind(); });
  24461. svr.wait_until_ready();
  24462. auto another_host = "example.com";
  24463. auto wrong_ip = "192.0.2.1";
  24464. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24465. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24466. ASSERT_TRUE(client.connect());
  24467. EXPECT_TRUE(client.is_open());
  24468. client.close();
  24469. svr.stop();
  24470. t.join();
  24471. }
  24472. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24473. Server svr;
  24474. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24475. std::string msg;
  24476. while (ws.read(msg)) {}
  24477. });
  24478. auto port = svr.bind_to_any_port(HOST);
  24479. std::thread t([&]() { svr.listen_after_bind(); });
  24480. svr.wait_until_ready();
  24481. auto wrong_ip = "192.0.2.1";
  24482. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24483. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24484. client.set_connection_timeout(1);
  24485. client.set_read_timeout(1);
  24486. client.set_write_timeout(1);
  24487. EXPECT_FALSE(client.connect());
  24488. EXPECT_FALSE(client.is_open());
  24489. svr.stop();
  24490. t.join();
  24491. }
  24492. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24493. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24494. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24495. // (RFC 6761) is only a map key and the Host header value.
  24496. auto host = "target.invalid";
  24497. Server svr;
  24498. std::string received_host;
  24499. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24500. received_host = req.get_header_value("Host");
  24501. std::string msg;
  24502. while (ws.read(msg)) {}
  24503. });
  24504. auto port = svr.bind_to_any_port(HOST);
  24505. std::thread t([&]() { svr.listen_after_bind(); });
  24506. // ASSERT_* below returns from the test body, which would leave t joinable
  24507. // and make ~thread call std::terminate.
  24508. auto se = detail::scope_exit([&] {
  24509. svr.stop();
  24510. if (t.joinable()) { t.join(); }
  24511. });
  24512. svr.wait_until_ready();
  24513. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24514. std::to_string(port) + "/ws");
  24515. client.set_direct_hostname_addr_map({{host, HOST}});
  24516. ASSERT_TRUE(client.connect());
  24517. EXPECT_TRUE(client.is_open());
  24518. client.close();
  24519. svr.stop();
  24520. t.join();
  24521. // The mapping only redirects the connection; the identity stays host_.
  24522. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24523. }
  24524. class WebSocketIntegrationTest : public ::testing::Test {
  24525. protected:
  24526. void SetUp() override {
  24527. server_ = httplib::detail::make_unique<Server>();
  24528. setup_server();
  24529. start_server();
  24530. }
  24531. void TearDown() override {
  24532. server_->stop();
  24533. if (server_thread_.joinable()) { server_thread_.join(); }
  24534. }
  24535. void setup_server() {
  24536. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24537. std::string msg;
  24538. ws::ReadResult ret;
  24539. while ((ret = ws.read(msg))) {
  24540. if (ret == ws::Binary) {
  24541. ws.send(msg.data(), msg.size());
  24542. } else {
  24543. ws.send(msg);
  24544. }
  24545. }
  24546. });
  24547. server_->WebSocket("/ws-echo-string",
  24548. [](const Request &, ws::WebSocket &ws) {
  24549. std::string msg;
  24550. while (ws.read(msg)) {
  24551. ws.send("echo: " + msg);
  24552. }
  24553. });
  24554. server_->WebSocket(
  24555. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24556. // Echo back request metadata
  24557. ws.send("path:" + req.path);
  24558. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24559. std::string msg;
  24560. while (ws.read(msg)) {}
  24561. });
  24562. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24563. std::string msg;
  24564. ws.read(msg); // wait for a message
  24565. ws.close();
  24566. });
  24567. server_->WebSocket("/ws-close-status",
  24568. [](const Request &, ws::WebSocket &ws) {
  24569. std::string msg;
  24570. ws.read(msg); // wait for a message
  24571. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24572. });
  24573. server_->WebSocket(
  24574. "/ws-subprotocol",
  24575. [](const Request &, ws::WebSocket &ws) {
  24576. std::string msg;
  24577. while (ws.read(msg)) {
  24578. ws.send(msg);
  24579. }
  24580. },
  24581. [](const std::vector<std::string> &protocols) -> std::string {
  24582. for (const auto &p : protocols) {
  24583. if (p == "graphql-ws") { return p; }
  24584. }
  24585. return "";
  24586. });
  24587. server_->WebSocket(
  24588. "/ws-subprotocol-unoffered",
  24589. [](const Request &, ws::WebSocket &ws) {
  24590. std::string msg;
  24591. while (ws.read(msg)) {
  24592. ws.send(msg);
  24593. }
  24594. },
  24595. [](const std::vector<std::string> &) -> std::string {
  24596. return "admin";
  24597. });
  24598. }
  24599. void start_server() {
  24600. port_ = server_->bind_to_any_port(HOST);
  24601. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24602. server_->wait_until_ready();
  24603. }
  24604. std::unique_ptr<Server> server_;
  24605. std::thread server_thread_;
  24606. int port_ = 0;
  24607. };
  24608. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24609. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24610. "/ws-echo");
  24611. ASSERT_TRUE(client.connect());
  24612. ASSERT_TRUE(client.is_open());
  24613. ASSERT_TRUE(client.send("Hello WebSocket"));
  24614. std::string msg;
  24615. EXPECT_EQ(ws::Text, client.read(msg));
  24616. EXPECT_EQ("Hello WebSocket", msg);
  24617. client.close();
  24618. }
  24619. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24620. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24621. "/ws-echo");
  24622. ASSERT_TRUE(client.connect());
  24623. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24624. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24625. std::string msg;
  24626. EXPECT_EQ(ws::Binary, client.read(msg));
  24627. EXPECT_EQ(binary_data, msg);
  24628. client.close();
  24629. }
  24630. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24631. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24632. "/ws-echo");
  24633. ASSERT_TRUE(client.connect());
  24634. for (int i = 0; i < 10; i++) {
  24635. auto text = "message " + std::to_string(i);
  24636. ASSERT_TRUE(client.send(text));
  24637. std::string msg;
  24638. ASSERT_TRUE(client.read(msg));
  24639. EXPECT_EQ(text, msg);
  24640. }
  24641. client.close();
  24642. }
  24643. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24644. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24645. "/ws-close");
  24646. ASSERT_TRUE(client.connect());
  24647. // Send a message to trigger the server to close
  24648. ASSERT_TRUE(client.send("trigger close"));
  24649. // The server will close, so read should return false
  24650. std::string msg;
  24651. EXPECT_FALSE(client.read(msg));
  24652. EXPECT_FALSE(client.is_open());
  24653. }
  24654. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24656. "/ws-echo");
  24657. ASSERT_TRUE(client.connect());
  24658. // 128KB message
  24659. std::string large_data(128 * 1024, 'X');
  24660. ASSERT_TRUE(client.send(large_data));
  24661. std::string msg;
  24662. ASSERT_TRUE(client.read(msg));
  24663. EXPECT_EQ(large_data, msg);
  24664. client.close();
  24665. }
  24666. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24668. "/ws-echo");
  24669. ASSERT_TRUE(client.connect());
  24670. const int num_threads = 4;
  24671. std::vector<std::thread> threads;
  24672. std::atomic<int> send_count{0};
  24673. for (int t = 0; t < num_threads; t++) {
  24674. threads.emplace_back([&client, &send_count, t]() {
  24675. for (int i = 0; i < 5; i++) {
  24676. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24677. if (client.send(text)) { send_count++; }
  24678. }
  24679. });
  24680. }
  24681. for (auto &th : threads) {
  24682. th.join();
  24683. }
  24684. int received = 0;
  24685. std::string msg;
  24686. while (received < send_count.load()) {
  24687. if (!client.read(msg)) { break; }
  24688. received++;
  24689. }
  24690. EXPECT_EQ(send_count.load(), received);
  24691. client.close();
  24692. }
  24693. TEST_F(WebSocketIntegrationTest, ReadString) {
  24694. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24695. "/ws-echo-string");
  24696. ASSERT_TRUE(client.connect());
  24697. ASSERT_TRUE(client.send("hello"));
  24698. std::string msg;
  24699. ASSERT_TRUE(client.read(msg));
  24700. EXPECT_EQ("echo: hello", msg);
  24701. ASSERT_TRUE(client.send("world"));
  24702. ASSERT_TRUE(client.read(msg));
  24703. EXPECT_EQ("echo: world", msg);
  24704. client.close();
  24705. }
  24706. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24707. Headers headers = {{"X-Test-Header", "test-value"}};
  24708. ws::WebSocketClient client(
  24709. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24710. ASSERT_TRUE(client.connect());
  24711. std::string msg;
  24712. ASSERT_TRUE(client.read(msg));
  24713. EXPECT_EQ("path:/ws-request-info", msg);
  24714. ASSERT_TRUE(client.read(msg));
  24715. EXPECT_EQ("header:test-value", msg);
  24716. client.close();
  24717. }
  24718. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24719. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24720. "/ws-echo");
  24721. client.set_read_timeout(1, 0); // 1 second
  24722. ASSERT_TRUE(client.connect());
  24723. // Don't send anything — server echo handler waits for a message, so read()
  24724. // should time out. The connection survives it: nothing was consumed.
  24725. std::string msg;
  24726. EXPECT_EQ(client.read(msg), ws::Timeout);
  24727. EXPECT_TRUE(client.is_open());
  24728. // And it is still usable afterwards.
  24729. EXPECT_TRUE(client.send("after timeout"));
  24730. EXPECT_EQ(client.read(msg), ws::Text);
  24731. EXPECT_EQ(msg, "after timeout");
  24732. }
  24733. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24734. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24735. "/ws-echo");
  24736. client.set_read_timeout(1, 0);
  24737. ASSERT_TRUE(client.connect());
  24738. ASSERT_TRUE(client.send("first"));
  24739. std::string msg;
  24740. ASSERT_EQ(client.read(msg), ws::Text);
  24741. ASSERT_EQ(msg, "first");
  24742. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24743. // not be used with a read timeout: it would reprocess the previous message.
  24744. EXPECT_EQ(client.read(msg), ws::Timeout);
  24745. EXPECT_EQ(msg, "first");
  24746. }
  24747. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24748. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24749. "/ws-echo");
  24750. ASSERT_TRUE(client.connect());
  24751. // Setting it once the connection is open reaches the live stream, not just
  24752. // the seed for the next connect().
  24753. client.set_read_timeout(1, 0);
  24754. std::string msg;
  24755. EXPECT_EQ(client.read(msg), ws::Timeout);
  24756. EXPECT_TRUE(client.is_open());
  24757. }
  24758. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24760. "/ws-echo");
  24761. client.set_read_timeout(5, 0);
  24762. ASSERT_TRUE(client.connect());
  24763. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24764. // The server should reject it and close the connection.
  24765. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24766. client.send(oversized);
  24767. // The server's read() should have failed due to payload limit,
  24768. // so our read() should return false (connection closed).
  24769. std::string msg;
  24770. EXPECT_FALSE(client.read(msg));
  24771. }
  24772. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24773. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24774. "/ws-echo");
  24775. client.set_read_timeout(10, 0);
  24776. ASSERT_TRUE(client.connect());
  24777. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24778. // This should succeed.
  24779. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24780. ASSERT_TRUE(client.send(at_limit));
  24781. std::string msg;
  24782. ASSERT_TRUE(client.read(msg));
  24783. EXPECT_EQ(at_limit.size(), msg.size());
  24784. client.close();
  24785. }
  24786. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24787. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24788. "/nonexistent");
  24789. auto res = client.connect();
  24790. EXPECT_FALSE(res);
  24791. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24792. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24793. EXPECT_FALSE(client.is_open());
  24794. }
  24795. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24796. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24797. "/ws-echo");
  24798. ASSERT_TRUE(client.connect());
  24799. ASSERT_TRUE(client.send(""));
  24800. std::string msg;
  24801. EXPECT_EQ(ws::Text, client.read(msg));
  24802. EXPECT_EQ("", msg);
  24803. client.close();
  24804. }
  24805. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24807. "/ws-echo");
  24808. // First connection
  24809. ASSERT_TRUE(client.connect());
  24810. ASSERT_TRUE(client.send("first"));
  24811. std::string msg;
  24812. ASSERT_TRUE(client.read(msg));
  24813. EXPECT_EQ("first", msg);
  24814. client.close();
  24815. EXPECT_FALSE(client.is_open());
  24816. // Reconnect using the same client object
  24817. ASSERT_TRUE(client.connect());
  24818. ASSERT_TRUE(client.is_open());
  24819. ASSERT_TRUE(client.send("second"));
  24820. ASSERT_TRUE(client.read(msg));
  24821. EXPECT_EQ("second", msg);
  24822. client.close();
  24823. }
  24824. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24825. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24826. "/ws-close-status");
  24827. ASSERT_TRUE(client.connect());
  24828. // Trigger the server to close with GoingAway status
  24829. ASSERT_TRUE(client.send("trigger"));
  24830. // read() should return false after receiving the close frame
  24831. std::string msg;
  24832. EXPECT_FALSE(client.read(msg));
  24833. EXPECT_FALSE(client.is_open());
  24834. }
  24835. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24836. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24837. "/ws-echo");
  24838. ASSERT_TRUE(client.connect());
  24839. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24840. EXPECT_FALSE(client.is_open());
  24841. }
  24842. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24843. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24844. ws::WebSocketClient client(
  24845. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24846. ASSERT_TRUE(client.connect());
  24847. // Server should have selected graphql-ws
  24848. EXPECT_EQ("graphql-ws", client.subprotocol());
  24849. client.close();
  24850. }
  24851. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24852. Headers headers;
  24853. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24854. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24855. ws::WebSocketClient client(
  24856. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24857. ASSERT_TRUE(client.connect());
  24858. // The offer on the second field line counts too, so graphql-ws is selected
  24859. EXPECT_EQ("graphql-ws", client.subprotocol());
  24860. client.close();
  24861. }
  24862. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24863. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24864. ws::WebSocketClient client(
  24865. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24866. ASSERT_TRUE(client.connect());
  24867. // Server should not have selected any subprotocol
  24868. EXPECT_TRUE(client.subprotocol().empty());
  24869. client.close();
  24870. }
  24871. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24872. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24873. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24874. "/ws-subprotocol-unoffered",
  24875. headers);
  24876. ASSERT_TRUE(client.connect());
  24877. EXPECT_TRUE(client.subprotocol().empty());
  24878. client.close();
  24879. }
  24880. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24881. // Connect without requesting any subprotocol
  24882. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24883. "/ws-subprotocol");
  24884. ASSERT_TRUE(client.connect());
  24885. EXPECT_TRUE(client.subprotocol().empty());
  24886. client.close();
  24887. }
  24888. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24889. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24890. "/ws-echo");
  24891. client.set_tcp_nodelay(true);
  24892. client.set_connection_timeout(3, 0);
  24893. bool socket_options_called = false;
  24894. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24895. ASSERT_TRUE(client.connect());
  24896. ASSERT_TRUE(client.is_open());
  24897. EXPECT_TRUE(socket_options_called);
  24898. ASSERT_TRUE(client.send("hello"));
  24899. std::string msg;
  24900. auto result = client.read(msg);
  24901. EXPECT_EQ(result, ws::ReadResult::Text);
  24902. EXPECT_EQ(msg, "hello");
  24903. client.close();
  24904. }
  24905. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24906. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24907. "/ws-echo");
  24908. client.set_connection_timeout(std::chrono::seconds(3));
  24909. client.set_write_timeout(std::chrono::seconds(3));
  24910. // A sub-second remainder exercises the seconds/microseconds split.
  24911. client.set_read_timeout(std::chrono::milliseconds(1500));
  24912. ASSERT_TRUE(client.connect());
  24913. auto start = std::chrono::steady_clock::now();
  24914. std::string msg;
  24915. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24916. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24917. std::chrono::steady_clock::now() - start)
  24918. .count();
  24919. // Above 1s so that dropping the microseconds half of the split fails here.
  24920. // Ignoring the setter altogether would not reach this line at all: a client
  24921. // waits forever by default.
  24922. EXPECT_GE(elapsed, 1400);
  24923. EXPECT_LT(elapsed, 30000);
  24924. }
  24925. #ifndef _WIN32
  24926. // A send() that times out after part of the data went out returns the count
  24927. // written so far. Every byte of the frame must still be sent, or the peer reads
  24928. // the next frame's header and payload as the rest of this one.
  24929. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24930. signal(SIGPIPE, SIG_IGN);
  24931. const std::string large(4 * 1024 * 1024, 'A');
  24932. std::atomic<bool> large_sent{false};
  24933. std::atomic<bool> small_sent{false};
  24934. Server svr;
  24935. svr.set_write_timeout(0, 500000);
  24936. svr.set_socket_options([](socket_t sock) {
  24937. int size = 8192;
  24938. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24939. reinterpret_cast<const char *>(&size), sizeof(size));
  24940. });
  24941. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24942. large_sent = ws.send(large.data(), large.size());
  24943. small_sent = ws.send("after");
  24944. std::string msg;
  24945. while (ws.read(msg)) {}
  24946. });
  24947. auto port = svr.bind_to_any_port(HOST);
  24948. std::thread t([&]() { svr.listen_after_bind(); });
  24949. auto se = detail::scope_exit([&] {
  24950. svr.stop();
  24951. t.join();
  24952. });
  24953. svr.wait_until_ready();
  24954. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24955. std::to_string(port) + "/ws");
  24956. client.set_read_timeout(5);
  24957. client.set_socket_options([](socket_t sock) {
  24958. int size = 8192;
  24959. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24960. reinterpret_cast<const char *>(&size), sizeof(size));
  24961. });
  24962. ASSERT_TRUE(client.connect());
  24963. // Outlast the server's write timeout, then drain.
  24964. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24965. std::string msg;
  24966. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24967. EXPECT_TRUE(msg == large);
  24968. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24969. EXPECT_EQ("after", msg);
  24970. EXPECT_TRUE(large_sent);
  24971. EXPECT_TRUE(small_sent);
  24972. client.close();
  24973. }
  24974. #endif
  24975. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24976. Server svr;
  24977. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24978. if (!req.has_header("Authorization")) {
  24979. res.status = StatusCode::Unauthorized_401;
  24980. res.set_content("Unauthorized", "text/plain");
  24981. return Server::HandlerResponse::Handled;
  24982. }
  24983. return Server::HandlerResponse::Unhandled;
  24984. });
  24985. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24986. std::string msg;
  24987. while (ws.read(msg)) {
  24988. ws.send(msg);
  24989. }
  24990. });
  24991. auto port = svr.bind_to_any_port("localhost");
  24992. std::thread t([&]() { svr.listen_after_bind(); });
  24993. svr.wait_until_ready();
  24994. // Without Authorization header - should be rejected before upgrade
  24995. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24996. EXPECT_FALSE(client1.connect());
  24997. // The rejection is framed like any other HTTP response
  24998. {
  24999. Client cli("localhost", port);
  25000. Headers headers = {{"Upgrade", "websocket"},
  25001. {"Connection", "Upgrade"},
  25002. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25003. {"Sec-WebSocket-Version", "13"}};
  25004. auto res = cli.Get("/ws", headers);
  25005. ASSERT_TRUE(res);
  25006. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25007. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25008. EXPECT_EQ("Unauthorized", res->body);
  25009. }
  25010. // With Authorization header - should succeed
  25011. Headers headers = {{"Authorization", "Bearer token123"}};
  25012. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25013. headers);
  25014. ASSERT_TRUE(client2.connect());
  25015. ASSERT_TRUE(client2.send("hello"));
  25016. std::string msg;
  25017. ASSERT_TRUE(client2.read(msg));
  25018. EXPECT_EQ("hello", msg);
  25019. client2.close();
  25020. svr.stop();
  25021. t.join();
  25022. }
  25023. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25024. Server svr;
  25025. std::atomic<int> pre_routing_calls{0};
  25026. std::atomic<int> pre_request_calls{0};
  25027. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25028. pre_routing_calls++;
  25029. if (req.path == "/handled") {
  25030. res.set_content("handled", "text/plain");
  25031. return Server::HandlerResponse::Handled;
  25032. }
  25033. return Server::HandlerResponse::Unhandled;
  25034. });
  25035. svr.set_pre_request_handler([&](const Request &, Response &) {
  25036. pre_request_calls++;
  25037. return Server::HandlerResponse::Unhandled;
  25038. });
  25039. svr.Get("/http", [](const Request &, Response &res) {
  25040. res.set_content("http", "text/plain");
  25041. });
  25042. svr.WebSocket("/ws",
  25043. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25044. auto port = svr.bind_to_any_port("localhost");
  25045. std::thread t([&]() { svr.listen_after_bind(); });
  25046. auto se = detail::scope_exit([&] {
  25047. svr.stop();
  25048. t.join();
  25049. });
  25050. svr.wait_until_ready();
  25051. Headers upgrade = {{"Upgrade", "websocket"},
  25052. {"Connection", "Upgrade"},
  25053. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25054. {"Sec-WebSocket-Version", "13"}};
  25055. auto get = [&](const char *path) {
  25056. pre_routing_calls = 0;
  25057. return Client("localhost", port).Get(path, upgrade);
  25058. };
  25059. // No WebSocket route, but an HTTP one
  25060. auto res = get("/http");
  25061. ASSERT_TRUE(res);
  25062. EXPECT_EQ(StatusCode::OK_200, res->status);
  25063. EXPECT_EQ("http", res->body);
  25064. EXPECT_EQ(1, pre_routing_calls);
  25065. EXPECT_EQ(1, pre_request_calls);
  25066. // No route at all
  25067. res = get("/none");
  25068. ASSERT_TRUE(res);
  25069. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25070. EXPECT_EQ(1, pre_routing_calls);
  25071. // Answered by the pre-routing handler
  25072. res = get("/handled");
  25073. ASSERT_TRUE(res);
  25074. EXPECT_EQ(StatusCode::OK_200, res->status);
  25075. EXPECT_EQ("handled", res->body);
  25076. EXPECT_EQ(1, pre_routing_calls);
  25077. // A WebSocket route
  25078. pre_routing_calls = 0;
  25079. pre_request_calls = 0;
  25080. {
  25081. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25082. "/ws");
  25083. ASSERT_TRUE(client.connect());
  25084. std::string msg;
  25085. ASSERT_TRUE(client.read(msg));
  25086. EXPECT_EQ("ws", msg);
  25087. client.close();
  25088. }
  25089. EXPECT_EQ(1, pre_routing_calls);
  25090. EXPECT_EQ(1, pre_request_calls);
  25091. }
  25092. // An upgrade request answered by a hook leaves its body unread, so that body
  25093. // must not be served as the next request on the connection.
  25094. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25095. Server svr;
  25096. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25097. if (req.path == "/pre-routing") {
  25098. res.set_content("pre-routing", "text/plain");
  25099. return Server::HandlerResponse::Handled;
  25100. }
  25101. return Server::HandlerResponse::Unhandled;
  25102. });
  25103. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25104. if (req.matched_route == "/pre-request") {
  25105. res.set_content("pre-request", "text/plain");
  25106. return Server::HandlerResponse::Handled;
  25107. }
  25108. return Server::HandlerResponse::Unhandled;
  25109. });
  25110. svr.Get("/smuggled", [](const Request &, Response &res) {
  25111. res.set_content("smuggled", "text/plain");
  25112. });
  25113. svr.WebSocket("/pre-request",
  25114. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25115. auto port = svr.bind_to_any_port(HOST);
  25116. std::thread t([&]() { svr.listen_after_bind(); });
  25117. auto se = detail::scope_exit([&] {
  25118. svr.stop();
  25119. t.join();
  25120. });
  25121. svr.wait_until_ready();
  25122. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25123. for (auto path : {"/pre-routing", "/pre-request"}) {
  25124. std::string req = std::string("GET ") + path +
  25125. " HTTP/1.1\r\n"
  25126. "Host: localhost\r\n"
  25127. "Upgrade: websocket\r\n"
  25128. "Connection: Upgrade\r\n"
  25129. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25130. "Sec-WebSocket-Version: 13\r\n"
  25131. "Content-Length: " +
  25132. std::to_string(body.size()) + "\r\n\r\n" + body;
  25133. std::string res;
  25134. ASSERT_TRUE(send_request(5, req, &res, port));
  25135. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25136. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25137. // Only one response, and the body was not served as a request
  25138. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25139. }
  25140. }
  25141. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25142. Server svr;
  25143. std::atomic<int> pre_request_calls{0};
  25144. std::atomic<bool> route_matched{false};
  25145. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25146. pre_request_calls++;
  25147. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25148. if (req.get_header_value("Authorization") != "Bearer token123") {
  25149. res.status = StatusCode::Unauthorized_401;
  25150. res.set_content("Unauthorized", "text/plain");
  25151. return Server::HandlerResponse::Handled;
  25152. }
  25153. return Server::HandlerResponse::Unhandled;
  25154. });
  25155. std::atomic<bool> handler_called{false};
  25156. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25157. handler_called = true;
  25158. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25159. });
  25160. auto port = svr.bind_to_any_port("localhost");
  25161. std::thread t([&]() { svr.listen_after_bind(); });
  25162. svr.wait_until_ready();
  25163. // Without Authorization header - should be rejected before upgrade
  25164. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25165. "/ws/1");
  25166. EXPECT_FALSE(client1.connect());
  25167. EXPECT_FALSE(handler_called);
  25168. EXPECT_EQ(1, pre_request_calls);
  25169. EXPECT_TRUE(route_matched);
  25170. // The rejection is an ordinary HTTP response, not a protocol switch
  25171. {
  25172. Client cli("localhost", port);
  25173. Headers headers = {{"Upgrade", "websocket"},
  25174. {"Connection", "Upgrade"},
  25175. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25176. {"Sec-WebSocket-Version", "13"}};
  25177. auto res = cli.Get("/ws/1", headers);
  25178. ASSERT_TRUE(res);
  25179. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25180. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25181. EXPECT_EQ("Unauthorized", res->body);
  25182. }
  25183. EXPECT_FALSE(handler_called);
  25184. // With Authorization header - should succeed
  25185. Headers headers = {{"Authorization", "Bearer token123"}};
  25186. ws::WebSocketClient client2(
  25187. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25188. ASSERT_TRUE(client2.connect());
  25189. std::string msg;
  25190. ASSERT_TRUE(client2.read(msg));
  25191. EXPECT_EQ("/ws/:id 2", msg);
  25192. EXPECT_TRUE(handler_called);
  25193. client2.close();
  25194. svr.stop();
  25195. t.join();
  25196. }
  25197. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25198. static Headers websocket_upgrade_headers() {
  25199. return {{"Upgrade", "websocket"},
  25200. {"Connection", "Upgrade"},
  25201. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25202. {"Sec-WebSocket-Version", "13"},
  25203. {"Sec-WebSocket-Protocol", "chat"}};
  25204. }
  25205. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25206. Server svr;
  25207. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25208. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25209. return Server::HandlerResponse::Unhandled;
  25210. });
  25211. svr.set_pre_request_handler([](const Request &req, Response &) {
  25212. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25213. return Server::HandlerResponse::Unhandled;
  25214. });
  25215. svr.set_exception_handler(
  25216. [](const Request &, Response &res, std::exception_ptr ep) {
  25217. try {
  25218. std::rethrow_exception(ep);
  25219. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25220. });
  25221. auto handler = [](const Request &, ws::WebSocket &) {};
  25222. svr.WebSocket("/pre-routing", handler);
  25223. svr.WebSocket("/pre-request", handler);
  25224. svr.WebSocket("/sub-protocol", handler,
  25225. [](const std::vector<std::string> &) -> std::string {
  25226. throw std::runtime_error("/sub-protocol");
  25227. });
  25228. auto port = svr.bind_to_any_port(HOST);
  25229. ASSERT_GT(port, 0);
  25230. thread t = thread([&] { svr.listen_after_bind(); });
  25231. auto se = detail::scope_exit([&] {
  25232. svr.stop();
  25233. t.join();
  25234. ASSERT_FALSE(svr.is_running());
  25235. });
  25236. svr.wait_until_ready();
  25237. Client cli(HOST, port);
  25238. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25239. auto res = cli.Get(path, websocket_upgrade_headers());
  25240. if (!res) {
  25241. ADD_FAILURE() << path << ": " << to_string(res.error());
  25242. continue;
  25243. }
  25244. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25245. EXPECT_EQ(path, res->body);
  25246. }
  25247. }
  25248. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25249. Server svr;
  25250. svr.set_pre_routing_handler(
  25251. [](const Request &, Response &) -> Server::HandlerResponse {
  25252. throw std::runtime_error("pre-routing");
  25253. });
  25254. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25255. auto port = svr.bind_to_any_port(HOST);
  25256. ASSERT_GT(port, 0);
  25257. thread t = thread([&] { svr.listen_after_bind(); });
  25258. auto se = detail::scope_exit([&] {
  25259. svr.stop();
  25260. t.join();
  25261. ASSERT_FALSE(svr.is_running());
  25262. });
  25263. svr.wait_until_ready();
  25264. Client cli(HOST, port);
  25265. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25266. ASSERT_TRUE(res) << to_string(res.error());
  25267. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25268. }
  25269. #endif
  25270. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25271. Server svr;
  25272. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25273. // A read timeout is how a handler gets control back. Without it, a handler
  25274. // parked in read() can never write on the connection it is reading.
  25275. ws.set_read_timeout(std::chrono::milliseconds(100));
  25276. std::string msg;
  25277. while (ws.is_open()) {
  25278. auto r = ws.read(msg);
  25279. if (r == httplib::ws::Timeout) {
  25280. ws.send("tick");
  25281. continue;
  25282. }
  25283. if (r == httplib::ws::Fail) { break; }
  25284. ws.send(msg);
  25285. }
  25286. });
  25287. auto port = svr.bind_to_any_port("localhost");
  25288. std::thread t([&]() { svr.listen_after_bind(); });
  25289. svr.wait_until_ready();
  25290. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25291. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25292. ASSERT_TRUE(client.connect());
  25293. // The client sends nothing, so anything it receives came out of the
  25294. // handler's timeout path.
  25295. std::string msg;
  25296. ASSERT_EQ(client.read(msg), ws::Text);
  25297. EXPECT_EQ("tick", msg);
  25298. client.close();
  25299. svr.stop();
  25300. t.join();
  25301. }
  25302. // Stream::read may return fewer bytes than asked for. This is that contract at
  25303. // its worst -- one byte per call -- which is what a frame header straddling a
  25304. // read buffer's boundary looks like to the frame parser.
  25305. class WsByteAtATimeStream : public Stream {
  25306. public:
  25307. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25308. bool is_readable() const override { return true; }
  25309. bool wait_readable() const override { return true; }
  25310. bool wait_writable() const override { return true; }
  25311. ssize_t read(char *ptr, size_t size) override {
  25312. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25313. *ptr = data_[pos_++];
  25314. return 1;
  25315. }
  25316. ssize_t write(const char *, size_t size) override {
  25317. return static_cast<ssize_t>(size);
  25318. }
  25319. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25320. ip = "127.0.0.1";
  25321. port = 0;
  25322. }
  25323. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25324. ip = "127.0.0.1";
  25325. port = 0;
  25326. }
  25327. socket_t socket() const override { return INVALID_SOCKET; }
  25328. time_t duration() const override { return 0; }
  25329. private:
  25330. std::string data_;
  25331. size_t pos_ = 0;
  25332. };
  25333. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25334. // The payload uses the 16-bit extended length, so the header, the length
  25335. // and the mask key are all multi-byte fields here. Each used to be read
  25336. // with a single read() call, which fails as soon as one is split. The
  25337. // payload is also a little over one read chunk, so it is read in two.
  25338. std::string body;
  25339. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25340. body += static_cast<char>(i % 251);
  25341. }
  25342. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25343. std::string frame;
  25344. frame += static_cast<char>(0x81); // FIN + Text
  25345. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25346. frame += static_cast<char>(body.size() >> 8);
  25347. frame += static_cast<char>(body.size() & 0xff);
  25348. for (size_t i = 0; i < 4; i++) {
  25349. frame += static_cast<char>(mask[i]);
  25350. }
  25351. for (size_t i = 0; i < body.size(); i++) {
  25352. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25353. }
  25354. WsByteAtATimeStream strm(frame);
  25355. ws::Opcode opcode;
  25356. std::string payload;
  25357. bool fin = false;
  25358. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25359. /*expect_masked=*/true, body.size()),
  25360. ws::impl::FrameRead::Ok);
  25361. EXPECT_TRUE(fin);
  25362. EXPECT_EQ(opcode, ws::Opcode::Text);
  25363. EXPECT_EQ(payload, body);
  25364. }
  25365. // Keeps what is written, counting the writes, and reads it back.
  25366. class WsWriteCountingStream : public Stream {
  25367. public:
  25368. bool is_readable() const override { return true; }
  25369. bool wait_readable() const override { return true; }
  25370. bool wait_writable() const override { return true; }
  25371. ssize_t read(char *ptr, size_t size) override {
  25372. auto n = (std::min)(size, data_.size() - pos_);
  25373. if (n == 0) { return 0; }
  25374. memcpy(ptr, data_.data() + pos_, n);
  25375. pos_ += n;
  25376. return static_cast<ssize_t>(n);
  25377. }
  25378. ssize_t write(const char *ptr, size_t size) override {
  25379. writes++;
  25380. data_.append(ptr, size);
  25381. return static_cast<ssize_t>(size);
  25382. }
  25383. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25384. ip = "127.0.0.1";
  25385. port = 0;
  25386. }
  25387. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25388. ip = "127.0.0.1";
  25389. port = 0;
  25390. }
  25391. socket_t socket() const override { return INVALID_SOCKET; }
  25392. time_t duration() const override { return 0; }
  25393. int writes = 0;
  25394. private:
  25395. std::string data_;
  25396. size_t pos_ = 0;
  25397. };
  25398. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25399. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25400. // masked and not, reads back as written; a payload over one chunk follows
  25401. // its first in more writes.
  25402. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25403. for (auto mask : {false, true}) {
  25404. std::string body(len, '\0');
  25405. for (size_t i = 0; i < len; i++) {
  25406. body[i] = static_cast<char>(i % 251);
  25407. }
  25408. WsWriteCountingStream strm;
  25409. ASSERT_TRUE(detail::write_websocket_frame(
  25410. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25411. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25412. ws::Opcode opcode;
  25413. std::string payload;
  25414. bool fin = false;
  25415. ASSERT_EQ(
  25416. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25417. ws::impl::FrameRead::Ok)
  25418. << len << " " << mask;
  25419. EXPECT_TRUE(fin);
  25420. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25421. EXPECT_EQ(body, payload) << len << " " << mask;
  25422. }
  25423. }
  25424. }
  25425. // Hands out its pieces one read at a time, timing out between each two.
  25426. class WsTimeoutBetweenPiecesStream : public Stream {
  25427. public:
  25428. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25429. : pieces_(std::move(pieces)) {}
  25430. bool is_readable() const override { return true; }
  25431. bool wait_readable() const override { return true; }
  25432. bool wait_writable() const override { return true; }
  25433. ssize_t read(char *ptr, size_t size) override {
  25434. if (time_out_) {
  25435. time_out_ = false;
  25436. error_ = Error::Timeout;
  25437. return -1;
  25438. }
  25439. if (i_ >= pieces_.size()) {
  25440. error_ = Error::ConnectionClosed;
  25441. return 0;
  25442. }
  25443. auto &piece = pieces_[i_];
  25444. auto n = (std::min)(size, piece.size() - at_);
  25445. memcpy(ptr, piece.data() + at_, n);
  25446. at_ += n;
  25447. if (at_ == piece.size()) {
  25448. i_++;
  25449. at_ = 0;
  25450. time_out_ = true;
  25451. }
  25452. return static_cast<ssize_t>(n);
  25453. }
  25454. ssize_t write(const char *, size_t size) override {
  25455. return static_cast<ssize_t>(size);
  25456. }
  25457. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25458. ip = "127.0.0.1";
  25459. port = 0;
  25460. }
  25461. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25462. ip = "127.0.0.1";
  25463. port = 0;
  25464. }
  25465. socket_t socket() const override { return INVALID_SOCKET; }
  25466. time_t duration() const override { return 0; }
  25467. private:
  25468. std::vector<std::string> pieces_;
  25469. size_t i_ = 0;
  25470. size_t at_ = 0;
  25471. bool time_out_ = false;
  25472. };
  25473. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25474. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25475. std::string frame = "\x81\x85";
  25476. frame.append(4, '\0');
  25477. frame += "Hello";
  25478. // The header's first byte, then its second with half the mask key, then
  25479. // the rest
  25480. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25481. frame.substr(4)};
  25482. WsTimeoutBetweenPiecesStream strm(pieces);
  25483. ws::impl::FrameReader reader;
  25484. ws::Opcode opcode;
  25485. std::string payload;
  25486. bool fin = false;
  25487. for (int i = 0; i < 2; i++) {
  25488. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25489. reader.read(strm, opcode, payload, fin, true, 0));
  25490. EXPECT_TRUE(reader.begun());
  25491. }
  25492. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25493. reader.read(strm, opcode, payload, fin, true, 0));
  25494. EXPECT_FALSE(reader.begun());
  25495. EXPECT_TRUE(fin);
  25496. EXPECT_EQ(ws::Opcode::Text, opcode);
  25497. EXPECT_EQ("Hello", payload);
  25498. // Read in one go, the frame cannot be gone on with after a timeout
  25499. WsTimeoutBetweenPiecesStream again(pieces);
  25500. EXPECT_EQ(
  25501. ws::impl::FrameRead::Fail,
  25502. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25503. }
  25504. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25505. std::string body(2000, 'x');
  25506. std::string frame;
  25507. frame += static_cast<char>(0x82); // FIN + Binary
  25508. frame += static_cast<char>(126); // 16-bit length follows
  25509. frame += static_cast<char>(body.size() >> 8);
  25510. frame += static_cast<char>(body.size() & 0xff);
  25511. frame += body;
  25512. detail::BufferStream strm;
  25513. strm.write(frame.data(), frame.size());
  25514. ws::Opcode opcode;
  25515. std::string payload;
  25516. bool fin;
  25517. EXPECT_EQ(
  25518. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25519. ws::impl::FrameRead::Ok);
  25520. EXPECT_EQ(body, payload);
  25521. }
  25522. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25523. // The header announces the largest payload allowed, and only 3 bytes of it
  25524. // ever arrive.
  25525. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25526. std::string frame;
  25527. frame += static_cast<char>(0x82); // FIN + Binary
  25528. frame += static_cast<char>(127); // 64-bit length follows
  25529. for (int shift = 56; shift >= 0; shift -= 8) {
  25530. frame += static_cast<char>((len >> shift) & 0xff);
  25531. }
  25532. frame += "abc";
  25533. detail::BufferStream strm;
  25534. strm.write(frame.data(), frame.size());
  25535. ws::Opcode opcode;
  25536. std::string payload;
  25537. bool fin;
  25538. EXPECT_EQ(
  25539. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25540. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25541. ws::impl::FrameRead::Fail);
  25542. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25543. }
  25544. TEST(WebSocketTest, QueryStringInHandshake) {
  25545. Server svr;
  25546. std::mutex mtx;
  25547. std::string received_target;
  25548. std::string received_token;
  25549. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25550. {
  25551. std::lock_guard<std::mutex> lock(mtx);
  25552. received_target = req.target;
  25553. if (req.has_param("token")) {
  25554. received_token = req.get_param_value("token");
  25555. }
  25556. }
  25557. std::string msg;
  25558. while (ws.read(msg)) {
  25559. ws.send(msg);
  25560. }
  25561. });
  25562. auto port = svr.bind_to_any_port("localhost");
  25563. std::thread t([&]() { svr.listen_after_bind(); });
  25564. svr.wait_until_ready();
  25565. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25566. "/ws?token=ABC&session=123");
  25567. ASSERT_TRUE(client.connect());
  25568. // Round-trip ensures the handler has run and captured the request.
  25569. ASSERT_TRUE(client.send("hello"));
  25570. std::string msg;
  25571. ASSERT_TRUE(client.read(msg));
  25572. EXPECT_EQ("hello", msg);
  25573. client.close();
  25574. {
  25575. std::lock_guard<std::mutex> lock(mtx);
  25576. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25577. EXPECT_EQ("ABC", received_token);
  25578. }
  25579. svr.stop();
  25580. t.join();
  25581. }
  25582. // Run a handshake against a throwaway server and hand the request the server
  25583. // received back to the caller, so tests can assert on the headers the client
  25584. // actually put on the wire.
  25585. static void capture_websocket_handshake_request(
  25586. const Headers &client_headers,
  25587. std::function<void(const Request &, int port)> verify) {
  25588. Server svr;
  25589. std::mutex mtx;
  25590. Request received;
  25591. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25592. {
  25593. std::lock_guard<std::mutex> lock(mtx);
  25594. received = req;
  25595. }
  25596. std::string msg;
  25597. while (ws.read(msg)) {
  25598. ws.send(msg);
  25599. }
  25600. });
  25601. auto port = svr.bind_to_any_port("localhost");
  25602. std::thread t([&]() { svr.listen_after_bind(); });
  25603. auto se = detail::scope_exit([&] {
  25604. svr.stop();
  25605. t.join();
  25606. });
  25607. svr.wait_until_ready();
  25608. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25609. client_headers);
  25610. ASSERT_TRUE(client.connect());
  25611. ASSERT_TRUE(client.send("hello"));
  25612. std::string msg;
  25613. ASSERT_TRUE(client.read(msg));
  25614. client.close();
  25615. {
  25616. std::lock_guard<std::mutex> lock(mtx);
  25617. verify(received, port);
  25618. }
  25619. }
  25620. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25621. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25622. // Non-default port must be present in the Host header. Default ports
  25623. // (80/443) are omitted; that logic is covered by
  25624. // MakeHostAndPortStringTest.
  25625. EXPECT_EQ("localhost:" + std::to_string(port),
  25626. req.get_header_value("Host"));
  25627. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25628. req.get_header_value("User-Agent"));
  25629. EXPECT_FALSE(req.has_header("Accept"));
  25630. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25631. EXPECT_FALSE(req.has_header("Content-Length"));
  25632. });
  25633. }
  25634. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25635. capture_websocket_handshake_request(
  25636. {{"Host", "example.com"},
  25637. {"User-Agent", "custom-agent"},
  25638. {"X-Custom", "value"}},
  25639. [](const Request &req, int) {
  25640. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25641. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25642. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25643. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25644. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25645. });
  25646. }
  25647. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25648. capture_websocket_handshake_request(
  25649. {{"Upgrade", "bogus"},
  25650. {"Connection", "close"},
  25651. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25652. {"Sec-WebSocket-Version", "8"}},
  25653. [](const Request &req, int) {
  25654. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25655. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25656. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25657. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25658. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25659. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25660. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25661. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25662. req.get_header_value("Sec-WebSocket-Key"));
  25663. });
  25664. }
  25665. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25666. // A header the client refuses to send must abort the handshake before any
  25667. // part of it reaches the wire; a lone request line would otherwise sit in
  25668. // the peer's buffer as a truncated request.
  25669. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25670. ASSERT_NE(INVALID_SOCKET, srv);
  25671. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25672. sockaddr_in addr{};
  25673. addr.sin_family = AF_INET;
  25674. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25675. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25676. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25677. ASSERT_EQ(0, ::listen(srv, 1));
  25678. sockaddr_in bound{};
  25679. socklen_t bound_len = sizeof(bound);
  25680. ASSERT_EQ(
  25681. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25682. auto port = ntohs(bound.sin_port);
  25683. ssize_t received = -1;
  25684. std::thread t([&] {
  25685. // Bound every blocking call so a regression fails the test with a bad
  25686. // value instead of hanging the suite.
  25687. fd_set rfds;
  25688. FD_ZERO(&rfds);
  25689. FD_SET(srv, &rfds);
  25690. timeval tv{5, 0};
  25691. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25692. 0) {
  25693. return;
  25694. }
  25695. sockaddr_in cli_addr{};
  25696. socklen_t cli_len = sizeof(cli_addr);
  25697. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25698. if (cli == INVALID_SOCKET) { return; }
  25699. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25700. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25701. char buf[4096];
  25702. received = ::recv(cli, buf, sizeof(buf), 0);
  25703. });
  25704. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25705. // connect() has already shut the socket down by the time it returns false,
  25706. // so the peer sees EOF without waiting for the client to be destroyed.
  25707. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25708. {{"X-Bad", "a\r\nInjected: 1"}});
  25709. EXPECT_FALSE(client.connect());
  25710. t.join();
  25711. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25712. EXPECT_EQ(0, received);
  25713. }
  25714. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25715. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25716. // contains "upgrade" as a substring is a different token and must not
  25717. // start a WebSocket handshake.
  25718. auto make_request = [](const std::vector<std::string> &connection_values) {
  25719. Request req;
  25720. req.method = "GET";
  25721. req.headers.emplace("Upgrade", "websocket");
  25722. for (const auto &value : connection_values) {
  25723. req.headers.emplace("Connection", value);
  25724. }
  25725. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25726. req.headers.emplace("Sec-WebSocket-Version", "13");
  25727. return req;
  25728. };
  25729. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25730. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25731. EXPECT_TRUE(
  25732. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25733. EXPECT_TRUE(
  25734. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25735. EXPECT_TRUE(
  25736. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25737. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25738. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25739. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25740. EXPECT_FALSE(
  25741. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25742. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25743. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25744. }
  25745. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25746. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25747. // asks recipients to match each protocol-name case-insensitively, and RFC
  25748. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25749. // client naming websocket alongside another protocol, or on a second field
  25750. // line, is offering websocket; a value that merely contains "websocket" as a
  25751. // substring is a different protocol name and is not.
  25752. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25753. Request req;
  25754. req.method = "GET";
  25755. for (const auto &value : upgrade_values) {
  25756. req.headers.emplace("Upgrade", value);
  25757. }
  25758. req.headers.emplace("Connection", "Upgrade");
  25759. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25760. req.headers.emplace("Sec-WebSocket-Version", "13");
  25761. return req;
  25762. };
  25763. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25764. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25765. EXPECT_TRUE(
  25766. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25767. EXPECT_TRUE(
  25768. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25769. EXPECT_TRUE(
  25770. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25771. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25772. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25773. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25774. EXPECT_FALSE(
  25775. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25776. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25777. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25778. }
  25779. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25780. Server svr;
  25781. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25782. auto port = svr.bind_to_any_port("localhost");
  25783. std::thread t([&]() { svr.listen_after_bind(); });
  25784. auto se = detail::scope_exit([&] {
  25785. svr.stop();
  25786. t.join();
  25787. });
  25788. svr.wait_until_ready();
  25789. Headers headers = {{"Upgrade", "websocket"},
  25790. {"Connection", "notupgrade"},
  25791. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25792. {"Sec-WebSocket-Version", "13"}};
  25793. Client cli("localhost", port);
  25794. auto res = cli.Get("/ws", headers);
  25795. // The route exists only as a WebSocket route, so a request that fails the
  25796. // handshake check falls through to ordinary routing.
  25797. ASSERT_TRUE(res);
  25798. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25799. }
  25800. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25801. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25802. // Connection value is the only thing left for the client to reject.
  25803. Server svr;
  25804. svr.Get("/ws", [](const Request &req, Response &res) {
  25805. res.status = StatusCode::SwitchingProtocol_101;
  25806. res.set_header("Upgrade", "websocket");
  25807. res.set_header("Connection", "notupgrade");
  25808. res.set_header("Sec-WebSocket-Accept",
  25809. detail::websocket_accept_key(
  25810. req.get_header_value("Sec-WebSocket-Key")));
  25811. });
  25812. auto port = svr.bind_to_any_port("localhost");
  25813. std::thread t([&]() { svr.listen_after_bind(); });
  25814. auto se = detail::scope_exit([&] {
  25815. svr.stop();
  25816. t.join();
  25817. });
  25818. svr.wait_until_ready();
  25819. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25820. auto res = client.connect();
  25821. EXPECT_FALSE(res);
  25822. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25823. EXPECT_FALSE(client.is_open());
  25824. }
  25825. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25826. Server svr;
  25827. svr.Get("/ws", [](const Request &req, Response &res) {
  25828. res.status = StatusCode::SwitchingProtocol_101;
  25829. res.set_header("Upgrade", "websocket");
  25830. res.set_header("Connection", "Upgrade");
  25831. res.set_header("Sec-WebSocket-Accept",
  25832. detail::websocket_accept_key(
  25833. req.get_header_value("Sec-WebSocket-Key")));
  25834. res.set_header("Sec-WebSocket-Protocol", "admin");
  25835. });
  25836. auto port = svr.bind_to_any_port("localhost");
  25837. std::thread t([&]() { svr.listen_after_bind(); });
  25838. auto se = detail::scope_exit([&] {
  25839. svr.stop();
  25840. t.join();
  25841. });
  25842. svr.wait_until_ready();
  25843. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25844. // Server selects a subprotocol the client never offered
  25845. {
  25846. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25847. ws::WebSocketClient client(url, headers);
  25848. auto res = client.connect();
  25849. EXPECT_FALSE(res);
  25850. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25851. EXPECT_FALSE(client.is_open());
  25852. EXPECT_TRUE(client.subprotocol().empty());
  25853. }
  25854. // Client offered none but the server named one anyway
  25855. {
  25856. ws::WebSocketClient client(url);
  25857. auto res = client.connect();
  25858. EXPECT_FALSE(res);
  25859. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25860. EXPECT_FALSE(client.is_open());
  25861. EXPECT_TRUE(client.subprotocol().empty());
  25862. }
  25863. }
  25864. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25865. // The socket path doubles as the URL host, so it must not contain '/'.
  25866. const char *shard = getenv("GTEST_SHARD_INDEX");
  25867. const std::string sock_path =
  25868. shard ? std::string("httplib-ws-") + shard + ".sock"
  25869. : std::string("httplib-ws.sock");
  25870. std::remove(sock_path.c_str());
  25871. Server svr;
  25872. std::mutex mtx;
  25873. std::string received_host;
  25874. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25875. {
  25876. std::lock_guard<std::mutex> lock(mtx);
  25877. received_host = req.get_header_value("Host");
  25878. }
  25879. std::string msg;
  25880. while (ws.read(msg)) {
  25881. ws.send(msg);
  25882. }
  25883. });
  25884. svr.set_address_family(AF_UNIX);
  25885. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25886. auto se = detail::scope_exit([&] {
  25887. svr.stop();
  25888. t.join();
  25889. std::remove(sock_path.c_str());
  25890. });
  25891. svr.wait_until_ready();
  25892. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25893. client.set_address_family(AF_UNIX);
  25894. ASSERT_TRUE(client.connect());
  25895. ASSERT_TRUE(client.send("hello"));
  25896. std::string msg;
  25897. ASSERT_TRUE(client.read(msg));
  25898. client.close();
  25899. {
  25900. std::lock_guard<std::mutex> lock(mtx);
  25901. // There is no host:port for a Unix socket, so the same "localhost"
  25902. // placeholder the HTTP client uses is expected.
  25903. EXPECT_EQ("localhost", received_host);
  25904. }
  25905. }
  25906. // Two threads must never parse WebSocket frames from the same stream.
  25907. // close() used to read the peer's Close reply with its own frame read, so it
  25908. // raced a reader thread that was in the middle of a payload: the payload loop
  25909. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25910. // so bytes taken by close() were replaced with bytes from further along the
  25911. // stream. The message kept its length and silently changed content.
  25912. //
  25913. // The raw peer below sends a frame header plus part of the payload, waits for
  25914. // the handler to call close(), and only then sends the rest. Whichever thread
  25915. // would win the race for those bytes, the message must arrive intact, because
  25916. // close() must not touch the stream while read() owns it.
  25917. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25918. #ifndef _WIN32
  25919. signal(SIGPIPE, SIG_IGN);
  25920. #endif
  25921. const size_t payload_len = 120; // fits the 7-bit length field
  25922. const size_t prefix_len = 8;
  25923. const int attempts = 8;
  25924. std::string expected(payload_len, '\0');
  25925. for (size_t i = 0; i < payload_len; i++) {
  25926. expected[i] = static_cast<char>('a' + i % 26);
  25927. }
  25928. std::atomic<bool> peer_stalled{false};
  25929. std::atomic<bool> handler_done{false};
  25930. std::mutex received_mutex;
  25931. std::vector<std::string> received;
  25932. // Bound every wait, so a regression fails the test instead of hanging the
  25933. // suite.
  25934. auto wait_for = [](const std::atomic<bool> &flag) {
  25935. for (int i = 0; i < 500 && !flag; i++) {
  25936. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25937. }
  25938. };
  25939. Server svr;
  25940. svr.set_websocket_ping_interval(0);
  25941. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25942. std::thread reader([&]() {
  25943. std::string msg;
  25944. while (ws.read(msg)) {
  25945. std::lock_guard<std::mutex> guard(received_mutex);
  25946. received.push_back(msg);
  25947. }
  25948. });
  25949. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25950. // inside a frame when close() runs.
  25951. wait_for(peer_stalled);
  25952. ws.close();
  25953. reader.join();
  25954. handler_done = true;
  25955. });
  25956. auto port = svr.bind_to_any_port("127.0.0.1");
  25957. std::thread t([&]() { svr.listen_after_bind(); });
  25958. auto se = detail::scope_exit([&] {
  25959. svr.stop();
  25960. t.join();
  25961. });
  25962. svr.wait_until_ready();
  25963. auto send_bytes = [](socket_t s, const std::string &data) {
  25964. #ifdef _WIN32
  25965. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25966. #else
  25967. auto n = ::send(s, data.data(), data.size(), 0);
  25968. #endif
  25969. return n == static_cast<decltype(n)>(data.size());
  25970. };
  25971. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25972. // Every length used here fits the 7-bit length field.
  25973. auto masked_header = [](uint8_t first_byte, size_t len) {
  25974. std::string h;
  25975. h += static_cast<char>(first_byte);
  25976. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25977. h.append(4, '\0'); // mask key
  25978. return h;
  25979. };
  25980. for (int attempt = 0; attempt < attempts; attempt++) {
  25981. peer_stalled = false;
  25982. handler_done = false;
  25983. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25984. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25985. auto se_sock = detail::scope_exit([&] {
  25986. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25987. });
  25988. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25989. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25990. sockaddr_in addr{};
  25991. addr.sin_family = AF_INET;
  25992. addr.sin_port = htons(static_cast<uint16_t>(port));
  25993. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25994. ASSERT_EQ(
  25995. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25996. << "attempt " << attempt;
  25997. ASSERT_TRUE(send_bytes(sock,
  25998. "GET /ws HTTP/1.1\r\n"
  25999. "Host: 127.0.0.1\r\n"
  26000. "Upgrade: websocket\r\n"
  26001. "Connection: Upgrade\r\n"
  26002. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26003. "Sec-WebSocket-Version: 13\r\n"
  26004. "\r\n"))
  26005. << "attempt " << attempt;
  26006. std::string response;
  26007. while (response.find("\r\n\r\n") == std::string::npos) {
  26008. char buf[512];
  26009. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26010. if (n <= 0) { break; }
  26011. response.append(buf, static_cast<size_t>(n));
  26012. }
  26013. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26014. << "attempt " << attempt;
  26015. // Send the header of a Binary message but only the first prefix_len bytes
  26016. // of its payload, leaving the reader thread stalled inside the payload.
  26017. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26018. expected.substr(0, prefix_len)))
  26019. << "attempt " << attempt;
  26020. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26021. peer_stalled = true;
  26022. // Let close() send its Close frame and park in its own read before the
  26023. // rest of the payload arrives, so both threads are waiting for it.
  26024. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26025. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26026. close_frame += static_cast<char>(0x03); // status 1000
  26027. close_frame += static_cast<char>(0xE8);
  26028. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26029. << "attempt " << attempt;
  26030. // Closing the peer releases the reader thread even on the buggy path,
  26031. // where it waits for bytes another thread already consumed.
  26032. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26033. detail::close_socket(sock);
  26034. sock = INVALID_SOCKET;
  26035. wait_for(handler_done);
  26036. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26037. }
  26038. std::lock_guard<std::mutex> guard(received_mutex);
  26039. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26040. << "a message in flight when close() ran was dropped";
  26041. for (size_t i = 0; i < received.size(); i++) {
  26042. EXPECT_EQ(expected, received[i]) << "message " << i;
  26043. }
  26044. }
  26045. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26046. // returning the socket, or INVALID_SOCKET.
  26047. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26048. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26049. if (sock == INVALID_SOCKET) { return sock; }
  26050. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26051. sockaddr_in addr{};
  26052. addr.sin_family = AF_INET;
  26053. addr.sin_port = htons(static_cast<uint16_t>(port));
  26054. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26055. std::string req = "GET " + path +
  26056. " HTTP/1.1\r\n"
  26057. "Host: 127.0.0.1\r\n"
  26058. "Upgrade: websocket\r\n"
  26059. "Connection: Upgrade\r\n"
  26060. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26061. "Sec-WebSocket-Version: 13\r\n"
  26062. "\r\n";
  26063. std::string res;
  26064. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26065. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26066. static_cast<ssize_t>(req.size())) {
  26067. char c;
  26068. while (res.find("\r\n\r\n") == std::string::npos &&
  26069. ::recv(sock, &c, 1, 0) == 1) {
  26070. res += c;
  26071. }
  26072. }
  26073. if (res.find(" 101 ") == std::string::npos) {
  26074. detail::close_socket(sock);
  26075. return INVALID_SOCKET;
  26076. }
  26077. return sock;
  26078. }
  26079. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26080. // The payload must fit the 7-bit length field.
  26081. static std::string masked_frame(uint8_t first_byte,
  26082. const std::string &payload) {
  26083. std::string f;
  26084. f += static_cast<char>(first_byte);
  26085. f += static_cast<char>(0x80 | payload.size());
  26086. f.append(4, '\0');
  26087. return f + payload;
  26088. }
  26089. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26090. std::atomic<bool> done{false};
  26091. std::string received;
  26092. Server svr;
  26093. svr.set_websocket_ping_interval(0);
  26094. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26095. std::string msg;
  26096. if (ws.read(msg) == ws::Binary) { received = msg; }
  26097. done = true;
  26098. });
  26099. auto port = svr.bind_to_any_port("127.0.0.1");
  26100. std::thread t([&]() { svr.listen_after_bind(); });
  26101. auto se = detail::scope_exit([&] {
  26102. svr.stop();
  26103. t.join();
  26104. });
  26105. svr.wait_until_ready();
  26106. auto sock = connect_raw_websocket(port, "/ws");
  26107. ASSERT_NE(INVALID_SOCKET, sock);
  26108. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26109. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26110. masked_frame(0x89, "p") + // FIN + Ping
  26111. masked_frame(0x80, "lo"); // FIN + Continuation
  26112. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26113. for (int i = 0; i < 500 && !done; i++) {
  26114. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26115. }
  26116. ASSERT_TRUE(done);
  26117. EXPECT_EQ("Hello", received);
  26118. // The Ping between the fragments is answered with a Pong.
  26119. char pong[3];
  26120. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26121. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26122. }
  26123. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26124. #ifndef _WIN32
  26125. signal(SIGPIPE, SIG_IGN);
  26126. #endif
  26127. std::atomic<bool> read_ended{false};
  26128. std::atomic<bool> sending{true};
  26129. Server svr;
  26130. svr.set_websocket_ping_interval(0);
  26131. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26132. std::thread reader([&]() {
  26133. std::string msg;
  26134. while (ws.read(msg)) {}
  26135. read_ended = true;
  26136. });
  26137. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26138. ws.close();
  26139. reader.join();
  26140. });
  26141. auto port = svr.bind_to_any_port("127.0.0.1");
  26142. std::thread t([&]() { svr.listen_after_bind(); });
  26143. auto se = detail::scope_exit([&] {
  26144. svr.stop();
  26145. t.join();
  26146. });
  26147. svr.wait_until_ready();
  26148. auto sock = connect_raw_websocket(port, "/ws");
  26149. ASSERT_NE(INVALID_SOCKET, sock);
  26150. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26151. // A Text message whose empty continuation frames never end
  26152. std::thread sender([&]() {
  26153. auto data = masked_frame(0x01, "");
  26154. while (sending) {
  26155. data += masked_frame(0x00, "");
  26156. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26157. return;
  26158. }
  26159. data.clear();
  26160. }
  26161. });
  26162. for (int i = 0; i < 300 && !read_ended; i++) {
  26163. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26164. }
  26165. sending = false;
  26166. sender.join();
  26167. EXPECT_TRUE(read_ended);
  26168. }
  26169. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26170. Server svr;
  26171. svr.set_websocket_ping_interval(-1);
  26172. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26173. std::string msg;
  26174. while (ws.read(msg)) {}
  26175. });
  26176. auto port = svr.bind_to_any_port("127.0.0.1");
  26177. std::thread t([&]() { svr.listen_after_bind(); });
  26178. auto se = detail::scope_exit([&] {
  26179. svr.stop();
  26180. t.join();
  26181. });
  26182. svr.wait_until_ready();
  26183. auto sock = connect_raw_websocket(port, "/ws");
  26184. ASSERT_NE(INVALID_SOCKET, sock);
  26185. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26186. // Nothing comes while the client stays quiet.
  26187. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26188. char c;
  26189. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26190. }
  26191. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26192. // and that has to end a read() already waiting on the peer, on every platform.
  26193. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26194. // The peer sends no pings, and its handler never calls read(), which is
  26195. // where pongs are written.
  26196. std::mutex mutex;
  26197. std::condition_variable cv;
  26198. auto release = false;
  26199. svr.set_websocket_ping_interval(0);
  26200. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26201. std::unique_lock<std::mutex> lock(mutex);
  26202. cv.wait(lock, [&] { return release; });
  26203. });
  26204. auto port = svr.bind_to_any_port(HOST);
  26205. std::thread t([&]() { svr.listen_after_bind(); });
  26206. auto se = detail::scope_exit([&] {
  26207. {
  26208. std::lock_guard<std::mutex> lock(mutex);
  26209. release = true;
  26210. }
  26211. cv.notify_all();
  26212. svr.stop();
  26213. t.join();
  26214. });
  26215. svr.wait_until_ready();
  26216. ws::WebSocketClient client(std::string(scheme) +
  26217. "://localhost:" + std::to_string(port) + "/ws");
  26218. #ifdef CPPHTTPLIB_SSL_ENABLED
  26219. client.enable_server_certificate_verification(false);
  26220. #endif
  26221. // A ping a second, given up on after two go unanswered: about 3s
  26222. client.set_websocket_ping_interval(1);
  26223. client.set_websocket_max_missed_pongs(2);
  26224. // Well past that, so that a read the timeout ends instead stands out
  26225. client.set_read_timeout(10);
  26226. ASSERT_TRUE(client.connect());
  26227. auto start = std::chrono::steady_clock::now();
  26228. std::string msg;
  26229. EXPECT_EQ(ws::Fail, client.read(msg));
  26230. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26231. std::chrono::steady_clock::now() - start)
  26232. .count(),
  26233. 6000);
  26234. EXPECT_FALSE(client.is_open());
  26235. }
  26236. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26237. Server svr;
  26238. check_pong_timeout_ends_read(svr, "ws");
  26239. }
  26240. #ifdef CPPHTTPLIB_SSL_ENABLED
  26241. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26242. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26243. ASSERT_TRUE(svr.is_valid());
  26244. check_pong_timeout_ends_read(svr, "wss");
  26245. }
  26246. #endif
  26247. // listen() returns only after every handler has, so Server::stop() has to end
  26248. // a WebSocket handler's read() waiting on a client that stays connected and
  26249. // quiet, whether or not the handler bounded its reads, and the client's
  26250. // connection ends with it.
  26251. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26252. bool bounded) {
  26253. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26254. if (bounded) { ws.set_read_timeout(0, 50000); }
  26255. std::string msg;
  26256. while (ws.read(msg) != ws::Fail) {}
  26257. });
  26258. auto port = svr.bind_to_any_port(HOST);
  26259. std::thread t([&]() { svr.listen_after_bind(); });
  26260. auto se = detail::scope_exit([&] {
  26261. if (t.joinable()) {
  26262. svr.stop();
  26263. t.join();
  26264. }
  26265. });
  26266. svr.wait_until_ready();
  26267. ws::WebSocketClient client(std::string(scheme) +
  26268. "://localhost:" + std::to_string(port) + "/ws");
  26269. #ifdef CPPHTTPLIB_SSL_ENABLED
  26270. client.enable_server_certificate_verification(false);
  26271. #endif
  26272. client.set_read_timeout(2);
  26273. ASSERT_TRUE(client.connect());
  26274. auto stopped = std::async(std::launch::async, [&] {
  26275. svr.stop();
  26276. t.join();
  26277. });
  26278. std::string msg;
  26279. EXPECT_EQ(ws::Fail, client.read(msg));
  26280. EXPECT_FALSE(client.is_open());
  26281. auto in_time =
  26282. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26283. // A handler the stop did not reach ends when the client leaves
  26284. if (!in_time) { client.close(); }
  26285. stopped.wait();
  26286. EXPECT_TRUE(in_time);
  26287. }
  26288. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26289. Server svr;
  26290. check_stop_ends_websocket_read(svr, "ws", false);
  26291. }
  26292. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26293. Server svr;
  26294. check_stop_ends_websocket_read(svr, "ws", true);
  26295. }
  26296. #ifdef CPPHTTPLIB_SSL_ENABLED
  26297. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26298. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26299. ASSERT_TRUE(svr.is_valid());
  26300. check_stop_ends_websocket_read(svr, "wss", false);
  26301. }
  26302. #endif
  26303. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26304. // dropped connection, whether the handler waits for a message or for the rest
  26305. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26306. // time out inside the message as well, and the stop ends them too.
  26307. static void check_stop_closes_with_going_away(const std::string &sent,
  26308. bool bounded = false) {
  26309. Server svr;
  26310. svr.set_websocket_ping_interval(0);
  26311. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26312. if (bounded) { ws.set_read_timeout(0, 10000); }
  26313. std::string msg;
  26314. while (ws.read(msg) != ws::Fail) {}
  26315. });
  26316. auto port = svr.bind_to_any_port("127.0.0.1");
  26317. std::thread t([&]() { svr.listen_after_bind(); });
  26318. auto se = detail::scope_exit([&] {
  26319. svr.stop();
  26320. t.join();
  26321. });
  26322. svr.wait_until_ready();
  26323. // Closed before the join above, which a handler the stop did not reach
  26324. // would otherwise hold up.
  26325. auto sock = connect_raw_websocket(port, "/ws");
  26326. ASSERT_NE(INVALID_SOCKET, sock);
  26327. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26328. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26329. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26330. // Let the handler take what was sent and wait for more
  26331. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26332. svr.stop();
  26333. // FIN + Close, its length, then the code: unmasked, from a server
  26334. std::string head;
  26335. char c;
  26336. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26337. head += c;
  26338. }
  26339. const std::string reason = "server stopping";
  26340. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26341. "\x03\xe9",
  26342. head);
  26343. }
  26344. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26345. check_stop_closes_with_going_away("");
  26346. }
  26347. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26348. // A Text frame without FIN: the first fragment of a message
  26349. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26350. }
  26351. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26352. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26353. /*bounded=*/true);
  26354. }
  26355. // A handler that bounds its reads gets control back within its timeout even
  26356. // while a message arrives in pieces, and the message whole once the last has
  26357. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26358. // sent a while after the one before, much longer than the handler's timeout.
  26359. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26360. const std::string &expected) {
  26361. std::atomic<bool> done{false};
  26362. std::string received;
  26363. std::chrono::steady_clock::duration longest{};
  26364. Server svr;
  26365. svr.set_websocket_ping_interval(0);
  26366. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26367. ws.set_read_timeout(0, 10000);
  26368. std::string msg;
  26369. ws::ReadResult r;
  26370. do {
  26371. auto began = std::chrono::steady_clock::now();
  26372. r = ws.read(msg);
  26373. longest = (std::max)(longest, std::chrono::steady_clock::now() - began);
  26374. } while (r == ws::Timeout);
  26375. if (r == ws::Text) { received = msg; }
  26376. done = true;
  26377. });
  26378. auto port = svr.bind_to_any_port("127.0.0.1");
  26379. std::thread t([&]() { svr.listen_after_bind(); });
  26380. auto se = detail::scope_exit([&] {
  26381. svr.stop();
  26382. t.join();
  26383. });
  26384. svr.wait_until_ready();
  26385. auto sock = connect_raw_websocket(port, "/ws");
  26386. ASSERT_NE(INVALID_SOCKET, sock);
  26387. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26388. for (const auto &piece : pieces) {
  26389. ASSERT_EQ(static_cast<ssize_t>(piece.size()),
  26390. detail::send_socket(sock, piece.data(), piece.size(), 0));
  26391. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26392. }
  26393. for (int i = 0; i < 500 && !done; i++) {
  26394. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26395. }
  26396. ASSERT_TRUE(done);
  26397. EXPECT_EQ(expected, received);
  26398. // Far under the 200 ms between the pieces, however loaded the machine
  26399. EXPECT_LT(longest, std::chrono::milliseconds(150));
  26400. }
  26401. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26402. // The header's first byte, then its second with half the mask key, then
  26403. // the rest: what a frame written in several writes may look like when
  26404. // Nagle's algorithm holds the later ones back for an ACK.
  26405. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26406. check_bounded_read_resumes(
  26407. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26408. }
  26409. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26410. check_bounded_read_resumes(
  26411. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26412. }
  26413. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26414. Server svr;
  26415. svr.set_websocket_ping_interval(0);
  26416. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26417. std::string msg;
  26418. while (ws.read(msg)) {}
  26419. });
  26420. auto port = svr.bind_to_any_port("127.0.0.1");
  26421. std::thread t([&]() { svr.listen_after_bind(); });
  26422. auto se = detail::scope_exit([&] {
  26423. svr.stop();
  26424. t.join();
  26425. });
  26426. svr.wait_until_ready();
  26427. // Each Close payload and the reply it should get: an echo when valid, 1002
  26428. // otherwise.
  26429. std::vector<std::pair<std::string, std::string>> cases = {
  26430. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26431. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26432. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26433. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26434. };
  26435. // Also between the fragments of a message.
  26436. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26437. for (const auto &c : cases) {
  26438. auto sock = connect_raw_websocket(port, "/ws");
  26439. ASSERT_NE(INVALID_SOCKET, sock);
  26440. auto frames = prefix + masked_frame(0x88, c.first);
  26441. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26442. std::string reply;
  26443. char buf[256];
  26444. while (reply.size() < 2 + c.second.size()) {
  26445. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26446. if (n <= 0) { break; }
  26447. reply.append(buf, static_cast<size_t>(n));
  26448. }
  26449. detail::close_socket(sock);
  26450. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26451. c.second,
  26452. reply);
  26453. }
  26454. }
  26455. }
  26456. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26457. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26458. protected:
  26459. void SetUp() override {
  26460. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26461. SERVER_PRIVATE_KEY_FILE);
  26462. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26463. std::string msg;
  26464. ws::ReadResult ret;
  26465. while ((ret = ws.read(msg))) {
  26466. if (ret == ws::Binary) {
  26467. ws.send(msg.data(), msg.size());
  26468. } else {
  26469. ws.send(msg);
  26470. }
  26471. }
  26472. });
  26473. port_ = server_->bind_to_any_port(HOST);
  26474. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26475. server_->wait_until_ready();
  26476. }
  26477. void TearDown() override {
  26478. server_->stop();
  26479. if (server_thread_.joinable()) { server_thread_.join(); }
  26480. }
  26481. std::unique_ptr<SSLServer> server_;
  26482. std::thread server_thread_;
  26483. int port_ = 0;
  26484. };
  26485. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26486. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26487. {
  26488. ws::WebSocketClient client(url);
  26489. client.enable_server_certificate_verification(false);
  26490. auto calls = 0;
  26491. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26492. calls++;
  26493. return false;
  26494. });
  26495. EXPECT_FALSE(client.connect());
  26496. EXPECT_GT(calls, 0);
  26497. }
  26498. {
  26499. ws::WebSocketClient client(url);
  26500. client.enable_server_certificate_verification(false);
  26501. client.set_session_verifier([](tls::session_t) {
  26502. return SSLVerifierResponse::CertificateRejected;
  26503. });
  26504. EXPECT_FALSE(client.connect());
  26505. }
  26506. {
  26507. ws::WebSocketClient client(url);
  26508. client.enable_server_certificate_verification(false);
  26509. client.set_session_verifier([](tls::session_t) {
  26510. return SSLVerifierResponse::CertificateAccepted;
  26511. });
  26512. EXPECT_TRUE(client.connect());
  26513. }
  26514. }
  26515. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26516. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26517. "/ws-echo");
  26518. client.enable_server_certificate_verification(false);
  26519. ASSERT_TRUE(client.connect());
  26520. ASSERT_TRUE(client.is_open());
  26521. ASSERT_TRUE(client.send("Hello WSS"));
  26522. std::string msg;
  26523. EXPECT_EQ(ws::Text, client.read(msg));
  26524. EXPECT_EQ("Hello WSS", msg);
  26525. client.close();
  26526. }
  26527. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26528. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26529. "/ws-echo");
  26530. client.enable_server_certificate_verification(false);
  26531. EXPECT_TRUE(client.connect());
  26532. }
  26533. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26534. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26535. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26536. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26537. // client (without calling close() first) is the only path that runs
  26538. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26539. // bug exactly.
  26540. //
  26541. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26542. // when linked against an instrumented libssl; run under Valgrind to catch it
  26543. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26544. // suite (the freed session otherwise stalls on the close handshake) — this test
  26545. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26546. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26547. {
  26548. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26549. "/ws-echo");
  26550. client.enable_server_certificate_verification(false);
  26551. client.set_read_timeout(2, 0);
  26552. client.set_write_timeout(2, 0);
  26553. ASSERT_TRUE(client.connect());
  26554. ASSERT_TRUE(client.is_open());
  26555. ASSERT_TRUE(client.send("still open"));
  26556. // Intentionally do NOT call client.close(): leaving scope runs
  26557. // shutdown_and_close() with the WebSocket still open, which must send the
  26558. // close frame while the TLS session is still alive.
  26559. }
  26560. }
  26561. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26562. // shutdown_and_close() at the start of connect(), reproducing the same
  26563. // use-after-free within the test body rather than at scope exit. The second
  26564. // connect must succeed and echo, proving the close handshake ran over a live
  26565. // session. See the note above about memory-tool requirements.
  26566. TEST_F(WebSocketSSLIntegrationTest,
  26567. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26568. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26569. "/ws-echo");
  26570. client.enable_server_certificate_verification(false);
  26571. client.set_read_timeout(2, 0);
  26572. client.set_write_timeout(2, 0);
  26573. ASSERT_TRUE(client.connect());
  26574. ASSERT_TRUE(client.is_open());
  26575. ASSERT_TRUE(client.send("still open"));
  26576. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26577. // the still-open connection, which must not touch a freed TLS session.
  26578. ASSERT_TRUE(client.connect());
  26579. ASSERT_TRUE(client.is_open());
  26580. ASSERT_TRUE(client.send("after reconnect"));
  26581. std::string msg;
  26582. EXPECT_EQ(ws::Text, client.read(msg));
  26583. EXPECT_EQ("after reconnect", msg);
  26584. client.close();
  26585. }
  26586. #endif
  26587. #ifdef CPPHTTPLIB_SSL_ENABLED
  26588. class WebSocketSSLCATest : public ::testing::Test {
  26589. protected:
  26590. void SetUp() override {
  26591. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26592. SERVER_PRIVATE_KEY_FILE);
  26593. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26594. std::string msg;
  26595. while (ws.read(msg)) {
  26596. ws.send(msg);
  26597. }
  26598. });
  26599. port_ = server_->bind_to_any_port("127.0.0.1");
  26600. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26601. server_->wait_until_ready();
  26602. }
  26603. void TearDown() override {
  26604. server_->stop();
  26605. if (server_thread_.joinable()) { server_thread_.join(); }
  26606. }
  26607. std::string url() const {
  26608. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26609. }
  26610. std::unique_ptr<SSLServer> server_;
  26611. std::thread server_thread_;
  26612. int port_ = 0;
  26613. };
  26614. // A custom CA loaded as PEM verifies the server with full certificate
  26615. // verification enabled
  26616. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26617. ws::WebSocketClient client(url());
  26618. std::string cert;
  26619. read_file(SERVER_CERT2_FILE, cert);
  26620. client.load_ca_cert_store(cert.c_str(), cert.size());
  26621. ASSERT_TRUE(client.connect());
  26622. ASSERT_TRUE(client.send("hello"));
  26623. std::string msg;
  26624. EXPECT_EQ(ws::Text, client.read(msg));
  26625. EXPECT_EQ("hello", msg);
  26626. client.close();
  26627. }
  26628. // A custom CA that does not cover the server must fail verification (the
  26629. // custom CA is exclusive; system certs are not loaded alongside it)
  26630. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26631. ws::WebSocketClient client(url());
  26632. std::string cert;
  26633. read_file(CLIENT_CA_CERT_FILE, cert);
  26634. client.load_ca_cert_store(cert.c_str(), cert.size());
  26635. auto res = client.connect();
  26636. ASSERT_FALSE(res);
  26637. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26638. EXPECT_EQ(-1, res.status());
  26639. EXPECT_NE(0u, res.ssl_backend_error());
  26640. }
  26641. // The same CA as a file path rather than PEM in memory
  26642. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26643. ws::WebSocketClient client(url());
  26644. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26645. ASSERT_TRUE(client.connect());
  26646. ASSERT_TRUE(client.send("hello"));
  26647. std::string msg;
  26648. EXPECT_EQ(ws::Text, client.read(msg));
  26649. EXPECT_EQ("hello", msg);
  26650. client.close();
  26651. }
  26652. // ...and a CA file that does not cover the server still fails, so it is the
  26653. // path above that decides the outcome
  26654. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26655. ws::WebSocketClient client(url());
  26656. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26657. ASSERT_FALSE(client.connect());
  26658. }
  26659. // Regression test: reconnecting with a native custom CA store used to reuse
  26660. // a store handle the previous TLS context had already freed (use-after-free
  26661. // under the OpenSSL backend). The context now lives as long as the client.
  26662. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26663. ws::WebSocketClient client(url());
  26664. std::string cert;
  26665. read_file(SERVER_CERT2_FILE, cert);
  26666. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26667. ASSERT_TRUE(client.connect());
  26668. client.close();
  26669. ASSERT_TRUE(client.connect());
  26670. ASSERT_TRUE(client.send("again"));
  26671. std::string msg;
  26672. EXPECT_EQ(ws::Text, client.read(msg));
  26673. EXPECT_EQ("again", msg);
  26674. client.close();
  26675. }
  26676. // Regression test: a certificate with a trusted chain but no identity match
  26677. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26678. // verification entirely for IP hosts, so this connection succeeded there.
  26679. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26680. // chain verification while the identity check must still fail.
  26681. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26683. ASSERT_TRUE(svr.is_valid());
  26684. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26685. std::string msg;
  26686. while (ws.read(msg)) {
  26687. ws.send(msg);
  26688. }
  26689. });
  26690. auto port = svr.bind_to_any_port("127.0.0.1");
  26691. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26692. auto se = detail::scope_exit([&] {
  26693. svr.stop();
  26694. t.join();
  26695. });
  26696. svr.wait_until_ready();
  26697. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26698. "/echo");
  26699. std::string cert;
  26700. read_file(SERVER_CERT_FILE, cert);
  26701. client.load_ca_cert_store(cert.c_str(), cert.size());
  26702. ASSERT_FALSE(client.connect());
  26703. }
  26704. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26705. // SNI, so nothing binds the host name to the TLS session. These bind the
  26706. // server to "localhost" instead, the only shape that exercises the SNI and
  26707. // hostname-verification path with certificate verification left enabled.
  26708. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26709. protected:
  26710. void Start(const char *cert_file) {
  26711. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26712. SERVER_PRIVATE_KEY_FILE);
  26713. ASSERT_TRUE(server_->is_valid());
  26714. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26715. std::string msg;
  26716. while (ws.read(msg)) {
  26717. ws.send(msg);
  26718. }
  26719. });
  26720. port_ = server_->bind_to_any_port("localhost");
  26721. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26722. server_->wait_until_ready();
  26723. }
  26724. void TearDown() override {
  26725. if (server_) { server_->stop(); }
  26726. if (server_thread_.joinable()) { server_thread_.join(); }
  26727. }
  26728. std::string url() const {
  26729. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26730. }
  26731. std::unique_ptr<SSLServer> server_;
  26732. std::thread server_thread_;
  26733. int port_ = 0;
  26734. };
  26735. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26736. // out and the connection is usable
  26737. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26738. Start(SERVER_CERT2_FILE);
  26739. ws::WebSocketClient client(url());
  26740. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26741. ASSERT_TRUE(client.connect());
  26742. ASSERT_TRUE(client.send("hello"));
  26743. std::string msg;
  26744. EXPECT_EQ(ws::Text, client.read(msg));
  26745. EXPECT_EQ("hello", msg);
  26746. client.close();
  26747. }
  26748. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26749. // while the identity check must still reject "localhost"
  26750. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26751. Start(SERVER_CERT_FILE);
  26752. ws::WebSocketClient client(url());
  26753. client.set_ca_cert_path(SERVER_CERT_FILE);
  26754. auto res = client.connect();
  26755. ASSERT_FALSE(res);
  26756. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26757. EXPECT_EQ(-1, res.status());
  26758. }
  26759. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26760. // disabled: the chain is still checked, only the identity check is skipped
  26761. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26762. Start(SERVER_CERT_FILE);
  26763. ws::WebSocketClient client(url());
  26764. client.set_ca_cert_path(SERVER_CERT_FILE);
  26765. client.enable_server_hostname_verification(false);
  26766. ASSERT_TRUE(client.connect());
  26767. ASSERT_TRUE(client.send("hello"));
  26768. std::string msg;
  26769. EXPECT_EQ(ws::Text, client.read(msg));
  26770. EXPECT_EQ("hello", msg);
  26771. client.close();
  26772. }
  26773. // A CA that did not sign the server certificate fails the chain, even though
  26774. // the name would match
  26775. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26776. Start(SERVER_CERT2_FILE);
  26777. ws::WebSocketClient client(url());
  26778. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26779. ASSERT_FALSE(client.connect());
  26780. }
  26781. // With verification disabled, neither the chain nor the name is checked
  26782. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26783. Start(SERVER_CERT_FILE);
  26784. ws::WebSocketClient client(url());
  26785. client.enable_server_certificate_verification(false);
  26786. ASSERT_TRUE(client.connect());
  26787. ASSERT_TRUE(client.send("hello"));
  26788. std::string msg;
  26789. EXPECT_EQ(ws::Text, client.read(msg));
  26790. EXPECT_EQ("hello", msg);
  26791. client.close();
  26792. }
  26793. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26794. protected:
  26795. void SetUp() override {
  26796. server_ = httplib::detail::make_unique<SSLServer>(
  26797. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26798. ASSERT_TRUE(server_->is_valid());
  26799. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26800. std::string msg;
  26801. while (ws.read(msg)) {
  26802. ws.send(msg);
  26803. }
  26804. });
  26805. port_ = server_->bind_to_any_port("localhost");
  26806. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26807. server_->wait_until_ready();
  26808. }
  26809. void TearDown() override {
  26810. server_->stop();
  26811. if (server_thread_.joinable()) { server_thread_.join(); }
  26812. }
  26813. std::string url() const {
  26814. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26815. }
  26816. void ConnectWithClientCert(const std::string &client_cert_file,
  26817. const std::string &client_private_key_file,
  26818. const char *private_key_password) {
  26819. std::string cert_pem, key_pem;
  26820. read_file(client_cert_file, cert_pem);
  26821. read_file(client_private_key_file, key_pem);
  26822. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26823. key_pem.c_str(), key_pem.size(),
  26824. private_key_password};
  26825. ConnectWithPem(pem);
  26826. }
  26827. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26828. ws::WebSocketClient client(url(), pem);
  26829. ASSERT_TRUE(client.is_valid());
  26830. client.enable_server_certificate_verification(false);
  26831. ASSERT_TRUE(client.connect());
  26832. ASSERT_TRUE(client.send("hello"));
  26833. std::string msg;
  26834. EXPECT_EQ(ws::Text, client.read(msg));
  26835. EXPECT_EQ("hello", msg);
  26836. client.close();
  26837. }
  26838. std::unique_ptr<SSLServer> server_;
  26839. std::thread server_thread_;
  26840. int port_ = 0;
  26841. };
  26842. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26843. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26844. }
  26845. // Control for the tests above: the fixture's server really does require a
  26846. // client certificate, so it is the PEM the constructor installed that decides
  26847. // the outcome.
  26848. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26849. ws::WebSocketClient client(url());
  26850. ASSERT_TRUE(client.is_valid());
  26851. client.enable_server_certificate_verification(false);
  26852. EXPECT_FALSE(client.connect());
  26853. }
  26854. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26855. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26856. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26857. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26858. }
  26859. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26860. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26861. std::string cert_pem, key_pem;
  26862. read_file(CLIENT_CERT_FILE, cert_pem);
  26863. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26864. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26865. std::vector<char> key(key_pem.begin(), key_pem.end());
  26866. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26867. key.size(), nullptr};
  26868. ConnectWithPem(pem);
  26869. }
  26870. #endif
  26871. #if !defined(_WIN32)
  26872. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26873. auto secret_dir = std::string("./symlink_test_secret");
  26874. auto served_dir = std::string("./symlink_test_served");
  26875. auto secret_file = secret_dir + "/secret.txt";
  26876. auto symlink_path = served_dir + "/escape";
  26877. // Setup: create directories and files
  26878. mkdir(secret_dir.c_str(), 0755);
  26879. mkdir(served_dir.c_str(), 0755);
  26880. {
  26881. std::ofstream ofs(secret_file);
  26882. ofs << "SECRET_DATA";
  26883. }
  26884. // Create symlink using absolute path so it resolves correctly
  26885. #ifdef PATH_MAX
  26886. char abs_secret[PATH_MAX];
  26887. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26888. #else
  26889. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26890. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26891. ASSERT_NE(nullptr, abs_secret);
  26892. #endif
  26893. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26894. auto se = detail::scope_exit([&] {
  26895. unlink(symlink_path.c_str());
  26896. unlink(secret_file.c_str());
  26897. rmdir(served_dir.c_str());
  26898. rmdir(secret_dir.c_str());
  26899. });
  26900. Server svr;
  26901. svr.set_mount_point("/", served_dir);
  26902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26903. auto se2 = detail::scope_exit([&] {
  26904. svr.stop();
  26905. listen_thread.join();
  26906. });
  26907. svr.wait_until_ready();
  26908. Client cli("localhost", PORT);
  26909. // Symlink pointing outside base dir should be blocked
  26910. auto res = cli.Get("/escape/secret.txt");
  26911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26912. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26913. }
  26914. #else
  26915. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26916. auto secret_dir = std::string("junction_test_secret");
  26917. auto served_dir = std::string("junction_test_served");
  26918. auto secret_file = secret_dir + "\\secret.txt";
  26919. auto junction_path = served_dir + "\\escape";
  26920. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26921. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26922. {
  26923. std::ofstream ofs(secret_file);
  26924. ofs << "SECRET_DATA";
  26925. }
  26926. // A junction needs no privilege to create, unlike a symlink
  26927. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  26928. ASSERT_EQ(0, std::system(cmd.c_str()));
  26929. auto se = detail::scope_exit([&] {
  26930. ::RemoveDirectoryA(junction_path.c_str());
  26931. std::remove(secret_file.c_str());
  26932. ::RemoveDirectoryA(served_dir.c_str());
  26933. ::RemoveDirectoryA(secret_dir.c_str());
  26934. });
  26935. Server svr;
  26936. svr.set_mount_point("/", served_dir);
  26937. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26938. auto se2 = detail::scope_exit([&] {
  26939. svr.stop();
  26940. listen_thread.join();
  26941. });
  26942. svr.wait_until_ready();
  26943. Client cli("localhost", PORT);
  26944. // Junction pointing outside base dir should be blocked
  26945. auto res = cli.Get("/escape/secret.txt");
  26946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26947. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26948. }
  26949. #endif
  26950. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  26951. // "GET /smuggled" request), reads the first response, and only then sends the
  26952. // embedded request as the body. Returns how many times /smuggled ran.
  26953. //
  26954. // The body is sent AFTER receiving the first response (as in the original
  26955. // PoC) so that the stream_line_reader cannot buffer it together with the
  26956. // headers of the first request.
  26957. static int count_smuggled_requests(const std::string &outer_head,
  26958. std::string &first_response) {
  26959. Server svr;
  26960. svr.set_mount_point("/", "./www");
  26961. std::atomic<int> smuggled_count(0);
  26962. svr.Get("/smuggled", [&](const Request &, Response &res) {
  26963. smuggled_count++;
  26964. res.set_content("oops", "text/plain");
  26965. });
  26966. svr.Post("/post", [&](const Request &req, Response &res) {
  26967. res.set_content(req.body, "text/plain");
  26968. });
  26969. auto port = svr.bind_to_any_port("localhost");
  26970. thread t = thread([&] { svr.listen_after_bind(); });
  26971. auto se = detail::scope_exit([&] {
  26972. svr.stop();
  26973. t.join();
  26974. });
  26975. svr.wait_until_ready();
  26976. auto error = Error::Success;
  26977. auto sock = detail::create_client_socket(
  26978. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  26979. /*connection_timeout_sec=*/2, 0,
  26980. /*read_timeout_sec=*/2, 0,
  26981. /*write_timeout_sec=*/2, 0, std::string(), error);
  26982. EXPECT_NE(INVALID_SOCKET, sock);
  26983. if (sock == INVALID_SOCKET) { return -1; }
  26984. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26985. // The "smuggled" request will be sent as the body of the outer request
  26986. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  26987. "Host: localhost\r\n"
  26988. "Connection: close\r\n"
  26989. "\r\n";
  26990. auto head = outer_head;
  26991. auto len = std::to_string(smuggled.size());
  26992. for (auto pos = head.find("{len}"); pos != std::string::npos;
  26993. pos = head.find("{len}", pos + len.size())) {
  26994. head.replace(pos, 5, len);
  26995. }
  26996. // Step 1: Send only the outer request headers (no body yet)
  26997. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  26998. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  26999. // Step 2: Read the first response
  27000. char buf[4096];
  27001. for (;;) {
  27002. auto n = recv(sock, buf, sizeof(buf), 0);
  27003. if (n <= 0) break;
  27004. first_response.append(buf, static_cast<size_t>(n));
  27005. // Stop once we have a complete response (headers + body)
  27006. auto hdr_end = first_response.find("\r\n\r\n");
  27007. if (hdr_end != std::string::npos) {
  27008. // Check for Content-Length to know when the body is complete
  27009. auto cl_pos = first_response.find("Content-Length:");
  27010. if (cl_pos != std::string::npos) {
  27011. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27012. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27013. auto cl = std::stoul(
  27014. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27015. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27016. } else {
  27017. break; // No Content-Length, assume headers-only response
  27018. }
  27019. }
  27020. }
  27021. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27022. // vulnerable server the keep-alive loop reads this as a second request. The
  27023. // server may already have closed the connection, so the result is ignored.
  27024. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27025. // Half-close so that a server which drained the body sees EOF and closes,
  27026. // instead of the read below waiting for the read timeout.
  27027. #ifdef _WIN32
  27028. ::shutdown(sock, SD_SEND);
  27029. #else
  27030. ::shutdown(sock, SHUT_WR);
  27031. #endif
  27032. // Step 4: Read until the server closes the connection
  27033. for (;;) {
  27034. auto n = recv(sock, buf, sizeof(buf), 0);
  27035. if (n <= 0) break;
  27036. }
  27037. return smuggled_count.load();
  27038. }
  27039. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27040. // A GET request with Content-Length to a static file handler must have its
  27041. // body drained before the keep-alive connection is reused. Otherwise the
  27042. // unread body bytes are interpreted as the next HTTP request.
  27043. std::string first_response;
  27044. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27045. "Host: localhost\r\n"
  27046. "Content-Length: {len}\r\n"
  27047. "\r\n",
  27048. first_response));
  27049. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27050. }
  27051. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27052. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27053. // be answered with 400 and the connection closed. Treating it as "no body"
  27054. // leaves the body to be parsed as the next request.
  27055. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27056. const char *targets[] = {
  27057. "GET /file", // handler that never reads the body
  27058. "GET /not-found", // no handler matches (404)
  27059. "POST /post", // handler that reads the body
  27060. };
  27061. for (auto target : targets) {
  27062. for (auto value : values) {
  27063. std::string first_response;
  27064. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27065. " HTTP/1.1\r\n"
  27066. "Host: localhost\r\n"
  27067. "Content-Length: " +
  27068. value + "\r\n\r\n",
  27069. first_response))
  27070. << target << " with Content-Length: " << value;
  27071. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27072. << target << " with Content-Length: " << value;
  27073. }
  27074. }
  27075. }
  27076. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27077. // A 400 for an unparseable request line leaves the rest of the message
  27078. // unread, so the connection must be closed rather than reused.
  27079. std::string first_response;
  27080. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27081. "Host: localhost\r\n"
  27082. "Content-Length: {len}\r\n"
  27083. "\r\n",
  27084. first_response));
  27085. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27086. }
  27087. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27088. // Same as above for a header block that fails to parse.
  27089. std::string first_response;
  27090. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27091. "Host: localhost\r\n"
  27092. "Bad Header\r\n"
  27093. "Content-Length: {len}\r\n"
  27094. "\r\n",
  27095. first_response));
  27096. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27097. }
  27098. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27099. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27100. // server must not read another request on that connection, even when the
  27101. // request had no body to drain.
  27102. std::string first_response;
  27103. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27104. "Host: localhost\r\n"
  27105. "\r\n",
  27106. first_response));
  27107. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27108. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27109. }
  27110. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27111. // A content reader that stops early leaves the stream inside the body.
  27112. // Draining the whole Content-Length from there, or reading the body again,
  27113. // reads into the next request, and whatever follows is parsed as a request
  27114. // of its own.
  27115. Server svr;
  27116. std::atomic<int> smuggled_count(0);
  27117. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27118. svr.Post("/upload", [](const Request &req, Response &res,
  27119. const ContentReader &content_reader) {
  27120. // Stop at the last chunk, so the whole body has been read however it
  27121. // arrives.
  27122. auto length = req.get_header_value_u64("Content-Length");
  27123. size_t total = 0;
  27124. auto consumed = content_reader([&](const char *, size_t n) {
  27125. total += n;
  27126. return total < length;
  27127. });
  27128. EXPECT_FALSE(consumed);
  27129. if (req.has_param("retry")) {
  27130. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27131. }
  27132. // Replace the 400 the aborted read set, which would close the connection.
  27133. res.set_redirect("/done");
  27134. });
  27135. auto port = svr.bind_to_any_port(HOST);
  27136. thread t = thread([&] { svr.listen_after_bind(); });
  27137. auto se = detail::scope_exit([&] {
  27138. svr.stop();
  27139. t.join();
  27140. });
  27141. svr.wait_until_ready();
  27142. // A front end sees the second request as a POST whose body is the GET. The
  27143. // first body is as long as the POST's headers, so draining it again reads
  27144. // exactly those and leaves the GET to be parsed next.
  27145. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27146. "Host: localhost\r\n"
  27147. "\r\n";
  27148. std::string second_head = "POST /post HTTP/1.1\r\n"
  27149. "Host: localhost\r\n"
  27150. "Content-Length: " +
  27151. std::to_string(inner.size()) +
  27152. "\r\n"
  27153. "\r\n";
  27154. for (auto target : {"/upload", "/upload?retry"}) {
  27155. smuggled_count = 0;
  27156. std::string request = "POST " + std::string(target) +
  27157. " HTTP/1.1\r\n"
  27158. "Host: localhost\r\n"
  27159. "Content-Length: " +
  27160. std::to_string(second_head.size()) +
  27161. "\r\n"
  27162. "\r\n" +
  27163. std::string(second_head.size(), 'A') + second_head +
  27164. inner;
  27165. std::string response;
  27166. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27167. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27168. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27169. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27170. EXPECT_EQ(0, smuggled_count.load()) << target;
  27171. }
  27172. }
  27173. // An error response closes the connection anyway, so the body is left unread
  27174. // with a redirect, such as one to a login page.
  27175. static void serve_redirects(Server &svr,
  27176. const std::function<void(int)> &client) {
  27177. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27178. res.set_redirect("/login");
  27179. return Server::HandlerResponse::Handled;
  27180. });
  27181. auto port = svr.bind_to_any_port(HOST);
  27182. ASSERT_GT(port, 0);
  27183. thread t = thread([&] { svr.listen_after_bind(); });
  27184. auto se = detail::scope_exit([&] {
  27185. svr.stop();
  27186. t.join();
  27187. ASSERT_FALSE(svr.is_running());
  27188. });
  27189. svr.wait_until_ready();
  27190. client(port);
  27191. }
  27192. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27193. Server svr;
  27194. serve_redirects(svr, [](int port) {
  27195. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27196. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27197. std::to_string(body.size()) + "\r\n\r\n" + body +
  27198. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27199. std::string resp;
  27200. ASSERT_TRUE(send_request(1, req, &resp, port));
  27201. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27202. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27203. });
  27204. }
  27205. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27206. Server svr;
  27207. svr.set_read_timeout(0, 200000);
  27208. serve_redirects(svr, [](int port) {
  27209. // A byte every 100 ms keeps each read within the read timeout, but not the
  27210. // body as a whole, so the server closes and the bytes sent after that fail.
  27211. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27212. "Content-Length: 10\r\n\r\n"};
  27213. parts.resize(11, "x");
  27214. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27215. });
  27216. }
  27217. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27218. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27219. // must be rejected with 400 Bad Request.
  27220. Server svr;
  27221. svr.Post("/test", [&](const Request &, Response &res) {
  27222. res.set_content("ok", "text/plain");
  27223. });
  27224. thread t = thread([&] { svr.listen(HOST, PORT); });
  27225. auto se = detail::scope_exit([&] {
  27226. svr.stop();
  27227. t.join();
  27228. ASSERT_FALSE(svr.is_running());
  27229. });
  27230. svr.wait_until_ready();
  27231. // Exact "chunked"
  27232. {
  27233. auto req = "POST /test HTTP/1.1\r\n"
  27234. "Host: localhost\r\n"
  27235. "Content-Length: 5\r\n"
  27236. "Transfer-Encoding: chunked\r\n"
  27237. "Connection: close\r\n"
  27238. "\r\n"
  27239. "hello";
  27240. std::string response;
  27241. ASSERT_TRUE(send_request(1, req, &response));
  27242. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27243. response.substr(0, response.find("\r\n")));
  27244. }
  27245. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27246. {
  27247. auto req = "POST /test HTTP/1.1\r\n"
  27248. "Host: localhost\r\n"
  27249. "Content-Length: 5\r\n"
  27250. "Transfer-Encoding: gzip, chunked\r\n"
  27251. "Connection: close\r\n"
  27252. "\r\n"
  27253. "hello";
  27254. std::string response;
  27255. ASSERT_TRUE(send_request(1, req, &response));
  27256. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27257. response.substr(0, response.find("\r\n")));
  27258. }
  27259. }
  27260. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27261. Server svr;
  27262. svr.Post("/test", [&](const Request &, Response &res) {
  27263. res.set_content("ok", "text/plain");
  27264. });
  27265. thread t = thread([&] { svr.listen(HOST, PORT); });
  27266. auto se = detail::scope_exit([&] {
  27267. svr.stop();
  27268. t.join();
  27269. ASSERT_FALSE(svr.is_running());
  27270. });
  27271. svr.wait_until_ready();
  27272. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27273. // length cannot be determined, so the server must answer 400 and close
  27274. // rather than treat the request as bodyless and leave the body in the
  27275. // socket for the next request to pick up.
  27276. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27277. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27278. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27279. std::string response;
  27280. ASSERT_TRUE(send_request(1, req, &response));
  27281. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27282. response.substr(0, response.find("\r\n")))
  27283. << transfer_encoding;
  27284. }
  27285. // RFC 9110 5.3: the codings may also be split across several
  27286. // Transfer-Encoding lines, which combine in the order they were received.
  27287. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27288. // just like the single-line "chunked, gzip" above.
  27289. {
  27290. auto req = "POST /test HTTP/1.1\r\n"
  27291. "Host: localhost\r\n"
  27292. "Transfer-Encoding: chunked\r\n"
  27293. "Transfer-Encoding: gzip\r\n"
  27294. "\r\n"
  27295. "0\r\n\r\n";
  27296. std::string response;
  27297. ASSERT_TRUE(send_request(1, req, &response));
  27298. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27299. response.substr(0, response.find("\r\n")));
  27300. }
  27301. }
  27302. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27303. Server svr;
  27304. svr.Post("/test", [&](const Request &, Response &res) {
  27305. res.set_content("ok", "text/plain");
  27306. });
  27307. auto port = svr.bind_to_any_port(HOST);
  27308. ASSERT_GT(port, 0);
  27309. thread t = thread([&] { svr.listen_after_bind(); });
  27310. auto se = detail::scope_exit([&] {
  27311. svr.stop();
  27312. t.join();
  27313. ASSERT_FALSE(svr.is_running());
  27314. });
  27315. svr.wait_until_ready();
  27316. for (auto transfer_encoding :
  27317. {"Transfer-Encoding: gzip, chunked\r\n",
  27318. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27319. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27320. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27321. transfer_encoding + "\r\n0\r\n\r\n";
  27322. std::string response;
  27323. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27324. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27325. response.substr(0, response.find("\r\n")))
  27326. << transfer_encoding;
  27327. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27328. << transfer_encoding;
  27329. }
  27330. }
  27331. // Regression for issue #2450: a DELETE without Content-Length on a
  27332. // keep-alive connection must not let the post-response drain consume the
  27333. // next request's bytes.
  27334. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27335. Server svr;
  27336. std::atomic<int> delete_count(0);
  27337. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27338. delete_count++;
  27339. res.status = StatusCode::NoContent_204;
  27340. });
  27341. auto port = svr.bind_to_any_port(HOST);
  27342. thread t = thread([&] { svr.listen_after_bind(); });
  27343. auto se = detail::scope_exit([&] {
  27344. svr.stop();
  27345. t.join();
  27346. });
  27347. svr.wait_until_ready();
  27348. auto error = Error::Success;
  27349. auto sock = detail::create_client_socket(
  27350. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27351. /*connection_timeout_sec=*/2, 0,
  27352. /*read_timeout_sec=*/2, 0,
  27353. /*write_timeout_sec=*/2, 0, std::string(), error);
  27354. ASSERT_NE(INVALID_SOCKET, sock);
  27355. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27356. auto send_request_and_read_response = [&](const std::string &req,
  27357. std::string &out) -> bool {
  27358. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27359. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27360. char buf[4096];
  27361. for (;;) {
  27362. auto n = recv(sock, buf, sizeof(buf), 0);
  27363. if (n <= 0) { return !out.empty(); }
  27364. out.append(buf, static_cast<size_t>(n));
  27365. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27366. }
  27367. };
  27368. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27369. "Host: localhost\r\n"
  27370. "\r\n";
  27371. std::string resp1;
  27372. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27373. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27374. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27375. "Host: localhost\r\n"
  27376. "Connection: close\r\n"
  27377. "\r\n";
  27378. std::string resp2;
  27379. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27380. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27381. EXPECT_EQ(2, delete_count.load());
  27382. }
  27383. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27384. Server svr;
  27385. svr.Post("/ingest", [&](const Request &, Response &res,
  27386. const ContentReader &content_reader) {
  27387. auto consumed = content_reader([](const char *, size_t) { return false; });
  27388. EXPECT_FALSE(consumed);
  27389. res.status = StatusCode::Conflict_409;
  27390. res.set_header("Connection", "close");
  27391. });
  27392. auto port = svr.bind_to_any_port(HOST);
  27393. thread t = thread([&] { svr.listen_after_bind(); });
  27394. auto se = detail::scope_exit([&] {
  27395. svr.stop();
  27396. t.join();
  27397. });
  27398. svr.wait_until_ready();
  27399. auto error = Error::Success;
  27400. auto sock = detail::create_client_socket(
  27401. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27402. /*connection_timeout_sec=*/2, 0,
  27403. /*read_timeout_sec=*/1, 0,
  27404. /*write_timeout_sec=*/2, 0, std::string(), error);
  27405. ASSERT_NE(INVALID_SOCKET, sock);
  27406. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27407. std::string request = "POST /ingest HTTP/1.1\r\n"
  27408. "Host: localhost\r\n"
  27409. "Transfer-Encoding: chunked\r\n"
  27410. "\r\n"
  27411. "4\r\n"
  27412. "data\r\n";
  27413. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27414. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27415. std::string response;
  27416. ssize_t received = 0;
  27417. do {
  27418. char buf[4096];
  27419. received = recv(sock, buf, sizeof(buf), 0);
  27420. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27421. } while (received > 0);
  27422. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27423. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27424. EXPECT_EQ(0, received);
  27425. }
  27426. namespace no_proxy_test {
  27427. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27428. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27429. // calling listen().
  27430. class ScopedServer {
  27431. public:
  27432. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27433. ~ScopedServer() {
  27434. svr_.stop();
  27435. if (th_.joinable()) { th_.join(); }
  27436. }
  27437. Server &svr() { return svr_; }
  27438. int port() const { return port_; }
  27439. void listen() {
  27440. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27441. svr_.wait_until_ready();
  27442. }
  27443. private:
  27444. Server svr_;
  27445. std::thread th_;
  27446. int port_ = 0;
  27447. };
  27448. class ProxyAndTargetServers {
  27449. public:
  27450. ProxyAndTargetServers() {
  27451. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27452. proxy_hits_++;
  27453. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27454. res.set_content("via-proxy", "text/plain");
  27455. });
  27456. target_.Get(".*", [this](const Request &req, Response &res) {
  27457. target_hits_++;
  27458. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27459. res.set_content("direct", "text/plain");
  27460. });
  27461. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27462. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27463. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27464. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27465. proxy_mock_.wait_until_ready();
  27466. target_.wait_until_ready();
  27467. }
  27468. ~ProxyAndTargetServers() {
  27469. proxy_mock_.stop();
  27470. target_.stop();
  27471. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27472. if (target_thread_.joinable()) { target_thread_.join(); }
  27473. }
  27474. Server &proxy_mock() { return proxy_mock_; }
  27475. Server &target() { return target_; }
  27476. int proxy_port() const { return proxy_port_; }
  27477. int target_port() const { return target_port_; }
  27478. int proxy_hits() const { return proxy_hits_.load(); }
  27479. int target_hits() const { return target_hits_.load(); }
  27480. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27481. void reset_counters() {
  27482. proxy_hits_ = 0;
  27483. target_hits_ = 0;
  27484. last_had_proxy_authz_ = false;
  27485. }
  27486. private:
  27487. Server proxy_mock_;
  27488. Server target_;
  27489. std::thread proxy_thread_;
  27490. std::thread target_thread_;
  27491. int proxy_port_ = 0;
  27492. int target_port_ = 0;
  27493. std::atomic<int> proxy_hits_{0};
  27494. std::atomic<int> target_hits_{0};
  27495. std::atomic<bool> last_had_proxy_authz_{false};
  27496. };
  27497. inline std::unique_ptr<Client> make_client(const std::string &host,
  27498. ProxyAndTargetServers &s) {
  27499. auto cli = detail::make_unique<Client>(host, s.target_port());
  27500. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27501. cli->set_proxy("127.0.0.1", s.proxy_port());
  27502. return cli;
  27503. }
  27504. } // namespace no_proxy_test
  27505. using no_proxy_test::make_client;
  27506. using no_proxy_test::ProxyAndTargetServers;
  27507. // A stream request carries the credentials a buffered request does
  27508. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27509. no_proxy_test::ScopedServer origin;
  27510. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27511. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27512. });
  27513. origin.listen();
  27514. Client cli("127.0.0.1", origin.port());
  27515. cli.set_basic_auth("user", "pass");
  27516. auto handle = cli.open_stream("GET", "/x");
  27517. ASSERT_TRUE(handle.is_valid());
  27518. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27519. Client bearer("127.0.0.1", origin.port());
  27520. bearer.set_bearer_token_auth("tok");
  27521. auto handle2 = bearer.open_stream("GET", "/x");
  27522. ASSERT_TRUE(handle2.is_valid());
  27523. EXPECT_EQ("Bearer tok", read_all(handle2));
  27524. }
  27525. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27526. // takes its own credentials, as for a buffered request
  27527. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27528. std::string target, authz, proxy_authz;
  27529. no_proxy_test::ScopedServer proxy;
  27530. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27531. target = req.target;
  27532. authz = req.get_header_value("Authorization");
  27533. proxy_authz = req.get_header_value("Proxy-Authorization");
  27534. res.set_content("ok", "text/plain");
  27535. });
  27536. proxy.listen();
  27537. Client cli("origin.example", 8080);
  27538. cli.set_proxy("127.0.0.1", proxy.port());
  27539. cli.set_proxy_basic_auth("puser", "ppass");
  27540. cli.set_basic_auth("user", "pass");
  27541. auto handle = cli.open_stream("GET", "/x");
  27542. ASSERT_TRUE(handle.is_valid());
  27543. EXPECT_EQ("ok", read_all(handle));
  27544. EXPECT_EQ("http://origin.example:8080/x", target);
  27545. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27546. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27547. }
  27548. // In absolute-form the path follows the authority, so a path that does not
  27549. // begin with '/' would make the proxy connect to another host
  27550. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27551. std::vector<std::string> targets;
  27552. no_proxy_test::ScopedServer proxy;
  27553. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27554. targets.push_back(req.target);
  27555. res.set_content("ok", "text/plain");
  27556. });
  27557. proxy.listen();
  27558. Client cli("origin.example", 8080);
  27559. cli.set_proxy("127.0.0.1", proxy.port());
  27560. cli.set_basic_auth("user", "pass");
  27561. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27562. auto res = cli.Get(path);
  27563. EXPECT_FALSE(res) << path;
  27564. auto handle = cli.open_stream("GET", path);
  27565. EXPECT_FALSE(handle.is_valid()) << path;
  27566. }
  27567. EXPECT_TRUE(targets.empty());
  27568. auto res = cli.Get("/x");
  27569. ASSERT_TRUE(res);
  27570. ASSERT_EQ(1u, targets.size());
  27571. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27572. }
  27573. TEST(NoProxyTest, ExactHostnameBypasses) {
  27574. ProxyAndTargetServers s;
  27575. auto cli = make_client("example.com", s);
  27576. cli->set_no_proxy({"example.com"});
  27577. auto res = cli->Get("/");
  27578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27579. EXPECT_EQ(0, s.proxy_hits());
  27580. EXPECT_EQ(1, s.target_hits());
  27581. }
  27582. TEST(NoProxyTest, SubdomainBypasses) {
  27583. ProxyAndTargetServers s;
  27584. auto cli = make_client("foo.example.com", s);
  27585. cli->set_no_proxy({"example.com"});
  27586. auto res = cli->Get("/");
  27587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27588. EXPECT_EQ(0, s.proxy_hits());
  27589. EXPECT_EQ(1, s.target_hits());
  27590. }
  27591. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27592. // Regression guard: "evilexample.com" must not be considered a subdomain
  27593. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27594. // check would let traffic bypass the proxy and leak credentials direct
  27595. // to the attacker host.
  27596. ProxyAndTargetServers s;
  27597. auto cli = make_client("evilexample.com", s);
  27598. cli->set_no_proxy({"example.com"});
  27599. auto res = cli->Get("/");
  27600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27601. EXPECT_GE(s.proxy_hits(), 1);
  27602. EXPECT_EQ(0, s.target_hits());
  27603. }
  27604. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27605. ProxyAndTargetServers s;
  27606. auto cli = make_client("example.com.evil.com", s);
  27607. cli->set_no_proxy({"example.com"});
  27608. auto res = cli->Get("/");
  27609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27610. EXPECT_GE(s.proxy_hits(), 1);
  27611. EXPECT_EQ(0, s.target_hits());
  27612. }
  27613. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27614. ProxyAndTargetServers s;
  27615. auto cli = make_client("example.com", s);
  27616. cli->set_no_proxy({".example.com"});
  27617. auto res = cli->Get("/");
  27618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27619. EXPECT_EQ(0, s.proxy_hits());
  27620. EXPECT_EQ(1, s.target_hits());
  27621. }
  27622. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27623. ProxyAndTargetServers s;
  27624. auto cli = make_client("Example.COM", s);
  27625. cli->set_no_proxy({"EXAMPLE.com"});
  27626. auto res = cli->Get("/");
  27627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27628. EXPECT_EQ(0, s.proxy_hits());
  27629. EXPECT_EQ(1, s.target_hits());
  27630. }
  27631. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27632. ProxyAndTargetServers s;
  27633. auto cli = make_client("example.com.", s);
  27634. cli->set_no_proxy({"example.com"});
  27635. auto res = cli->Get("/");
  27636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27637. EXPECT_EQ(0, s.proxy_hits());
  27638. EXPECT_EQ(1, s.target_hits());
  27639. }
  27640. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27641. // Trailing dots must be normalized on BOTH sides — host and entry.
  27642. // An implementation that only strips the host-side trailing dot would
  27643. // fail to match host "example.com" against entry "example.com." because
  27644. // a literal substring search would compare 11 chars against 12.
  27645. ProxyAndTargetServers s;
  27646. auto cli = make_client("example.com", s);
  27647. cli->set_no_proxy({"example.com."});
  27648. auto res = cli->Get("/");
  27649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27650. EXPECT_EQ(0, s.proxy_hits());
  27651. EXPECT_EQ(1, s.target_hits());
  27652. }
  27653. TEST(NoProxyTest, WildcardBypassesEverything) {
  27654. ProxyAndTargetServers s;
  27655. auto cli = make_client("anything.invalid.test", s);
  27656. cli->set_no_proxy({"*"});
  27657. auto res = cli->Get("/");
  27658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27659. EXPECT_EQ(0, s.proxy_hits());
  27660. EXPECT_EQ(1, s.target_hits());
  27661. }
  27662. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27663. ProxyAndTargetServers s;
  27664. Client cli("127.0.0.1", s.target_port());
  27665. cli.set_proxy("127.0.0.1", s.proxy_port());
  27666. cli.set_no_proxy({"127.0.0.1"});
  27667. auto res = cli.Get("/");
  27668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27669. EXPECT_EQ(0, s.proxy_hits());
  27670. EXPECT_EQ(1, s.target_hits());
  27671. }
  27672. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27673. ProxyAndTargetServers s;
  27674. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27675. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27676. cli.set_proxy("127.0.0.1", s.proxy_port());
  27677. cli.set_no_proxy({"::1"});
  27678. auto res = cli.Get("/");
  27679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27680. EXPECT_EQ(0, s.proxy_hits());
  27681. EXPECT_EQ(1, s.target_hits());
  27682. }
  27683. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27684. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27685. // must still be recognized as IPv6 for CIDR matching. Implementations
  27686. // that detect IPv6 only when the host begins with '[' would parse the
  27687. // host as a hostname and miss the match.
  27688. ProxyAndTargetServers s;
  27689. Client cli("fe80::1", s.target_port());
  27690. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27691. cli.set_proxy("127.0.0.1", s.proxy_port());
  27692. cli.set_no_proxy({"fe80::/10"});
  27693. auto res = cli.Get("/");
  27694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27695. EXPECT_EQ(0, s.proxy_hits());
  27696. EXPECT_EQ(1, s.target_hits());
  27697. }
  27698. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  27699. ProxyAndTargetServers s;
  27700. Client cli("::1", s.target_port());
  27701. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27702. cli.set_proxy("127.0.0.1", s.proxy_port());
  27703. cli.set_no_proxy({"[::1]"});
  27704. auto res = cli.Get("/");
  27705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27706. EXPECT_EQ(0, s.proxy_hits());
  27707. EXPECT_EQ(1, s.target_hits());
  27708. }
  27709. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27710. ProxyAndTargetServers s;
  27711. Client cli("fe80::1", s.target_port());
  27712. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27713. cli.set_proxy("127.0.0.1", s.proxy_port());
  27714. cli.set_no_proxy({"[fe80::]/10"});
  27715. auto res = cli.Get("/");
  27716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27717. EXPECT_EQ(0, s.proxy_hits());
  27718. EXPECT_EQ(1, s.target_hits());
  27719. }
  27720. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27721. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27722. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27723. // tricks via address-family conversion.
  27724. ProxyAndTargetServers s;
  27725. Client cli("::ffff:127.0.0.1", s.target_port());
  27726. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27727. cli.set_proxy("127.0.0.1", s.proxy_port());
  27728. cli.set_no_proxy({"127.0.0.1"});
  27729. auto res = cli.Get("/");
  27730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27731. EXPECT_GE(s.proxy_hits(), 1);
  27732. EXPECT_EQ(0, s.target_hits());
  27733. }
  27734. TEST(NoProxyTest, IPv4CidrMatch) {
  27735. ProxyAndTargetServers s;
  27736. Client cli("127.0.0.1", s.target_port());
  27737. cli.set_proxy("127.0.0.1", s.proxy_port());
  27738. cli.set_no_proxy({"127.0.0.0/8"});
  27739. auto res = cli.Get("/");
  27740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27741. EXPECT_EQ(0, s.proxy_hits());
  27742. EXPECT_EQ(1, s.target_hits());
  27743. }
  27744. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27745. ProxyAndTargetServers s;
  27746. Client cli("127.0.0.1", s.target_port());
  27747. cli.set_proxy("127.0.0.1", s.proxy_port());
  27748. cli.set_no_proxy({"10.0.0.0/8"});
  27749. auto res = cli.Get("/");
  27750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27751. EXPECT_GE(s.proxy_hits(), 1);
  27752. EXPECT_EQ(0, s.target_hits());
  27753. }
  27754. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27755. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27756. // IPv4 target matches.
  27757. ProxyAndTargetServers s;
  27758. Client cli("127.0.0.1", s.target_port());
  27759. cli.set_proxy("127.0.0.1", s.proxy_port());
  27760. cli.set_no_proxy({"0.0.0.0/0"});
  27761. auto res = cli.Get("/");
  27762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27763. EXPECT_EQ(0, s.proxy_hits());
  27764. EXPECT_EQ(1, s.target_hits());
  27765. }
  27766. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  27767. ProxyAndTargetServers s;
  27768. Client cli("127.0.0.1", s.target_port());
  27769. cli.set_proxy("127.0.0.1", s.proxy_port());
  27770. cli.set_no_proxy({"127.0.0.1"});
  27771. auto res = cli.Get("/");
  27772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27773. EXPECT_EQ(0, s.proxy_hits());
  27774. EXPECT_EQ(1, s.target_hits());
  27775. }
  27776. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27777. ProxyAndTargetServers s;
  27778. Client cli("127.0.0.1", s.target_port());
  27779. cli.set_proxy("127.0.0.1", s.proxy_port());
  27780. cli.set_no_proxy({"127.0.0.0/33"});
  27781. auto res = cli.Get("/");
  27782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27783. EXPECT_GE(s.proxy_hits(), 1);
  27784. EXPECT_EQ(0, s.target_hits());
  27785. }
  27786. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27787. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27788. ProxyAndTargetServers s;
  27789. Client cli("127.0.0.1", s.target_port());
  27790. cli.set_proxy("127.0.0.1", s.proxy_port());
  27791. cli.set_no_proxy({"127.0.0.1/"});
  27792. auto res = cli.Get("/");
  27793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27794. EXPECT_GE(s.proxy_hits(), 1);
  27795. EXPECT_EQ(0, s.target_hits());
  27796. }
  27797. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  27798. ProxyAndTargetServers s;
  27799. auto cli = make_client("internal.corp", s);
  27800. cli->set_proxy_basic_auth("u", "p");
  27801. cli->set_no_proxy({"internal.corp"});
  27802. auto res = cli->Get("/");
  27803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27804. EXPECT_EQ(1, s.target_hits());
  27805. EXPECT_EQ(0, s.proxy_hits());
  27806. EXPECT_FALSE(s.last_had_proxy_authz())
  27807. << "Proxy-Authorization must not be sent direct to the target";
  27808. }
  27809. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27810. ProxyAndTargetServers s;
  27811. auto cli = make_client("public.example", s);
  27812. cli->set_proxy_basic_auth("u", "p");
  27813. cli->set_no_proxy({"internal.corp"}); // does not match
  27814. auto res = cli->Get("/");
  27815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27816. EXPECT_GE(s.proxy_hits(), 1);
  27817. EXPECT_TRUE(s.last_had_proxy_authz());
  27818. }
  27819. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27820. std::atomic<int> hits{0};
  27821. std::atomic<int> hits_with_authz{0};
  27822. no_proxy_test::ScopedServer proxy_mock;
  27823. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27824. hits++;
  27825. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27826. if (req.target.find("/redir") != std::string::npos) {
  27827. res.set_redirect("http://other.example/landed");
  27828. } else {
  27829. res.set_content("via-proxy", "text/plain");
  27830. }
  27831. });
  27832. proxy_mock.listen();
  27833. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27834. hits = 0;
  27835. hits_with_authz = 0;
  27836. Client cli("public.example", 80);
  27837. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27838. cli.set_proxy_basic_auth(c.first, c.second);
  27839. cli.set_follow_location(true);
  27840. // The redirect to another host goes through the proxy as well
  27841. auto res = cli.Get("/redir");
  27842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27843. EXPECT_EQ(2, hits.load());
  27844. EXPECT_EQ(2, hits_with_authz.load());
  27845. }
  27846. }
  27847. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27848. ProxyAndTargetServers s;
  27849. auto cli = make_client("anything.test", s);
  27850. auto res = cli->Get("/");
  27851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27852. EXPECT_GE(s.proxy_hits(), 1);
  27853. EXPECT_EQ(0, s.target_hits());
  27854. }
  27855. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27856. ProxyAndTargetServers s;
  27857. auto cli = make_client("example.com", s);
  27858. cli->set_no_proxy({"example.com:8080"});
  27859. auto res = cli->Get("/");
  27860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27861. EXPECT_GE(s.proxy_hits(), 1);
  27862. EXPECT_EQ(0, s.target_hits());
  27863. }
  27864. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27865. ProxyAndTargetServers s;
  27866. auto cli = make_client("anything.test", s);
  27867. cli->set_no_proxy({"", " ", "\t"});
  27868. auto res = cli->Get("/");
  27869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27870. EXPECT_GE(s.proxy_hits(), 1);
  27871. EXPECT_EQ(0, s.target_hits());
  27872. }
  27873. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27874. // An entry with leading/trailing whitespace must still match — env-style
  27875. // values are commonly pasted with stray spaces and an implementation
  27876. // that feeds the raw token directly to inet_pton would fail to match
  27877. // valid CIDRs because of the spaces.
  27878. ProxyAndTargetServers s;
  27879. Client cli("127.0.0.1", s.target_port());
  27880. cli.set_proxy("127.0.0.1", s.proxy_port());
  27881. cli.set_no_proxy({" 127.0.0.0/8 "});
  27882. auto res = cli.Get("/");
  27883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27884. EXPECT_EQ(0, s.proxy_hits());
  27885. EXPECT_EQ(1, s.target_hits());
  27886. }
  27887. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27888. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27889. // go direct and must NOT carry Proxy-Authorization.
  27890. std::atomic<int> proxy_hits{0};
  27891. std::atomic<int> target_hits{0};
  27892. std::atomic<bool> target_saw_authz{false};
  27893. no_proxy_test::ScopedServer proxy_mock, target;
  27894. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27895. proxy_hits++;
  27896. res.status = 302;
  27897. res.set_header("Location", "http://127.0.0.1:" +
  27898. std::to_string(target.port()) + "/landed");
  27899. });
  27900. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27901. target_hits++;
  27902. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27903. res.set_content("direct", "text/plain");
  27904. });
  27905. proxy_mock.listen();
  27906. target.listen();
  27907. Client cli("public.example", target.port());
  27908. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27909. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27910. cli.set_proxy_basic_auth("u", "p");
  27911. cli.set_no_proxy({"127.0.0.1"});
  27912. cli.set_follow_location(true);
  27913. auto res = cli.Get("/redir");
  27914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27915. EXPECT_GE(proxy_hits.load(), 1);
  27916. EXPECT_GE(target_hits.load(), 1);
  27917. EXPECT_FALSE(target_saw_authz.load());
  27918. }
  27919. #ifdef CPPHTTPLIB_SSL_ENABLED
  27920. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27921. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27922. // proxy creds would be sent to the (possibly hostile) origin.
  27923. std::atomic<int> target_hits{0};
  27924. std::atomic<bool> target_saw_proxy_authz{false};
  27925. no_proxy_test::ScopedServer target;
  27926. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27927. target_hits++;
  27928. if (req.has_header("Proxy-Authorization")) {
  27929. target_saw_proxy_authz = true;
  27930. }
  27931. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27932. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  27933. "nonce=\"abc\", algorithm=MD5");
  27934. });
  27935. target.listen();
  27936. // The proxy address is set to the target's port: the bypass MUST kick in;
  27937. // if it doesn't, the test still routes "via proxy" to the same server and
  27938. // the Proxy-Authorization assertion below catches the leak.
  27939. Client cli("evil.example", target.port());
  27940. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  27941. cli.set_proxy("127.0.0.1", target.port());
  27942. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27943. cli.set_no_proxy({"evil.example"});
  27944. auto res = cli.Get("/x");
  27945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27946. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27947. EXPECT_EQ(1, target_hits.load());
  27948. EXPECT_FALSE(target_saw_proxy_authz.load());
  27949. }
  27950. #endif
  27951. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  27952. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  27953. std::atomic<int> proxy_hits{0};
  27954. std::atomic<int> bypass_hits{0};
  27955. std::atomic<bool> proxy_saw_c_url{false};
  27956. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  27957. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27958. proxy_hits++;
  27959. if (req.path.find("/start") != std::string::npos) {
  27960. res.status = 302;
  27961. res.set_header("Location", "http://127.0.0.1:" +
  27962. std::to_string(bypass_server.port()) +
  27963. "/middle");
  27964. return;
  27965. }
  27966. if (req.path.find("/end") != std::string::npos) {
  27967. proxy_saw_c_url = true;
  27968. res.set_content("c-via-proxy", "text/plain");
  27969. return;
  27970. }
  27971. res.set_content("unexpected", "text/plain");
  27972. });
  27973. // public.example's "advertised" port is arbitrary (the request never lands
  27974. // there — it goes through the proxy), but use a dynamic value to stay
  27975. // friendly with sharded parallel runs.
  27976. int public_port = bypass_server.port();
  27977. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  27978. bypass_hits++;
  27979. res.status = 302;
  27980. res.set_header("Location", "http://public.example:" +
  27981. std::to_string(public_port) + "/end");
  27982. });
  27983. proxy_mock.listen();
  27984. bypass_server.listen();
  27985. Client cli("public.example", public_port);
  27986. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27987. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27988. cli.set_no_proxy({"127.0.0.1"});
  27989. cli.set_follow_location(true);
  27990. auto res = cli.Get("/start");
  27991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27992. EXPECT_EQ(StatusCode::OK_200, res->status);
  27993. EXPECT_EQ("c-via-proxy", res->body);
  27994. EXPECT_GE(proxy_hits.load(), 2);
  27995. EXPECT_GE(bypass_hits.load(), 1);
  27996. EXPECT_TRUE(proxy_saw_c_url.load());
  27997. }
  27998. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  27999. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28000. // request reconnects to the correct endpoint.
  28001. std::atomic<int> proxy_hits{0};
  28002. std::atomic<int> target_hits{0};
  28003. no_proxy_test::ScopedServer proxy_mock, target;
  28004. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28005. proxy_hits++;
  28006. res.set_content("via-proxy", "text/plain");
  28007. });
  28008. target.svr().Get(".*", [&](const Request &, Response &res) {
  28009. target_hits++;
  28010. res.set_content("direct", "text/plain");
  28011. });
  28012. proxy_mock.listen();
  28013. target.listen();
  28014. Client cli("public.example", target.port());
  28015. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28016. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28017. cli.set_keep_alive(true);
  28018. auto res1 = cli.Get("/a");
  28019. ASSERT_TRUE(res1);
  28020. EXPECT_EQ("via-proxy", res1->body);
  28021. EXPECT_EQ(1, proxy_hits.load());
  28022. EXPECT_EQ(0, target_hits.load());
  28023. cli.set_no_proxy({"public.example"});
  28024. auto res2 = cli.Get("/b");
  28025. ASSERT_TRUE(res2);
  28026. EXPECT_EQ("direct", res2->body);
  28027. EXPECT_EQ(1, proxy_hits.load());
  28028. EXPECT_EQ(1, target_hits.load());
  28029. }
  28030. // Forward declarations (see the base64_encode note).
  28031. namespace httplib {
  28032. namespace detail {
  28033. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28034. int shutdown_socket(socket_t sock) noexcept;
  28035. } // namespace detail
  28036. } // namespace httplib
  28037. namespace proxy_tunnel_test {
  28038. const char *const kTunnelEstablished =
  28039. "HTTP/1.1 200 Connection established\r\n\r\n";
  28040. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28041. using ConnectReply = std::function<std::string(const std::string &head)>;
  28042. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28043. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28044. class ScopedConnectProxy {
  28045. public:
  28046. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28047. : forward_port_(forward_port), reply_(std::move(reply)) {
  28048. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28049. if (listen_sock_ == INVALID_SOCKET) { return; }
  28050. auto a = loopback(0);
  28051. auto addr = reinterpret_cast<sockaddr *>(&a);
  28052. socklen_t alen = sizeof(a);
  28053. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28054. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28055. ::listen(listen_sock_, 4) != 0) {
  28056. return;
  28057. }
  28058. port_ = ntohs(a.sin_port);
  28059. th_ = std::thread([this] { run(); });
  28060. }
  28061. ~ScopedConnectProxy() {
  28062. if (th_.joinable()) {
  28063. stop_ = true;
  28064. auto wake = connect_to(port_);
  28065. th_.join();
  28066. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28067. }
  28068. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28069. }
  28070. int port() const { return port_; }
  28071. int connect_hits() const { return connect_hits_.load(); }
  28072. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28073. std::string connect_request() const {
  28074. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28075. return connect_request_;
  28076. }
  28077. private:
  28078. static sockaddr_in loopback(int port) {
  28079. sockaddr_in a{};
  28080. a.sin_family = AF_INET;
  28081. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28082. a.sin_port = htons(static_cast<unsigned short>(port));
  28083. return a;
  28084. }
  28085. static socket_t connect_to(int port) {
  28086. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28087. if (sock == INVALID_SOCKET) { return sock; }
  28088. auto a = loopback(port);
  28089. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28090. detail::close_socket(sock);
  28091. return INVALID_SOCKET;
  28092. }
  28093. return sock;
  28094. }
  28095. static bool send_all(socket_t sock, const char *data, size_t size) {
  28096. while (size > 0) {
  28097. auto n = detail::send_socket(sock, data, size, 0);
  28098. if (n <= 0) { return false; }
  28099. data += n;
  28100. size -= static_cast<size_t>(n);
  28101. }
  28102. return true;
  28103. }
  28104. void run() {
  28105. for (;;) {
  28106. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28107. if (stop_) {
  28108. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28109. return;
  28110. }
  28111. if (client == INVALID_SOCKET) { continue; }
  28112. serve(client);
  28113. detail::close_socket(client);
  28114. }
  28115. }
  28116. void serve(socket_t client) {
  28117. std::string head;
  28118. char buf[2048];
  28119. while (head.find("\r\n\r\n") == std::string::npos) {
  28120. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28121. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28122. if (n <= 0) { return; }
  28123. head.append(buf, static_cast<size_t>(n));
  28124. }
  28125. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28126. connect_hits_++;
  28127. {
  28128. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28129. connect_request_ = head;
  28130. }
  28131. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28132. if (!send_all(client, res.data(), res.size()) ||
  28133. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28134. return;
  28135. }
  28136. auto origin = connect_to(forward_port_);
  28137. if (origin == INVALID_SOCKET) { return; }
  28138. // When either side stops, shut both down so the other pump returns too.
  28139. auto pump = [&](socket_t from, socket_t to) {
  28140. char b[8192];
  28141. for (;;) {
  28142. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28143. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28144. }
  28145. detail::shutdown_socket(client);
  28146. detail::shutdown_socket(origin);
  28147. };
  28148. std::thread up([&] { pump(client, origin); });
  28149. pump(origin, client);
  28150. up.join();
  28151. detail::close_socket(origin);
  28152. }
  28153. int forward_port_;
  28154. ConnectReply reply_;
  28155. socket_t listen_sock_ = INVALID_SOCKET;
  28156. int port_ = 0;
  28157. std::thread th_;
  28158. std::atomic<bool> stop_{false};
  28159. std::atomic<int> connect_hits_{0};
  28160. mutable std::mutex connect_request_mutex_;
  28161. std::string connect_request_;
  28162. };
  28163. } // namespace proxy_tunnel_test
  28164. #ifdef CPPHTTPLIB_SSL_ENABLED
  28165. namespace proxy_tunnel_test {
  28166. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28167. class ScopedSSLServer {
  28168. public:
  28169. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28170. port_ = svr_.bind_to_any_port("127.0.0.1");
  28171. }
  28172. ~ScopedSSLServer() {
  28173. svr_.stop();
  28174. if (th_.joinable()) { th_.join(); }
  28175. }
  28176. SSLServer &svr() { return svr_; }
  28177. int port() const { return port_; }
  28178. void listen() {
  28179. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28180. svr_.wait_until_ready();
  28181. }
  28182. private:
  28183. SSLServer svr_;
  28184. std::thread th_;
  28185. int port_ = 0;
  28186. };
  28187. // Sends one request through the CONNECT proxy to the TLS origin with a
  28188. // credential configured for each hop, and checks that each credential reaches
  28189. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28190. // origin's (every header in origin_headers) on the tunnelled request.
  28191. void CredentialsStayWithTheirHop(
  28192. const std::function<void(SSLClient &)> &set_credentials,
  28193. const std::string &scheme,
  28194. const std::vector<std::string> &origin_headers = {"Authorization"},
  28195. bool stream = false) {
  28196. std::atomic<int> origin_hits{0};
  28197. std::atomic<bool> origin_saw_proxy_authz{false};
  28198. std::atomic<bool> origin_saw_headers{false};
  28199. ScopedSSLServer origin;
  28200. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28201. origin_hits++;
  28202. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28203. origin_saw_headers =
  28204. std::all_of(origin_headers.begin(), origin_headers.end(),
  28205. [&](const std::string &h) { return req.has_header(h); });
  28206. res.set_content("ok", "text/plain");
  28207. });
  28208. origin.listen();
  28209. ScopedConnectProxy proxy(origin.port());
  28210. ASSERT_NE(0, proxy.port());
  28211. // Pinned to 127.0.0.1 for the same reason as the test below.
  28212. SSLClient cli("127.0.0.1", origin.port());
  28213. cli.enable_server_certificate_verification(false);
  28214. cli.set_proxy("127.0.0.1", proxy.port());
  28215. set_credentials(cli);
  28216. if (stream) {
  28217. auto handle = cli.open_stream("GET", "/x");
  28218. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28219. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28220. } else {
  28221. auto res = cli.Get("/x");
  28222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28223. EXPECT_EQ(StatusCode::OK_200, res->status);
  28224. }
  28225. EXPECT_EQ(1, origin_hits.load());
  28226. EXPECT_EQ(1, proxy.connect_hits());
  28227. EXPECT_TRUE(origin_saw_headers.load());
  28228. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28229. << "Proxy-Authorization must not be sent inside the tunnel";
  28230. auto connect_req = proxy.connect_request();
  28231. EXPECT_NE(std::string::npos,
  28232. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28233. for (const auto &h : origin_headers) {
  28234. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28235. << h << " must not be sent to the proxy on CONNECT";
  28236. }
  28237. }
  28238. } // namespace proxy_tunnel_test
  28239. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28240. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28241. [](SSLClient &cli) {
  28242. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28243. cli.set_basic_auth("origin-user", "origin-pass");
  28244. },
  28245. "Basic");
  28246. }
  28247. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28248. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28249. [](SSLClient &cli) {
  28250. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28251. cli.set_basic_auth("origin-user", "origin-pass");
  28252. },
  28253. "Basic", {"Authorization"}, true);
  28254. }
  28255. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28256. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28257. [](SSLClient &cli) {
  28258. cli.set_proxy_bearer_token_auth("proxy-token");
  28259. cli.set_bearer_token_auth("origin-token");
  28260. },
  28261. "Bearer");
  28262. }
  28263. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28264. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28265. [](SSLClient &cli) {
  28266. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28267. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28268. {"Cookie", "sid=origin-session"},
  28269. {"X-Api-Key", "origin-key"}});
  28270. },
  28271. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28272. }
  28273. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28274. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28275. // retry; otherwise proxy creds would be sent to the origin.
  28276. std::atomic<int> origin_hits{0};
  28277. std::atomic<bool> origin_saw_proxy_authz{false};
  28278. proxy_tunnel_test::ScopedSSLServer origin;
  28279. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28280. origin_hits++;
  28281. if (req.has_header("Proxy-Authorization")) {
  28282. origin_saw_proxy_authz = true;
  28283. }
  28284. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28285. res.set_header("Proxy-Authenticate",
  28286. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28287. "algorithm=MD5");
  28288. });
  28289. origin.listen();
  28290. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28291. ASSERT_NE(0, proxy.port());
  28292. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28293. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28294. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28295. // and answer with its own status, making this test flaky.
  28296. SSLClient cli("127.0.0.1", origin.port());
  28297. cli.enable_server_certificate_verification(false);
  28298. cli.set_proxy("127.0.0.1", proxy.port());
  28299. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28300. auto res = cli.Get("/x");
  28301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28302. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28303. EXPECT_EQ(1, origin_hits.load());
  28304. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28305. EXPECT_EQ(1, proxy.connect_hits());
  28306. }
  28307. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28308. std::string origin_sni;
  28309. std::string origin_host;
  28310. proxy_tunnel_test::ScopedSSLServer origin;
  28311. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28312. origin_sni = req.sni();
  28313. origin_host = req.get_header_value("Host");
  28314. res.set_content("ok", "text/plain");
  28315. });
  28316. origin.listen();
  28317. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28318. ASSERT_NE(0, proxy.port());
  28319. SSLClient cli("origin.example", origin.port());
  28320. cli.enable_server_certificate_verification(false);
  28321. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28322. cli.set_proxy("127.0.0.1", proxy.port());
  28323. auto res = cli.Get("/x");
  28324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28325. EXPECT_EQ(StatusCode::OK_200, res->status);
  28326. auto port = std::to_string(origin.port());
  28327. auto target = "127.0.0.1:" + port;
  28328. auto connect_req = proxy.connect_request();
  28329. EXPECT_EQ(1, proxy.connect_hits());
  28330. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28331. EXPECT_NE(std::string::npos,
  28332. connect_req.find("\r\nHost: " + target + "\r\n"));
  28333. EXPECT_EQ("origin.example", origin_sni);
  28334. EXPECT_EQ("origin.example:" + port, origin_host);
  28335. }
  28336. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28337. proxy_tunnel_test::ScopedSSLServer origin;
  28338. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28339. res.set_content("ok", "text/plain");
  28340. });
  28341. origin.listen();
  28342. proxy_tunnel_test::ScopedConnectProxy proxy(
  28343. origin.port(), [](const std::string &head) -> std::string {
  28344. if (head.find(
  28345. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28346. std::string::npos) {
  28347. return proxy_tunnel_test::kTunnelEstablished;
  28348. }
  28349. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28350. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28351. "nonce=\"abc\", algorithm=MD5\r\n"
  28352. "Content-Length: 0\r\n\r\n";
  28353. });
  28354. ASSERT_NE(0, proxy.port());
  28355. SSLClient cli("origin.example", origin.port());
  28356. cli.enable_server_certificate_verification(false);
  28357. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28358. cli.set_proxy("127.0.0.1", proxy.port());
  28359. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28360. auto res = cli.Get("/x");
  28361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28362. EXPECT_EQ(StatusCode::OK_200, res->status);
  28363. // The retried CONNECT is the one the proxy saw last.
  28364. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28365. auto connect_req = proxy.connect_request();
  28366. EXPECT_EQ(2, proxy.connect_hits());
  28367. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28368. EXPECT_NE(std::string::npos,
  28369. connect_req.find("\r\nHost: " + target + "\r\n"));
  28370. }
  28371. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28372. proxy_tunnel_test::ScopedSSLServer origin;
  28373. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28374. res.set_content("ok", "text/plain");
  28375. });
  28376. origin.listen();
  28377. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28378. ASSERT_NE(0, proxy.port());
  28379. SSLClient cli("origin.example", origin.port());
  28380. cli.enable_server_certificate_verification(false);
  28381. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28382. cli.set_proxy("127.0.0.1", proxy.port());
  28383. auto res = cli.Get("/x");
  28384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28385. EXPECT_EQ(StatusCode::OK_200, res->status);
  28386. auto target = "origin.example:" + std::to_string(origin.port());
  28387. auto connect_req = proxy.connect_request();
  28388. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28389. EXPECT_NE(std::string::npos,
  28390. connect_req.find("\r\nHost: " + target + "\r\n"));
  28391. }
  28392. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28393. proxy_tunnel_test::ScopedSSLServer origin;
  28394. auto port = std::to_string(origin.port());
  28395. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28396. res.set_redirect("https://next.example:" + port + "/y");
  28397. });
  28398. origin.svr().Get("/y", [](const Request &, Response &res) {
  28399. res.set_content("ok", "text/plain");
  28400. });
  28401. origin.listen();
  28402. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28403. ASSERT_NE(0, proxy.port());
  28404. SSLClient cli("origin.example", origin.port());
  28405. cli.enable_server_certificate_verification(false);
  28406. cli.set_tunnel_hostname_addr_map(
  28407. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28408. cli.set_proxy("127.0.0.1", proxy.port());
  28409. cli.set_follow_location(true);
  28410. auto res = cli.Get("/x");
  28411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28412. EXPECT_EQ("ok", res->body);
  28413. // The last CONNECT is the redirect client's.
  28414. ASSERT_EQ(2, proxy.connect_hits());
  28415. auto target = "127.0.0.1:" + port;
  28416. auto connect_req = proxy.connect_request();
  28417. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28418. EXPECT_NE(std::string::npos,
  28419. connect_req.find("\r\nHost: " + target + "\r\n"));
  28420. }
  28421. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28422. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28423. std::atomic<int> origin_hits{0};
  28424. proxy_tunnel_test::ScopedSSLServer origin;
  28425. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28426. origin_hits++;
  28427. res.set_content("ok", "text/plain");
  28428. });
  28429. origin.listen();
  28430. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28431. ASSERT_NE(0, proxy.port());
  28432. SSLClient cli("127.0.0.1", origin.port());
  28433. cli.enable_server_certificate_verification(false);
  28434. cli.set_proxy("127.0.0.1", proxy.port());
  28435. cli.set_keep_alive(true);
  28436. cli.set_session_verifier(
  28437. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28438. auto res = cli.Get("/x");
  28439. EXPECT_FALSE(res);
  28440. ASSERT_FALSE(cli.is_socket_open());
  28441. res = cli.Get("/x");
  28442. EXPECT_FALSE(res);
  28443. EXPECT_EQ(2, proxy.connect_hits());
  28444. auto handle = cli.open_stream("GET", "/x");
  28445. EXPECT_FALSE(handle.is_valid());
  28446. EXPECT_EQ(3, proxy.connect_hits());
  28447. EXPECT_EQ(0, origin_hits.load());
  28448. }
  28449. #endif
  28450. namespace proxy_tunnel_test {
  28451. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28452. // anything else gets a 407 with `challenge`.
  28453. ConnectReply require_proxy_auth(const std::string &expected,
  28454. const std::string &challenge) {
  28455. return [=](const std::string &head) -> std::string {
  28456. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28457. std::string::npos) {
  28458. return kTunnelEstablished;
  28459. }
  28460. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28461. "Proxy-Authenticate: " +
  28462. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28463. };
  28464. }
  28465. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28466. // request, then echoes.
  28467. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28468. ws.send(
  28469. "authorization:" + req.get_header_value("Authorization") +
  28470. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28471. std::string msg;
  28472. while (ws.read(msg)) {
  28473. ws.send(msg);
  28474. }
  28475. }
  28476. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28477. class ScopedWebSocketOrigin {
  28478. public:
  28479. ScopedWebSocketOrigin() {
  28480. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28481. server_.listen();
  28482. }
  28483. int port() const { return server_.port(); }
  28484. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28485. std::string url() const {
  28486. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28487. }
  28488. private:
  28489. no_proxy_test::ScopedServer server_;
  28490. };
  28491. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28492. // passed as a constructor header, and checks that each reaches only its hop.
  28493. void WebSocketCredentialsStayWithTheirHop(
  28494. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28495. const std::string &proxy_authz, const std::string &origin_authz) {
  28496. ScopedWebSocketOrigin origin;
  28497. ScopedConnectProxy proxy(
  28498. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28499. ASSERT_NE(0, proxy.port());
  28500. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28501. client.set_proxy("127.0.0.1", proxy.port());
  28502. set_proxy_credentials(client);
  28503. auto res = client.connect();
  28504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28505. std::string msg;
  28506. ASSERT_TRUE(client.read(msg));
  28507. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28508. client.close();
  28509. EXPECT_EQ(1, proxy.connect_hits());
  28510. EXPECT_EQ(std::string::npos,
  28511. proxy.connect_request().find("\r\nAuthorization: "))
  28512. << "origin credentials must not be sent to the proxy";
  28513. }
  28514. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28515. void WebSocketSetterCredentialsStayWithTheirHop(
  28516. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28517. const std::string &proxy_authz, const std::string &origin_authz) {
  28518. ScopedWebSocketOrigin origin;
  28519. ScopedConnectProxy proxy(
  28520. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28521. ASSERT_NE(0, proxy.port());
  28522. ws::WebSocketClient client(origin.url());
  28523. client.set_proxy("127.0.0.1", proxy.port());
  28524. set_credentials(client);
  28525. auto res = client.connect();
  28526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28527. std::string msg;
  28528. ASSERT_TRUE(client.read(msg));
  28529. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28530. client.close();
  28531. EXPECT_EQ(1, proxy.connect_hits());
  28532. EXPECT_EQ(std::string::npos,
  28533. proxy.connect_request().find("\r\nAuthorization: "))
  28534. << "origin credentials must not be sent to the proxy";
  28535. }
  28536. } // namespace proxy_tunnel_test
  28537. namespace {
  28538. // Connects `client` and returns the Authorization header its upgrade
  28539. // request carried, or "<failed>" when the connection could not be opened.
  28540. std::string websocket_authorization(ws::WebSocketClient &client) {
  28541. if (!client.connect()) { return "<failed>"; }
  28542. std::string msg;
  28543. if (!client.read(msg)) { return "<failed>"; }
  28544. client.close();
  28545. auto prefix = std::string("authorization:");
  28546. auto end = msg.find("|proxy-authorization:");
  28547. return msg.substr(prefix.size(), end - prefix.size());
  28548. }
  28549. } // namespace
  28550. TEST(WebSocketClientAuthTest, BasicAuth) {
  28551. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28552. ws::WebSocketClient client(origin.url());
  28553. client.set_basic_auth("user", "pass");
  28554. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28555. websocket_authorization(client));
  28556. }
  28557. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28558. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28559. ws::WebSocketClient client(origin.url());
  28560. client.set_basic_auth("user", "");
  28561. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28562. websocket_authorization(client));
  28563. }
  28564. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28565. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28566. ws::WebSocketClient client(origin.url());
  28567. client.set_bearer_token_auth("token123");
  28568. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28569. }
  28570. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28571. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28572. ws::WebSocketClient client(origin.url());
  28573. client.set_bearer_token_auth("token123");
  28574. client.set_basic_auth("user", "pass");
  28575. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28576. websocket_authorization(client));
  28577. }
  28578. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28579. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28580. ws::WebSocketClient client(origin.url(),
  28581. {{"Authorization", "Bearer from-header"}});
  28582. client.set_bearer_token_auth("from-setter");
  28583. client.set_basic_auth("user", "pass");
  28584. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28585. }
  28586. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28587. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28588. ws::WebSocketClient client(origin.url());
  28589. EXPECT_EQ("", websocket_authorization(client));
  28590. client.set_bearer_token_auth("first");
  28591. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28592. client.set_bearer_token_auth("second");
  28593. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28594. client.set_bearer_token_auth("");
  28595. EXPECT_EQ("", websocket_authorization(client));
  28596. }
  28597. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28598. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28599. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28600. ASSERT_NE(0, proxy.port());
  28601. ws::WebSocketClient client(origin.url());
  28602. client.set_proxy("127.0.0.1", proxy.port());
  28603. auto res = client.connect();
  28604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28605. std::string msg;
  28606. ASSERT_TRUE(client.read(msg));
  28607. ASSERT_TRUE(client.send("hello"));
  28608. ASSERT_TRUE(client.read(msg));
  28609. EXPECT_EQ("hello", msg);
  28610. client.close();
  28611. EXPECT_EQ(1, proxy.connect_hits());
  28612. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28613. auto connect_req = proxy.connect_request();
  28614. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28615. EXPECT_NE(std::string::npos,
  28616. connect_req.find("\r\nHost: " + target + "\r\n"));
  28617. }
  28618. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28619. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28620. [](ws::WebSocketClient &cli) {
  28621. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28622. },
  28623. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28624. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28625. }
  28626. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28627. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28628. [](ws::WebSocketClient &cli) {
  28629. cli.set_proxy_bearer_token_auth("proxy-token");
  28630. },
  28631. "Bearer proxy-token", "Bearer origin-token");
  28632. }
  28633. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28634. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28635. [](ws::WebSocketClient &cli) {
  28636. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28637. cli.set_basic_auth("origin-user", "origin-pass");
  28638. },
  28639. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28640. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28641. }
  28642. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28643. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28644. [](ws::WebSocketClient &cli) {
  28645. cli.set_proxy_bearer_token_auth("proxy-token");
  28646. cli.set_bearer_token_auth("origin-token");
  28647. },
  28648. "Bearer proxy-token", "Bearer origin-token");
  28649. }
  28650. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28651. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28652. proxy_tunnel_test::ScopedConnectProxy proxy(
  28653. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28654. "Basic " + detail::base64_encode("proxy-user:"),
  28655. "Basic realm=\"proxy\""));
  28656. ASSERT_NE(0, proxy.port());
  28657. ws::WebSocketClient client(origin.url());
  28658. client.set_proxy("127.0.0.1", proxy.port());
  28659. client.set_proxy_basic_auth("proxy-user", "");
  28660. auto res = client.connect();
  28661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28662. client.close();
  28663. EXPECT_EQ(1, proxy.connect_hits());
  28664. }
  28665. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28666. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28667. proxy_tunnel_test::ScopedConnectProxy proxy(
  28668. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28669. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28670. ASSERT_NE(0, proxy.port());
  28671. ws::WebSocketClient client(origin.url());
  28672. client.set_proxy("127.0.0.1", proxy.port());
  28673. auto res = client.connect();
  28674. EXPECT_FALSE(res);
  28675. EXPECT_EQ(Error::ProxyConnection, res.error());
  28676. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28677. EXPECT_EQ("Basic realm=\"proxy\"",
  28678. res.get_header_value("Proxy-Authenticate"));
  28679. EXPECT_FALSE(client.is_open());
  28680. }
  28681. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28682. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28683. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28684. ASSERT_NE(0, proxy.port());
  28685. ws::WebSocketClient client(origin.url());
  28686. client.set_proxy("127.0.0.1", proxy.port());
  28687. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28688. client.set_no_proxy({"127.0.0.1"});
  28689. auto res = client.connect();
  28690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28691. std::string msg;
  28692. ASSERT_TRUE(client.read(msg));
  28693. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28694. << "proxy credentials must not reach a bypassed origin";
  28695. client.close();
  28696. EXPECT_EQ(0, proxy.connect_hits());
  28697. }
  28698. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28699. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28700. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28701. ASSERT_NE(0, proxy.port());
  28702. ws::WebSocketClient client(origin.url());
  28703. client.set_proxy("127.0.0.1", proxy.port());
  28704. ASSERT_TRUE(client.connect());
  28705. ASSERT_TRUE(client.connect());
  28706. client.close();
  28707. EXPECT_EQ(2, proxy.connect_hits());
  28708. }
  28709. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28710. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28711. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28712. ASSERT_NE(0, proxy.port());
  28713. auto port = std::to_string(origin.port());
  28714. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28715. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28716. client.set_proxy("127.0.0.1", proxy.port());
  28717. auto res = client.connect();
  28718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28719. std::string msg;
  28720. ASSERT_TRUE(client.read(msg));
  28721. client.close();
  28722. EXPECT_EQ(1, proxy.connect_hits());
  28723. auto target = "127.0.0.1:" + port;
  28724. auto connect_req = proxy.connect_request();
  28725. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28726. EXPECT_NE(std::string::npos,
  28727. connect_req.find("\r\nHost: " + target + "\r\n"));
  28728. }
  28729. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28730. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28731. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28732. ASSERT_NE(0, proxy.port());
  28733. auto port = std::to_string(origin.port());
  28734. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28735. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28736. client.set_proxy("127.0.0.1", proxy.port());
  28737. auto res = client.connect();
  28738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28739. client.close();
  28740. auto target = "origin.example:" + port;
  28741. auto connect_req = proxy.connect_request();
  28742. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28743. EXPECT_NE(std::string::npos,
  28744. connect_req.find("\r\nHost: " + target + "\r\n"));
  28745. }
  28746. #ifdef CPPHTTPLIB_SSL_ENABLED
  28747. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28748. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28749. proxy_tunnel_test::ScopedConnectProxy proxy(
  28750. origin.port(), [](const std::string &head) -> std::string {
  28751. if (head.find(
  28752. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28753. std::string::npos) {
  28754. return proxy_tunnel_test::kTunnelEstablished;
  28755. }
  28756. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28757. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28758. "nonce=\"abc\", algorithm=MD5\r\n"
  28759. "Content-Length: 0\r\n\r\n";
  28760. });
  28761. ASSERT_NE(0, proxy.port());
  28762. ws::WebSocketClient client(origin.url());
  28763. client.set_proxy("127.0.0.1", proxy.port());
  28764. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28765. auto res = client.connect();
  28766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28767. std::string msg;
  28768. ASSERT_TRUE(client.read(msg));
  28769. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28770. client.close();
  28771. EXPECT_EQ(2, proxy.connect_hits());
  28772. }
  28773. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28774. proxy_tunnel_test::ScopedSSLServer origin;
  28775. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28776. origin.listen();
  28777. proxy_tunnel_test::ScopedConnectProxy proxy(
  28778. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28779. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28780. ASSERT_NE(0, proxy.port());
  28781. ws::WebSocketClient client(
  28782. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28783. client.enable_server_certificate_verification(false);
  28784. client.set_proxy("127.0.0.1", proxy.port());
  28785. client.set_proxy_bearer_token_auth("proxy-token");
  28786. auto res = client.connect();
  28787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28788. std::string msg;
  28789. ASSERT_TRUE(client.read(msg));
  28790. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28791. << "Proxy-Authorization must not be sent inside the tunnel";
  28792. client.close();
  28793. EXPECT_EQ(1, proxy.connect_hits());
  28794. }
  28795. #endif
  28796. // ---------------------------------------------------------------------------
  28797. // Poller
  28798. // ---------------------------------------------------------------------------
  28799. namespace poller_test {
  28800. struct PollerBackend {
  28801. const char *name;
  28802. std::unique_ptr<detail::Poller> (*create)();
  28803. };
  28804. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  28805. *os << backend.name;
  28806. }
  28807. // Every backend runs the same contract tests. A new one is added here only.
  28808. std::vector<PollerBackend> poller_backends() {
  28809. return {
  28810. {"poll", &detail::PollPoller::create},
  28811. #ifdef __linux__
  28812. {"epoll", &detail::EpollPoller::create},
  28813. #endif
  28814. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  28815. {"kqueue", &detail::KqueuePoller::create},
  28816. #endif
  28817. };
  28818. }
  28819. // A descriptor whose readability the test controls.
  28820. struct TestSocketPair {
  28821. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  28822. TestSocketPair() { detail::create_socket_pair(fd); }
  28823. ~TestSocketPair() {
  28824. for (auto s : fd) {
  28825. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  28826. }
  28827. }
  28828. bool ok() const { return fd[0] != INVALID_SOCKET; }
  28829. socket_t reader() const { return fd[0]; }
  28830. void make_readable() {
  28831. const char c = 1;
  28832. detail::send_socket(fd[1], &c, 1, 0);
  28833. }
  28834. void close_writer() {
  28835. detail::close_socket(fd[1]);
  28836. fd[1] = INVALID_SOCKET;
  28837. }
  28838. };
  28839. using Tokens = std::vector<detail::Poller::Token>;
  28840. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  28841. protected:
  28842. void SetUp() override {
  28843. poller_ = GetParam().create();
  28844. ASSERT_TRUE(poller_ != nullptr);
  28845. }
  28846. Tokens wait_for(int timeout_ms) {
  28847. Tokens ready;
  28848. poller_->wait(timeout_ms, ready);
  28849. std::sort(ready.begin(), ready.end());
  28850. return ready;
  28851. }
  28852. std::unique_ptr<detail::Poller> poller_;
  28853. };
  28854. } // namespace poller_test
  28855. using poller_test::PollerTest;
  28856. using poller_test::TestSocketPair;
  28857. using poller_test::Tokens;
  28858. INSTANTIATE_TEST_SUITE_P(
  28859. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  28860. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  28861. return std::string(p.param.name);
  28862. });
  28863. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  28864. TestSocketPair sp;
  28865. ASSERT_TRUE(sp.ok());
  28866. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  28867. EXPECT_EQ(Tokens{}, wait_for(0));
  28868. sp.make_readable();
  28869. EXPECT_EQ(Tokens{7}, wait_for(1000));
  28870. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  28871. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  28872. EXPECT_EQ(Tokens{8}, wait_for(1000));
  28873. }
  28874. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  28875. TestSocketPair sp;
  28876. ASSERT_TRUE(sp.ok());
  28877. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28878. poller_->disarm(sp.reader());
  28879. poller_->disarm(sp.reader()); // disarming twice is harmless
  28880. sp.make_readable();
  28881. EXPECT_EQ(Tokens{}, wait_for(0));
  28882. }
  28883. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  28884. TestSocketPair sp;
  28885. ASSERT_TRUE(sp.ok());
  28886. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28887. auto start = std::chrono::steady_clock::now();
  28888. EXPECT_EQ(Tokens{}, wait_for(30));
  28889. auto elapsed = std::chrono::steady_clock::now() - start;
  28890. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  28891. EXPECT_LT(elapsed, std::chrono::seconds(1));
  28892. }
  28893. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  28894. std::vector<std::unique_ptr<TestSocketPair>> sps;
  28895. for (detail::Poller::Token i = 0; i < 8; i++) {
  28896. sps.emplace_back(new TestSocketPair());
  28897. ASSERT_TRUE(sps.back()->ok());
  28898. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  28899. }
  28900. sps[0]->make_readable();
  28901. sps[3]->make_readable();
  28902. sps[7]->make_readable();
  28903. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  28904. // The others are still armed, the delivered ones are not.
  28905. sps[1]->make_readable();
  28906. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28907. EXPECT_EQ(Tokens{}, wait_for(0));
  28908. }
  28909. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  28910. TestSocketPair s0, s1, s2;
  28911. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  28912. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  28913. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  28914. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  28915. // A delivery may move another entry inside the poller.
  28916. s0.make_readable();
  28917. EXPECT_EQ(Tokens{0}, wait_for(1000));
  28918. // The entries left must still be found by descriptor.
  28919. poller_->disarm(s2.reader());
  28920. s1.make_readable();
  28921. s2.make_readable();
  28922. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28923. }
  28924. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  28925. TestSocketPair sp;
  28926. ASSERT_TRUE(sp.ok());
  28927. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  28928. sp.close_writer();
  28929. EXPECT_EQ(Tokens{5}, wait_for(1000));
  28930. char c;
  28931. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  28932. }
  28933. TEST_P(PollerTest, WakeEndsABlockedWait) {
  28934. std::thread waker([&] {
  28935. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  28936. poller_->wake();
  28937. });
  28938. Tokens ready;
  28939. auto start = std::chrono::steady_clock::now();
  28940. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  28941. waker.join();
  28942. EXPECT_TRUE(ready.empty());
  28943. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  28944. }
  28945. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  28946. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  28947. Tokens ready;
  28948. EXPECT_TRUE(poller_->wait(1000, ready));
  28949. }
  28950. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  28951. for (int i = 0; i < 1000; i++) {
  28952. poller_->wake();
  28953. }
  28954. Tokens ready;
  28955. EXPECT_TRUE(poller_->wait(0, ready));
  28956. EXPECT_FALSE(poller_->wait(0, ready));
  28957. poller_->wake();
  28958. EXPECT_TRUE(poller_->wait(0, ready));
  28959. }
  28960. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  28961. // Two threads publish changes and wake() after each, as a reactor's workers
  28962. // do. Every change must be seen without a wait() timing out. A lost wake()
  28963. // needs an unlucky interleaving, hence the rounds.
  28964. for (int round = 0; round < 5; round++) {
  28965. SCOPED_TRACE(round);
  28966. const int per_thread = 20000;
  28967. std::atomic<int> posted{0};
  28968. auto post = [&] {
  28969. for (int i = 0; i < per_thread; i++) {
  28970. posted++;
  28971. poller_->wake();
  28972. }
  28973. };
  28974. std::thread t1(post), t2(post);
  28975. auto lost = false;
  28976. Tokens ready;
  28977. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  28978. if (!poller_->wait(1000, ready)) {
  28979. lost = true;
  28980. break;
  28981. }
  28982. }
  28983. t1.join();
  28984. t2.join();
  28985. ASSERT_FALSE(lost);
  28986. }
  28987. }
  28988. TEST(PollerFactoryTest, MakePollerWorks) {
  28989. auto poller = detail::make_poller();
  28990. ASSERT_TRUE(poller != nullptr);
  28991. poller->wake();
  28992. std::vector<detail::Poller::Token> ready;
  28993. EXPECT_TRUE(poller->wait(1000, ready));
  28994. }
  28995. // ---------------------------------------------------------------------------
  28996. // Keep-alive parking
  28997. // ---------------------------------------------------------------------------
  28998. namespace parking_test {
  28999. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29000. // runs once the port is bound and listening, before the server accepts.
  29001. struct RunningServer {
  29002. explicit RunningServer(
  29003. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29004. : svr_(svr) {
  29005. port = svr_.bind_to_any_port("127.0.0.1");
  29006. if (before_listen) { before_listen(port); }
  29007. thread = std::thread([this] { svr_.listen_after_bind(); });
  29008. svr_.wait_until_ready();
  29009. }
  29010. ~RunningServer() {
  29011. svr_.stop();
  29012. if (thread.joinable()) { thread.join(); }
  29013. }
  29014. Server &svr_;
  29015. int port = 0;
  29016. std::thread thread;
  29017. };
  29018. struct Sockets {
  29019. std::vector<socket_t> socks;
  29020. ~Sockets() {
  29021. for (auto s : socks) {
  29022. detail::close_socket(s);
  29023. }
  29024. }
  29025. socket_t connect(int port) {
  29026. auto error = Error::Success;
  29027. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29028. false, false, nullptr, 2, 0, 2, 0, 2,
  29029. 0, std::string(), error);
  29030. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29031. return s;
  29032. }
  29033. };
  29034. std::chrono::steady_clock::time_point in_ms(int ms) {
  29035. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29036. }
  29037. bool readable_by(socket_t sock,
  29038. std::chrono::steady_clock::time_point deadline) {
  29039. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29040. deadline - std::chrono::steady_clock::now())
  29041. .count();
  29042. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29043. }
  29044. bool send_get(socket_t sock, const std::string &path = "/") {
  29045. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29046. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29047. static_cast<ssize_t>(req.size());
  29048. }
  29049. // Reads one response whose body is "ok".
  29050. bool receives_ok(socket_t sock, int timeout_ms) {
  29051. auto deadline = in_ms(timeout_ms);
  29052. std::string buf;
  29053. while (readable_by(sock, deadline)) {
  29054. char tmp[1024];
  29055. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29056. if (n <= 0) { return false; }
  29057. buf.append(tmp, static_cast<size_t>(n));
  29058. auto end = buf.find("\r\n\r\n");
  29059. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29060. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29061. buf.compare(end + 4, 2, "ok") == 0;
  29062. }
  29063. }
  29064. return false;
  29065. }
  29066. bool get_ok(socket_t sock, int timeout_ms) {
  29067. return send_get(sock) && receives_ok(sock, timeout_ms);
  29068. }
  29069. // Whether the server closes `sock` by `deadline`.
  29070. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29071. char c;
  29072. return readable_by(sock, deadline) &&
  29073. detail::read_socket(sock, &c, 1, 0) <= 0;
  29074. }
  29075. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29076. auto deadline = in_ms(timeout_ms);
  29077. while (!cond()) {
  29078. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29079. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29080. }
  29081. return true;
  29082. }
  29083. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29084. svr.new_task_queue = std::move(new_task_queue);
  29085. svr.set_keep_alive_parking(true);
  29086. svr.Get("/", [](const Request &, Response &res) {
  29087. res.set_content("ok", "text/plain");
  29088. });
  29089. }
  29090. std::function<TaskQueue *(void)> threads(size_t n) {
  29091. return [n] { return new ThreadPool(n); };
  29092. }
  29093. // Counts what the event loop managed to queue, so that a test can wait for it.
  29094. class CountingTaskQueue final : public TaskQueue {
  29095. public:
  29096. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29097. std::atomic<int> &full)
  29098. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29099. bool enqueue(std::function<void()> fn) override {
  29100. auto queued = pool_.enqueue([this, fn]() {
  29101. fn();
  29102. // Holds the worker back from taking the next job.
  29103. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29104. });
  29105. (queued ? ok_ : full_)++;
  29106. return queued;
  29107. }
  29108. void shutdown() override { pool_.shutdown(); }
  29109. std::atomic<int> pause_after_ms{0};
  29110. private:
  29111. ThreadPool pool_;
  29112. std::atomic<int> &ok_;
  29113. std::atomic<int> &full_;
  29114. };
  29115. // Holds handlers until it opens, or for 3 seconds at most.
  29116. class Gate {
  29117. public:
  29118. void wait() {
  29119. std::unique_lock<std::mutex> lock(m_);
  29120. entered_++;
  29121. cv_.notify_all();
  29122. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29123. }
  29124. void open() {
  29125. std::lock_guard<std::mutex> guard(m_);
  29126. open_ = true;
  29127. cv_.notify_all();
  29128. }
  29129. int entered() {
  29130. std::lock_guard<std::mutex> guard(m_);
  29131. return entered_;
  29132. }
  29133. private:
  29134. std::mutex m_;
  29135. std::condition_variable cv_;
  29136. bool open_ = false;
  29137. int entered_ = 0;
  29138. };
  29139. } // namespace parking_test
  29140. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29141. using namespace parking_test;
  29142. Server svr;
  29143. serve_ok(svr, threads(1));
  29144. RunningServer running(svr);
  29145. Sockets socks;
  29146. // One kept-alive connection that has been served, and many that have not
  29147. // sent anything yet. None of them may keep the only worker.
  29148. auto served = socks.connect(running.port);
  29149. ASSERT_TRUE(get_ok(served, 2000));
  29150. for (int i = 0; i < 49; i++) {
  29151. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29152. }
  29153. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29154. EXPECT_TRUE(get_ok(served, 1000));
  29155. }
  29156. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29157. using namespace parking_test;
  29158. Server svr;
  29159. serve_ok(svr, threads(1));
  29160. svr.set_keep_alive_timeout(1);
  29161. RunningServer running(svr);
  29162. Sockets socks;
  29163. for (int i = 0; i < 3; i++) {
  29164. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29165. }
  29166. // One worker waiting on each in turn would take about 3 seconds.
  29167. auto deadline = in_ms(2000);
  29168. for (auto s : socks.socks) {
  29169. EXPECT_TRUE(sees_eof(s, deadline));
  29170. }
  29171. }
  29172. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29173. using namespace parking_test;
  29174. std::atomic<int> queued{0}, full{0};
  29175. Server svr;
  29176. // One worker and room for one queued task.
  29177. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29178. Gate gate;
  29179. svr.Get("/block", [&](const Request &, Response &res) {
  29180. gate.wait();
  29181. res.set_content("ok", "text/plain");
  29182. });
  29183. RunningServer running(svr);
  29184. // Before the server stops, so that a failed run does not wait for the
  29185. // handler's timeout.
  29186. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29187. Sockets socks;
  29188. auto a = socks.connect(running.port);
  29189. ASSERT_TRUE(get_ok(a, 2000));
  29190. // B keeps the only worker busy.
  29191. auto b = socks.connect(running.port);
  29192. ASSERT_TRUE(send_get(b, "/block"));
  29193. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29194. // A new connection C fills the queue.
  29195. auto c = socks.connect(running.port);
  29196. ASSERT_TRUE(send_get(c));
  29197. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29198. // A's next request finds the queue full, but A has been served before, so it
  29199. // waits instead of being cut off.
  29200. ASSERT_TRUE(send_get(a));
  29201. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29202. gate.open();
  29203. EXPECT_TRUE(receives_ok(b, 2000));
  29204. EXPECT_TRUE(receives_ok(c, 2000));
  29205. EXPECT_TRUE(receives_ok(a, 2000));
  29206. }
  29207. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29208. using namespace parking_test;
  29209. std::atomic<int> queued{0}, full{0};
  29210. CountingTaskQueue *queue = nullptr;
  29211. Server svr;
  29212. // Two workers and room for one queued task.
  29213. serve_ok(svr,
  29214. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29215. Gate first, second;
  29216. svr.Get("/first", [&](const Request &, Response &res) {
  29217. first.wait();
  29218. res.set_content("ok", "text/plain");
  29219. });
  29220. svr.Get("/second", [&](const Request &, Response &res) {
  29221. second.wait();
  29222. res.set_content("ok", "text/plain");
  29223. });
  29224. RunningServer running(svr);
  29225. auto open_gates = detail::scope_exit([&] {
  29226. first.open();
  29227. second.open();
  29228. });
  29229. Sockets socks;
  29230. auto a = socks.connect(running.port);
  29231. ASSERT_TRUE(get_ok(a, 2000));
  29232. // B and D take both workers, and C fills the queue. One at a time: the
  29233. // queue has room for one job only until a worker takes it.
  29234. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29235. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29236. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29237. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29238. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29239. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29240. // A's next request waits in the backlog.
  29241. ASSERT_TRUE(send_get(a));
  29242. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29243. // B's worker finishes, then takes C off the queue only later, which makes
  29244. // room for A.
  29245. queue->pause_after_ms = 200;
  29246. first.open();
  29247. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29248. queue->pause_after_ms = 0;
  29249. second.open();
  29250. EXPECT_TRUE(receives_ok(a, 2000));
  29251. }
  29252. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29253. using namespace parking_test;
  29254. Server svr;
  29255. serve_ok(svr, threads(1));
  29256. svr.set_keep_alive_timeout(0);
  29257. // The request is on the socket before the server accepts the connection,
  29258. // so it does not race the 10 ms floor. Without the floor the connection is
  29259. // closed unread.
  29260. Sockets socks;
  29261. auto sock = INVALID_SOCKET;
  29262. RunningServer running(svr, [&](int port) {
  29263. sock = socks.connect(port);
  29264. send_get(sock);
  29265. });
  29266. EXPECT_TRUE(receives_ok(sock, 1000));
  29267. }
  29268. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29269. using namespace parking_test;
  29270. for (int round = 0; round < 5; round++) {
  29271. SCOPED_TRACE(round);
  29272. Server svr;
  29273. serve_ok(svr, threads(2));
  29274. RunningServer running(svr);
  29275. Sockets socks;
  29276. for (int i = 0; i < 20; i++) {
  29277. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29278. }
  29279. auto start = std::chrono::steady_clock::now();
  29280. svr.stop();
  29281. running.thread.join();
  29282. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29283. std::chrono::milliseconds(500));
  29284. auto deadline = in_ms(1000);
  29285. for (auto s : socks.socks) {
  29286. EXPECT_TRUE(sees_eof(s, deadline));
  29287. }
  29288. }
  29289. }
  29290. #ifdef CPPHTTPLIB_SSL_ENABLED
  29291. namespace parking_test {
  29292. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29293. // that has opened a connection ahead of time. Freeing the session sends no
  29294. // close_notify, so the connection stays quiet.
  29295. bool handshake_only(socket_t sock) {
  29296. auto ctx = tls::create_client_context();
  29297. tls::set_verify_client(ctx, false);
  29298. auto session = tls::create_session(ctx, sock);
  29299. auto se = detail::scope_exit([&] {
  29300. tls::free_session(session);
  29301. tls::free_context(ctx);
  29302. });
  29303. tls::TlsError err;
  29304. return session &&
  29305. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29306. }
  29307. Client tls_client(int port) {
  29308. Client cli("https://127.0.0.1:" + std::to_string(port));
  29309. cli.enable_server_certificate_verification(false);
  29310. cli.set_keep_alive(true);
  29311. cli.set_connection_timeout(1);
  29312. cli.set_read_timeout(1);
  29313. return cli;
  29314. }
  29315. bool tls_get_ok(Client &cli) {
  29316. auto res = cli.Get("/");
  29317. return res && res->body == "ok";
  29318. }
  29319. } // namespace parking_test
  29320. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29321. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29322. struct {
  29323. unsigned long version;
  29324. bool safe;
  29325. } cases[] = {
  29326. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29327. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29328. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29329. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29330. };
  29331. for (const auto &c : cases) {
  29332. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29333. << std::hex << c.version;
  29334. }
  29335. }
  29336. #endif
  29337. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29338. using namespace parking_test;
  29339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29340. ASSERT_TRUE(svr.is_valid());
  29341. serve_ok(svr, threads(1));
  29342. svr.set_read_timeout(1); // so that a failing run does not take long
  29343. RunningServer running(svr);
  29344. Sockets socks;
  29345. // One served connection, some that have not started their handshake, and
  29346. // one that has finished it and gone quiet. None may keep the only worker.
  29347. auto served = tls_client(running.port);
  29348. ASSERT_TRUE(tls_get_ok(served));
  29349. for (int i = 0; i < 10; i++) {
  29350. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29351. }
  29352. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29353. auto other = tls_client(running.port);
  29354. EXPECT_TRUE(tls_get_ok(other));
  29355. EXPECT_TRUE(tls_get_ok(served));
  29356. }
  29357. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29358. using namespace parking_test;
  29359. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29360. ASSERT_TRUE(svr.is_valid());
  29361. serve_ok(svr, threads(1));
  29362. RunningServer running(svr);
  29363. Sockets socks;
  29364. auto plain = socks.connect(running.port);
  29365. ASSERT_TRUE(send_get(plain));
  29366. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29367. EXPECT_NE(0, svr.ssl_last_error());
  29368. }
  29369. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29370. using namespace parking_test;
  29371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29372. ASSERT_TRUE(svr.is_valid());
  29373. serve_ok(svr, threads(2));
  29374. RunningServer running(svr);
  29375. std::vector<Client> clients;
  29376. for (int i = 0; i < 5; i++) {
  29377. clients.push_back(tls_client(running.port));
  29378. ASSERT_TRUE(tls_get_ok(clients.back()));
  29379. }
  29380. auto start = std::chrono::steady_clock::now();
  29381. svr.stop();
  29382. running.thread.join();
  29383. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29384. std::chrono::milliseconds(500));
  29385. }
  29386. #endif